diff
stringlengths 164
2.11M
| is_single_chunk
bool 2
classes | is_single_function
bool 2
classes | buggy_function
stringlengths 0
335k
⌀ | fixed_function
stringlengths 23
335k
⌀ |
---|---|---|---|---|
diff --git a/tests/tests/app/src/android/app/cts/InstrumentationTest.java b/tests/tests/app/src/android/app/cts/InstrumentationTest.java
index 3007d807..a2c8eb80 100644
--- a/tests/tests/app/src/android/app/cts/InstrumentationTest.java
+++ b/tests/tests/app/src/android/app/cts/InstrumentationTest.java
@@ -1,971 +1,970 @@
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.app.cts;
import java.util.List;
import android.app.Activity;
import android.app.Application;
import android.app.Instrumentation;
import android.app.Instrumentation.ActivityMonitor;
import android.app.Instrumentation.ActivityResult;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Debug;
import android.os.IBinder;
import android.os.SystemClock;
import android.test.InstrumentationTestCase;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.ViewGroup.LayoutParams;
import com.android.cts.stub.R;
import dalvik.annotation.TestLevel;
import dalvik.annotation.TestTargetClass;
import dalvik.annotation.TestTargetNew;
import dalvik.annotation.TestTargets;
import dalvik.annotation.ToBeFixed;
@TestTargetClass(Instrumentation.class)
public class InstrumentationTest extends InstrumentationTestCase {
private static final int WAIT_TIME = 1000;
private Instrumentation mInstrumentation;
private InstrumentationTestActivity mActivity;
private Intent mIntent;
private boolean mRunOnMainSyncResult;
private Context mContext;
private MotionEvent mMotionEvent;
@Override
protected void setUp() throws Exception {
super.setUp();
mInstrumentation = getInstrumentation();
mContext = mInstrumentation.getTargetContext();
final long downTime = SystemClock.uptimeMillis();
final long eventTime = SystemClock.uptimeMillis();
// use coordinates for MotionEvent that do not include the status bar
// TODO: is there a more deterministic way to get these values
final long x = 50;
final long y = 50;
final int metaState = 0;
mMotionEvent = MotionEvent.obtain(downTime, eventTime, MotionEvent.ACTION_DOWN, x, y,
metaState);
mIntent = new Intent(mContext, InstrumentationTestActivity.class);
mIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mActivity = (InstrumentationTestActivity) mInstrumentation.startActivitySync(mIntent);
}
protected void tearDown() throws Exception {
mInstrumentation = null;
mIntent = null;
if (mActivity != null) {
mActivity.finish();
}
super.tearDown();
}
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "Instrumentation",
args = {}
)
public void testConstructor() throws Exception {
new Instrumentation();
}
@TestTargets({
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "addMonitor",
args = {ActivityMonitor.class}
),
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "addMonitor",
args = {IntentFilter.class, ActivityResult.class, boolean.class}
),
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "addMonitor",
args = {String.class, ActivityResult.class, boolean.class}
),
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "checkMonitorHit",
args = {ActivityMonitor.class, int.class}
),
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "waitForMonitor",
args = {ActivityMonitor.class}
),
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "waitForMonitorWithTimeout",
args = {ActivityMonitor.class, long.class}
),
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "removeMonitor",
args = {ActivityMonitor.class}
),
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "startActivitySync",
args = {Intent.class}
)
})
public void testMonitor() throws Exception {
if (mActivity != null)
mActivity.finish();
ActivityResult result = new ActivityResult(Activity.RESULT_OK, new Intent());
ActivityMonitor monitor = new ActivityMonitor(
InstrumentationTestActivity.class.getName(), result, false);
mInstrumentation.addMonitor(monitor);
Intent intent = new Intent(mContext, InstrumentationTestActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mContext.startActivity(intent);
Activity activity = mInstrumentation.waitForMonitorWithTimeout(monitor, WAIT_TIME);
assertTrue(activity instanceof InstrumentationTestActivity);
assertTrue(mInstrumentation.checkMonitorHit(monitor, 1));
activity.finish();
mInstrumentation.addMonitor(monitor);
mInstrumentation.removeMonitor(monitor);
Activity a = mInstrumentation.startActivitySync(intent);
assertTrue(a instanceof InstrumentationTestActivity);
activity = mInstrumentation.waitForMonitorWithTimeout(monitor, WAIT_TIME);
assertNull(activity);
a.finish();
IntentFilter filter = new IntentFilter();
ActivityMonitor am = mInstrumentation.addMonitor(filter, result, false);
mContext.startActivity(intent);
mInstrumentation.waitForIdleSync();
activity = am.waitForActivity();
assertTrue(activity instanceof InstrumentationTestActivity);
activity.finish();
mInstrumentation.removeMonitor(am);
am = mInstrumentation
.addMonitor(InstrumentationTestActivity.class.getName(), result, false);
mContext.startActivity(intent);
activity = am.waitForActivity();
assertTrue(activity instanceof InstrumentationTestActivity);
activity.finish();
mInstrumentation.removeMonitor(am);
}
@TestTargets({
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "callActivityOnCreate",
args = {Activity.class, Bundle.class}
),
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "waitForIdleSync",
args = {}
)
})
public void testCallActivityOnCreate() throws Throwable {
mActivity.setOnCreateCalled(false);
runTestOnUiThread(new Runnable() {
public void run() {
mInstrumentation.callActivityOnCreate(mActivity, new Bundle());
}
});
mInstrumentation.waitForIdleSync();
assertTrue(mActivity.isOnCreateCalled());
}
@TestTargets({
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "stopAllocCounting",
args = {}
),
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "startAllocCounting",
args = {}
),
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "getAllocCounts",
args = {}
),
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "getBinderCounts",
args = {}
)
})
public void testAllocCounting() throws Exception {
mInstrumentation.startAllocCounting();
Bundle b = mInstrumentation.getAllocCounts();
assertTrue(b.size() > 0);
b = mInstrumentation.getBinderCounts();
assertTrue(b.size() > 0);
int globeAllocCount = Debug.getGlobalAllocCount();
int globeAllocSize = Debug.getGlobalAllocSize();
int globeExternalAllCount = Debug.getGlobalExternalAllocCount();
int globeExternalAllSize = Debug.getGlobalExternalAllocSize();
int threadAllocCount = Debug.getThreadAllocCount();
assertTrue(Debug.getGlobalAllocCount() >= globeAllocCount);
assertTrue(Debug.getGlobalAllocSize() >= globeAllocSize);
assertTrue(Debug.getGlobalExternalAllocCount() >= globeExternalAllCount);
assertTrue(Debug.getGlobalExternalAllocSize() >= globeExternalAllSize);
assertTrue(Debug.getThreadAllocCount() >= threadAllocCount);
mInstrumentation.stopAllocCounting();
globeAllocCount = Debug.getGlobalAllocCount();
globeAllocSize = Debug.getGlobalAllocSize();
globeExternalAllCount = Debug.getGlobalExternalAllocCount();
globeExternalAllSize = Debug.getGlobalExternalAllocSize();
threadAllocCount = Debug.getThreadAllocCount();
assertEquals(globeAllocCount, Debug.getGlobalAllocCount());
assertEquals(globeAllocSize, Debug.getGlobalAllocSize());
assertEquals(globeExternalAllCount, Debug.getGlobalExternalAllocCount());
assertEquals(globeExternalAllSize, Debug.getGlobalExternalAllocSize());
assertEquals(threadAllocCount, Debug.getThreadAllocCount());
}
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "sendTrackballEventSync",
args = {MotionEvent.class}
)
public void testSendTrackballEventSync() throws Exception {
mInstrumentation.sendTrackballEventSync(mMotionEvent);
mInstrumentation.waitForIdleSync();
MotionEvent motionEvent = mActivity.getMotionEvent();
assertEquals(mMotionEvent.getMetaState(), motionEvent.getMetaState());
assertEquals(mMotionEvent.getEventTime(), motionEvent.getEventTime());
assertEquals(mMotionEvent.getDownTime(), motionEvent.getDownTime());
}
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "callApplicationOnCreate",
args = {Application.class}
)
public void testCallApplicationOnCreate() throws Exception {
InstrumentationTestStub ca = new InstrumentationTestStub();
mInstrumentation.callApplicationOnCreate(ca);
assertTrue(ca.mIsOnCreateCalled);
}
@TestTargets({
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "getContext",
args = {}
),
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "getTargetContext",
args = {}
)
})
public void testContext() throws Exception {
Context c1 = mInstrumentation.getContext();
Context c2 = mInstrumentation.getTargetContext();
assertNotSame(c1.getPackageName(), c2.getPackageName());
}
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "invokeMenuActionSync",
args = {Activity.class, int.class, int.class}
)
public void testInvokeMenuActionSync() throws Exception {
final int resId = R.id.goto_menu_id;
mInstrumentation.invokeMenuActionSync(mActivity, resId, 0);
mInstrumentation.waitForIdleSync();
assertEquals(resId, mActivity.getMenuID());
}
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "callActivityOnPostCreate",
args = {Activity.class, Bundle.class}
)
public void testCallActivityOnPostCreate() throws Throwable {
mActivity.setOnPostCreate(false);
runTestOnUiThread(new Runnable() {
public void run() {
mInstrumentation.callActivityOnPostCreate(mActivity, new Bundle());
}
});
mInstrumentation.waitForIdleSync();
assertTrue(mActivity.isOnPostCreate());
}
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "callActivityOnNewIntent",
args = {Activity.class, Intent.class}
)
public void testCallActivityOnNewIntent() throws Throwable {
mActivity.setOnNewIntentCalled(false);
runTestOnUiThread(new Runnable() {
public void run() {
mInstrumentation.callActivityOnNewIntent(mActivity, null);
}
});
mInstrumentation.waitForIdleSync();
assertTrue(mActivity.isOnNewIntentCalled());
}
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "callActivityOnResume",
args = {Activity.class}
)
public void testCallActivityOnResume() throws Throwable {
mActivity.setOnResume(false);
runTestOnUiThread(new Runnable() {
public void run() {
mInstrumentation.callActivityOnResume(mActivity);
}
});
mInstrumentation.waitForIdleSync();
assertTrue(mActivity.isOnResume());
}
@TestTargets({
@TestTargetNew(
level = TestLevel.NOT_FEASIBLE,
notes = "can't start a Instrumentation to test this method",
method = "onCreate",
args = {Bundle.class}
),
@TestTargetNew(
level = TestLevel.NOT_FEASIBLE,
notes = "can't start a Instrumentation to test this method",
method = "onDestroy",
args = {}
),
@TestTargetNew(
level = TestLevel.NOT_FEASIBLE,
notes = "call this method will crash the process",
method = "finish",
args = {int.class, Bundle.class}
),
@TestTargetNew(
level = TestLevel.NOT_FEASIBLE,
notes = "can't start a Instrumentation to test this method",
method = "onStart",
args = {}
),
@TestTargetNew(
level = TestLevel.NOT_FEASIBLE,
notes = "can't start a Instrumentation to test this method",
method = "onException",
args = {Object.class, Throwable.class}
),
@TestTargetNew(
level = TestLevel.PARTIAL,
method = "start",
args = {}
),
@TestTargetNew(
level = TestLevel.NOT_FEASIBLE,
method = "sendStatus",
args = {int.class, Bundle.class}
)
})
public void testMisc() throws Exception {
}
@TestTargets({
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "setAutomaticPerformanceSnapshots",
args = {}
),
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "startPerformanceSnapshot",
args = {}
),
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "endPerformanceSnapshot",
args = {}
)
})
public void testPerformanceSnapshot() throws Exception {
mInstrumentation.setAutomaticPerformanceSnapshots();
mInstrumentation.startPerformanceSnapshot();
mInstrumentation.endPerformanceSnapshot();
}
@TestTargets({
@TestTargetNew(
level = TestLevel.NOT_FEASIBLE,
method = "isProfiling",
args = {}
),
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "startProfiling",
args = {}
),
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "stopProfiling",
args = {}
)
})
public void testProfiling() throws Exception {
// by default, profiling was disabled. but after set the handleProfiling attribute in the
// manifest file for this Instrumentation to true, the profiling was also disabled.
assertFalse(mInstrumentation.isProfiling());
mInstrumentation.startProfiling();
mInstrumentation.stopProfiling();
}
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "invokeContextMenuAction",
args = {Activity.class, int.class, int.class}
)
public void testInvokeContextMenuAction() throws Exception {
MockActivity activity = new MockActivity();
final int id = 1;
final int flag = 2;
mInstrumentation.invokeContextMenuAction(activity, id, flag);
mInstrumentation.waitForIdleSync();
assertEquals(id, activity.mWindow.mId);
assertEquals(flag, activity.mWindow.mFlags);
}
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "sendStringSync",
args = {String.class}
)
public void testSendStringSync() {
final String text = "abcd";
mInstrumentation.sendStringSync(text);
mInstrumentation.waitForIdleSync();
List<KeyEvent> keyUpList = mActivity.getKeyUpList();
List<KeyEvent> keyDownList = mActivity.getKeyDownList();
assertEquals(text.length(), keyDownList.size());
assertEquals(text.length(), keyUpList.size());
for (int i = 0; i < keyDownList.size(); i++) {
assertEquals(KeyEvent.KEYCODE_A + i, keyDownList.get(i).getKeyCode());
}
for (int i = 0; i < keyUpList.size(); i++) {
assertEquals(KeyEvent.KEYCODE_A + i, keyUpList.get(i).getKeyCode());
}
}
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "callActivityOnSaveInstanceState",
args = {Activity.class, Bundle.class}
)
public void testCallActivityOnSaveInstanceState() {
final Bundle bundle = new Bundle();
mActivity.setOnSaveInstanceState(false);
mInstrumentation.callActivityOnSaveInstanceState(mActivity, bundle);
mInstrumentation.waitForIdleSync();
assertTrue(mActivity.isOnSaveInstanceState());
assertSame(bundle, mActivity.getBundle());
}
@TestTargets({
@TestTargetNew(
level = TestLevel.PARTIAL,
method = "setInTouchMode",
args = {boolean.class}
),
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "sendPointerSync",
args = {MotionEvent.class}
)
})
public void testSendPointerSync() throws Exception {
mInstrumentation.waitForIdleSync();
mInstrumentation.setInTouchMode(true);
mInstrumentation.sendPointerSync(mMotionEvent);
mInstrumentation.waitForIdleSync();
assertTrue(mActivity.isOnTouchEventCalled());
mActivity.setOnTouchEventCalled(false);
}
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "getComponentName",
args = {}
)
public void testGetComponentName() throws Exception {
ComponentName com = getInstrumentation().getComponentName();
assertNotNull(com.getPackageName());
assertNotNull(com.getClassName());
assertNotNull(com.getShortClassName());
}
@TestTargets({
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "newApplication",
args = {Class.class, Context.class}
),
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "newApplication",
args = {ClassLoader.class, String.class, Context.class}
)
})
public void testNewApplication() throws Exception {
final String className = "android.app.cts.MockApplication";
ClassLoader cl = getClass().getClassLoader();
Application app = mInstrumentation.newApplication(cl, className, mContext);
assertEquals(className, app.getClass().getName());
app = Instrumentation.newApplication(MockApplication.class, mContext);
assertEquals(className, app.getClass().getName());
}
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "runOnMainSync",
args = {Runnable.class}
)
public void testRunOnMainSync() throws Exception {
mRunOnMainSyncResult = false;
mInstrumentation.runOnMainSync(new Runnable() {
public void run() {
mRunOnMainSyncResult = true;
}
});
mInstrumentation.waitForIdleSync();
assertTrue(mRunOnMainSyncResult);
}
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "callActivityOnPause",
args = {Activity.class}
)
public void testCallActivityOnPause() throws Exception {
mActivity.setOnPauseCalled(false);
mInstrumentation.callActivityOnPause(mActivity);
mInstrumentation.waitForIdleSync();
assertTrue(mActivity.isOnPauseCalled());
}
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "callActivityOnDestroy",
args = {Activity.class}
)
public void testCallActivityOnDestroy() throws Exception {
mActivity.setOnDestroyCalled(false);
mInstrumentation.callActivityOnDestroy(mActivity);
mInstrumentation.waitForIdleSync();
assertTrue(mActivity.isOnDestroyCalled());
}
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "sendKeyDownUpSync",
args = {int.class}
)
public void testSendKeyDownUpSync() throws Exception {
mInstrumentation.sendKeyDownUpSync(KeyEvent.KEYCODE_0);
mInstrumentation.waitForIdleSync();
assertEquals(1, mActivity.getKeyUpList().size());
assertEquals(1, mActivity.getKeyDownList().size());
assertEquals(KeyEvent.KEYCODE_0, mActivity.getKeyUpList().get(0).getKeyCode());
assertEquals(KeyEvent.KEYCODE_0, mActivity.getKeyDownList().get(0).getKeyCode());
}
@TestTargets({
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "newActivity",
args = {ClassLoader.class, String.class, Intent.class}
),
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "newActivity",
args = {Class.class, Context.class, IBinder.class, Application.class, Intent.class,
ActivityInfo.class, CharSequence.class, Activity.class, String.class,
Object.class}
)
})
public void testNewActivity() throws Exception {
Intent intent = new Intent();
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
ClassLoader cl = getClass().getClassLoader();
Activity activity = mInstrumentation.newActivity(cl, InstrumentationTestActivity.class
.getName(), intent);
assertEquals(InstrumentationTestActivity.class.getName(), activity.getClass().getName());
activity.finish();
activity = null;
intent = new Intent(mContext, InstrumentationTestActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Activity father = new Activity();
ActivityInfo info = new ActivityInfo();
activity = mInstrumentation
.newActivity(InstrumentationTestActivity.class, mContext, null, null, intent, info,
InstrumentationTestActivity.class.getName(), father, null, null);
assertEquals(father, activity.getParent());
assertEquals(InstrumentationTestActivity.class.getName(), activity.getClass().getName());
activity.finish();
}
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "callActivityOnStart",
args = {Activity.class}
)
public void testCallActivityOnStart() throws Exception {
mActivity.setOnStart(false);
mInstrumentation.callActivityOnStart(mActivity);
mInstrumentation.waitForIdleSync();
assertTrue(mActivity.isOnStart());
}
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "waitForIdle",
args = {Runnable.class}
)
public void testWaitForIdle() throws Exception {
MockRunnable mr = new MockRunnable();
- mInstrumentation.waitForIdle(mr);
-
assertFalse(mr.isRunCalled());
+ mInstrumentation.waitForIdle(mr);
Thread.sleep(WAIT_TIME);
assertTrue(mr.isRunCalled());
}
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "sendCharacterSync",
args = {int.class}
)
public void testSendCharacterSync() throws Exception {
mInstrumentation.sendCharacterSync(KeyEvent.KEYCODE_0);
mInstrumentation.waitForIdleSync();
assertEquals(KeyEvent.KEYCODE_0, mActivity.getKeyDownCode());
assertEquals(KeyEvent.KEYCODE_0, mActivity.getKeyUpCode());
}
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "callActivityOnRestart",
args = {Activity.class}
)
public void testCallActivityOnRestart() throws Exception {
mActivity.setOnRestart(false);
mInstrumentation.callActivityOnRestart(mActivity);
mInstrumentation.waitForIdleSync();
assertTrue(mActivity.isOnRestart());
}
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "callActivityOnStop",
args = {Activity.class}
)
public void testCallActivityOnStop() throws Exception {
mActivity.setOnStop(false);
mInstrumentation.callActivityOnStop(mActivity);
mInstrumentation.waitForIdleSync();
assertTrue(mActivity.isOnStop());
}
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "callActivityOnUserLeaving",
args = {Activity.class}
)
public void testCallActivityOnUserLeaving() throws Exception {
assertFalse(mActivity.isOnLeave());
mInstrumentation.callActivityOnUserLeaving(mActivity);
mInstrumentation.waitForIdleSync();
assertTrue(mActivity.isOnLeave());
}
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "callActivityOnRestoreInstanceState",
args = {Activity.class, Bundle.class}
)
public void testCallActivityOnRestoreInstanceState() throws Exception {
mActivity.setOnRestoreInstanceState(false);
mInstrumentation.callActivityOnRestoreInstanceState(mActivity, new Bundle());
mInstrumentation.waitForIdleSync();
assertTrue(mActivity.isOnRestoreInstanceState());
}
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "sendKeySync",
args = {KeyEvent.class}
)
public void testSendKeySync() throws Exception {
KeyEvent key = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_0);
mInstrumentation.sendKeySync(key);
mInstrumentation.waitForIdleSync();
assertEquals(KeyEvent.KEYCODE_0, mActivity.getKeyDownCode());
}
private static class MockRunnable implements Runnable {
private boolean mIsRunCalled ;
public void run() {
mIsRunCalled = true;
}
public boolean isRunCalled() {
return mIsRunCalled;
}
}
private class MockActivity extends Activity {
MockWindow mWindow = new MockWindow(mContext);
@Override
public Window getWindow() {
return mWindow;
}
private class MockWindow extends Window {
public int mId;
public int mFlags;
public MockWindow(Context context) {
super(context);
}
@Override
public void addContentView(View view, LayoutParams params) {
}
@Override
public void closeAllPanels() {
}
@Override
public void closePanel(int featureId) {
}
@Override
public View getCurrentFocus() {
return null;
}
@Override
public View getDecorView() {
return null;
}
@Override
public LayoutInflater getLayoutInflater() {
return null;
}
@Override
public int getVolumeControlStream() {
return 0;
}
@Override
public boolean isFloating() {
return false;
}
@Override
public boolean isShortcutKey(int keyCode, KeyEvent event) {
return false;
}
@Override
protected void onActive() {
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
}
@Override
public void openPanel(int featureId, KeyEvent event) {
}
@Override
public View peekDecorView() {
return null;
}
@Override
public boolean performContextMenuIdentifierAction(int id, int flags) {
mId = id;
mFlags = flags;
return false;
}
@Override
public boolean performPanelIdentifierAction(int featureId, int id, int flags) {
return false;
}
@Override
public boolean performPanelShortcut(int featureId, int keyCode,
KeyEvent event, int flags) {
return false;
}
@Override
public void restoreHierarchyState(Bundle savedInstanceState) {
}
@Override
public Bundle saveHierarchyState() {
return null;
}
@Override
public void setBackgroundDrawable(Drawable drawable) {
}
@Override
public void setChildDrawable(int featureId, Drawable drawable) {
}
@Override
public void setChildInt(int featureId, int value) {
}
@Override
public void setContentView(int layoutResID) {
}
@Override
public void setContentView(View view) {
}
@Override
public void setContentView(View view, LayoutParams params) {
}
@Override
public void setFeatureDrawable(int featureId, Drawable drawable) {
}
@Override
public void setFeatureDrawableAlpha(int featureId, int alpha) {
}
@Override
public void setFeatureDrawableResource(int featureId, int resId) {
}
@Override
public void setFeatureDrawableUri(int featureId, Uri uri) {
}
@Override
public void setFeatureInt(int featureId, int value) {
}
@Override
public void setTitle(CharSequence title) {
}
@Override
public void setTitleColor(int textColor) {
}
@Override
public void setVolumeControlStream(int streamType) {
}
@Override
public boolean superDispatchKeyEvent(KeyEvent event) {
return false;
}
@Override
public boolean superDispatchTouchEvent(MotionEvent event) {
return false;
}
@Override
public boolean superDispatchTrackballEvent(MotionEvent event) {
return false;
}
@Override
public void takeKeyEvents(boolean get) {
}
@Override
public void togglePanel(int featureId, KeyEvent event) {
}
}
}
private static class InstrumentationTestStub extends Application {
boolean mIsOnCreateCalled = false;
@Override
public void onCreate() {
super.onCreate();
mIsOnCreateCalled = true;
}
}
}
| false | false | null | null |
diff --git a/src/com/android/calendar/EventInfoFragment.java b/src/com/android/calendar/EventInfoFragment.java
index c96789b7..25288951 100644
--- a/src/com/android/calendar/EventInfoFragment.java
+++ b/src/com/android/calendar/EventInfoFragment.java
@@ -1,1254 +1,1256 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR 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.calendar;
import com.android.calendar.CalendarController.EventType;
import com.android.calendar.event.EditEventHelper;
import com.android.calendar.event.EventViewUtils;
import android.app.Activity;
import android.app.Fragment;
import android.content.ActivityNotFoundException;
import android.content.AsyncQueryHandler;
import android.content.ContentProviderOperation;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.OperationApplicationException;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.graphics.PorterDuff;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Bundle;
import android.os.RemoteException;
import android.pim.EventRecurrence;
import android.provider.ContactsContract;
import android.provider.Calendar.Attendees;
import android.provider.Calendar.Calendars;
import android.provider.Calendar.Events;
import android.provider.Calendar.Reminders;
import android.provider.ContactsContract.CommonDataKinds;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.Data;
import android.provider.ContactsContract.Intents;
import android.provider.ContactsContract.Presence;
import android.provider.ContactsContract.QuickContact;
import android.provider.ContactsContract.CommonDataKinds.Email;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.text.format.DateUtils;
import android.text.format.Time;
import android.text.util.Linkify;
import android.text.util.Rfc822Token;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.QuickContactBadge;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.TimeZone;
import java.util.regex.Pattern;
public class EventInfoFragment extends Fragment implements View.OnClickListener,
AdapterView.OnItemSelectedListener {
public static final boolean DEBUG = true;
public static final String TAG = "EventInfoActivity";
private static final String BUNDLE_KEY_EVENT_ID = "key_event_id";
private static final String BUNDLE_KEY_START_MILLIS = "key_start_millis";
private static final String BUNDLE_KEY_END_MILLIS = "key_end_millis";
private static final int MAX_REMINDERS = 5;
/**
* These are the corresponding indices into the array of strings
* "R.array.change_response_labels" in the resource file.
*/
static final int UPDATE_SINGLE = 0;
static final int UPDATE_ALL = 1;
// Query tokens for QueryHandler
private static final int TOKEN_QUERY_EVENT = 0;
private static final int TOKEN_QUERY_CALENDARS = 1;
private static final int TOKEN_QUERY_ATTENDEES = 2;
private static final int TOKEN_QUERY_REMINDERS = 3;
private static final int TOKEN_QUERY_DUPLICATE_CALENDARS = 4;
private static final String[] EVENT_PROJECTION = new String[] {
Events._ID, // 0 do not remove; used in DeleteEventHelper
Events.TITLE, // 1 do not remove; used in DeleteEventHelper
Events.RRULE, // 2 do not remove; used in DeleteEventHelper
Events.ALL_DAY, // 3 do not remove; used in DeleteEventHelper
Events.CALENDAR_ID, // 4 do not remove; used in DeleteEventHelper
Events.DTSTART, // 5 do not remove; used in DeleteEventHelper
Events._SYNC_ID, // 6 do not remove; used in DeleteEventHelper
Events.EVENT_TIMEZONE, // 7 do not remove; used in DeleteEventHelper
Events.DESCRIPTION, // 8
Events.EVENT_LOCATION, // 9
Events.HAS_ALARM, // 10
Calendars.ACCESS_LEVEL, // 11
Calendars.COLOR, // 12
Events.HAS_ATTENDEE_DATA, // 13
Events.GUESTS_CAN_MODIFY, // 14
// TODO Events.GUESTS_CAN_INVITE_OTHERS has not been implemented in calendar provider
Events.GUESTS_CAN_INVITE_OTHERS, // 15
Events.ORGANIZER, // 16
Events.ORIGINAL_EVENT // 17 do not remove; used in DeleteEventHelper
};
private static final int EVENT_INDEX_ID = 0;
private static final int EVENT_INDEX_TITLE = 1;
private static final int EVENT_INDEX_RRULE = 2;
private static final int EVENT_INDEX_ALL_DAY = 3;
private static final int EVENT_INDEX_CALENDAR_ID = 4;
private static final int EVENT_INDEX_SYNC_ID = 6;
private static final int EVENT_INDEX_EVENT_TIMEZONE = 7;
private static final int EVENT_INDEX_DESCRIPTION = 8;
private static final int EVENT_INDEX_EVENT_LOCATION = 9;
private static final int EVENT_INDEX_HAS_ALARM = 10;
private static final int EVENT_INDEX_ACCESS_LEVEL = 11;
private static final int EVENT_INDEX_COLOR = 12;
private static final int EVENT_INDEX_HAS_ATTENDEE_DATA = 13;
private static final int EVENT_INDEX_GUESTS_CAN_MODIFY = 14;
private static final int EVENT_INDEX_CAN_INVITE_OTHERS = 15;
private static final int EVENT_INDEX_ORGANIZER = 16;
private static final String[] ATTENDEES_PROJECTION = new String[] {
Attendees._ID, // 0
Attendees.ATTENDEE_NAME, // 1
Attendees.ATTENDEE_EMAIL, // 2
Attendees.ATTENDEE_RELATIONSHIP, // 3
Attendees.ATTENDEE_STATUS, // 4
};
private static final int ATTENDEES_INDEX_ID = 0;
private static final int ATTENDEES_INDEX_NAME = 1;
private static final int ATTENDEES_INDEX_EMAIL = 2;
private static final int ATTENDEES_INDEX_RELATIONSHIP = 3;
private static final int ATTENDEES_INDEX_STATUS = 4;
private static final String ATTENDEES_WHERE = Attendees.EVENT_ID + "=?";
private static final String ATTENDEES_SORT_ORDER = Attendees.ATTENDEE_NAME + " ASC, "
+ Attendees.ATTENDEE_EMAIL + " ASC";
static final String[] CALENDARS_PROJECTION = new String[] {
Calendars._ID, // 0
Calendars.DISPLAY_NAME, // 1
Calendars.OWNER_ACCOUNT, // 2
Calendars.ORGANIZER_CAN_RESPOND // 3
};
static final int CALENDARS_INDEX_DISPLAY_NAME = 1;
static final int CALENDARS_INDEX_OWNER_ACCOUNT = 2;
static final int CALENDARS_INDEX_OWNER_CAN_RESPOND = 3;
static final String CALENDARS_WHERE = Calendars._ID + "=?";
static final String CALENDARS_DUPLICATE_NAME_WHERE = Calendars.DISPLAY_NAME + "=?";
private static final String[] REMINDERS_PROJECTION = new String[] {
Reminders._ID, // 0
Reminders.MINUTES, // 1
};
private static final int REMINDERS_INDEX_MINUTES = 1;
private static final String REMINDERS_WHERE = Reminders.EVENT_ID + "=? AND (" +
Reminders.METHOD + "=" + Reminders.METHOD_ALERT + " OR " + Reminders.METHOD + "=" +
Reminders.METHOD_DEFAULT + ")";
private static final String REMINDERS_SORT = Reminders.MINUTES;
private static final int MENU_GROUP_REMINDER = 1;
private static final int MENU_GROUP_EDIT = 2;
private static final int MENU_GROUP_DELETE = 3;
private static final int MENU_ADD_REMINDER = 1;
private static final int MENU_EDIT = 2;
private static final int MENU_DELETE = 3;
private static final int ATTENDEE_ID_NONE = -1;
private static final int ATTENDEE_NO_RESPONSE = -1;
private static final int[] ATTENDEE_VALUES = {
ATTENDEE_NO_RESPONSE,
Attendees.ATTENDEE_STATUS_ACCEPTED,
Attendees.ATTENDEE_STATUS_TENTATIVE,
Attendees.ATTENDEE_STATUS_DECLINED,
};
private View mView;
private LinearLayout mRemindersContainer;
private LinearLayout mOrganizerContainer;
private TextView mOrganizerView;
private Uri mUri;
private long mEventId;
private Cursor mEventCursor;
private Cursor mAttendeesCursor;
private Cursor mCalendarsCursor;
private long mStartMillis;
private long mEndMillis;
private boolean mHasAttendeeData;
private boolean mIsOrganizer;
private long mCalendarOwnerAttendeeId = ATTENDEE_ID_NONE;
private boolean mOrganizerCanRespond;
private String mCalendarOwnerAccount;
private boolean mCanModifyCalendar;
private boolean mIsBusyFreeCalendar;
private boolean mCanModifyEvent;
private int mNumOfAttendees;
private String mOrganizer;
private ArrayList<Integer> mOriginalMinutes = new ArrayList<Integer>();
private ArrayList<LinearLayout> mReminderItems = new ArrayList<LinearLayout>(0);
private ArrayList<Integer> mReminderValues;
private ArrayList<String> mReminderLabels;
private int mDefaultReminderMinutes;
private boolean mOriginalHasAlarm;
private EditResponseHelper mEditResponseHelper;
private int mResponseOffset;
private int mOriginalAttendeeResponse;
private int mAttendeeResponseFromIntent = ATTENDEE_NO_RESPONSE;
private boolean mIsRepeating;
private boolean mIsDuplicateName;
private Pattern mWildcardPattern = Pattern.compile("^.*$");
private LayoutInflater mLayoutInflater;
private LinearLayout mReminderAdder;
// TODO This can be removed when the contacts content provider doesn't return duplicates
private int mUpdateCounts;
private static class ViewHolder {
QuickContactBadge badge;
ImageView presence;
int updateCounts;
}
private HashMap<String, ViewHolder> mViewHolders = new HashMap<String, ViewHolder>();
private PresenceQueryHandler mPresenceQueryHandler;
private static final Uri CONTACT_DATA_WITH_PRESENCE_URI = Data.CONTENT_URI;
int PRESENCE_PROJECTION_CONTACT_ID_INDEX = 0;
int PRESENCE_PROJECTION_PRESENCE_INDEX = 1;
int PRESENCE_PROJECTION_EMAIL_INDEX = 2;
int PRESENCE_PROJECTION_PHOTO_ID_INDEX = 3;
private static final String[] PRESENCE_PROJECTION = new String[] {
Email.CONTACT_ID, // 0
Email.CONTACT_PRESENCE, // 1
Email.DATA, // 2
Email.PHOTO_ID, // 3
};
ArrayList<Attendee> mAcceptedAttendees = new ArrayList<Attendee>();
ArrayList<Attendee> mDeclinedAttendees = new ArrayList<Attendee>();
ArrayList<Attendee> mTentativeAttendees = new ArrayList<Attendee>();
ArrayList<Attendee> mNoResponseAttendees = new ArrayList<Attendee>();
private int mColor;
private QueryHandler mHandler;
private class QueryHandler extends AsyncQueryService {
public QueryHandler(Context context) {
super(context);
}
@Override
protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
// if the activity is finishing, then close the cursor and return
final Activity activity = getActivity();
if (activity == null || activity.isFinishing()) {
cursor.close();
return;
}
switch (token) {
case TOKEN_QUERY_EVENT:
mEventCursor = Utils.matrixCursorFromCursor(cursor);
if (initEventCursor()) {
// The cursor is empty. This can happen if the event was
// deleted.
// FRAG_TODO we should no longer rely on Activity.finish()
activity.finish();
return;
}
updateEvent(mView);
// start calendar query
Uri uri = Calendars.CONTENT_URI;
String[] args = new String[] {
Long.toString(mEventCursor.getLong(EVENT_INDEX_CALENDAR_ID))};
startQuery(TOKEN_QUERY_CALENDARS, null, uri, CALENDARS_PROJECTION,
CALENDARS_WHERE, args, null);
break;
case TOKEN_QUERY_CALENDARS:
mCalendarsCursor = Utils.matrixCursorFromCursor(cursor);
updateCalendar(mView);
// FRAG_TODO fragments shouldn't set the title anymore
updateTitle();
// update the action bar since our option set might have changed
activity.invalidateOptionsMenu();
// this is used for both attendees and reminders
args = new String[] { Long.toString(mEventId) };
// start attendees query
uri = Attendees.CONTENT_URI;
startQuery(TOKEN_QUERY_ATTENDEES, null, uri, ATTENDEES_PROJECTION,
ATTENDEES_WHERE, args, ATTENDEES_SORT_ORDER);
// start reminders query
mOriginalHasAlarm = mEventCursor.getInt(EVENT_INDEX_HAS_ALARM) != 0;
if (mOriginalHasAlarm) {
uri = Reminders.CONTENT_URI;
startQuery(TOKEN_QUERY_REMINDERS, null, uri, REMINDERS_PROJECTION,
REMINDERS_WHERE, args, REMINDERS_SORT);
} else {
// if no reminders, hide the appropriate fields
updateRemindersVisibility();
}
break;
case TOKEN_QUERY_ATTENDEES:
mAttendeesCursor = Utils.matrixCursorFromCursor(cursor);
initAttendeesCursor(mView);
updateResponse(mView);
break;
case TOKEN_QUERY_REMINDERS:
MatrixCursor reminderCursor = Utils.matrixCursorFromCursor(cursor);
try {
// First pass: collect all the custom reminder minutes
// (e.g., a reminder of 8 minutes) into a global list.
while (reminderCursor.moveToNext()) {
int minutes = reminderCursor.getInt(REMINDERS_INDEX_MINUTES);
EventViewUtils.addMinutesToList(
activity, mReminderValues, mReminderLabels, minutes);
}
// Second pass: create the reminder spinners
reminderCursor.moveToPosition(-1);
while (reminderCursor.moveToNext()) {
int minutes = reminderCursor.getInt(REMINDERS_INDEX_MINUTES);
mOriginalMinutes.add(minutes);
EventViewUtils.addReminder(activity, mRemindersContainer,
EventInfoFragment.this, mReminderItems, mReminderValues,
mReminderLabels, minutes);
}
} finally {
updateRemindersVisibility();
reminderCursor.close();
}
break;
case TOKEN_QUERY_DUPLICATE_CALENDARS:
mIsDuplicateName = cursor.getCount() > 1;
String calendarName = mCalendarsCursor.getString(CALENDARS_INDEX_DISPLAY_NAME);
String ownerAccount = mCalendarsCursor.getString(CALENDARS_INDEX_OWNER_ACCOUNT);
if (mIsDuplicateName && !calendarName.equalsIgnoreCase(ownerAccount)) {
Resources res = activity.getResources();
TextView ownerText = (TextView) mView.findViewById(R.id.owner);
ownerText.setText(ownerAccount);
ownerText.setTextColor(res.getColor(R.color.calendar_owner_text_color));
} else {
setVisibilityCommon(mView, R.id.owner, View.GONE);
}
setTextCommon(mView, R.id.calendar, calendarName);
break;
}
cursor.close();
}
}
public EventInfoFragment() {
mUri = null;
}
public EventInfoFragment(Uri uri, long startMillis, long endMillis, int attendeeResponse) {
mUri = uri;
mStartMillis = startMillis;
mEndMillis = endMillis;
mAttendeeResponseFromIntent = attendeeResponse;
}
public EventInfoFragment(long eventId, long startMillis, long endMillis) {
this(ContentUris.withAppendedId(Events.CONTENT_URI, eventId),
startMillis, endMillis, EventInfoActivity.ATTENDEE_NO_RESPONSE);
mEventId = eventId;
}
// This is called when one of the "remove reminder" buttons is selected.
public void onClick(View v) {
LinearLayout reminderItem = (LinearLayout) v.getParent();
LinearLayout parent = (LinearLayout) reminderItem.getParent();
parent.removeView(reminderItem);
mReminderItems.remove(reminderItem);
updateRemindersVisibility();
}
public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
// If they selected the "No response" option, then don't display the
// dialog asking which events to change.
if (id == 0 && mResponseOffset == 0) {
return;
}
// If this is not a repeating event, then don't display the dialog
// asking which events to change.
if (!mIsRepeating) {
return;
}
// If the selection is the same as the original, then don't display the
// dialog asking which events to change.
int index = findResponseIndexFor(mOriginalAttendeeResponse);
if (position == index + mResponseOffset) {
return;
}
// This is a repeating event. We need to ask the user if they mean to
// change just this one instance or all instances.
mEditResponseHelper.showDialog(mEditResponseHelper.getWhichEvents());
}
public void onNothingSelected(AdapterView<?> parent) {
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mEditResponseHelper = new EditResponseHelper(activity);
setHasOptionsMenu(true);
mHandler = new QueryHandler(activity);
mPresenceQueryHandler = new PresenceQueryHandler(activity, activity.getContentResolver());
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mLayoutInflater = inflater;
mView = inflater.inflate(R.layout.event_info_activity, null);
mRemindersContainer = (LinearLayout) mView.findViewById(R.id.reminders_container);
mOrganizerContainer = (LinearLayout) mView.findViewById(R.id.organizer_container);
mOrganizerView = (TextView) mView.findViewById(R.id.organizer);
// Initialize the reminder values array.
Resources r = getActivity().getResources();
String[] strings = r.getStringArray(R.array.reminder_minutes_values);
int size = strings.length;
ArrayList<Integer> list = new ArrayList<Integer>(size);
for (int i = 0 ; i < size ; i++) {
list.add(Integer.parseInt(strings[i]));
}
mReminderValues = list;
String[] labels = r.getStringArray(R.array.reminder_minutes_labels);
mReminderLabels = new ArrayList<String>(Arrays.asList(labels));
SharedPreferences prefs = CalendarPreferenceActivity.getSharedPreferences(getActivity());
String durationString =
prefs.getString(CalendarPreferenceActivity.KEY_DEFAULT_REMINDER, "0");
mDefaultReminderMinutes = Integer.parseInt(durationString);
// Setup the + Add Reminder Button
View.OnClickListener addReminderOnClickListener = new View.OnClickListener() {
public void onClick(View v) {
addReminder();
}
};
ImageButton reminderAddButton = (ImageButton) mView.findViewById(R.id.reminder_add);
reminderAddButton.setOnClickListener(addReminderOnClickListener);
mReminderAdder = (LinearLayout) mView.findViewById(R.id.reminder_adder);
if (mUri == null) {
// restore event ID from bundle
mEventId = savedInstanceState.getLong(BUNDLE_KEY_EVENT_ID);
mUri = ContentUris.withAppendedId(Events.CONTENT_URI, mEventId);
mStartMillis = savedInstanceState.getLong(BUNDLE_KEY_START_MILLIS);
mEndMillis = savedInstanceState.getLong(BUNDLE_KEY_END_MILLIS);
}
// start loading the data
mHandler.startQuery(TOKEN_QUERY_EVENT, null, mUri, EVENT_PROJECTION,
null, null, null);
return mView;
}
private void updateTitle() {
Resources res = getActivity().getResources();
if (mCanModifyCalendar && !mIsOrganizer) {
getActivity().setTitle(res.getString(R.string.event_info_title_invite));
} else {
getActivity().setTitle(res.getString(R.string.event_info_title));
}
}
/**
* Initializes the event cursor, which is expected to point to the first
* (and only) result from a query.
* @return true if the cursor is empty.
*/
private boolean initEventCursor() {
if ((mEventCursor == null) || (mEventCursor.getCount() == 0)) {
return true;
}
mEventCursor.moveToFirst();
mEventId = mEventCursor.getInt(EVENT_INDEX_ID);
String rRule = mEventCursor.getString(EVENT_INDEX_RRULE);
mIsRepeating = (rRule != null);
return false;
}
private static class Attendee {
String mName;
String mEmail;
Attendee(String name, String email) {
mName = name;
mEmail = email;
}
}
@SuppressWarnings("fallthrough")
private void initAttendeesCursor(View view) {
mOriginalAttendeeResponse = ATTENDEE_NO_RESPONSE;
mCalendarOwnerAttendeeId = ATTENDEE_ID_NONE;
mNumOfAttendees = 0;
if (mAttendeesCursor != null) {
mNumOfAttendees = mAttendeesCursor.getCount();
if (mAttendeesCursor.moveToFirst()) {
mAcceptedAttendees.clear();
mDeclinedAttendees.clear();
mTentativeAttendees.clear();
mNoResponseAttendees.clear();
do {
int status = mAttendeesCursor.getInt(ATTENDEES_INDEX_STATUS);
String name = mAttendeesCursor.getString(ATTENDEES_INDEX_NAME);
String email = mAttendeesCursor.getString(ATTENDEES_INDEX_EMAIL);
if (mAttendeesCursor.getInt(ATTENDEES_INDEX_RELATIONSHIP) ==
Attendees.RELATIONSHIP_ORGANIZER) {
// Overwrites the one from Event table if available
if (name != null && name.length() > 0) {
mOrganizer = name;
} else if (email != null && email.length() > 0) {
mOrganizer = email;
}
}
if (mCalendarOwnerAttendeeId == ATTENDEE_ID_NONE &&
mCalendarOwnerAccount.equalsIgnoreCase(email)) {
mCalendarOwnerAttendeeId = mAttendeesCursor.getInt(ATTENDEES_INDEX_ID);
mOriginalAttendeeResponse = mAttendeesCursor.getInt(ATTENDEES_INDEX_STATUS);
} else {
// Don't show your own status in the list because:
// 1) it doesn't make sense for event without other guests.
// 2) there's a spinner for that for events with guests.
switch(status) {
case Attendees.ATTENDEE_STATUS_ACCEPTED:
mAcceptedAttendees.add(new Attendee(name, email));
break;
case Attendees.ATTENDEE_STATUS_DECLINED:
mDeclinedAttendees.add(new Attendee(name, email));
break;
case Attendees.ATTENDEE_STATUS_NONE:
mNoResponseAttendees.add(new Attendee(name, email));
// Fallthrough so that no response is a subset of tentative
default:
mTentativeAttendees.add(new Attendee(name, email));
}
}
} while (mAttendeesCursor.moveToNext());
mAttendeesCursor.moveToFirst();
updateAttendees(view);
}
}
// only show the organizer if we're not the organizer and if
// we have attendee data (might have been removed by the server
// for events with a lot of attendees).
if (!mIsOrganizer && mHasAttendeeData) {
mOrganizerContainer.setVisibility(View.VISIBLE);
mOrganizerView.setText(mOrganizer);
} else {
mOrganizerContainer.setVisibility(View.GONE);
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putLong(BUNDLE_KEY_EVENT_ID, mEventId);
outState.putLong(BUNDLE_KEY_START_MILLIS, mStartMillis);
outState.putLong(BUNDLE_KEY_END_MILLIS, mEndMillis);
}
@Override
public void onDestroyView() {
ArrayList<Integer> reminderMinutes = EventViewUtils.reminderItemsToMinutes(mReminderItems,
mReminderValues);
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>(3);
boolean changed = EditEventHelper.saveReminders(ops, mEventId, reminderMinutes,
mOriginalMinutes, false /* no force save */);
mHandler.startBatch(mHandler.getNextToken(), null,
Calendars.CONTENT_URI.getAuthority(), ops, Utils.UNDO_DELAY);
// Update the "hasAlarm" field for the event
Uri uri = ContentUris.withAppendedId(Events.CONTENT_URI, mEventId);
int len = reminderMinutes.size();
boolean hasAlarm = len > 0;
if (hasAlarm != mOriginalHasAlarm) {
ContentValues values = new ContentValues();
values.put(Events.HAS_ALARM, hasAlarm ? 1 : 0);
mHandler.startUpdate(mHandler.getNextToken(), null, uri, values,
null, null, Utils.UNDO_DELAY);
}
changed |= saveResponse();
if (changed) {
Toast.makeText(getActivity(), R.string.saving_event, Toast.LENGTH_SHORT).show();
}
super.onDestroyView();
}
@Override
public void onDestroy() {
super.onDestroy();
if (mEventCursor != null) {
mEventCursor.close();
}
if (mCalendarsCursor != null) {
mCalendarsCursor.close();
}
if (mAttendeesCursor != null) {
mAttendeesCursor.close();
}
}
private boolean canAddReminders() {
return !mIsBusyFreeCalendar && mReminderItems.size() < MAX_REMINDERS;
}
private void addReminder() {
// TODO: when adding a new reminder, make it different from the
// last one in the list (if any).
if (mDefaultReminderMinutes == 0) {
EventViewUtils.addReminder(getActivity(), mRemindersContainer, this, mReminderItems,
mReminderValues, mReminderLabels, 10 /* minutes */);
} else {
EventViewUtils.addReminder(getActivity(), mRemindersContainer, this, mReminderItems,
mReminderValues, mReminderLabels, mDefaultReminderMinutes);
}
updateRemindersVisibility();
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
MenuItem item;
item = menu.add(MENU_GROUP_REMINDER, MENU_ADD_REMINDER, 0,
R.string.add_new_reminder);
item.setIcon(R.drawable.ic_menu_reminder);
item.setAlphabeticShortcut('r');
item.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
item = menu.add(MENU_GROUP_EDIT, MENU_EDIT, 0, R.string.edit_event_label);
item.setIcon(android.R.drawable.ic_menu_edit);
item.setAlphabeticShortcut('e');
item.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
item = menu.add(MENU_GROUP_DELETE, MENU_DELETE, 0, R.string.delete_event_label);
item.setIcon(android.R.drawable.ic_menu_delete);
item.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
super.onCreateOptionsMenu(menu, inflater);
}
@Override
public void onPrepareOptionsMenu(Menu menu) {
boolean canAddReminders = canAddReminders();
menu.setGroupVisible(MENU_GROUP_REMINDER, canAddReminders);
menu.setGroupEnabled(MENU_GROUP_REMINDER, canAddReminders);
menu.setGroupVisible(MENU_GROUP_EDIT, mCanModifyEvent);
menu.setGroupEnabled(MENU_GROUP_EDIT, mCanModifyEvent);
menu.setGroupVisible(MENU_GROUP_DELETE, mCanModifyCalendar);
menu.setGroupEnabled(MENU_GROUP_DELETE, mCanModifyCalendar);
super.onPrepareOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case MENU_ADD_REMINDER:
addReminder();
break;
case MENU_EDIT:
doEdit();
break;
case MENU_DELETE:
doDelete();
break;
}
return true;
}
// @Override
// public boolean onKeyDown(int keyCode, KeyEvent event) {
// if (keyCode == KeyEvent.KEYCODE_DEL) {
// doDelete();
// return true;
// }
// return super.onKeyDown(keyCode, event);
// }
private void updateRemindersVisibility() {
if (mIsBusyFreeCalendar) {
mRemindersContainer.setVisibility(View.GONE);
} else {
mRemindersContainer.setVisibility(View.VISIBLE);
mReminderAdder.setVisibility(canAddReminders() ? View.VISIBLE : View.GONE);
}
}
/**
* Asynchronously saves the response to an invitation if the user changed
* the response. Returns true if the database will be updated.
*
* @param cr the ContentResolver
* @return true if the database will be changed
*/
private boolean saveResponse() {
if (mAttendeesCursor == null || mEventCursor == null) {
return false;
}
Spinner spinner = (Spinner) getView().findViewById(R.id.response_value);
int position = spinner.getSelectedItemPosition() - mResponseOffset;
if (position <= 0) {
return false;
}
int status = ATTENDEE_VALUES[position];
// If the status has not changed, then don't update the database
if (status == mOriginalAttendeeResponse) {
return false;
}
// If we never got an owner attendee id we can't set the status
if (mCalendarOwnerAttendeeId == ATTENDEE_ID_NONE) {
return false;
}
if (!mIsRepeating) {
// This is a non-repeating event
updateResponse(mEventId, mCalendarOwnerAttendeeId, status);
return true;
}
// This is a repeating event
int whichEvents = mEditResponseHelper.getWhichEvents();
switch (whichEvents) {
case -1:
return false;
case UPDATE_SINGLE:
createExceptionResponse(mEventId, mCalendarOwnerAttendeeId, status);
return true;
case UPDATE_ALL:
updateResponse(mEventId, mCalendarOwnerAttendeeId, status);
return true;
default:
Log.e(TAG, "Unexpected choice for updating invitation response");
break;
}
return false;
}
private void updateResponse(long eventId, long attendeeId, int status) {
// Update the attendee status in the attendees table. the provider
// takes care of updating the self attendance status.
ContentValues values = new ContentValues();
if (!TextUtils.isEmpty(mCalendarOwnerAccount)) {
values.put(Attendees.ATTENDEE_EMAIL, mCalendarOwnerAccount);
}
values.put(Attendees.ATTENDEE_STATUS, status);
values.put(Attendees.EVENT_ID, eventId);
Uri uri = ContentUris.withAppendedId(Attendees.CONTENT_URI, attendeeId);
mHandler.startUpdate(mHandler.getNextToken(), null, uri, values,
null, null, Utils.UNDO_DELAY);
}
private void createExceptionResponse(long eventId, long attendeeId,
int status) {
if (mEventCursor == null || !mEventCursor.moveToFirst()) {
return;
}
ContentValues values = new ContentValues();
String title = mEventCursor.getString(EVENT_INDEX_TITLE);
String timezone = mEventCursor.getString(EVENT_INDEX_EVENT_TIMEZONE);
int calendarId = mEventCursor.getInt(EVENT_INDEX_CALENDAR_ID);
boolean allDay = mEventCursor.getInt(EVENT_INDEX_ALL_DAY) != 0;
String syncId = mEventCursor.getString(EVENT_INDEX_SYNC_ID);
values.put(Events.TITLE, title);
values.put(Events.EVENT_TIMEZONE, timezone);
values.put(Events.ALL_DAY, allDay ? 1 : 0);
values.put(Events.CALENDAR_ID, calendarId);
values.put(Events.DTSTART, mStartMillis);
values.put(Events.DTEND, mEndMillis);
values.put(Events.ORIGINAL_EVENT, syncId);
values.put(Events.ORIGINAL_INSTANCE_TIME, mStartMillis);
values.put(Events.ORIGINAL_ALL_DAY, allDay ? 1 : 0);
values.put(Events.STATUS, Events.STATUS_CONFIRMED);
values.put(Events.SELF_ATTENDEE_STATUS, status);
// Create a recurrence exception
mHandler.startInsert(mHandler.getNextToken(), null,
Events.CONTENT_URI, values, Utils.UNDO_DELAY);
}
private int findResponseIndexFor(int response) {
int size = ATTENDEE_VALUES.length;
for (int index = 0; index < size; index++) {
if (ATTENDEE_VALUES[index] == response) {
return index;
}
}
return 0;
}
private void doEdit() {
CalendarController.getInstance(getActivity()).sendEventRelatedEvent(
this, EventType.EDIT_EVENT, mEventId, mStartMillis, mEndMillis, 0, 0);
}
private void doDelete() {
CalendarController.getInstance(getActivity()).sendEventRelatedEvent(
this, EventType.DELETE_EVENT, mEventId, mStartMillis, mEndMillis, 0, 0);
}
private void updateEvent(View view) {
if (mEventCursor == null) {
return;
}
String eventName = mEventCursor.getString(EVENT_INDEX_TITLE);
if (eventName == null || eventName.length() == 0) {
eventName = getActivity().getString(R.string.no_title_label);
}
boolean allDay = mEventCursor.getInt(EVENT_INDEX_ALL_DAY) != 0;
String location = mEventCursor.getString(EVENT_INDEX_EVENT_LOCATION);
String description = mEventCursor.getString(EVENT_INDEX_DESCRIPTION);
String rRule = mEventCursor.getString(EVENT_INDEX_RRULE);
boolean hasAlarm = mEventCursor.getInt(EVENT_INDEX_HAS_ALARM) != 0;
String eventTimezone = mEventCursor.getString(EVENT_INDEX_EVENT_TIMEZONE);
mColor = mEventCursor.getInt(EVENT_INDEX_COLOR) & 0xbbffffff;
View calBackground = view.findViewById(R.id.cal_background);
calBackground.setBackgroundColor(mColor);
TextView title = (TextView) view.findViewById(R.id.title);
title.setTextColor(mColor);
View divider = view.findViewById(R.id.divider);
divider.getBackground().setColorFilter(mColor, PorterDuff.Mode.SRC_IN);
// What
if (eventName != null) {
setTextCommon(view, R.id.title, eventName);
}
// When
String when;
int flags;
if (allDay) {
flags = DateUtils.FORMAT_UTC | DateUtils.FORMAT_SHOW_WEEKDAY
| DateUtils.FORMAT_SHOW_DATE;
} else {
flags = DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE;
if (DateFormat.is24HourFormat(getActivity())) {
flags |= DateUtils.FORMAT_24HOUR;
}
}
when = DateUtils.formatDateRange(getActivity(), mStartMillis, mEndMillis, flags);
setTextCommon(view, R.id.when, when);
// Show the event timezone if it is different from the local timezone
Time time = new Time();
String localTimezone = time.timezone;
if (allDay) {
localTimezone = Time.TIMEZONE_UTC;
}
if (eventTimezone != null && !localTimezone.equals(eventTimezone) && !allDay) {
String displayName;
TimeZone tz = TimeZone.getTimeZone(localTimezone);
if (tz == null || tz.getID().equals("GMT")) {
displayName = localTimezone;
} else {
displayName = tz.getDisplayName();
}
setTextCommon(view, R.id.timezone, displayName);
+ setVisibilityCommon(view, R.id.timezone_container, View.VISIBLE);
} else {
setVisibilityCommon(view, R.id.timezone_container, View.GONE);
}
// Repeat
if (rRule != null) {
EventRecurrence eventRecurrence = new EventRecurrence();
eventRecurrence.parse(rRule);
Time date = new Time();
if (allDay) {
date.timezone = Time.TIMEZONE_UTC;
}
date.set(mStartMillis);
eventRecurrence.setStartDate(date);
String repeatString = EventRecurrenceFormatter.getRepeatString(
getActivity().getResources(), eventRecurrence);
setTextCommon(view, R.id.repeat, repeatString);
+ setVisibilityCommon(view, R.id.repeat_container, View.VISIBLE);
} else {
setVisibilityCommon(view, R.id.repeat_container, View.GONE);
}
// Where
if (location == null || location.length() == 0) {
setVisibilityCommon(view, R.id.where, View.GONE);
} else {
final TextView textView = (TextView) view.findViewById(R.id.where);
if (textView != null) {
textView.setAutoLinkMask(0);
textView.setText(location);
Linkify.addLinks(textView, mWildcardPattern, "geo:0,0?q=");
textView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
try {
return v.onTouchEvent(event);
} catch (ActivityNotFoundException e) {
// ignore
return true;
}
}
});
}
}
// Description
if (description == null || description.length() == 0) {
setVisibilityCommon(view, R.id.description, View.GONE);
} else {
setTextCommon(view, R.id.description, description);
}
}
private void updateCalendar(View view) {
mCalendarOwnerAccount = "";
if (mCalendarsCursor != null && mEventCursor != null) {
mCalendarsCursor.moveToFirst();
String tempAccount = mCalendarsCursor.getString(CALENDARS_INDEX_OWNER_ACCOUNT);
mCalendarOwnerAccount = (tempAccount == null) ? "" : tempAccount;
mOrganizerCanRespond = mCalendarsCursor.getInt(CALENDARS_INDEX_OWNER_CAN_RESPOND) != 0;
String displayName = mCalendarsCursor.getString(CALENDARS_INDEX_DISPLAY_NAME);
// start duplicate calendars query
mHandler.startQuery(TOKEN_QUERY_DUPLICATE_CALENDARS, null, Calendars.CONTENT_URI,
CALENDARS_PROJECTION, CALENDARS_DUPLICATE_NAME_WHERE,
new String[] {displayName}, null);
String eventOrganizer = mEventCursor.getString(EVENT_INDEX_ORGANIZER);
mIsOrganizer = mCalendarOwnerAccount.equalsIgnoreCase(eventOrganizer);
mHasAttendeeData = mEventCursor.getInt(EVENT_INDEX_HAS_ATTENDEE_DATA) != 0;
mOrganizer = eventOrganizer;
mCanModifyCalendar =
mEventCursor.getInt(EVENT_INDEX_ACCESS_LEVEL) >= Calendars.CONTRIBUTOR_ACCESS;
mIsBusyFreeCalendar =
mEventCursor.getInt(EVENT_INDEX_ACCESS_LEVEL) == Calendars.FREEBUSY_ACCESS;
mCanModifyEvent = mCanModifyCalendar
&& (mIsOrganizer || (mEventCursor.getInt(EVENT_INDEX_GUESTS_CAN_MODIFY) != 0));
} else {
setVisibilityCommon(view, R.id.calendar_container, View.GONE);
}
}
private void updateAttendees(View view) {
LinearLayout attendeesLayout = (LinearLayout) view.findViewById(R.id.attendee_list);
attendeesLayout.removeAllViewsInLayout();
++mUpdateCounts;
if(mAcceptedAttendees.size() == 0 && mDeclinedAttendees.size() == 0 &&
mTentativeAttendees.size() == mNoResponseAttendees.size()) {
// If all guests have no response just list them as guests,
CharSequence guestsLabel =
getActivity().getResources().getText(R.string.attendees_label);
addAttendeesToLayout(mNoResponseAttendees, attendeesLayout, guestsLabel);
} else {
// If we have any responses then divide them up by response
CharSequence[] entries;
entries = getActivity().getResources().getTextArray(R.array.response_labels2);
addAttendeesToLayout(mAcceptedAttendees, attendeesLayout, entries[0]);
addAttendeesToLayout(mDeclinedAttendees, attendeesLayout, entries[2]);
addAttendeesToLayout(mTentativeAttendees, attendeesLayout, entries[1]);
}
}
private void addAttendeesToLayout(ArrayList<Attendee> attendees, LinearLayout attendeeList,
CharSequence sectionTitle) {
if (attendees.size() == 0) {
return;
}
// Yes/No/Maybe Title
View titleView = mLayoutInflater.inflate(R.layout.contact_item, null);
titleView.findViewById(R.id.badge).setVisibility(View.GONE);
View divider = titleView.findViewById(R.id.separator);
divider.getBackground().setColorFilter(mColor, PorterDuff.Mode.SRC_IN);
TextView title = (TextView) titleView.findViewById(R.id.name);
title.setText(getActivity().getString(R.string.response_label, sectionTitle,
attendees.size()));
title.setTextAppearance(getActivity(), R.style.TextAppearance_EventInfo_Label);
attendeeList.addView(titleView);
// Attendees
int numOfAttendees = attendees.size();
StringBuilder selection = new StringBuilder(Email.DATA + " IN (");
String[] selectionArgs = new String[numOfAttendees];
for (int i = 0; i < numOfAttendees; ++i) {
Attendee attendee = attendees.get(i);
selectionArgs[i] = attendee.mEmail;
View v = mLayoutInflater.inflate(R.layout.contact_item, null);
v.setTag(attendee);
View separator = v.findViewById(R.id.separator);
separator.getBackground().setColorFilter(mColor, PorterDuff.Mode.SRC_IN);
// Text
TextView tv = (TextView) v.findViewById(R.id.name);
String name = attendee.mName;
if (name == null || name.length() == 0) {
name = attendee.mEmail;
}
tv.setText(name);
ViewHolder vh = new ViewHolder();
vh.badge = (QuickContactBadge) v.findViewById(R.id.badge);
vh.badge.assignContactFromEmail(attendee.mEmail, true);
vh.presence = (ImageView) v.findViewById(R.id.presence);
mViewHolders.put(attendee.mEmail, vh);
if (i == 0) {
selection.append('?');
} else {
selection.append(", ?");
}
attendeeList.addView(v);
}
selection.append(')');
mPresenceQueryHandler.startQuery(mUpdateCounts, attendees, CONTACT_DATA_WITH_PRESENCE_URI,
PRESENCE_PROJECTION, selection.toString(), selectionArgs, null);
}
private class PresenceQueryHandler extends AsyncQueryHandler {
Context mContext;
public PresenceQueryHandler(Context context, ContentResolver cr) {
super(cr);
mContext = context;
}
@Override
protected void onQueryComplete(int queryIndex, Object cookie, Cursor cursor) {
if (cursor == null) {
if (DEBUG) {
Log.e(TAG, "onQueryComplete: cursor == null");
}
return;
}
try {
cursor.moveToPosition(-1);
while (cursor.moveToNext()) {
String email = cursor.getString(PRESENCE_PROJECTION_EMAIL_INDEX);
int contactId = cursor.getInt(PRESENCE_PROJECTION_CONTACT_ID_INDEX);
ViewHolder vh = mViewHolders.get(email);
int photoId = cursor.getInt(PRESENCE_PROJECTION_PHOTO_ID_INDEX);
if (DEBUG) {
Log.e(TAG, "onQueryComplete Id: " + contactId + " PhotoId: " + photoId
+ " Email: " + email);
}
if (vh == null) {
continue;
}
ImageView presenceView = vh.presence;
if (presenceView != null) {
int status = cursor.getInt(PRESENCE_PROJECTION_PRESENCE_INDEX);
presenceView.setImageResource(Presence.getPresenceIconResourceId(status));
presenceView.setVisibility(View.VISIBLE);
}
if (photoId > 0 && vh.updateCounts < queryIndex) {
vh.updateCounts = queryIndex;
Uri personUri = ContentUris.withAppendedId(Contacts.CONTENT_URI,
contactId);
// TODO, modify to batch queries together
ContactsAsyncHelper.updateImageViewWithContactPhotoAsync(mContext,
vh.badge, personUri, R.drawable.ic_contact_picture);
}
}
} finally {
cursor.close();
}
}
}
void updateResponse(View view) {
// we only let the user accept/reject/etc. a meeting if:
// a) you can edit the event's containing calendar AND
// b) you're not the organizer and only attendee AND
// c) organizerCanRespond is enabled for the calendar
// (if the attendee data has been hidden, the visible number of attendees
// will be 1 -- the calendar owner's).
// (there are more cases involved to be 100% accurate, such as
// paying attention to whether or not an attendee status was
// included in the feed, but we're currently omitting those corner cases
// for simplicity).
if (!mCanModifyCalendar || (mHasAttendeeData && mIsOrganizer && mNumOfAttendees <= 1) ||
(mIsOrganizer && !mOrganizerCanRespond)) {
setVisibilityCommon(view, R.id.response_container, View.GONE);
return;
}
setVisibilityCommon(view, R.id.response_container, View.VISIBLE);
Spinner spinner = (Spinner) view.findViewById(R.id.response_value);
mResponseOffset = 0;
/* If the user has previously responded to this event
* we should not allow them to select no response again.
* Switch the entries to a set of entries without the
* no response option.
*/
if ((mOriginalAttendeeResponse != Attendees.ATTENDEE_STATUS_INVITED)
&& (mOriginalAttendeeResponse != ATTENDEE_NO_RESPONSE)
&& (mOriginalAttendeeResponse != Attendees.ATTENDEE_STATUS_NONE)) {
CharSequence[] entries;
entries = getActivity().getResources().getTextArray(R.array.response_labels2);
mResponseOffset = -1;
ArrayAdapter<CharSequence> adapter =
new ArrayAdapter<CharSequence>(getActivity(),
android.R.layout.simple_spinner_item, entries);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
}
int index;
if (mAttendeeResponseFromIntent != ATTENDEE_NO_RESPONSE) {
index = findResponseIndexFor(mAttendeeResponseFromIntent);
} else {
index = findResponseIndexFor(mOriginalAttendeeResponse);
}
spinner.setSelection(index + mResponseOffset);
spinner.setOnItemSelectedListener(this);
}
private void setTextCommon(View view, int id, CharSequence text) {
TextView textView = (TextView) view.findViewById(id);
if (textView == null)
return;
textView.setText(text);
}
private void setVisibilityCommon(View view, int id, int visibility) {
View v = view.findViewById(id);
if (v != null) {
v.setVisibility(visibility);
}
return;
}
/**
* Taken from com.google.android.gm.HtmlConversationActivity
*
* Send the intent that shows the Contact info corresponding to the email address.
*/
public void showContactInfo(Attendee attendee, Rect rect) {
// First perform lookup query to find existing contact
final ContentResolver resolver = getActivity().getContentResolver();
final String address = attendee.mEmail;
final Uri dataUri = Uri.withAppendedPath(CommonDataKinds.Email.CONTENT_FILTER_URI,
Uri.encode(address));
final Uri lookupUri = ContactsContract.Data.getContactLookupUri(resolver, dataUri);
if (lookupUri != null) {
// Found matching contact, trigger QuickContact
QuickContact.showQuickContact(getActivity(), rect, lookupUri,
QuickContact.MODE_MEDIUM, null);
} else {
// No matching contact, ask user to create one
final Uri mailUri = Uri.fromParts("mailto", address, null);
final Intent intent = new Intent(Intents.SHOW_OR_CREATE_CONTACT, mailUri);
// Pass along full E-mail string for possible create dialog
Rfc822Token sender = new Rfc822Token(attendee.mName, attendee.mEmail, null);
intent.putExtra(Intents.EXTRA_CREATE_DESCRIPTION, sender.toString());
// Only provide personal name hint if we have one
final String senderPersonal = attendee.mName;
if (!TextUtils.isEmpty(senderPersonal)) {
intent.putExtra(Intents.Insert.NAME, senderPersonal);
}
startActivity(intent);
}
}
}
| false | true | private void updateEvent(View view) {
if (mEventCursor == null) {
return;
}
String eventName = mEventCursor.getString(EVENT_INDEX_TITLE);
if (eventName == null || eventName.length() == 0) {
eventName = getActivity().getString(R.string.no_title_label);
}
boolean allDay = mEventCursor.getInt(EVENT_INDEX_ALL_DAY) != 0;
String location = mEventCursor.getString(EVENT_INDEX_EVENT_LOCATION);
String description = mEventCursor.getString(EVENT_INDEX_DESCRIPTION);
String rRule = mEventCursor.getString(EVENT_INDEX_RRULE);
boolean hasAlarm = mEventCursor.getInt(EVENT_INDEX_HAS_ALARM) != 0;
String eventTimezone = mEventCursor.getString(EVENT_INDEX_EVENT_TIMEZONE);
mColor = mEventCursor.getInt(EVENT_INDEX_COLOR) & 0xbbffffff;
View calBackground = view.findViewById(R.id.cal_background);
calBackground.setBackgroundColor(mColor);
TextView title = (TextView) view.findViewById(R.id.title);
title.setTextColor(mColor);
View divider = view.findViewById(R.id.divider);
divider.getBackground().setColorFilter(mColor, PorterDuff.Mode.SRC_IN);
// What
if (eventName != null) {
setTextCommon(view, R.id.title, eventName);
}
// When
String when;
int flags;
if (allDay) {
flags = DateUtils.FORMAT_UTC | DateUtils.FORMAT_SHOW_WEEKDAY
| DateUtils.FORMAT_SHOW_DATE;
} else {
flags = DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE;
if (DateFormat.is24HourFormat(getActivity())) {
flags |= DateUtils.FORMAT_24HOUR;
}
}
when = DateUtils.formatDateRange(getActivity(), mStartMillis, mEndMillis, flags);
setTextCommon(view, R.id.when, when);
// Show the event timezone if it is different from the local timezone
Time time = new Time();
String localTimezone = time.timezone;
if (allDay) {
localTimezone = Time.TIMEZONE_UTC;
}
if (eventTimezone != null && !localTimezone.equals(eventTimezone) && !allDay) {
String displayName;
TimeZone tz = TimeZone.getTimeZone(localTimezone);
if (tz == null || tz.getID().equals("GMT")) {
displayName = localTimezone;
} else {
displayName = tz.getDisplayName();
}
setTextCommon(view, R.id.timezone, displayName);
} else {
setVisibilityCommon(view, R.id.timezone_container, View.GONE);
}
// Repeat
if (rRule != null) {
EventRecurrence eventRecurrence = new EventRecurrence();
eventRecurrence.parse(rRule);
Time date = new Time();
if (allDay) {
date.timezone = Time.TIMEZONE_UTC;
}
date.set(mStartMillis);
eventRecurrence.setStartDate(date);
String repeatString = EventRecurrenceFormatter.getRepeatString(
getActivity().getResources(), eventRecurrence);
setTextCommon(view, R.id.repeat, repeatString);
} else {
setVisibilityCommon(view, R.id.repeat_container, View.GONE);
}
// Where
if (location == null || location.length() == 0) {
setVisibilityCommon(view, R.id.where, View.GONE);
} else {
final TextView textView = (TextView) view.findViewById(R.id.where);
if (textView != null) {
textView.setAutoLinkMask(0);
textView.setText(location);
Linkify.addLinks(textView, mWildcardPattern, "geo:0,0?q=");
textView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
try {
return v.onTouchEvent(event);
} catch (ActivityNotFoundException e) {
// ignore
return true;
}
}
});
}
}
// Description
if (description == null || description.length() == 0) {
setVisibilityCommon(view, R.id.description, View.GONE);
} else {
setTextCommon(view, R.id.description, description);
}
}
| private void updateEvent(View view) {
if (mEventCursor == null) {
return;
}
String eventName = mEventCursor.getString(EVENT_INDEX_TITLE);
if (eventName == null || eventName.length() == 0) {
eventName = getActivity().getString(R.string.no_title_label);
}
boolean allDay = mEventCursor.getInt(EVENT_INDEX_ALL_DAY) != 0;
String location = mEventCursor.getString(EVENT_INDEX_EVENT_LOCATION);
String description = mEventCursor.getString(EVENT_INDEX_DESCRIPTION);
String rRule = mEventCursor.getString(EVENT_INDEX_RRULE);
boolean hasAlarm = mEventCursor.getInt(EVENT_INDEX_HAS_ALARM) != 0;
String eventTimezone = mEventCursor.getString(EVENT_INDEX_EVENT_TIMEZONE);
mColor = mEventCursor.getInt(EVENT_INDEX_COLOR) & 0xbbffffff;
View calBackground = view.findViewById(R.id.cal_background);
calBackground.setBackgroundColor(mColor);
TextView title = (TextView) view.findViewById(R.id.title);
title.setTextColor(mColor);
View divider = view.findViewById(R.id.divider);
divider.getBackground().setColorFilter(mColor, PorterDuff.Mode.SRC_IN);
// What
if (eventName != null) {
setTextCommon(view, R.id.title, eventName);
}
// When
String when;
int flags;
if (allDay) {
flags = DateUtils.FORMAT_UTC | DateUtils.FORMAT_SHOW_WEEKDAY
| DateUtils.FORMAT_SHOW_DATE;
} else {
flags = DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE;
if (DateFormat.is24HourFormat(getActivity())) {
flags |= DateUtils.FORMAT_24HOUR;
}
}
when = DateUtils.formatDateRange(getActivity(), mStartMillis, mEndMillis, flags);
setTextCommon(view, R.id.when, when);
// Show the event timezone if it is different from the local timezone
Time time = new Time();
String localTimezone = time.timezone;
if (allDay) {
localTimezone = Time.TIMEZONE_UTC;
}
if (eventTimezone != null && !localTimezone.equals(eventTimezone) && !allDay) {
String displayName;
TimeZone tz = TimeZone.getTimeZone(localTimezone);
if (tz == null || tz.getID().equals("GMT")) {
displayName = localTimezone;
} else {
displayName = tz.getDisplayName();
}
setTextCommon(view, R.id.timezone, displayName);
setVisibilityCommon(view, R.id.timezone_container, View.VISIBLE);
} else {
setVisibilityCommon(view, R.id.timezone_container, View.GONE);
}
// Repeat
if (rRule != null) {
EventRecurrence eventRecurrence = new EventRecurrence();
eventRecurrence.parse(rRule);
Time date = new Time();
if (allDay) {
date.timezone = Time.TIMEZONE_UTC;
}
date.set(mStartMillis);
eventRecurrence.setStartDate(date);
String repeatString = EventRecurrenceFormatter.getRepeatString(
getActivity().getResources(), eventRecurrence);
setTextCommon(view, R.id.repeat, repeatString);
setVisibilityCommon(view, R.id.repeat_container, View.VISIBLE);
} else {
setVisibilityCommon(view, R.id.repeat_container, View.GONE);
}
// Where
if (location == null || location.length() == 0) {
setVisibilityCommon(view, R.id.where, View.GONE);
} else {
final TextView textView = (TextView) view.findViewById(R.id.where);
if (textView != null) {
textView.setAutoLinkMask(0);
textView.setText(location);
Linkify.addLinks(textView, mWildcardPattern, "geo:0,0?q=");
textView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
try {
return v.onTouchEvent(event);
} catch (ActivityNotFoundException e) {
// ignore
return true;
}
}
});
}
}
// Description
if (description == null || description.length() == 0) {
setVisibilityCommon(view, R.id.description, View.GONE);
} else {
setTextCommon(view, R.id.description, description);
}
}
|
diff --git a/jython/tests/java/javatests/TestSupport.java b/jython/tests/java/javatests/TestSupport.java
index 8076824e..89e9c738 100644
--- a/jython/tests/java/javatests/TestSupport.java
+++ b/jython/tests/java/javatests/TestSupport.java
@@ -1,50 +1,64 @@
//Copyright (c) Corporation for National Research Initiatives
package javatests;
+import java.lang.reflect.Field;
+import java.lang.NoSuchFieldException;
+
/**
* @author updikca1
*/
public class TestSupport {
public static class AssertionError extends RuntimeException {
public AssertionError() {
super();
}
public AssertionError(String message) {
super(message);
}
public AssertionError(String message, Throwable cause) {
super(message, cause);
}
public AssertionError(Throwable cause) {
super(cause);
}
}
public static void assertThat(boolean test, String message) {
if (!test) {
throw new AssertionError(message);
}
}
public static void fail(String message) {
throw new AssertionError(message);
}
public static void assertEquals(Object a, Object b, String message) {
assertThat(a.equals(b), message + "[a.equals(b) failed]");
assertThat(b.equals(a), message + "[b.equals(a) failed]");
}
public static void assertNotEquals(Object a, Object b, String message) {
assertThat( !a.equals(b), message + "[not a.equals(b) failed]");
assertThat( !b.equals(a), message + "[not b.equals(a) failed]");
}
+
+ public static Field getField(Class cls, String name) {
+ try {
+ Field f = cls.getDeclaredField(name);
+ f.setAccessible(true);
+ return f;
+ } catch (NoSuchFieldException ex) {
+ throw new RuntimeException(ex);
+ }
+ }
+
}
| false | false | null | null |
diff --git a/src/main/java/org/candlepin/config/ConfigProperties.java b/src/main/java/org/candlepin/config/ConfigProperties.java
index 46d23f3c6..02abd27b1 100644
--- a/src/main/java/org/candlepin/config/ConfigProperties.java
+++ b/src/main/java/org/candlepin/config/ConfigProperties.java
@@ -1,253 +1,253 @@
/**
* Copyright (c) 2009 - 2012 Red Hat, Inc.
*
* This software is licensed to you under the GNU General Public License,
* version 2 (GPLv2). There is NO WARRANTY for this software, express or
* implied, including the implied warranties of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
* along with this software; if not, see
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
*
* Red Hat trademarks are not licensed under GPLv2. No permission is
* granted to use or replicate Red Hat trademarks that are incorporated
* in this software or its documentation.
*/
package org.candlepin.config;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.candlepin.pinsetter.tasks.CancelJobJob;
import org.candlepin.pinsetter.tasks.CertificateRevocationListTask;
import org.candlepin.pinsetter.tasks.ImportRecordJob;
import org.candlepin.pinsetter.tasks.JobCleaner;
import org.candlepin.pinsetter.tasks.StatisticHistoryTask;
/**
* Defines a map of default properties used to prepopulate the {@link Config}.
* Also holds static keys for config lookup.
*/
public class ConfigProperties {
private ConfigProperties() {
}
public static final String CANDLEPIN_URL = "candlepin.url";
public static final String CA_KEY = "candlepin.ca_key";
public static final String CA_CERT = "candlepin.ca_cert";
public static final String FAIL_ON_UNKNOWN_IMPORT_PROPERTIES =
"candlepin.importer.fail_on_unknown";
public static final String CA_CERT_UPSTREAM = "candlepin.upstream_ca_cert";
public static final String CA_KEY_PASSWORD = "candlepin.ca_key_password";
public static final String HORNETQ_BASE_DIR = "candlepin.audit.hornetq.base_dir";
public static final String HORNETQ_LARGE_MSG_SIZE =
"candlepin.audit.hornetq.large_msg_size";
public static final String AUDIT_LISTENERS = "candlepin.audit.listeners";
public static final String AUDIT_LOG_FILE = "candlepin.audit.log_file";
public static final String AUDIT_LOG_VERBOSE = "candlepin.audit.log_verbose";
public static final String PRETTY_PRINT = "candlepin.pretty_print";
public static final String REVOKE_ENTITLEMENT_IN_FIFO_ORDER =
"candlepin.entitlement.revoke.order.fifo";
public static final String ACTIVATION_DEBUG_PREFIX =
"candlepin.subscription.activation.debug_prefix";
// Space separated list of resources to hide in the GET / list:
public static final String HIDDEN_RESOURCES = "candlepin.hidden_resources";
// Authentication
public static final String TRUSTED_AUTHENTICATION = "candlepin.auth.trusted.enable";
public static final String SSL_AUTHENTICATION = "candlepin.auth.ssl.enable";
public static final String OAUTH_AUTHENTICATION = "candlepin.auth.oauth.enable";
public static final String BASIC_AUTHENTICATION = "candlepin.auth.basic.enable";
// Pinsetter
public static final String TASKS = "pinsetter.tasks";
public static final String DEFAULT_TASKS = "pinsetter.default_tasks";
public static final String ENABLE_PINSETTER = "candlepin.pinsetter.enable";
private static final String[] DEFAULT_TASK_LIST = new String[]{
CertificateRevocationListTask.class.getName(),
JobCleaner.class.getName(), ImportRecordJob.class.getName(),
StatisticHistoryTask.class.getName(),
CancelJobJob.class.getName()};
public static final String SYNC_WORK_DIR = "candlepin.sync.work_dir";
public static final String CONSUMER_FACTS_MATCHER =
"candlepin.consumer.facts.match_regex";
public static final String SHARD_USERNAME = "candlepin.shard.username";
public static final String SHARD_PASSWORD = "candlepin.shard.password";
public static final String SHARD_WEBAPP = "candlepin.shard.webapp";
public static final String STANDALONE = "candlepin.standalone";
public static final String ENV_CONTENT_FILTERING =
"candlepin.environment_content_filtering";
public static final String CONSUMER_SYSTEM_NAME_PATTERN =
"candlepin.consumer_system_name_pattern";
public static final String CONSUMER_PERSON_NAME_PATTERN =
"candlepin.consumer_person_name_pattern";
- public static final String WEBAPP_PREFIX = "candlepin.export.webapp.prefix";
- public static final String WEBAPP_HOSTNAME = "candlepin.export.webapp.hostname";
+ public static final String PREFIX_WEBURL = "candlepin.export.prefix.weburl";
+ public static final String PREFIX_APIURL = "candlepin.export.prefix.apiurl";
public static final String PASSPHRASE_SECRET_FILE =
"candlepin.passphrase.path";
public static final String PRODUCT_CACHE_MAX = "candlepin.cache.product_cache_max";
public static final String ENABLE_CERT_V3 = "candlepin.enable_cert_v3";
public static final String INTEGER_FACTS =
"candlepin.integer_facts";
private static final String INTEGER_FACT_LIST =
"";
public static final String NON_NEG_INTEGER_FACTS =
"candlepin.positive_integer_facts";
private static final String NON_NEG_INTEGER_FACT_LIST =
"cpu.core(s)_per_socket," +
"cpu.cpu(s)," +
"cpu.cpu_socket(s)," +
"lscpu.core(s)_per_socket," +
"lscpu.cpu(s)," +
"lscpu.numa_node(s)," +
"lscpu.numa_node0_cpu(s)," +
"lscpu.socket(s)," +
"lscpu.thread(s)_per_core";
public static final String INTEGER_ATTRIBUTES =
"candlepin.integer_attributes";
private static final String INTEGER_ATTRIBUTE_LIST = "";
public static final String NON_NEG_INTEGER_ATTRIBUTES =
"candlepin.positive_integer_attributes";
private static final String NON_NEG_INTEGER_ATTRIBUTE_LIST =
"sockets," +
"warning_period," +
"ram";
public static final String LONG_ATTRIBUTES =
"candlepin.long_attributes";
private static final String LONG_ATTRIBUTE_LIST =
"";
public static final String NON_NEG_LONG_ATTRIBUTES =
"candlepin.positive_long_attributes";
private static final String NON_NEG_LONG_ATTRIBUTE_LIST =
"metadata_expire";
public static final String BOOLEAN_ATTRIBUTES = "candlepin.boolean_attributes";
private static final String BOOLEAN_ATTRIBUTE_LIST =
"management_enabled," +
"virt_only";
public static final Map<String, String> DEFAULT_PROPERTIES =
new HashMap<String, String>() {
private static final long serialVersionUID = 1L;
{
this.put(CANDLEPIN_URL, "https://localhost");
this.put(CA_KEY, "/etc/candlepin/certs/candlepin-ca.key");
this.put(CA_CERT, "/etc/candlepin/certs/candlepin-ca.crt");
this.put(CA_CERT_UPSTREAM, "/etc/candlepin/certs/upstream");
this.put(ACTIVATION_DEBUG_PREFIX, "");
this.put(HORNETQ_BASE_DIR, "/var/lib/candlepin/hornetq");
this.put(HORNETQ_LARGE_MSG_SIZE, new Integer(10 * 1024).toString());
this.put(AUDIT_LISTENERS,
"org.candlepin.audit.DatabaseListener," +
"org.candlepin.audit.LoggingListener," +
"org.candlepin.audit.ActivationListener");
this.put(AUDIT_LOG_FILE, "/var/log/candlepin/audit.log");
this.put(AUDIT_LOG_VERBOSE, "false");
this.put(PRETTY_PRINT, "false");
this.put(REVOKE_ENTITLEMENT_IN_FIFO_ORDER, "true");
this.put(CRL_FILE_PATH, "/var/lib/candlepin/candlepin-crl.crl");
this.put(SYNC_WORK_DIR, "/var/cache/candlepin/sync");
this.put(CONSUMER_FACTS_MATCHER, ".*");
this.put(TRUSTED_AUTHENTICATION, "true");
this.put(SSL_AUTHENTICATION, "true");
this.put(OAUTH_AUTHENTICATION, "true");
this.put(BASIC_AUTHENTICATION, "true");
// By default, environments should be hidden so clients do not need to
// submit one when registering.
this.put(HIDDEN_RESOURCES, "environments");
this.put(FAIL_ON_UNKNOWN_IMPORT_PROPERTIES, "false");
// Pinsetter
// prevent Quartz from checking for updates
this.put("org.quartz.scheduler.skipUpdateCheck", "true");
this.put("org.quartz.threadPool.class",
"org.quartz.simpl.SimpleThreadPool");
this.put("org.quartz.threadPool.threadCount", "15");
this.put("org.quartz.threadPool.threadPriority", "5");
this.put(DEFAULT_TASKS, StringUtils.join(DEFAULT_TASK_LIST, ","));
this.put(IDENTITY_CERT_YEAR_ADDENDUM, "16");
this.put(IDENTITY_CERT_EXPIRY_THRESHOLD, "90");
this.put(SHARD_WEBAPP, "candlepin");
this.put(ENABLE_PINSETTER, "true");
// defaults
this.put(SHARD_USERNAME, "admin");
this.put(SHARD_PASSWORD, "admin");
this.put(STANDALONE, "true");
this.put(ENV_CONTENT_FILTERING, "true");
// what constitutes a valid consumer name
this.put(CONSUMER_SYSTEM_NAME_PATTERN,
"[\\#\\?\\'\\`\\!@{}()\\[\\]\\?&\\w-\\.]+");
this.put(CONSUMER_PERSON_NAME_PATTERN,
"[\\#\\?\\'\\`\\!@{}()\\[\\]\\?&\\w-\\.]+");
- this.put(WEBAPP_PREFIX, "/candlepin");
- this.put(WEBAPP_HOSTNAME, "localhost:8443");
+ this.put(PREFIX_WEBURL, "localhost:8443/candlepin");
+ this.put(PREFIX_APIURL, "localhost:8443/candlepin");
this.put(PASSPHRASE_SECRET_FILE,
"/etc/katello/secure/passphrase");
/**
* Defines the maximum number of products allowed in the product cache.
* On deployments with a large number of products, it might be better
* to set this to a large number, keeping in mind that it will yield
* a larger memory footprint as the cache fills up.
*/
this.put(PRODUCT_CACHE_MAX, "100");
/**
* By default, disable cert v3.
*/
this.put(ENABLE_CERT_V3, "false");
/**
* As we do math on some facts and attributes, we need to constrain
* some values
*/
this.put(INTEGER_FACTS, INTEGER_FACT_LIST);
this.put(NON_NEG_INTEGER_FACTS, NON_NEG_INTEGER_FACT_LIST);
this.put(INTEGER_ATTRIBUTES, INTEGER_ATTRIBUTE_LIST);
this.put(NON_NEG_INTEGER_ATTRIBUTES, NON_NEG_INTEGER_ATTRIBUTE_LIST);
this.put(LONG_ATTRIBUTES, LONG_ATTRIBUTE_LIST);
this.put(NON_NEG_LONG_ATTRIBUTES, NON_NEG_LONG_ATTRIBUTE_LIST);
this.put(BOOLEAN_ATTRIBUTES, BOOLEAN_ATTRIBUTE_LIST);
}
};
public static final String CRL_FILE_PATH = "candlepin.crl.file";
public static final String IDENTITY_CERT_YEAR_ADDENDUM =
"candlepin.identityCert.yr.addendum";
/**
* Identity certificate expiry threshold in days
*/
public static final String IDENTITY_CERT_EXPIRY_THRESHOLD =
"candlepin.identityCert.expiry.threshold";
}
| false | false | null | null |
diff --git a/src/test/java/org/mule/module/facebook/automation/testcases/GetPhotoLikesTestCases.java b/src/test/java/org/mule/module/facebook/automation/testcases/GetPhotoLikesTestCases.java
index 31c05280..51f50eb1 100644
--- a/src/test/java/org/mule/module/facebook/automation/testcases/GetPhotoLikesTestCases.java
+++ b/src/test/java/org/mule/module/facebook/automation/testcases/GetPhotoLikesTestCases.java
@@ -1,69 +1,69 @@
/**
* Copyright (c) MuleSoft, Inc. All rights reserved. http://www.mulesoft.com
*
* The software in this package is published under the terms of the CPAL v1.0
* license, a copy of which has been included with this distribution in the
* LICENSE.md file.
*/
package org.mule.module.facebook.automation.testcases;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.File;
import java.util.HashMap;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.mule.api.MuleEvent;
import org.mule.api.processor.MessageProcessor;
import com.restfb.types.Post.Likes;
public class GetPhotoLikesTestCases extends FacebookTestParent {
@SuppressWarnings("unchecked")
@Before
public void setUp() throws Exception {
testObjects = (HashMap<String,Object>) context.getBean("getPhotoLikesTestData");
String profileId = getProfileId();
testObjects.put("profileId", profileId);
String caption = (String) testObjects.get("caption");
String photoFileName = (String) testObjects.get("photoFileName");
File photo = new File(getClass().getClassLoader().getResource(photoFileName).toURI());
String photoId = publishPhoto(profileId, caption, photo);
// for "get-photo-likes"
testObjects.put("photo", photoId);
like(photoId);
}
@Category({RegressionTests.class})
@Test
public void testGetPhotoLikes() {
try {
MessageProcessor flow = lookupFlowConstruct("get-photo-likes");
MuleEvent response = flow.process(getTestEvent(testObjects));
Likes result = (Likes) response.getMessage().getPayload();
assertTrue(result.getData().size() == 1);
} catch (Exception e) {
e.printStackTrace();
fail();
}
}
@After
public void tearDown() throws Exception {
- String photoId = (String) testObjects.get("photoId");
+ String photoId = (String) testObjects.get("photo");
deleteObject(photoId);
}
}
\ No newline at end of file
| true | false | null | null |
diff --git a/JodaTime/src/java/org/joda/time/base/AbstractInterval.java b/JodaTime/src/java/org/joda/time/base/AbstractInterval.java
index 201cb493..7205e8f5 100644
--- a/JodaTime/src/java/org/joda/time/base/AbstractInterval.java
+++ b/JodaTime/src/java/org/joda/time/base/AbstractInterval.java
@@ -1,448 +1,452 @@
/*
* Joda Software License, Version 1.0
*
*
* Copyright (c) 2001-2004 Stephen Colebourne.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Joda project (http://www.joda.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The name "Joda" must not be used to endorse or promote products
* derived from this software without prior written permission. For
* written permission, please contact [email protected].
*
* 5. Products derived from this software may not be called "Joda",
* nor may "Joda" appear in their name, without prior written
* permission of the Joda project.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Joda project and was originally
* created by Stephen Colebourne <[email protected]>. For more
* information on the Joda project, please see <http://www.joda.org/>.
*/
package org.joda.time.base;
import org.joda.time.DateTime;
import org.joda.time.DateTimeUtils;
import org.joda.time.Duration;
import org.joda.time.Interval;
import org.joda.time.MutableInterval;
import org.joda.time.Period;
import org.joda.time.PeriodType;
import org.joda.time.ReadableInstant;
import org.joda.time.ReadableInterval;
import org.joda.time.field.FieldUtils;
import org.joda.time.format.DateTimePrinter;
import org.joda.time.format.ISODateTimeFormat;
/**
* AbstractInterval provides the common behaviour for time intervals.
* <p>
* This class should generally not be used directly by API users. The
* {@link ReadableInterval} interface should be used when different
* kinds of intervals are to be referenced.
* <p>
* AbstractInterval subclasses may be mutable and not thread-safe.
*
* @author Brian S O'Neill
* @author Stephen Colebourne
* @since 1.0
*/
public abstract class AbstractInterval implements ReadableInterval {
/**
* Constructor.
*/
protected AbstractInterval() {
super();
}
//-----------------------------------------------------------------------
/**
* Validates an interval.
*
* @param start the start instant in milliseconds
* @param end the end instant in milliseconds
* @throws IllegalArgumentException if the interval is invalid
*/
protected void checkInterval(long start, long end) {
if (end < start) {
throw new IllegalArgumentException("The end instant must be greater or equal to the start");
}
}
//-----------------------------------------------------------------------
/**
* Gets the start of this time interval, which is inclusive, as a DateTime.
*
* @return the start of the time interval
*/
public DateTime getStart() {
return new DateTime(getStartMillis(), getChronology());
}
/**
* Gets the end of this time interval, which is exclusive, as a DateTime.
*
* @return the end of the time interval
*/
public DateTime getEnd() {
return new DateTime(getEndMillis(), getChronology());
}
//-----------------------------------------------------------------------
/**
* Does this time interval contain the specified millisecond instant.
* <p>
* Intervals are inclusive of the start instant and exclusive of the end.
*
* @param millisInstant the instant to compare to,
* millisecond instant from 1970-01-01T00:00:00Z
* @return true if this time interval contains the millisecond
*/
public boolean contains(long millisInstant) {
long thisStart = getStartMillis();
long thisEnd = getEndMillis();
return (millisInstant >= thisStart && millisInstant < thisEnd);
}
/**
* Does this time interval contain the current instant.
* <p>
* Intervals are inclusive of the start instant and exclusive of the end.
*
* @return true if this time interval contains the current instant
*/
public boolean containsNow() {
return contains(DateTimeUtils.currentTimeMillis());
}
/**
* Does this time interval contain the specified instant.
* <p>
* Intervals are inclusive of the start instant and exclusive of the end.
*
* @param instant the instant, null means now
* @return true if this time interval contains the instant
*/
public boolean contains(ReadableInstant instant) {
if (instant == null) {
return containsNow();
}
return contains(instant.getMillis());
}
/**
* Does this time interval contain the specified time interval completely.
* <p>
* Intervals are inclusive of the start instant and exclusive of the end.
*
* @param interval the time interval to compare to, null means now
* @return true if this time interval contains the time interval
*/
public boolean contains(ReadableInterval interval) {
if (interval == null) {
return containsNow();
}
long otherStart = interval.getStartMillis();
long otherEnd = interval.getEndMillis();
long thisStart = getStartMillis();
long thisEnd = getEndMillis();
return (otherStart >= thisStart && otherStart < thisEnd && otherEnd <= thisEnd);
}
/**
* Does this time interval overlap the specified time interval.
* <p>
* The intervals overlap if at least some of the time interval is in common.
* Intervals are inclusive of the start instant and exclusive of the end.
*
* @param interval the time interval to compare to, null means now
* @return true if the time intervals overlap
*/
public boolean overlaps(ReadableInterval interval) {
if (interval == null) {
return containsNow();
}
long otherStart = interval.getStartMillis();
long otherEnd = interval.getEndMillis();
long thisStart = getStartMillis();
long thisEnd = getEndMillis();
return (thisStart < otherEnd && otherStart < thisEnd);
}
//-----------------------------------------------------------------------
/**
* Is this time interval before the specified millisecond instant.
* <p>
* Intervals are inclusive of the start instant and exclusive of the end.
*
* @param millisInstant the instant to compare to,
* millisecond instant from 1970-01-01T00:00:00Z
* @return true if this time interval is before the instant
*/
public boolean isBefore(long millisInstant) {
return (getEndMillis() <= millisInstant);
}
/**
* Is this time interval before the current instant.
* <p>
* Intervals are inclusive of the start instant and exclusive of the end.
*
* @return true if this time interval is before the current instant
*/
public boolean isBeforeNow() {
return isBefore(DateTimeUtils.currentTimeMillis());
}
/**
* Is this time interval before the specified instant.
* <p>
* Intervals are inclusive of the start instant and exclusive of the end.
*
* @param instant the instant to compare to, null means now
* @return true if this time interval is before the instant
*/
public boolean isBefore(ReadableInstant instant) {
if (instant == null) {
return isBeforeNow();
}
return isBefore(instant.getMillis());
}
/**
* Is this time interval entirely before the specified instant.
* <p>
* Intervals are inclusive of the start instant and exclusive of the end.
*
* @param interval the interval to compare to, null means now
* @return true if this time interval is before the interval specified
*/
public boolean isBefore(ReadableInterval interval) {
if (interval == null) {
return isBeforeNow();
}
return isBefore(interval.getStartMillis());
}
//-----------------------------------------------------------------------
/**
* Is this time interval after the specified millisecond instant.
* <p>
* Intervals are inclusive of the start instant and exclusive of the end.
*
* @param millisInstant the instant to compare to,
* millisecond instant from 1970-01-01T00:00:00Z
* @return true if this time interval is after the instant
*/
public boolean isAfter(long millisInstant) {
return (getStartMillis() > millisInstant);
}
/**
* Is this time interval after the current instant.
* <p>
* Intervals are inclusive of the start instant and exclusive of the end.
*
* @return true if this time interval is after the current instant
*/
public boolean isAfterNow() {
return isAfter(DateTimeUtils.currentTimeMillis());
}
/**
* Is this time interval after the specified instant.
* <p>
* Intervals are inclusive of the start instant and exclusive of the end.
*
* @param instant the instant to compare to, null means now
* @return true if this time interval is after the instant
*/
public boolean isAfter(ReadableInstant instant) {
if (instant == null) {
return isAfterNow();
}
return isAfter(instant.getMillis());
}
/**
* Is this time interval entirely after the specified interval.
* <p>
* Intervals are inclusive of the start instant and exclusive of the end.
+ * Only the end time of the specified interval is used in the comparison.
*
* @param interval the interval to compare to, null means now
* @return true if this time interval is after the interval specified
*/
public boolean isAfter(ReadableInterval interval) {
+ long endMillis;
if (interval == null) {
- return isAfterNow();
+ endMillis = DateTimeUtils.currentTimeMillis();
+ } else {
+ endMillis = interval.getEndMillis();
}
- return isAfter(interval.getEndMillis());
+ return (getStartMillis() >= endMillis);
}
//-----------------------------------------------------------------------
/**
* Get this interval as an immutable <code>Interval</code> object.
*
* @return the interval as an Interval object
*/
public Interval toInterval() {
return new Interval(getStartMillis(), getEndMillis(), getChronology());
}
/**
* Get this time interval as a <code>MutableInterval</code>.
* <p>
* This will always return a new <code>MutableInterval</code> with the same interval.
*
* @return the time interval as a MutableInterval object
*/
public MutableInterval toMutableInterval() {
return new MutableInterval(getStartMillis(), getEndMillis(), getChronology());
}
//-----------------------------------------------------------------------
/**
* Gets the duration of this time interval in milliseconds.
* <p>
* The duration is equal to the end millis minus the start millis.
*
* @return the duration of the time interval in milliseconds
* @throws ArithmeticException if the duration exceeds the capacity of a long
*/
public long toDurationMillis() {
return FieldUtils.safeAdd(getEndMillis(), -getStartMillis());
}
/**
* Gets the duration of this time interval.
* <p>
* The duration is equal to the end millis minus the start millis.
*
* @return the duration of the time interval
* @throws ArithmeticException if the duration exceeds the capacity of a long
*/
public Duration toDuration() {
long durMillis = toDurationMillis();
if (durMillis == 0) {
return Duration.ZERO;
} else {
return new Duration(durMillis);
}
}
//-----------------------------------------------------------------------
/**
* Converts the duration of the interval to a <code>Period</code> using the
* All period type.
* <p>
* This method should be used to exract the field values describing the
* difference between the start and end instants.
*
* @return a time period derived from the interval
*/
public Period toPeriod() {
return new Period(getStartMillis(), getEndMillis(), getChronology());
}
/**
* Converts the duration of the interval to a <code>Period</code> using the
* specified period type.
* <p>
* This method should be used to exract the field values describing the
* difference between the start and end instants.
*
* @param type the requested type of the duration, null means AllType
* @return a time period derived from the interval
*/
public Period toPeriod(PeriodType type) {
return new Period(getStartMillis(), getEndMillis(), type, getChronology());
}
//-----------------------------------------------------------------------
/**
* Compares this object with the specified object for equality based
* on start and end millis plus the chronology.
* All ReadableInterval instances are accepted.
* <p>
* To compare the duration of two time intervals, use {@link #toDuration()}
* to get the durations and compare those.
*
* @param readableInterval a readable interval to check against
* @return true if the start and end millis are equal
*/
public boolean equals(Object readableInterval) {
if (this == readableInterval) {
return true;
}
if (readableInterval instanceof ReadableInterval == false) {
return false;
}
ReadableInterval other = (ReadableInterval) readableInterval;
return (getStartMillis() == other.getStartMillis() &&
getEndMillis() == other.getEndMillis() &&
getChronology() == other.getChronology());
}
/**
* Hashcode compatible with equals method.
*
* @return suitable hashcode
*/
public int hashCode() {
long start = getStartMillis();
long end = getEndMillis();
int result = 97;
result = 31 * result + ((int) (start ^ (start >>> 32)));
result = 31 * result + ((int) (end ^ (end >>> 32)));
result = 31 * result + getChronology().hashCode();
return result;
}
/**
* Output a string in ISO8601 interval format.
*
* @return re-parsable string
*/
public String toString() {
DateTimePrinter printer = ISODateTimeFormat.getInstance().dateHourMinuteSecondFraction();
StringBuffer buf = new StringBuffer(48);
printer.printTo(buf, getStartMillis(), getChronology());
buf.append('/');
printer.printTo(buf, getEndMillis(), getChronology());
return buf.toString();
}
}
diff --git a/JodaTime/src/test/org/joda/time/TestInterval_Basics.java b/JodaTime/src/test/org/joda/time/TestInterval_Basics.java
index 63a8b829..7862c5b9 100644
--- a/JodaTime/src/test/org/joda/time/TestInterval_Basics.java
+++ b/JodaTime/src/test/org/joda/time/TestInterval_Basics.java
@@ -1,708 +1,708 @@
/*
* Joda Software License, Version 1.0
*
*
* Copyright (c) 2001-2004 Stephen Colebourne.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Joda project (http://www.joda.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The name "Joda" must not be used to endorse or promote products
* derived from this software without prior written permission. For
* written permission, please contact [email protected].
*
* 5. Products derived from this software may not be called "Joda",
* nor may "Joda" appear in their name, without prior written
* permission of the Joda project.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Joda project and was originally
* created by Stephen Colebourne <[email protected]>. For more
* information on the Joda project, please see <http://www.joda.org/>.
*/
package org.joda.time;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Locale;
import java.util.TimeZone;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.joda.time.base.AbstractInterval;
/**
* This class is a Junit unit test for Instant.
*
* @author Stephen Colebourne
*/
public class TestInterval_Basics extends TestCase {
// Test in 2002/03 as time zones are more well known
// (before the late 90's they were all over the place)
private static final DateTimeZone PARIS = DateTimeZone.getInstance("Europe/Paris");
private static final DateTimeZone LONDON = DateTimeZone.getInstance("Europe/London");
private static final Chronology COPTIC_PARIS = Chronology.getCoptic(PARIS);
long y2002days = 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 +
366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 +
365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 +
366 + 365;
long y2003days = 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 +
366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 +
365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 +
366 + 365 + 365;
// 2002-06-09
private long TEST_TIME_NOW =
(y2002days + 31L + 28L + 31L + 30L + 31L + 9L -1L) * DateTimeConstants.MILLIS_PER_DAY;
// 2002-04-05
private long TEST_TIME1 =
(y2002days + 31L + 28L + 31L + 5L -1L) * DateTimeConstants.MILLIS_PER_DAY
+ 12L * DateTimeConstants.MILLIS_PER_HOUR
+ 24L * DateTimeConstants.MILLIS_PER_MINUTE;
// 2003-05-06
private long TEST_TIME2 =
(y2003days + 31L + 28L + 31L + 30L + 6L -1L) * DateTimeConstants.MILLIS_PER_DAY
+ 14L * DateTimeConstants.MILLIS_PER_HOUR
+ 28L * DateTimeConstants.MILLIS_PER_MINUTE;
private DateTimeZone originalDateTimeZone = null;
private TimeZone originalTimeZone = null;
private Locale originalLocale = null;
public static void main(String[] args) {
junit.textui.TestRunner.run(suite());
}
public static TestSuite suite() {
return new TestSuite(TestInterval_Basics.class);
}
public TestInterval_Basics(String name) {
super(name);
}
protected void setUp() throws Exception {
DateTimeUtils.setCurrentMillisFixed(TEST_TIME_NOW);
originalDateTimeZone = DateTimeZone.getDefault();
originalTimeZone = TimeZone.getDefault();
originalLocale = Locale.getDefault();
DateTimeZone.setDefault(LONDON);
TimeZone.setDefault(TimeZone.getTimeZone("Europe/London"));
Locale.setDefault(Locale.UK);
}
protected void tearDown() throws Exception {
DateTimeUtils.setCurrentMillisSystem();
DateTimeZone.setDefault(originalDateTimeZone);
TimeZone.setDefault(originalTimeZone);
Locale.setDefault(originalLocale);
originalDateTimeZone = null;
originalTimeZone = null;
originalLocale = null;
}
//-----------------------------------------------------------------------
public void testTest() {
assertEquals("2002-06-09T00:00:00.000Z", new Instant(TEST_TIME_NOW).toString());
assertEquals("2002-04-05T12:24:00.000Z", new Instant(TEST_TIME1).toString());
assertEquals("2003-05-06T14:28:00.000Z", new Instant(TEST_TIME2).toString());
}
//-----------------------------------------------------------------------
public void testGetMillis() {
Interval test = new Interval(TEST_TIME1, TEST_TIME2);
assertEquals(TEST_TIME1, test.getStartMillis());
assertEquals(TEST_TIME1, test.getStart().getMillis());
assertEquals(TEST_TIME2, test.getEndMillis());
assertEquals(TEST_TIME2, test.getEnd().getMillis());
assertEquals(TEST_TIME2 - TEST_TIME1, test.toDurationMillis());
assertEquals(TEST_TIME2 - TEST_TIME1, test.toDuration().getMillis());
}
public void testGetDuration1() {
Interval test = new Interval(TEST_TIME1, TEST_TIME2);
assertEquals(TEST_TIME2 - TEST_TIME1, test.toDurationMillis());
assertEquals(TEST_TIME2 - TEST_TIME1, test.toDuration().getMillis());
}
public void testGetDuration2() {
Interval test = new Interval(TEST_TIME1, TEST_TIME1);
assertSame(Duration.ZERO, test.toDuration());
}
public void testEqualsHashCode() {
Interval test1 = new Interval(TEST_TIME1, TEST_TIME2);
Interval test2 = new Interval(TEST_TIME1, TEST_TIME2);
assertEquals(true, test1.equals(test2));
assertEquals(true, test2.equals(test1));
assertEquals(true, test1.equals(test1));
assertEquals(true, test2.equals(test2));
assertEquals(true, test1.hashCode() == test2.hashCode());
assertEquals(true, test1.hashCode() == test1.hashCode());
assertEquals(true, test2.hashCode() == test2.hashCode());
Interval test3 = new Interval(TEST_TIME_NOW, TEST_TIME2);
assertEquals(false, test1.equals(test3));
assertEquals(false, test2.equals(test3));
assertEquals(false, test3.equals(test1));
assertEquals(false, test3.equals(test2));
assertEquals(false, test1.hashCode() == test3.hashCode());
assertEquals(false, test2.hashCode() == test3.hashCode());
Interval test4 = new Interval(TEST_TIME1, TEST_TIME2, Chronology.getGJ());
assertEquals(true, test4.equals(test4));
assertEquals(false, test1.equals(test4));
assertEquals(false, test2.equals(test4));
assertEquals(false, test4.equals(test1));
assertEquals(false, test4.equals(test2));
assertEquals(false, test1.hashCode() == test4.hashCode());
assertEquals(false, test2.hashCode() == test4.hashCode());
MutableInterval test5 = new MutableInterval(TEST_TIME1, TEST_TIME2);
assertEquals(true, test1.equals(test5));
assertEquals(true, test2.equals(test5));
assertEquals(false, test3.equals(test5));
assertEquals(true, test5.equals(test1));
assertEquals(true, test5.equals(test2));
assertEquals(false, test5.equals(test3));
assertEquals(true, test1.hashCode() == test5.hashCode());
assertEquals(true, test2.hashCode() == test5.hashCode());
assertEquals(false, test3.hashCode() == test5.hashCode());
assertEquals(false, test1.equals("Hello"));
assertEquals(true, test1.equals(new MockInterval()));
assertEquals(false, test1.equals(new DateTime(TEST_TIME1)));
}
class MockInterval extends AbstractInterval {
public MockInterval() {
super();
}
public Chronology getChronology() {
return Chronology.getISO();
}
public long getStartMillis() {
return TEST_TIME1;
}
public long getEndMillis() {
return TEST_TIME2;
}
}
//-----------------------------------------------------------------------
public void testContains_long() {
Interval test = new Interval(TEST_TIME1, TEST_TIME2);
assertEquals(true, test.contains(TEST_TIME1));
assertEquals(false, test.contains(TEST_TIME1 - 1));
assertEquals(true, test.contains(TEST_TIME1 + (TEST_TIME2 - TEST_TIME1) / 2));
assertEquals(false, test.contains(TEST_TIME2));
assertEquals(true, test.contains(TEST_TIME2 - 1));
}
public void testContainsNow() {
Interval test = new Interval(TEST_TIME1, TEST_TIME2);
DateTimeUtils.setCurrentMillisFixed(TEST_TIME1);
assertEquals(true, test.containsNow());
DateTimeUtils.setCurrentMillisFixed(TEST_TIME1 - 1);
assertEquals(false, test.containsNow());
DateTimeUtils.setCurrentMillisFixed(TEST_TIME1 + (TEST_TIME2 - TEST_TIME1) / 2);
assertEquals(true, test.containsNow());
DateTimeUtils.setCurrentMillisFixed(TEST_TIME2);
assertEquals(false, test.containsNow());
DateTimeUtils.setCurrentMillisFixed(TEST_TIME2 - 1);
assertEquals(true, test.containsNow());
}
public void testContains_RI() {
Interval test = new Interval(TEST_TIME1, TEST_TIME2);
assertEquals(true, test.contains(new Instant(TEST_TIME1)));
assertEquals(false, test.contains(new Instant(TEST_TIME1 - 1)));
assertEquals(true, test.contains(new Instant(TEST_TIME1 + (TEST_TIME2 - TEST_TIME1) / 2)));
assertEquals(false, test.contains(new Instant(TEST_TIME2)));
assertEquals(true, test.contains(new Instant(TEST_TIME2 - 1)));
assertEquals(true, test.contains((ReadableInstant) null));
}
//-----------------------------------------------------------------------
public void testContains_RInterval() {
Interval test = new Interval(TEST_TIME1, TEST_TIME2);
assertEquals(true, test.contains(new Interval(TEST_TIME1, TEST_TIME2)));
assertEquals(false, test.contains(new Interval(TEST_TIME1 - 1, TEST_TIME2)));
assertEquals(true, test.contains(new Interval(TEST_TIME1 + (TEST_TIME2 - TEST_TIME1) / 2, TEST_TIME2)));
assertEquals(false, test.contains(new Interval(TEST_TIME2, TEST_TIME2)));
assertEquals(true, test.contains(new Interval(TEST_TIME2 - 1, TEST_TIME2)));
assertEquals(true, test.contains(new Interval(TEST_TIME1, TEST_TIME2 - 1)));
assertEquals(false, test.contains(new Interval(TEST_TIME1 - 1, TEST_TIME2 - 1)));
assertEquals(true, test.contains(new Interval(TEST_TIME1 + (TEST_TIME2 - TEST_TIME1) / 2, TEST_TIME2 - 1)));
assertEquals(true, test.contains(new Interval(TEST_TIME2 - 1, TEST_TIME2 - 1)));
assertEquals(true, test.contains(new Interval(TEST_TIME2 - 2, TEST_TIME2 - 1)));
assertEquals(false, test.contains(new Interval(TEST_TIME1, TEST_TIME2 + 1)));
assertEquals(false, test.contains(new Interval(TEST_TIME1 - 1, TEST_TIME2 + 1)));
assertEquals(false, test.contains(new Interval(TEST_TIME1 + (TEST_TIME2 - TEST_TIME1) / 2, TEST_TIME2 + 1)));
assertEquals(false, test.contains(new Interval(TEST_TIME2, TEST_TIME2 + 1)));
assertEquals(false, test.contains(new Interval(TEST_TIME2 - 1, TEST_TIME2 + 1)));
assertEquals(false, test.contains(new Interval(TEST_TIME1 - 2, TEST_TIME1 - 1)));
assertEquals(true, test.contains((ReadableInterval) null));
}
public void testOverlaps_RInterval() {
Interval test = new Interval(TEST_TIME1, TEST_TIME2);
assertEquals(true, test.overlaps(new Interval(TEST_TIME1, TEST_TIME2)));
assertEquals(true, test.overlaps(new Interval(TEST_TIME1 - 1, TEST_TIME2)));
assertEquals(true, test.overlaps(new Interval(TEST_TIME1 + (TEST_TIME2 - TEST_TIME1) / 2, TEST_TIME2)));
assertEquals(false, test.overlaps(new Interval(TEST_TIME2, TEST_TIME2)));
assertEquals(true, test.overlaps(new Interval(TEST_TIME2 - 1, TEST_TIME2)));
assertEquals(true, test.overlaps(new Interval(TEST_TIME1, TEST_TIME2 + 1)));
assertEquals(true, test.overlaps(new Interval(TEST_TIME1 - 1, TEST_TIME2 + 1)));
assertEquals(true, test.overlaps(new Interval(TEST_TIME1 + (TEST_TIME2 - TEST_TIME1) / 2, TEST_TIME2 + 1)));
assertEquals(false, test.overlaps(new Interval(TEST_TIME2, TEST_TIME2 + 1)));
assertEquals(true, test.overlaps(new Interval(TEST_TIME2 - 1, TEST_TIME2 + 1)));
assertEquals(false, test.overlaps(new Interval(TEST_TIME1 - 1, TEST_TIME1 - 1)));
assertEquals(false, test.overlaps(new Interval(TEST_TIME1 - 1, TEST_TIME1)));
assertEquals(true, test.overlaps(new Interval(TEST_TIME1 - 1, TEST_TIME1 + 1)));
assertEquals(true, test.overlaps((ReadableInterval) null));
}
//-----------------------------------------------------------------------
public void testIsBefore_long() {
Interval test = new Interval(TEST_TIME1, TEST_TIME2);
assertEquals(false, test.isBefore(TEST_TIME1 - 1));
assertEquals(false, test.isBefore(TEST_TIME1));
assertEquals(false, test.isBefore(TEST_TIME1 + 1));
assertEquals(false, test.isBefore(TEST_TIME2 - 1));
assertEquals(true, test.isBefore(TEST_TIME2));
assertEquals(true, test.isBefore(TEST_TIME2 + 1));
}
public void testIsBeforeNow() {
Interval test = new Interval(TEST_TIME1, TEST_TIME2);
DateTimeUtils.setCurrentMillisFixed(TEST_TIME2 - 1);
assertEquals(false, test.isBeforeNow());
DateTimeUtils.setCurrentMillisFixed(TEST_TIME2);
assertEquals(true, test.isBeforeNow());
DateTimeUtils.setCurrentMillisFixed(TEST_TIME2 + 1);
assertEquals(true, test.isBeforeNow());
}
public void testIsBefore_RI() {
Interval test = new Interval(TEST_TIME1, TEST_TIME2);
assertEquals(false, test.isBefore(new Instant(TEST_TIME1 - 1)));
assertEquals(false, test.isBefore(new Instant(TEST_TIME1)));
assertEquals(false, test.isBefore(new Instant(TEST_TIME1 + 1)));
assertEquals(false, test.isBefore(new Instant(TEST_TIME2 - 1)));
assertEquals(true, test.isBefore(new Instant(TEST_TIME2)));
assertEquals(true, test.isBefore(new Instant(TEST_TIME2 + 1)));
assertEquals(false, test.isBefore((ReadableInstant) null));
}
public void testIsBefore_RInterval() {
Interval test = new Interval(TEST_TIME1, TEST_TIME2);
assertEquals(false, test.isBefore(new Interval(Long.MIN_VALUE, TEST_TIME1 - 1)));
assertEquals(false, test.isBefore(new Interval(Long.MIN_VALUE, TEST_TIME1)));
assertEquals(false, test.isBefore(new Interval(Long.MIN_VALUE, TEST_TIME1 + 1)));
assertEquals(false, test.isBefore(new Interval(TEST_TIME2 - 1, Long.MAX_VALUE)));
assertEquals(true, test.isBefore(new Interval(TEST_TIME2, Long.MAX_VALUE)));
assertEquals(true, test.isBefore(new Interval(TEST_TIME2 + 1, Long.MAX_VALUE)));
assertEquals(false, test.isBefore((ReadableInterval) null));
}
//-----------------------------------------------------------------------
public void testIsAfter_long() {
Interval test = new Interval(TEST_TIME1, TEST_TIME2);
assertEquals(true, test.isAfter(TEST_TIME1 - 1));
assertEquals(false, test.isAfter(TEST_TIME1));
assertEquals(false, test.isAfter(TEST_TIME1 + 1));
assertEquals(false, test.isAfter(TEST_TIME2 - 1));
assertEquals(false, test.isAfter(TEST_TIME2));
assertEquals(false, test.isAfter(TEST_TIME2 + 1));
}
public void testIsAfterNow() {
Interval test = new Interval(TEST_TIME1, TEST_TIME2);
DateTimeUtils.setCurrentMillisFixed(TEST_TIME1 - 1);
assertEquals(true, test.isAfterNow());
DateTimeUtils.setCurrentMillisFixed(TEST_TIME1);
assertEquals(false, test.isAfterNow());
DateTimeUtils.setCurrentMillisFixed(TEST_TIME1 + 1);
assertEquals(false, test.isAfterNow());
}
public void testIsAfter_RI() {
Interval test = new Interval(TEST_TIME1, TEST_TIME2);
assertEquals(true, test.isAfter(new Instant(TEST_TIME1 - 1)));
assertEquals(false, test.isAfter(new Instant(TEST_TIME1)));
assertEquals(false, test.isAfter(new Instant(TEST_TIME1 + 1)));
assertEquals(false, test.isAfter(new Instant(TEST_TIME2 - 1)));
assertEquals(false, test.isAfter(new Instant(TEST_TIME2)));
assertEquals(false, test.isAfter(new Instant(TEST_TIME2 + 1)));
assertEquals(false, test.isAfter((ReadableInstant) null));
}
public void testIsAfter_RInterval() {
Interval test = new Interval(TEST_TIME1, TEST_TIME2);
assertEquals(true, test.isAfter(new Interval(Long.MIN_VALUE, TEST_TIME1 - 1)));
- assertEquals(false, test.isAfter(new Interval(Long.MIN_VALUE, TEST_TIME1)));
+ assertEquals(true, test.isAfter(new Interval(Long.MIN_VALUE, TEST_TIME1)));
assertEquals(false, test.isAfter(new Interval(Long.MIN_VALUE, TEST_TIME1 + 1)));
assertEquals(false, test.isAfter(new Interval(TEST_TIME2 - 1, Long.MAX_VALUE)));
assertEquals(false, test.isAfter(new Interval(TEST_TIME2, Long.MAX_VALUE)));
assertEquals(false, test.isAfter(new Interval(TEST_TIME2 + 1, Long.MAX_VALUE)));
assertEquals(false, test.isAfter((ReadableInterval) null));
}
//-----------------------------------------------------------------------
public void testToInterval1() {
Interval test = new Interval(TEST_TIME1, TEST_TIME2, COPTIC_PARIS);
Interval result = test.toInterval();
assertSame(test, result);
}
//-----------------------------------------------------------------------
public void testToMutableInterval1() {
Interval test = new Interval(TEST_TIME1, TEST_TIME2, COPTIC_PARIS);
MutableInterval result = test.toMutableInterval();
assertEquals(test, result);
}
//-----------------------------------------------------------------------
public void testToPeriod() {
DateTime dt1 = new DateTime(2004, 6, 9, 7, 8, 9, 10, COPTIC_PARIS);
DateTime dt2 = new DateTime(2005, 8, 13, 12, 14, 16, 18, COPTIC_PARIS);
Interval base = new Interval(dt1, dt2);
Period test = base.toPeriod();
Period expected = new Period(dt1, dt2, PeriodType.standard());
assertEquals(expected, test);
}
//-----------------------------------------------------------------------
public void testToPeriod_PeriodType1() {
DateTime dt1 = new DateTime(2004, 6, 9, 7, 8, 9, 10, COPTIC_PARIS);
DateTime dt2 = new DateTime(2005, 8, 13, 12, 14, 16, 18, COPTIC_PARIS);
Interval base = new Interval(dt1, dt2);
Period test = base.toPeriod(null);
Period expected = new Period(dt1, dt2, PeriodType.standard());
assertEquals(expected, test);
}
public void testToPeriod_PeriodType2() {
DateTime dt1 = new DateTime(2004, 6, 9, 7, 8, 9, 10);
DateTime dt2 = new DateTime(2005, 8, 13, 12, 14, 16, 18);
Interval base = new Interval(dt1, dt2);
Period test = base.toPeriod(PeriodType.yearWeekDayTime());
Period expected = new Period(dt1, dt2, PeriodType.yearWeekDayTime());
assertEquals(expected, test);
}
//-----------------------------------------------------------------------
public void testSerialization() throws Exception {
Interval test = new Interval(TEST_TIME1, TEST_TIME2, COPTIC_PARIS);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(test);
byte[] bytes = baos.toByteArray();
oos.close();
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(bais);
Interval result = (Interval) ois.readObject();
ois.close();
assertEquals(test, result);
}
//-----------------------------------------------------------------------
public void testToString() {
DateTime dt1 = new DateTime(2004, 6, 9, 7, 8, 9, 10, DateTimeZone.UTC);
DateTime dt2 = new DateTime(2005, 8, 13, 12, 14, 16, 18, DateTimeZone.UTC);
Interval test = new Interval(dt1, dt2);
assertEquals("2004-06-09T07:08:09.010/2005-08-13T12:14:16.018", test.toString());
}
//-----------------------------------------------------------------------
public void testWithChronology1() {
Interval base = new Interval(TEST_TIME1, TEST_TIME2, COPTIC_PARIS);
Interval test = base.withChronology(Chronology.getBuddhist());
assertEquals(new Interval(TEST_TIME1, TEST_TIME2, Chronology.getBuddhist()), test);
}
public void testWithChronology2() {
Interval base = new Interval(TEST_TIME1, TEST_TIME2, COPTIC_PARIS);
Interval test = base.withChronology(null);
assertEquals(new Interval(TEST_TIME1, TEST_TIME2, Chronology.getISO()), test);
}
public void testWithChronology3() {
Interval base = new Interval(TEST_TIME1, TEST_TIME2, COPTIC_PARIS);
Interval test = base.withChronology(COPTIC_PARIS);
assertSame(base, test);
}
//-----------------------------------------------------------------------
public void testWithStartMillis_long1() {
Interval base = new Interval(TEST_TIME1, TEST_TIME2, COPTIC_PARIS);
Interval test = base.withStartMillis(TEST_TIME1 - 1);
assertEquals(new Interval(TEST_TIME1 - 1, TEST_TIME2, COPTIC_PARIS), test);
}
public void testWithStartMillis_long2() {
Interval test = new Interval(TEST_TIME1, TEST_TIME2);
try {
test.withStartMillis(TEST_TIME2 + 1);
fail();
} catch (IllegalArgumentException ex) {}
}
public void testWithStartMillis_long3() {
Interval base = new Interval(TEST_TIME1, TEST_TIME2, COPTIC_PARIS);
Interval test = base.withStartMillis(TEST_TIME1);
assertSame(base, test);
}
//-----------------------------------------------------------------------
public void testWithStartInstant_RI1() {
Interval base = new Interval(TEST_TIME1, TEST_TIME2, COPTIC_PARIS);
Interval test = base.withStart(new Instant(TEST_TIME1 - 1));
assertEquals(new Interval(TEST_TIME1 - 1, TEST_TIME2, COPTIC_PARIS), test);
}
public void testWithStartInstant_RI2() {
Interval test = new Interval(TEST_TIME1, TEST_TIME2);
try {
test.withStart(new Instant(TEST_TIME2 + 1));
fail();
} catch (IllegalArgumentException ex) {}
}
public void testWithStartInstant_RI3() {
Interval base = new Interval(TEST_TIME1, TEST_TIME2, COPTIC_PARIS);
Interval test = base.withStart(null);
assertEquals(new Interval(TEST_TIME_NOW, TEST_TIME2, COPTIC_PARIS), test);
}
//-----------------------------------------------------------------------
public void testWithEndMillis_long1() {
Interval base = new Interval(TEST_TIME1, TEST_TIME2, COPTIC_PARIS);
Interval test = base.withEndMillis(TEST_TIME2 - 1);
assertEquals(new Interval(TEST_TIME1, TEST_TIME2 - 1, COPTIC_PARIS), test);
}
public void testWithEndMillis_long2() {
Interval test = new Interval(TEST_TIME1, TEST_TIME2);
try {
test.withEndMillis(TEST_TIME1 - 1);
fail();
} catch (IllegalArgumentException ex) {}
}
public void testWithEndMillis_long3() {
Interval base = new Interval(TEST_TIME1, TEST_TIME2, COPTIC_PARIS);
Interval test = base.withEndMillis(TEST_TIME2);
assertSame(base, test);
}
//-----------------------------------------------------------------------
public void testWithEndInstant_RI1() {
Interval base = new Interval(TEST_TIME1, TEST_TIME2, COPTIC_PARIS);
Interval test = base.withEnd(new Instant(TEST_TIME2 - 1));
assertEquals(new Interval(TEST_TIME1, TEST_TIME2 - 1, COPTIC_PARIS), test);
}
public void testWithEndInstant_RI2() {
Interval test = new Interval(TEST_TIME1, TEST_TIME2);
try {
test.withEnd(new Instant(TEST_TIME1 - 1));
fail();
} catch (IllegalArgumentException ex) {}
}
public void testWithEndInstant_RI3() {
Interval base = new Interval(TEST_TIME1, TEST_TIME2, COPTIC_PARIS);
Interval test = base.withEnd(null);
assertEquals(new Interval(TEST_TIME1, TEST_TIME_NOW, COPTIC_PARIS), test);
}
//-----------------------------------------------------------------------
public void testWithDurationAfterStart1() throws Throwable {
Duration dur = new Duration(TEST_TIME2 - TEST_TIME_NOW);
Interval base = new Interval(TEST_TIME_NOW, TEST_TIME_NOW, COPTIC_PARIS);
Interval test = base.withDurationAfterStart(dur);
assertEquals(new Interval(TEST_TIME_NOW, TEST_TIME2, COPTIC_PARIS), test);
}
public void testWithDurationAfterStart2() throws Throwable {
Interval base = new Interval(TEST_TIME_NOW, TEST_TIME2, COPTIC_PARIS);
Interval test = base.withDurationAfterStart(null);
assertEquals(new Interval(TEST_TIME_NOW, TEST_TIME_NOW, COPTIC_PARIS), test);
}
public void testWithDurationAfterStart3() throws Throwable {
Duration dur = new Duration(-1);
Interval base = new Interval(TEST_TIME_NOW, TEST_TIME_NOW);
try {
base.withDurationAfterStart(dur);
fail();
} catch (IllegalArgumentException ex) {}
}
public void testWithDurationAfterStart4() throws Throwable {
Interval base = new Interval(TEST_TIME_NOW, TEST_TIME2, COPTIC_PARIS);
Interval test = base.withDurationAfterStart(base.toDuration());
assertSame(base, test);
}
//-----------------------------------------------------------------------
public void testWithDurationBeforeEnd1() throws Throwable {
Duration dur = new Duration(TEST_TIME_NOW - TEST_TIME1);
Interval base = new Interval(TEST_TIME_NOW, TEST_TIME_NOW, COPTIC_PARIS);
Interval test = base.withDurationBeforeEnd(dur);
assertEquals(new Interval(TEST_TIME1, TEST_TIME_NOW, COPTIC_PARIS), test);
}
public void testWithDurationBeforeEnd2() throws Throwable {
Interval base = new Interval(TEST_TIME_NOW, TEST_TIME2, COPTIC_PARIS);
Interval test = base.withDurationBeforeEnd(null);
assertEquals(new Interval(TEST_TIME2, TEST_TIME2, COPTIC_PARIS), test);
}
public void testWithDurationBeforeEnd3() throws Throwable {
Duration dur = new Duration(-1);
Interval base = new Interval(TEST_TIME_NOW, TEST_TIME_NOW);
try {
base.withDurationBeforeEnd(dur);
fail();
} catch (IllegalArgumentException ex) {}
}
public void testWithDurationBeforeEnd4() throws Throwable {
Interval base = new Interval(TEST_TIME_NOW, TEST_TIME2, COPTIC_PARIS);
Interval test = base.withDurationBeforeEnd(base.toDuration());
assertSame(base, test);
}
//-----------------------------------------------------------------------
public void testWithPeriodAfterStart1() throws Throwable {
DateTime dt = new DateTime(TEST_TIME_NOW, COPTIC_PARIS);
Period dur = new Period(0, 6, 0, 0, 1, 0, 0, 0);
Interval base = new Interval(dt, dt);
Interval test = base.withPeriodAfterStart(dur);
assertEquals(new Interval(dt, dur), test);
}
public void testWithPeriodAfterStart2() throws Throwable {
Interval base = new Interval(TEST_TIME_NOW, TEST_TIME2, COPTIC_PARIS);
Interval test = base.withPeriodAfterStart(null);
assertEquals(new Interval(TEST_TIME_NOW, TEST_TIME_NOW, COPTIC_PARIS), test);
}
public void testWithPeriodAfterStart3() throws Throwable {
Period per = new Period(0, 0, 0, 0, 0, 0, 0, -1);
Interval base = new Interval(TEST_TIME_NOW, TEST_TIME_NOW);
try {
base.withPeriodAfterStart(per);
fail();
} catch (IllegalArgumentException ex) {}
}
//-----------------------------------------------------------------------
public void testWithPeriodBeforeEnd1() throws Throwable {
DateTime dt = new DateTime(TEST_TIME_NOW, COPTIC_PARIS);
Period dur = new Period(0, 6, 0, 0, 1, 0, 0, 0);
Interval base = new Interval(dt, dt);
Interval test = base.withPeriodBeforeEnd(dur);
assertEquals(new Interval(dur, dt), test);
}
public void testWithPeriodBeforeEnd2() throws Throwable {
Interval base = new Interval(TEST_TIME_NOW, TEST_TIME2, COPTIC_PARIS);
Interval test = base.withPeriodBeforeEnd(null);
assertEquals(new Interval(TEST_TIME2, TEST_TIME2, COPTIC_PARIS), test);
}
public void testWithPeriodBeforeEnd3() throws Throwable {
Period per = new Period(0, 0, 0, 0, 0, 0, 0, -1);
Interval base = new Interval(TEST_TIME_NOW, TEST_TIME_NOW);
try {
base.withPeriodBeforeEnd(per);
fail();
} catch (IllegalArgumentException ex) {}
}
}
diff --git a/JodaTime/src/test/org/joda/time/TestMutableInterval_Basics.java b/JodaTime/src/test/org/joda/time/TestMutableInterval_Basics.java
index f14bd879..f5afa4e5 100644
--- a/JodaTime/src/test/org/joda/time/TestMutableInterval_Basics.java
+++ b/JodaTime/src/test/org/joda/time/TestMutableInterval_Basics.java
@@ -1,505 +1,505 @@
/*
* Joda Software License, Version 1.0
*
*
* Copyright (c) 2001-2004 Stephen Colebourne.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Joda project (http://www.joda.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The name "Joda" must not be used to endorse or promote products
* derived from this software without prior written permission. For
* written permission, please contact [email protected].
*
* 5. Products derived from this software may not be called "Joda",
* nor may "Joda" appear in their name, without prior written
* permission of the Joda project.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Joda project and was originally
* created by Stephen Colebourne <[email protected]>. For more
* information on the Joda project, please see <http://www.joda.org/>.
*/
package org.joda.time;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Locale;
import java.util.TimeZone;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.joda.time.base.AbstractInterval;
/**
* This class is a Junit unit test for Instant.
*
* @author Stephen Colebourne
*/
public class TestMutableInterval_Basics extends TestCase {
// Test in 2002/03 as time zones are more well known
// (before the late 90's they were all over the place)
private static final DateTimeZone PARIS = DateTimeZone.getInstance("Europe/Paris");
private static final DateTimeZone LONDON = DateTimeZone.getInstance("Europe/London");
private static final Chronology COPTIC_PARIS = Chronology.getCoptic(PARIS);
long y2002days = 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 +
366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 +
365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 +
366 + 365;
long y2003days = 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 +
366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 +
365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 +
366 + 365 + 365;
// 2002-06-09
private long TEST_TIME_NOW =
(y2002days + 31L + 28L + 31L + 30L + 31L + 9L -1L) * DateTimeConstants.MILLIS_PER_DAY;
// 2002-04-05
private long TEST_TIME1 =
(y2002days + 31L + 28L + 31L + 5L -1L) * DateTimeConstants.MILLIS_PER_DAY
+ 12L * DateTimeConstants.MILLIS_PER_HOUR
+ 24L * DateTimeConstants.MILLIS_PER_MINUTE;
// 2003-05-06
private long TEST_TIME2 =
(y2003days + 31L + 28L + 31L + 30L + 6L -1L) * DateTimeConstants.MILLIS_PER_DAY
+ 14L * DateTimeConstants.MILLIS_PER_HOUR
+ 28L * DateTimeConstants.MILLIS_PER_MINUTE;
private DateTimeZone originalDateTimeZone = null;
private TimeZone originalTimeZone = null;
private Locale originalLocale = null;
public static void main(String[] args) {
junit.textui.TestRunner.run(suite());
}
public static TestSuite suite() {
return new TestSuite(TestMutableInterval_Basics.class);
}
public TestMutableInterval_Basics(String name) {
super(name);
}
protected void setUp() throws Exception {
DateTimeUtils.setCurrentMillisFixed(TEST_TIME_NOW);
originalDateTimeZone = DateTimeZone.getDefault();
originalTimeZone = TimeZone.getDefault();
originalLocale = Locale.getDefault();
DateTimeZone.setDefault(LONDON);
TimeZone.setDefault(TimeZone.getTimeZone("Europe/London"));
Locale.setDefault(Locale.UK);
}
protected void tearDown() throws Exception {
DateTimeUtils.setCurrentMillisSystem();
DateTimeZone.setDefault(originalDateTimeZone);
TimeZone.setDefault(originalTimeZone);
Locale.setDefault(originalLocale);
originalDateTimeZone = null;
originalTimeZone = null;
originalLocale = null;
}
//-----------------------------------------------------------------------
public void testTest() {
assertEquals("2002-06-09T00:00:00.000Z", new Instant(TEST_TIME_NOW).toString());
assertEquals("2002-04-05T12:24:00.000Z", new Instant(TEST_TIME1).toString());
assertEquals("2003-05-06T14:28:00.000Z", new Instant(TEST_TIME2).toString());
}
//-----------------------------------------------------------------------
public void testGetMillis() {
MutableInterval test = new MutableInterval(TEST_TIME1, TEST_TIME2);
assertEquals(TEST_TIME1, test.getStartMillis());
assertEquals(TEST_TIME1, test.getStart().getMillis());
assertEquals(TEST_TIME2, test.getEndMillis());
assertEquals(TEST_TIME2, test.getEnd().getMillis());
assertEquals(TEST_TIME2 - TEST_TIME1, test.toDurationMillis());
assertEquals(TEST_TIME2 - TEST_TIME1, test.toDuration().getMillis());
}
public void testGetDuration1() {
MutableInterval test = new MutableInterval(TEST_TIME1, TEST_TIME2);
assertEquals(TEST_TIME2 - TEST_TIME1, test.toDurationMillis());
assertEquals(TEST_TIME2 - TEST_TIME1, test.toDuration().getMillis());
}
public void testGetDuration2() {
MutableInterval test = new MutableInterval(TEST_TIME1, TEST_TIME1);
assertSame(Duration.ZERO, test.toDuration());
}
public void testEqualsHashCode() {
MutableInterval test1 = new MutableInterval(TEST_TIME1, TEST_TIME2);
MutableInterval test2 = new MutableInterval(TEST_TIME1, TEST_TIME2);
assertEquals(true, test1.equals(test2));
assertEquals(true, test2.equals(test1));
assertEquals(true, test1.equals(test1));
assertEquals(true, test2.equals(test2));
assertEquals(true, test1.hashCode() == test2.hashCode());
assertEquals(true, test1.hashCode() == test1.hashCode());
assertEquals(true, test2.hashCode() == test2.hashCode());
MutableInterval test3 = new MutableInterval(TEST_TIME_NOW, TEST_TIME2);
assertEquals(false, test1.equals(test3));
assertEquals(false, test2.equals(test3));
assertEquals(false, test3.equals(test1));
assertEquals(false, test3.equals(test2));
assertEquals(false, test1.hashCode() == test3.hashCode());
assertEquals(false, test2.hashCode() == test3.hashCode());
MutableInterval test4 = new MutableInterval(TEST_TIME1, TEST_TIME2, Chronology.getGJ());
assertEquals(true, test4.equals(test4));
assertEquals(false, test1.equals(test4));
assertEquals(false, test2.equals(test4));
assertEquals(false, test4.equals(test1));
assertEquals(false, test4.equals(test2));
assertEquals(false, test1.hashCode() == test4.hashCode());
assertEquals(false, test2.hashCode() == test4.hashCode());
MutableInterval test5 = new MutableInterval(TEST_TIME1, TEST_TIME2);
assertEquals(true, test1.equals(test5));
assertEquals(true, test2.equals(test5));
assertEquals(false, test3.equals(test5));
assertEquals(true, test5.equals(test1));
assertEquals(true, test5.equals(test2));
assertEquals(false, test5.equals(test3));
assertEquals(true, test1.hashCode() == test5.hashCode());
assertEquals(true, test2.hashCode() == test5.hashCode());
assertEquals(false, test3.hashCode() == test5.hashCode());
assertEquals(false, test1.equals("Hello"));
assertEquals(true, test1.equals(new MockInterval()));
assertEquals(false, test1.equals(new DateTime(TEST_TIME1)));
}
class MockInterval extends AbstractInterval {
public MockInterval() {
super();
}
public Chronology getChronology() {
return Chronology.getISO();
}
public long getStartMillis() {
return TEST_TIME1;
}
public long getEndMillis() {
return TEST_TIME2;
}
}
//-----------------------------------------------------------------------
public void testContains_long() {
MutableInterval test = new MutableInterval(TEST_TIME1, TEST_TIME2);
assertEquals(true, test.contains(TEST_TIME1));
assertEquals(false, test.contains(TEST_TIME1 - 1));
assertEquals(true, test.contains(TEST_TIME1 + (TEST_TIME2 - TEST_TIME1) / 2));
assertEquals(false, test.contains(TEST_TIME2));
assertEquals(true, test.contains(TEST_TIME2 - 1));
}
public void testContainsNow() {
MutableInterval test = new MutableInterval(TEST_TIME1, TEST_TIME2);
DateTimeUtils.setCurrentMillisFixed(TEST_TIME1);
assertEquals(true, test.containsNow());
DateTimeUtils.setCurrentMillisFixed(TEST_TIME1 - 1);
assertEquals(false, test.containsNow());
DateTimeUtils.setCurrentMillisFixed(TEST_TIME1 + (TEST_TIME2 - TEST_TIME1) / 2);
assertEquals(true, test.containsNow());
DateTimeUtils.setCurrentMillisFixed(TEST_TIME2);
assertEquals(false, test.containsNow());
DateTimeUtils.setCurrentMillisFixed(TEST_TIME2 - 1);
assertEquals(true, test.containsNow());
}
public void testContains_RI() {
MutableInterval test = new MutableInterval(TEST_TIME1, TEST_TIME2);
assertEquals(true, test.contains(new Instant(TEST_TIME1)));
assertEquals(false, test.contains(new Instant(TEST_TIME1 - 1)));
assertEquals(true, test.contains(new Instant(TEST_TIME1 + (TEST_TIME2 - TEST_TIME1) / 2)));
assertEquals(false, test.contains(new Instant(TEST_TIME2)));
assertEquals(true, test.contains(new Instant(TEST_TIME2 - 1)));
assertEquals(true, test.contains((ReadableInstant) null));
}
//-----------------------------------------------------------------------
public void testContains_RInterval() {
MutableInterval test = new MutableInterval(TEST_TIME1, TEST_TIME2);
assertEquals(true, test.contains(new Interval(TEST_TIME1, TEST_TIME2)));
assertEquals(false, test.contains(new Interval(TEST_TIME1 - 1, TEST_TIME2)));
assertEquals(true, test.contains(new Interval(TEST_TIME1 + (TEST_TIME2 - TEST_TIME1) / 2, TEST_TIME2)));
assertEquals(false, test.contains(new Interval(TEST_TIME2, TEST_TIME2)));
assertEquals(true, test.contains(new Interval(TEST_TIME2 - 1, TEST_TIME2)));
assertEquals(true, test.contains(new Interval(TEST_TIME1, TEST_TIME2 - 1)));
assertEquals(false, test.contains(new Interval(TEST_TIME1 - 1, TEST_TIME2 - 1)));
assertEquals(true, test.contains(new Interval(TEST_TIME1 + (TEST_TIME2 - TEST_TIME1) / 2, TEST_TIME2 - 1)));
assertEquals(true, test.contains(new Interval(TEST_TIME2 - 1, TEST_TIME2 - 1)));
assertEquals(true, test.contains(new Interval(TEST_TIME2 - 2, TEST_TIME2 - 1)));
assertEquals(false, test.contains(new Interval(TEST_TIME1, TEST_TIME2 + 1)));
assertEquals(false, test.contains(new Interval(TEST_TIME1 - 1, TEST_TIME2 + 1)));
assertEquals(false, test.contains(new Interval(TEST_TIME1 + (TEST_TIME2 - TEST_TIME1) / 2, TEST_TIME2 + 1)));
assertEquals(false, test.contains(new Interval(TEST_TIME2, TEST_TIME2 + 1)));
assertEquals(false, test.contains(new Interval(TEST_TIME2 - 1, TEST_TIME2 + 1)));
assertEquals(false, test.contains(new Interval(TEST_TIME1 - 2, TEST_TIME1 - 1)));
assertEquals(true, test.contains((ReadableInterval) null));
}
public void testOverlaps_RInterval() {
MutableInterval test = new MutableInterval(TEST_TIME1, TEST_TIME2);
assertEquals(true, test.overlaps(new Interval(TEST_TIME1, TEST_TIME2)));
assertEquals(true, test.overlaps(new Interval(TEST_TIME1 - 1, TEST_TIME2)));
assertEquals(true, test.overlaps(new Interval(TEST_TIME1 + (TEST_TIME2 - TEST_TIME1) / 2, TEST_TIME2)));
assertEquals(false, test.overlaps(new Interval(TEST_TIME2, TEST_TIME2)));
assertEquals(true, test.overlaps(new Interval(TEST_TIME2 - 1, TEST_TIME2)));
assertEquals(true, test.overlaps(new Interval(TEST_TIME1, TEST_TIME2 + 1)));
assertEquals(true, test.overlaps(new Interval(TEST_TIME1 - 1, TEST_TIME2 + 1)));
assertEquals(true, test.overlaps(new Interval(TEST_TIME1 + (TEST_TIME2 - TEST_TIME1) / 2, TEST_TIME2 + 1)));
assertEquals(false, test.overlaps(new Interval(TEST_TIME2, TEST_TIME2 + 1)));
assertEquals(true, test.overlaps(new Interval(TEST_TIME2 - 1, TEST_TIME2 + 1)));
assertEquals(false, test.overlaps(new Interval(TEST_TIME1 - 1, TEST_TIME1 - 1)));
assertEquals(false, test.overlaps(new Interval(TEST_TIME1 - 1, TEST_TIME1)));
assertEquals(true, test.overlaps(new Interval(TEST_TIME1 - 1, TEST_TIME1 + 1)));
assertEquals(true, test.overlaps((ReadableInterval) null));
}
//-----------------------------------------------------------------------
public void testIsBefore_long() {
MutableInterval test = new MutableInterval(TEST_TIME1, TEST_TIME2);
assertEquals(false, test.isBefore(TEST_TIME1 - 1));
assertEquals(false, test.isBefore(TEST_TIME1));
assertEquals(false, test.isBefore(TEST_TIME1 + 1));
assertEquals(false, test.isBefore(TEST_TIME2 - 1));
assertEquals(true, test.isBefore(TEST_TIME2));
assertEquals(true, test.isBefore(TEST_TIME2 + 1));
}
public void testIsBeforeNow() {
MutableInterval test = new MutableInterval(TEST_TIME1, TEST_TIME2);
DateTimeUtils.setCurrentMillisFixed(TEST_TIME2 - 1);
assertEquals(false, test.isBeforeNow());
DateTimeUtils.setCurrentMillisFixed(TEST_TIME2);
assertEquals(true, test.isBeforeNow());
DateTimeUtils.setCurrentMillisFixed(TEST_TIME2 + 1);
assertEquals(true, test.isBeforeNow());
}
public void testIsBefore_RI() {
MutableInterval test = new MutableInterval(TEST_TIME1, TEST_TIME2);
assertEquals(false, test.isBefore(new Instant(TEST_TIME1 - 1)));
assertEquals(false, test.isBefore(new Instant(TEST_TIME1)));
assertEquals(false, test.isBefore(new Instant(TEST_TIME1 + 1)));
assertEquals(false, test.isBefore(new Instant(TEST_TIME2 - 1)));
assertEquals(true, test.isBefore(new Instant(TEST_TIME2)));
assertEquals(true, test.isBefore(new Instant(TEST_TIME2 + 1)));
assertEquals(false, test.isBefore((ReadableInstant) null));
}
public void testIsBefore_RInterval() {
MutableInterval test = new MutableInterval(TEST_TIME1, TEST_TIME2);
assertEquals(false, test.isBefore(new Interval(Long.MIN_VALUE, TEST_TIME1 - 1)));
assertEquals(false, test.isBefore(new Interval(Long.MIN_VALUE, TEST_TIME1)));
assertEquals(false, test.isBefore(new Interval(Long.MIN_VALUE, TEST_TIME1 + 1)));
assertEquals(false, test.isBefore(new Interval(TEST_TIME2 - 1, Long.MAX_VALUE)));
assertEquals(true, test.isBefore(new Interval(TEST_TIME2, Long.MAX_VALUE)));
assertEquals(true, test.isBefore(new Interval(TEST_TIME2 + 1, Long.MAX_VALUE)));
assertEquals(false, test.isBefore((ReadableInterval) null));
}
//-----------------------------------------------------------------------
public void testIsAfter_long() {
MutableInterval test = new MutableInterval(TEST_TIME1, TEST_TIME2);
assertEquals(true, test.isAfter(TEST_TIME1 - 1));
assertEquals(false, test.isAfter(TEST_TIME1));
assertEquals(false, test.isAfter(TEST_TIME1 + 1));
assertEquals(false, test.isAfter(TEST_TIME2 - 1));
assertEquals(false, test.isAfter(TEST_TIME2));
assertEquals(false, test.isAfter(TEST_TIME2 + 1));
}
public void testIsAfterNow() {
MutableInterval test = new MutableInterval(TEST_TIME1, TEST_TIME2);
DateTimeUtils.setCurrentMillisFixed(TEST_TIME1 - 1);
assertEquals(true, test.isAfterNow());
DateTimeUtils.setCurrentMillisFixed(TEST_TIME1);
assertEquals(false, test.isAfterNow());
DateTimeUtils.setCurrentMillisFixed(TEST_TIME1 + 1);
assertEquals(false, test.isAfterNow());
}
public void testIsAfter_RI() {
MutableInterval test = new MutableInterval(TEST_TIME1, TEST_TIME2);
assertEquals(true, test.isAfter(new Instant(TEST_TIME1 - 1)));
assertEquals(false, test.isAfter(new Instant(TEST_TIME1)));
assertEquals(false, test.isAfter(new Instant(TEST_TIME1 + 1)));
assertEquals(false, test.isAfter(new Instant(TEST_TIME2 - 1)));
assertEquals(false, test.isAfter(new Instant(TEST_TIME2)));
assertEquals(false, test.isAfter(new Instant(TEST_TIME2 + 1)));
assertEquals(false, test.isAfter((ReadableInstant) null));
}
public void testIsAfter_RInterval() {
MutableInterval test = new MutableInterval(TEST_TIME1, TEST_TIME2);
assertEquals(true, test.isAfter(new Interval(Long.MIN_VALUE, TEST_TIME1 - 1)));
- assertEquals(false, test.isAfter(new Interval(Long.MIN_VALUE, TEST_TIME1)));
+ assertEquals(true, test.isAfter(new Interval(Long.MIN_VALUE, TEST_TIME1)));
assertEquals(false, test.isAfter(new Interval(Long.MIN_VALUE, TEST_TIME1 + 1)));
assertEquals(false, test.isAfter(new Interval(TEST_TIME2 - 1, Long.MAX_VALUE)));
assertEquals(false, test.isAfter(new Interval(TEST_TIME2, Long.MAX_VALUE)));
assertEquals(false, test.isAfter(new Interval(TEST_TIME2 + 1, Long.MAX_VALUE)));
assertEquals(false, test.isAfter((ReadableInterval) null));
}
//-----------------------------------------------------------------------
public void testToInterval1() {
MutableInterval test = new MutableInterval(TEST_TIME1, TEST_TIME2, COPTIC_PARIS);
Interval result = test.toInterval();
assertEquals(test, result);
}
//-----------------------------------------------------------------------
public void testToMutableInterval1() {
MutableInterval test = new MutableInterval(TEST_TIME1, TEST_TIME2, COPTIC_PARIS);
MutableInterval result = test.toMutableInterval();
assertEquals(test, result);
assertNotSame(test, result);
}
//-----------------------------------------------------------------------
public void testToPeriod() {
DateTime dt1 = new DateTime(2004, 6, 9, 7, 8, 9, 10, COPTIC_PARIS);
DateTime dt2 = new DateTime(2005, 8, 13, 12, 14, 16, 18, COPTIC_PARIS);
MutableInterval base = new MutableInterval(dt1, dt2);
Period test = base.toPeriod();
Period expected = new Period(dt1, dt2, PeriodType.standard());
assertEquals(expected, test);
}
//-----------------------------------------------------------------------
public void testToPeriod_PeriodType1() {
DateTime dt1 = new DateTime(2004, 6, 9, 7, 8, 9, 10, COPTIC_PARIS);
DateTime dt2 = new DateTime(2005, 8, 13, 12, 14, 16, 18, COPTIC_PARIS);
MutableInterval base = new MutableInterval(dt1, dt2);
Period test = base.toPeriod(null);
Period expected = new Period(dt1, dt2, PeriodType.standard());
assertEquals(expected, test);
}
public void testToPeriod_PeriodType2() {
DateTime dt1 = new DateTime(2004, 6, 9, 7, 8, 9, 10);
DateTime dt2 = new DateTime(2005, 8, 13, 12, 14, 16, 18);
MutableInterval base = new MutableInterval(dt1, dt2);
Period test = base.toPeriod(PeriodType.yearWeekDayTime());
Period expected = new Period(dt1, dt2, PeriodType.yearWeekDayTime());
assertEquals(expected, test);
}
//-----------------------------------------------------------------------
public void testSerialization() throws Exception {
MutableInterval test = new MutableInterval(TEST_TIME1, TEST_TIME2);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(test);
byte[] bytes = baos.toByteArray();
oos.close();
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(bais);
MutableInterval result = (MutableInterval) ois.readObject();
ois.close();
assertEquals(test, result);
}
//-----------------------------------------------------------------------
public void testToString() {
DateTime dt1 = new DateTime(2004, 6, 9, 7, 8, 9, 10, DateTimeZone.UTC);
DateTime dt2 = new DateTime(2005, 8, 13, 12, 14, 16, 18, DateTimeZone.UTC);
MutableInterval test = new MutableInterval(dt1, dt2);
assertEquals("2004-06-09T07:08:09.010/2005-08-13T12:14:16.018", test.toString());
}
//-----------------------------------------------------------------------
public void testCopy() {
MutableInterval test = new MutableInterval(123L, 456L, COPTIC_PARIS);
MutableInterval cloned = test.copy();
assertEquals(test, cloned);
assertNotSame(test, cloned);
}
public void testClone() {
MutableInterval test = new MutableInterval(123L, 456L, COPTIC_PARIS);
MutableInterval cloned = (MutableInterval) test.clone();
assertEquals(test, cloned);
assertNotSame(test, cloned);
}
}
| false | false | null | null |
diff --git a/Paillarde/src/org/fr/ykatchou/paillardes/PaillardeMenu.java b/Paillarde/src/org/fr/ykatchou/paillardes/PaillardeMenu.java
index ff05db3..f9729e8 100644
--- a/Paillarde/src/org/fr/ykatchou/paillardes/PaillardeMenu.java
+++ b/Paillarde/src/org/fr/ykatchou/paillardes/PaillardeMenu.java
@@ -1,51 +1,59 @@
package org.fr.ykatchou.paillardes;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class PaillardeMenu extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Chanson.dbhelp = new DatabaseHelper(this);
// / BINDINGS
// //////////////////////////////////////////////////
Button b = (Button) findViewById(R.id.btn_list);
b.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(v.getContext(), PaillardeList.class);
Bundle b = new Bundle();
b.putString("filter", "");
i.putExtra("data", b);
startActivity(i);
}
});
+ b = (Button) findViewById(R.id.btn_search);
+ b.setOnClickListener(new OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ onSearchRequested();
+ }
+ });
+
b = (Button) findViewById(R.id.btn_about);
b.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(v.getContext(), About.class);
startActivity(i);
}
});
b = (Button) findViewById(R.id.btn_quit);
b.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
}
}
\ No newline at end of file
| true | false | null | null |
diff --git a/src/network/ServerConnection.java b/src/network/ServerConnection.java
index 53c293a..6ade6c9 100644
--- a/src/network/ServerConnection.java
+++ b/src/network/ServerConnection.java
@@ -1,330 +1,333 @@
package network;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import database.DatabaseUnit;
import logic.User;
import requests.xml.XMLSerializable;
import utils.PasswordHasher;
public class ServerConnection {
private DatabaseUnit dbUnit;
private Map<String, User> users;
private Map<String, String> passwords;
private List<ServerConnectionHandler> handlers;
private long nextDebtId, nextUserId, nextFriendRequestId;
private Timer timer;
private ServerSocket serverSocket = null;
private boolean shouldSave = true;
public ServerConnection(boolean readFromDatabase) {
this.handlers = new ArrayList<ServerConnectionHandler>();
users = new HashMap<String, User>();
passwords = new HashMap<String, String>();
nextDebtId = 1; nextUserId = 1; nextFriendRequestId = 1;
if(readFromDatabase) {
dbUnit = new DatabaseUnit();
try {
dbUnit.connect();
for(Map.Entry<User, String> entry : dbUnit.loadUsers().entrySet()) {
users.put(entry.getKey().getUsername(), entry.getKey());
passwords.put(entry.getKey().getUsername(), entry.getValue());
}
dbUnit.loadFriends(users);
dbUnit.loadDebts(users);
nextDebtId = dbUnit.getNextId(DatabaseUnit.TABLE_DEBT, DatabaseUnit.FIELD_DEBT_ID);
nextUserId = dbUnit.getNextId(DatabaseUnit.TABLE_USER, DatabaseUnit.FIELD_USER_ID);
nextFriendRequestId = dbUnit.getNextId(DatabaseUnit.TABLE_FRIEND_REQUEST, DatabaseUnit.FIELD_FRIEND_REQUEST_ID);
// Write to database and disconnect inactive users
(timer = new Timer()).schedule(new TimerTask() {
@Override
public void run() {
if(shouldSave) {
try {
saveAll();
} catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println("Failed writing to database!");
e.printStackTrace();
writeToLog("Exception while writing to database:\n" + e.toString());
}
} else System.out.println("Not writing to database. Saving is disabled.");
// Also check if we should disconnect any inactive users
- for (ServerConnectionHandler h : handlers) {
- if(h.getTimeOfLastCommand() + Constants.MINIMUM_INACTIVE_TIME_BEFORE_DISCONNECT < System.currentTimeMillis()) {
- System.out.println("Attempting to close connection");
- h.close();
+ // Lock the list
+ synchronized (this) {
+ for (ServerConnectionHandler h : handlers) {
+ if(h.getTimeOfLastCommand() + Constants.MINIMUM_INACTIVE_TIME_BEFORE_DISCONNECT < System.currentTimeMillis()) {
+ System.out.println("Attempting to close connection");
+ h.close();
+ }
}
}
}
}, Constants.TIME_BETWEEN_WRITES_TO_DATABASE, Constants.TIME_BETWEEN_WRITES_TO_DATABASE);
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
try {
System.out.println("Writing updates to database..");
saveAll();
System.out.println("Wrote updates to database.");
} catch (SQLException e) {
System.out.println("Failed writing to database.");
e.printStackTrace();
writeToLog("Shutdown hook failed: " + e.toString());
}
}
});
} catch (Exception e) {
System.out.println("FAILED TO LOAD!");
e.printStackTrace();
writeToLog("Failed to load from database: " + e.toString());
}
}
// Start command listener
new Thread(new Runnable() {
@Override
public void run() {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String command = "";
try {
while(!(command = reader.readLine()).equals("exit")) {
if(command.equals("save")) saveAll();
// Close all connections
else if(command.equals("disconnect")) {
disconnectUsers();
} else if(command.equals("ls connections")) {
listConnections();
} else if(command.equals("disable saving")) {
shouldSave = false;
} else if(command.equals("enable saving")) {
shouldSave = true;
} else {
System.out.println("Unknown command.");
}
}
System.out.println("Disconnecting users..");
disconnectUsers();
System.out.println("Stopping timer..");
timer.cancel();
System.out.println("Closing server socket..");
serverSocket.close();
System.out.println("Writing updates to database..");
saveAll();
System.out.println("Bye!");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
writeToLog(e.toString());
}
}
}).start();
}
/**
* Lists the current online users in System.out
*/
public synchronized void listConnections() {
for (ServerConnectionHandler h : handlers) {
if(h.getUser() == null) {
System.out.println("Anonymous user with IP address: " + h.getUserIp());
} else {
System.out.println(h.getUser().getUsername() + ": " + h.getUserIp());
}
}
if(handlers.isEmpty()) System.out.println("None");
}
public synchronized void disconnectUsers() {
System.out.println("Attempting to close all connections");
for (ServerConnectionHandler h : handlers) {
h.close();
}
}
public synchronized void writeToLog(String s) {
PrintWriter out = null;
try {
out = new PrintWriter(new BufferedWriter(new FileWriter(Constants.SERVER_LOG_FILE, true)));
Calendar cal = Calendar.getInstance();
cal.getTime();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
out.println(sdf.format(cal.getTime()) + ": " + s);
System.out.println("Wrote to error log.");
} catch (IOException e) {
System.out.println("Failed writing to log file.");
e.printStackTrace();
} finally {
try {
out.close();
} catch (Exception e) {}
}
}
public synchronized void saveAll() throws SQLException {
dbUnit.save(users.values(), passwords);
}
public synchronized void saveUser(User u) throws SQLException {
List<User> user = new ArrayList<User>();
user.add(u);
Map<String, String> pw = new HashMap<String, String>();
pw.put(u.getUsername(), passwords.get(u.getUsername()));
dbUnit.save(user, passwords);
}
public synchronized void addPassword(String username, String password) {
passwords.put(username, password);
}
public synchronized void addConnectionHandler(ServerConnectionHandler handler) {
this.handlers.add(handler);
}
public synchronized void removeConnectionHandler(ServerConnectionHandler handler) {
this.handlers.remove(handler);
}
/**
* @return The next available debt id
*/
public synchronized long getNextDebtId() {
return nextDebtId++;
}
/**
* @return The next available user id
*/
public synchronized long getNextUserId() {
return nextUserId++;
}
/**
* @return The next available friend request id
*/
public synchronized long getNextFriendRequestId() {
return nextFriendRequestId++;
}
/**
* Notifies the specified user by sending the given object to the user's UpdateListener
* @param username The user to notify
* @param objectToSend The object to send
*/
public void notifyUser(String username, XMLSerializable objectToSend) {
System.out.println("Notifying " + username);
ServerConnectionHandler handler = getHandler(username);
if(handler != null) {
handler.sendUpdate(objectToSend);
}
}
/**
* Returns the specified user's ServerConnectionHandler
* @param username The user's user name
* @return The user's ServerConnectionHandler
*/
public ServerConnectionHandler getHandler(String username) {
for (ServerConnectionHandler h : handlers) {
if(h.getUser().getUsername().equals(username)) return h;
}
return null;
}
/**
* Listens at the specified port for incoming connections.
* Incoming connections are given to a ServerConnectionHandler that is started in a separate Thread.
* This method will run "forever"
* @param port The port to listen to
*/
public void accept(int port) {
try {
serverSocket = new ServerSocket(port);
while(true) {
System.out.println("Listening for incomming connections..");
new ServerConnectionHandler(serverSocket.accept(), this).start();
}
} catch (IOException e) {
// TODO Auto-generated catch block
// e.printStackTrace();
writeToLog("Failed to accept incomming connection on port "+ port + ": " + e.toString());
System.out.println("Server socket closed.");
} finally {
try {
serverSocket.close();
} catch (Exception e) {}
}
}
/**
* Returns the user with the given username, or null if no user is found.
* @param username The username
* @return The user or null
*/
synchronized public User getUser(String username) {
return users.get(username);
}
synchronized public void addUser(User user, String password) {
users.put(user.getUsername(), user);
passwords.put(user.getUsername(), PasswordHasher.hashPassword(password));
}
synchronized public boolean checkPassword(User user, String password) {
return passwords.containsKey(user.getUsername())
&& passwords.get(user.getUsername()).equals(password);
}
public static void main(String[] args) {
ServerConnection server = new ServerConnection(true);
// START TEST DATA
// User arne = new User(1, "arnegopro");
// User stian = new User(2, "stian");
// User test = new User(0, "test");
// // All friends must also have a corresponding friend request to work with the database!
// stian.addFriendRequest(new FriendRequest(stian.getUsername(), test, FriendRequestStatus.PENDING, 0));
// stian.addFriendRequest(new FriendRequest(stian.getUsername(), arne, FriendRequestStatus.ACCEPTED, 1));
// stian.addFriend(arne);
// arne.addFriend(stian);
// server.addUser(arne, "qazqaz");
// server.addUser(stian, "asd");
// server.addUser(test, "test");
// Debt d1 = new Debt(0, 15, "kr", stian, arne, "Tralalala", stian, DebtStatus.CONFIRMED);
// stian.addConfirmedDebt(d1);
// arne.addConfirmedDebt(d1);
// Debt d2 = new Debt(1, 7, "kr", arne, stian, "Tralalla2", arne, DebtStatus.REQUESTED);
// stian.addPendingDebt(d2);
// arne.addPendingDebt(d2);
// server.nextDebtId = 2;
// server.nextFriendRequestId = 2;
// server.nextUserId = 3;
// END TEST DATA
// Print loaded users on startup
System.out.println("Loaded users:");
for (String s : server.users.keySet()) {
System.out.println(s);
}
// Accept connections on port 13337
server.accept(Constants.STANDARD_SERVER_PORT);
}
}
\ No newline at end of file
| true | false | null | null |
diff --git a/trunk/CruxShowcase/src/br/com/sysmap/crux/showcase/server/SensitiveServerServiceImpl.java b/trunk/CruxShowcase/src/br/com/sysmap/crux/showcase/server/SensitiveServerServiceImpl.java
index ed76c7eb3..d4a883c60 100644
--- a/trunk/CruxShowcase/src/br/com/sysmap/crux/showcase/server/SensitiveServerServiceImpl.java
+++ b/trunk/CruxShowcase/src/br/com/sysmap/crux/showcase/server/SensitiveServerServiceImpl.java
@@ -1,34 +1,32 @@
package br.com.sysmap.crux.showcase.server;
import br.com.sysmap.crux.showcase.client.remote.SensitiveServerService;
public class SensitiveServerServiceImpl implements SensitiveServerService
{
- @Override
public String sensitiveMethod()
{
try
{
Thread.sleep(3000);
}
catch (InterruptedException e)
{
// Nothing
}
return "Hello, Sensitive Method called!";
}
- @Override
public String sensitiveMethodNoBlock()
{
try
{
Thread.sleep(3000);
}
catch (InterruptedException e)
{
// Nothing
}
return "Hello, Sensitive Method called (No Block)!";
}
}
| false | false | null | null |
diff --git a/branches/kernel-1.2.x/kernel-impl/src/main/java/org/sakaiproject/tool/impl/SessionComponent.java b/branches/kernel-1.2.x/kernel-impl/src/main/java/org/sakaiproject/tool/impl/SessionComponent.java
index 58846484..e9ac10ae 100644
--- a/branches/kernel-1.2.x/kernel-impl/src/main/java/org/sakaiproject/tool/impl/SessionComponent.java
+++ b/branches/kernel-1.2.x/kernel-impl/src/main/java/org/sakaiproject/tool/impl/SessionComponent.java
@@ -1,574 +1,577 @@
/**********************************************************************************
* $URL$
* $Id$
***********************************************************************************
*
* Copyright (c) 2005, 2006, 2007, 2008 Sakai Foundation
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.osedu.org/licenses/ECL-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
**********************************************************************************/
package org.sakaiproject.tool.impl;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.Principal;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.lang.mutable.MutableLong;
import org.springframework.util.StringUtils;
import org.sakaiproject.component.cover.ComponentManager;
import org.sakaiproject.id.api.IdManager;
import org.sakaiproject.thread_local.api.ThreadLocalManager;
import org.sakaiproject.tool.api.NonPortableSession;
import org.sakaiproject.tool.api.Session;
import org.sakaiproject.tool.api.SessionAttributeListener;
import org.sakaiproject.tool.api.SessionManager;
import org.sakaiproject.tool.api.SessionStore;
import org.sakaiproject.tool.api.Tool;
import org.sakaiproject.tool.api.ToolManager;
import org.sakaiproject.tool.api.ToolSession;
/**
* <p>
* Standard implementation of the Sakai SessionManager.
* </p>
*/
public abstract class SessionComponent implements SessionManager, SessionStore
{
/** Our log (commons). */
private static Log M_log = LogFactory.getLog(SessionComponent.class);
/** The sessions - keyed by session id. */
protected Map<String, Session> m_sessions = new ConcurrentHashMap<String, Session>();
/**
* The expected time sessions may be ready for expiration. This is only an optimization
* for when Terracotta is in use, to prevent faulting Session objects into the local
* JVM when it is not necessary. Session.isInactive() method remains the ultimate authority
* to determine if a session is invalid or not.
*/
protected Map<String,MutableLong> expirationTimeSuggestionMap = new ConcurrentHashMap<String, MutableLong>();
private SessionAttributeListener sessionListener;
/** The maintenance. */
protected Maintenance m_maintenance = null;
/** Key in the ThreadLocalManager for binding our current session. */
protected final static String CURRENT_SESSION = "org.sakaiproject.api.kernel.session.current";
/** Key in the ThreadLocalManager for binding our current tool session. */
protected final static String CURRENT_TOOL_SESSION = "org.sakaiproject.api.kernel.session.current.tool";
/** Key in the ThreadLocalManager for access to the current servlet context (from tool-util/servlet/RequestFilter). */
protected final static String CURRENT_SERVLET_CONTEXT = "org.sakaiproject.util.RequestFilter.servlet_context";
/** The set of tool ids that represent tools that can be clustered */
protected Set<String> clusterableTools = new HashSet<String>();
/** Salt for predictable session IDs */
protected byte[] salt = null;
/**********************************************************************************************************************************************************************************************************************************************************
* Dependencies
*********************************************************************************************************************************************************************************************************************************************************/
/** Will be used to get the current tool id when checking the whitelist */
protected abstract ToolManager toolManager();
/**
* @return the ThreadLocalManager collaborator.
*/
protected abstract ThreadLocalManager threadLocalManager();
/**
* @return the IdManager collaborator.
*/
protected abstract IdManager idManager();
/**********************************************************************************************************************************************************************************************************************************************************
* Configuration
*********************************************************************************************************************************************************************************************************************************************************/
/** Configuration: default inactive period for sessions (seconds). */
protected int m_defaultInactiveInterval = 30 * 60;
/**
* Configuration - set the default inactive period for sessions.
*
* @param value
* The default inactive period for sessions.
*/
public void setInactiveInterval(String value)
{
try
{
m_defaultInactiveInterval = Integer.parseInt(value);
}
catch (Exception t)
{
System.out.println(t);
}
}
/**
* Configuration - set the default inactive period for sessions.
*
* @param value
* The default inactive period for sessions.
*/
public void setInactiveInterval(int value)
{
m_defaultInactiveInterval = value;
}
/**
* Configuration - set the default inactive period for sessions.
*
* @return The default inactive period for sessions.
*/
public int getInactiveInterval()
{
return m_defaultInactiveInterval;
}
/** Configuration: how often to check for inactive sessions (seconds). */
protected int m_checkEvery = 60;
/**
* Configuration: set how often to check for inactive sessions (seconds).
*
* @param value
* The how often to check for inactive sessions (seconds) value.
*/
public void setCheckEvery(String value)
{
try
{
m_checkEvery = Integer.parseInt(value);
}
catch (Exception t)
{
System.out.println(t);
}
}
/**********************************************************************************************************************************************************************************************************************************************************
* Init and Destroy
*********************************************************************************************************************************************************************************************************************************************************/
/**
* Final initialization, once all dependencies are set.
*/
public void init()
{
// start the maintenance thread
if (m_checkEvery > 0)
{
m_maintenance = new Maintenance();
m_maintenance.start();
}
// Salt generation 64 bits long
salt = new byte[8];
SecureRandom random;
try {
random = SecureRandom.getInstance("SHA1PRNG");
random.nextBytes(salt);
} catch (NoSuchAlgorithmException e) {
M_log.warn("Random number generator not available - using time randomness");
salt = String.valueOf(System.currentTimeMillis()).getBytes();
}
M_log.info("init(): interval: " + m_defaultInactiveInterval + " refresh: " + m_checkEvery);
}
/**
* Final cleanup.
*/
public void destroy()
{
if (m_maintenance != null)
{
m_maintenance.stop();
m_maintenance = null;
}
M_log.info("destroy()");
}
/**********************************************************************************************************************************************************************************************************************************************************
* Work interface methods: SessionManager
*********************************************************************************************************************************************************************************************************************************************************/
/**
* @inheritDoc
*/
public Session getSession(String sessionId)
{
MySession s = (MySession) m_sessions.get(sessionId);
return s;
}
public String makeSessionId(HttpServletRequest req, Principal principal)
{
MessageDigest sha;
String sessionId;
try {
sha = MessageDigest.getInstance("SHA-1");
sha.reset();
sha.update(principal.getName().getBytes("UTF-8"));
sha.update((byte) 0x0a);
- sha.update(req.getHeader("user-agent").getBytes("UTF-8"));
+ String ua = req.getHeader("user-agent");
+ if (ua != null) {
+ sha.update(ua.getBytes("UTF-8"));
+ }
sha.update(salt);
sessionId = byteArrayToHexStr(sha.digest());
} catch (NoSuchAlgorithmException e) {
// Fallback to new uuid rather than a non-hashed id
sessionId = idManager().createUuid();
} catch (UnsupportedEncodingException e) {
sessionId = idManager().createUuid();
}
return sessionId;
}
public List<Session> getSessions() {
return new ArrayList<Session>(m_sessions.values());
}
public void remove(String sessionId) {
m_sessions.remove(sessionId);
expirationTimeSuggestionMap.remove(sessionId);
}
/**
* Checks the current Tool ID to determine if this tool is marked for clustering.
*
* @return true if the tool is marked for clustering, false otherwise.
*/
public boolean isCurrentToolClusterable() {
ToolManager toolManager = toolManager();
Tool tool = null;
// ToolManager should exist. Protect against it being
// null and just log a message if it is.
if (toolManager != null) {
tool = toolManager.getCurrentTool();
// tool can be null, this is common during startup for example
if (tool != null) {
String toolId = tool.getId();
// if the tool exists, the toolid should. But protect and only
// log a message if it is null
if (toolId != null) {
return clusterableTools.contains(toolId);
} else {
M_log.error("SessionComponent.isCurrentToolClusterable(): toolId was null.");
}
}
} else {
M_log.error("SessionComponent.isCurrentToolClusterable(): toolManager was null.");
}
return false;
}
/**
* @inheritDoc
*/
public Session startSession()
{
String id = idManager().createUuid();
return startSession(id);
}
/**
* @inheritDoc
*/
public Session startSession(String id)
{
// create a non portable session object if this is a clustered environment
NonPortableSession nPS = new MyNonPortableSession();
// create a new MutableLong object representing the current time that both
// the Session and SessionManager can see.
MutableLong currentTime = currentTimeMutableLong();
// create a new session
Session s = new MySession(this,id,threadLocalManager(),idManager(),this,sessionListener,m_defaultInactiveInterval,nPS,currentTime);
// Place session into the main Session Storage, capture any old id
Session old = m_sessions.put(s.getId(), s);
// Place an entry in the expirationTimeSuggestionMap that corresponds to the entry in m_sessions
expirationTimeSuggestionMap.put(id, currentTime);
// check for id conflict
if (old != null)
{
M_log.warn("startSession: duplication id: " + s.getId());
}
return s;
}
protected MutableLong currentTimeMutableLong()
{
return new MutableLong(System.currentTimeMillis());
}
/**
* @inheritDoc
*/
public Session getCurrentSession()
{
Session rv = (Session) threadLocalManager().get(CURRENT_SESSION);
// if we don't have one already current, make one and bind it as current, but don't save it in our by-id table - let it just go away after the thread
if (rv == null)
{
String id = idManager().createUuid();
// create a non portable session object if this is a clustered environment
NonPortableSession nPS = new MyNonPortableSession();
rv = new MySession(this,id,threadLocalManager(),idManager(),this,sessionListener,m_defaultInactiveInterval,nPS,currentTimeMutableLong());
setCurrentSession(rv);
}
return rv;
}
/**
* @inheritDoc
*/
public String getCurrentSessionUserId()
{
Session s = (Session) threadLocalManager().get(CURRENT_SESSION);
if (s != null)
{
return s.getUserId();
}
return null;
}
/**
* @inheritDoc
*/
public ToolSession getCurrentToolSession()
{
return (ToolSession) threadLocalManager().get(CURRENT_TOOL_SESSION);
}
/**
* @inheritDoc
*/
public void setCurrentSession(Session s)
{
threadLocalManager().set(CURRENT_SESSION, s);
}
/**
* @inheritDoc
*/
public void setCurrentToolSession(ToolSession s)
{
threadLocalManager().set(CURRENT_TOOL_SESSION, s);
}
public String getClusterableTools() {
return StringUtils.collectionToCommaDelimitedString(clusterableTools);
// return clusterableTools;
}
public void setClusterableTools(String clusterableToolList) {
Set<?> newTools = StringUtils.commaDelimitedListToSet(clusterableToolList);
this.clusterableTools.clear();
for (Object o: newTools) {
if (o instanceof java.lang.String) {
this.clusterableTools.add((String)o);
} else {
M_log.error("SessionManager.setClusterableTools(String) unable to set value: "+o);
}
}
}
/**
* @inheritDoc
*/
public int getActiveUserCount(int secs)
{
Set<String> activeusers = new HashSet<String>(m_sessions.size());
long now = System.currentTimeMillis();
for (Iterator<Session> i = m_sessions.values().iterator(); i.hasNext();)
{
MySession s = (MySession) i.next();
if ((now - s.getLastAccessedTime()) < (secs * 1000))
{
activeusers.add(s.getUserId());
}
}
// Ignore admin and postmaster
activeusers.remove("admin");
activeusers.remove("postmaster");
activeusers.remove(null);
return activeusers.size();
}
/**********************************************************************************************************************************************************************************************************************************************************
* Maintenance
*********************************************************************************************************************************************************************************************************************************************************/
protected class Maintenance implements Runnable
{
/** My thread running my timeout checker. */
protected Thread m_maintenanceChecker = null;
/** Signal to the timeout checker to stop. */
protected boolean m_maintenanceCheckerStop = false;
/**
* Construct.
*/
public Maintenance()
{
}
/**
* Start the maintenance thread.
*/
public void start()
{
if (m_maintenanceChecker != null) return;
m_maintenanceChecker = new Thread(this, "Sakai.SessionComponent.Maintenance");
m_maintenanceCheckerStop = false;
m_maintenanceChecker.setDaemon(true);
m_maintenanceChecker.start();
}
/**
* Stop the maintenance thread.
*/
public void stop()
{
if (m_maintenanceChecker != null)
{
m_maintenanceCheckerStop = true;
m_maintenanceChecker.interrupt();
try
{
// wait for it to die
m_maintenanceChecker.join();
}
catch (InterruptedException ignore)
{
}
m_maintenanceChecker = null;
}
}
/**
* Run the maintenance thread. Every m_checkEvery seconds, check for expired sessions.
*/
public void run()
{
// since we might be running while the component manager is still being created and populated, such as at server
// startup, wait here for a complete component manager
ComponentManager.waitTillConfigured();
while (!m_maintenanceCheckerStop)
{
try
{
for (Map.Entry<String, MutableLong> entry: expirationTimeSuggestionMap.entrySet()) {
if (entry.getValue().longValue() < System.currentTimeMillis()) {
MySession s = (MySession)m_sessions.get(entry.getKey());
if (M_log.isDebugEnabled()) M_log.debug("checking session " + s.getId());
if (s.isInactive())
{
if (M_log.isDebugEnabled()) M_log.debug("invalidating session " + s.getId());
synchronized(s) {
s.invalidate();
}
}
}
}
}
catch (Exception e)
{
M_log.warn("run(): exception: " + e);
}
// cycle every REFRESH seconds
if (!m_maintenanceCheckerStop)
{
try
{
Thread.sleep(m_checkEvery * 1000L);
}
catch (Exception ignore)
{
}
}
}
}
}
public SessionAttributeListener getSessionListener() {
return sessionListener;
}
public void setSessionListener(SessionAttributeListener sessionListener) {
this.sessionListener = sessionListener;
}
private static String byteArrayToHexStr(byte[] data)
{
char[] chars = new char[data.length * 2];
for (int i = 0; i < data.length; i++)
{
byte current = data[i];
int hi = (current & 0xF0) >> 4;
int lo = current & 0x0F;
chars[2*i] = (char) (hi < 10 ? ('0' + hi) : ('A' + hi - 10));
chars[2*i+1] = (char) (lo < 10 ? ('0' + lo) : ('A' + lo - 10));
}
return new String(chars);
}
}
| true | false | null | null |
diff --git a/src/eu/cassandra/server/api/Runs.java b/src/eu/cassandra/server/api/Runs.java
index ae40a5f..055c2d0 100644
--- a/src/eu/cassandra/server/api/Runs.java
+++ b/src/eu/cassandra/server/api/Runs.java
@@ -1,289 +1,296 @@
/*
Copyright 2011-2013 The Cassandra Consortium (cassandra-fp7.eu)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package eu.cassandra.server.api;
import java.net.UnknownHostException;
+import java.text.SimpleDateFormat;
+import java.util.Calendar;
import java.util.HashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import javax.servlet.ServletContext;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import org.bson.types.ObjectId;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import com.mongodb.MongoException;
import com.mongodb.util.JSON;
import eu.cassandra.server.mongo.MongoActivities;
import eu.cassandra.server.mongo.MongoActivityModels;
import eu.cassandra.server.mongo.MongoAppliances;
import eu.cassandra.server.mongo.MongoConsumptionModels;
import eu.cassandra.server.mongo.MongoDemographics;
import eu.cassandra.server.mongo.MongoDistributions;
import eu.cassandra.server.mongo.MongoInstallations;
import eu.cassandra.server.mongo.MongoPersons;
import eu.cassandra.server.mongo.MongoProjects;
import eu.cassandra.server.mongo.MongoRuns;
import eu.cassandra.server.mongo.MongoScenarios;
import eu.cassandra.server.mongo.MongoSimParam;
import eu.cassandra.server.mongo.util.DBConn;
import eu.cassandra.server.mongo.util.PrettyJSONPrinter;
import eu.cassandra.sim.Simulation;
@Path("runs")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class Runs {
@javax.ws.rs.core.Context
ServletContext context;
/**
*
* Gets the scenarios under a project id
* @param message contains the project_id to search the related scenarios
* @return
*/
@GET
public String getRuns(@QueryParam("prj_id") String prj_id, @QueryParam("count") boolean count,
@Context HttpHeaders httpHeaders) {
return PrettyJSONPrinter.prettyPrint(new MongoRuns().getRuns(httpHeaders,prj_id,count));
}
/**
* Create a run.
* In order to create and start a run, we need to have the simulation
* parameter id passed as a JSON property via the POST request. After that
* the procedure goes as follows:
* <ol>
* <i>Create a database to hold the run documents and results (dbname same as run_id)</i>
* <i>Parse the smp_id from the JSON request</i>
* <i>From smp_id get scn_id</i>
* <i>From scn_id gather all scenario documents and create a full JSON scenario</i>
* <i>If the scenario is dynamic, instantiate as documents all the virtual installations</i>
* <i>Store the full scenario in a new MongoDB database</i>
* <i>Create thread with JSON scenario</i>
* <i>Run the thread</i>
* <i>Store the run document</i>
* </ol>
*/
@POST
public String createRun(String message) {
DBObject query = new BasicDBObject(); // A query
try {
// Create the new database
Mongo m = new Mongo("localhost");
ObjectId objid = new ObjectId();
String dbname = objid.toString();
DB db = m.getDB(dbname);
// Create the scenario document
DBObject scenario = new BasicDBObject();
// Simulation params
DBObject jsonMessage = (DBObject) JSON.parse(message);
String smp_id = (String)jsonMessage.get("smp_id");
query.put("_id", new ObjectId(smp_id));
DBObject simParams = DBConn.getConn().getCollection(MongoSimParam.COL_SIMPARAM).findOne(query);
if(simParams == null) {
return "{ \"success\": false, \"message\": \"Sim creation failed\", \"exception\": { \"error\": \"No simulation params found\" }}";
}
db.getCollection(MongoSimParam.COL_SIMPARAM).insert(simParams);
scenario.put("sim_params", simParams);
// Scenario
String scn_id = (String) simParams.get("scn_id");
query.put("_id", new ObjectId(scn_id));
DBObject scn = DBConn.getConn().getCollection(MongoScenarios.COL_SCENARIOS).findOne(query);
db.getCollection(MongoScenarios.COL_SCENARIOS).insert(scn);
scenario.put("scenario", scn);
// Project
String prj_id = (String)scn.get("project_id");
query.put("_id", new ObjectId(prj_id));
DBObject project = DBConn.getConn().getCollection(MongoProjects.COL_PROJECTS).findOne(query);
db.getCollection(MongoProjects.COL_PROJECTS).insert(project);
scenario.put("project", project);
// Demographics
query = new BasicDBObject();
query.put("scn_id", scn_id);
String setup = (String)scn.get("setup");
+ String name = (String)scn.get("name");
boolean isDynamic = setup.equalsIgnoreCase("dynamic");
if(isDynamic) {
DBObject demog = DBConn.getConn().getCollection(MongoDemographics.COL_DEMOGRAPHICS).findOne(query);
db.getCollection(MongoDemographics.COL_DEMOGRAPHICS).insert(demog);
scenario.put("demog", demog);
}
// Installations
query = new BasicDBObject();
query.put("scenario_id", scn_id);
DBCursor cursor = DBConn.getConn().getCollection(MongoInstallations.COL_INSTALLATIONS).find(query);
if(cursor.size() == 0) {
return "{ \"success\": false, \"message\": \"Sim creation failed\", \"exception\": { \"error\": \"No istallations found\" }}";
}
int countInst = 0;
while(cursor.hasNext()) {
countInst++;
DBObject obj = cursor.next();
if(!isDynamic) db.getCollection(MongoInstallations.COL_INSTALLATIONS).insert(obj);
// Persons
String inst_id = obj.get("_id").toString();
query = new BasicDBObject();
query.put("inst_id", inst_id);
DBCursor persons = DBConn.getConn().getCollection(MongoPersons.COL_PERSONS).find(query);
int personCount = 0;
while(persons.hasNext()) {
personCount++;
DBObject person = persons.next();
if(!isDynamic) db.getCollection(MongoPersons.COL_PERSONS).insert(person);
// Activities
String pers_id = person.get("_id").toString();
query = new BasicDBObject();
query.put("pers_id", pers_id);
DBCursor activities = DBConn.getConn().getCollection(MongoActivities.COL_ACTIVITIES).find(query);
int countAct = 0;
while(activities.hasNext()) {
countAct++;
DBObject activity = activities.next();
if(!isDynamic) db.getCollection(MongoActivities.COL_ACTIVITIES).insert(activity);
// Activity Models
String act_id = activity.get("_id").toString();
query = new BasicDBObject();
query.put("act_id", act_id);
DBCursor activityModels =
DBConn.getConn().getCollection(MongoActivityModels.COL_ACTMODELS).find(query);
int countActMod = 0;
while(activityModels.hasNext()) {
countActMod++;
DBObject activityModel = activityModels.next();
if(!isDynamic) db.getCollection(MongoActivityModels.COL_ACTMODELS).insert(activityModel);
// Duration distribution
String dur_id = activityModel.get("duration").toString();
query = new BasicDBObject();
query.put("_id", new ObjectId(dur_id));
DBObject durDist =
DBConn.getConn().getCollection(MongoDistributions.COL_DISTRIBUTIONS).findOne(query);
if(!isDynamic) db.getCollection(MongoDistributions.COL_DISTRIBUTIONS).insert(durDist);
activityModel.put("duration", durDist);
// Start time distribution
String start_id = activityModel.get("startTime").toString();
query = new BasicDBObject();
query.put("_id", new ObjectId(start_id));
DBObject startDist =
DBConn.getConn().getCollection(MongoDistributions.COL_DISTRIBUTIONS).findOne(query);
if(!isDynamic) db.getCollection(MongoDistributions.COL_DISTRIBUTIONS).insert(startDist);
activityModel.put("start", startDist);
// Repetitions distribution
String rep_id = activityModel.get("repeatsNrOfTime").toString();
query = new BasicDBObject();
query.put("_id", new ObjectId(rep_id));
DBObject repDist =
DBConn.getConn().getCollection(MongoDistributions.COL_DISTRIBUTIONS).findOne(query);
if(!isDynamic) db.getCollection(MongoDistributions.COL_DISTRIBUTIONS).insert(repDist);
activityModel.put("repetitions", repDist);
activity.put("actmod"+countActMod, activityModel);
}
activity.put("actmodcount", new Integer(countActMod));
person.put("activity"+countAct, activity);
}
person.put("activitycount", new Integer(countAct));
obj.put("person"+personCount, person);
}
obj.put("personcount", new Integer(personCount));
// Appliances
query = new BasicDBObject();
query.put("inst_id", inst_id);
DBCursor appliances = DBConn.getConn().getCollection(MongoAppliances.COL_APPLIANCES).find(query);
int countApps = 0;
while(appliances.hasNext()) {
countApps++;
DBObject appliance = appliances.next();
if(!isDynamic) db.getCollection(MongoAppliances.COL_APPLIANCES).insert(appliance);
// Consumption model
String app_id = appliance.get("_id").toString();
query = new BasicDBObject();
query.put("app_id", app_id);
DBObject consModel =
DBConn.getConn().getCollection(MongoConsumptionModels.COL_CONSMODELS).findOne(query);
if(!isDynamic) db.getCollection(MongoConsumptionModels.COL_CONSMODELS).insert(consModel);
appliance.put("consmod", consModel);
obj.put("app"+countApps, appliance);
}
obj.put("appcount", new Integer(countApps));
scenario.put("inst"+countInst,obj);
}
scenario.put("instcount", new Integer(countInst));
// Scenario building finished
HashMap<String,Future<?>> runs = (HashMap<String,Future<?>>)context.getAttribute("MY_RUNS");
Simulation sim = new Simulation(scenario.toString(), dbname);
sim.setup();
ExecutorService executor = (ExecutorService)context.getAttribute("MY_EXECUTOR");
Future<?> f = executor.submit(sim);
System.out.println(dbname);
runs.put(dbname, f);
BasicDBObject run = new BasicDBObject();
+ Calendar calendar = Calendar.getInstance();
+ SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmm");
+ String runName = "Run for " + name + " on " + sdf.format(calendar.getTime());
run.put("_id", objid);
+ run.put("name", runName);
run.put("started", System.currentTimeMillis());
run.put("ended", -1);
run.put("prj_id", prj_id);
run.put("percentage", 0);
DBConn.getConn().getCollection(MongoRuns.COL_RUNS).insert(run);
String returnMsg = "{ \"success\": true, \"message\": \"Sim creation successful\", \"data\": { \"run_id\": \"" + dbname + "\" } }";
System.out.println(returnMsg);
return returnMsg;
} catch (UnknownHostException | MongoException e1) {
String returnMsg = "{ \"success\": false, \"message\": \"Sim creation failed\", \"exception\": { \"hostMongoException\": \""+ e1.getMessage() + "\" } }";
System.out.println(returnMsg);
return returnMsg;
} catch(Exception e) {
String returnMsg = "{ \"success\": false, \"message\": \"Sim creation failed\", \"exception\": { \"generalException\": \"" + e.getMessage() + "\" } }";
System.out.println(returnMsg);
return returnMsg;
}
}
}
| false | false | null | null |
diff --git a/src/org/osm2world/core/world/modules/RoadModule.java b/src/org/osm2world/core/world/modules/RoadModule.java
index 0d17065..b8f3966 100644
--- a/src/org/osm2world/core/world/modules/RoadModule.java
+++ b/src/org/osm2world/core/world/modules/RoadModule.java
@@ -1,1797 +1,1798 @@
package org.osm2world.core.world.modules;
import static java.lang.Math.abs;
import static java.util.Arrays.asList;
import static java.util.Collections.reverse;
import static org.openstreetmap.josm.plugins.graphview.core.data.EmptyTagGroup.EMPTY_TAG_GROUP;
import static org.openstreetmap.josm.plugins.graphview.core.util.ValueStringParser.parseOsmDecimal;
import static org.osm2world.core.math.GeometryUtil.*;
import static org.osm2world.core.math.VectorXYZ.*;
import static org.osm2world.core.math.algorithms.TriangulationUtil.triangulate;
import static org.osm2world.core.target.common.material.Materials.*;
import static org.osm2world.core.world.modules.common.WorldModuleGeometryUtil.*;
import static org.osm2world.core.world.modules.common.WorldModuleParseUtil.*;
import static org.osm2world.core.world.modules.common.WorldModuleTexturingUtil.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.openstreetmap.josm.plugins.graphview.core.data.Tag;
import org.openstreetmap.josm.plugins.graphview.core.data.TagGroup;
import org.osm2world.core.map_data.data.MapArea;
import org.osm2world.core.map_data.data.MapData;
import org.osm2world.core.map_data.data.MapNode;
import org.osm2world.core.map_data.data.MapWaySegment;
import org.osm2world.core.map_elevation.data.GroundState;
import org.osm2world.core.map_elevation.data.NodeElevationProfile;
import org.osm2world.core.map_elevation.data.WaySegmentElevationProfile;
import org.osm2world.core.math.GeometryUtil;
import org.osm2world.core.math.PolygonXYZ;
import org.osm2world.core.math.SimplePolygonXZ;
import org.osm2world.core.math.TriangleXYZ;
import org.osm2world.core.math.TriangleXZ;
import org.osm2world.core.math.VectorXYZ;
import org.osm2world.core.math.VectorXZ;
import org.osm2world.core.target.RenderableToAllTargets;
import org.osm2world.core.target.Target;
import org.osm2world.core.target.common.material.Material;
import org.osm2world.core.target.common.material.Materials;
import org.osm2world.core.world.data.NodeWorldObject;
import org.osm2world.core.world.data.TerrainBoundaryWorldObject;
import org.osm2world.core.world.data.WaySegmentWorldObject;
import org.osm2world.core.world.modules.common.ConfigurableWorldModule;
import org.osm2world.core.world.modules.common.WorldModuleParseUtil;
import org.osm2world.core.world.network.AbstractNetworkWaySegmentWorldObject;
import org.osm2world.core.world.network.JunctionNodeWorldObject;
import org.osm2world.core.world.network.NetworkAreaWorldObject;
import org.osm2world.core.world.network.VisibleConnectorNodeWorldObject;
/**
* adds roads to the world
*/
public class RoadModule extends ConfigurableWorldModule {
@Override
public void applyTo(MapData grid) {
for (MapWaySegment line : grid.getMapWaySegments()) {
if (isRoad(line.getTags())) {
line.addRepresentation(new Road(line, line.getTags()));
}
}
for (MapArea area : grid.getMapAreas()) {
if (isRoad(area.getTags())) {
List<VectorXZ> coords = new ArrayList<VectorXZ>();
for (MapNode node : area.getBoundaryNodes()) {
coords.add(node.getPos());
}
coords.remove(coords.size()-1);
area.addRepresentation(new RoadArea(area));
}
}
for (MapNode node : grid.getMapNodes()) {
TagGroup tags = node.getOsmNode().tags;
List<Road> connectedRoads = getConnectedRoads(node, false);
if (connectedRoads.size() > 2) {
node.addRepresentation(new RoadJunction(node));
} else if (connectedRoads.size() == 2
&& "crossing".equals(tags.getValue("highway"))) {
node.addRepresentation(new RoadCrossingAtConnector(node));
} else if (connectedRoads.size() == 2) {
Road road1 = connectedRoads.get(0);
Road road2 = connectedRoads.get(1);
if (road1.getWidth() != road2.getWidth()
/* TODO: || lane layouts not identical */) {
node.addRepresentation(new RoadConnector(node));
}
}
}
}
private static boolean isRoad(TagGroup tags) {
if (tags.containsKey("highway")
&& !tags.contains("highway", "construction")
&& !tags.contains("highway", "proposed")) {
return true;
} else {
return tags.contains("railway", "platform")
|| tags.contains("leisure", "track");
}
}
private static boolean isSteps(TagGroup tags) {
return tags.contains(new Tag("highway","steps"));
}
private static boolean isPath(TagGroup tags) {
String highwayValue = tags.getValue("highway");
return "path".equals(highwayValue)
|| "footway".equals(highwayValue)
|| "cycleway".equals(highwayValue)
|| "bridleway".equals(highwayValue)
|| "steps".equals(highwayValue);
}
private static boolean isOneway(TagGroup tags) {
return tags.contains("oneway", "yes")
|| (!tags.contains("oneway", "no")
&& (tags.contains("highway", "motorway")
|| (tags.contains("highway", "motorway_link"))));
}
private static int getDefaultLanes(TagGroup tags) {
String highwayValue = tags.getValue("highway");
if (highwayValue == null
|| isPath(tags)
|| highwayValue.endsWith("_link")
|| "service".equals(highwayValue)
|| "track".equals(highwayValue)
|| "residential".equals(highwayValue)
- || "pedestrian".equals(highwayValue)) {
+ || "pedestrian".equals(highwayValue)
+ || "platform".equals(highwayValue)) {
return 1;
} else if ("motorway".equals(highwayValue)){
return 2;
} else {
return isOneway(tags) ? 1 : 2;
}
}
/**
* determines surface for a junction or connector/crossing.
* If the node has an explicit surface tag, this is evaluated.
* Otherwise, the result depends on the surface values of adjacent roads.
*/
private static Material getSurfaceForNode(MapNode node) {
Material surface = getSurfaceMaterial(
node.getTags().getValue("surface"), null);
if (surface == null) {
/* choose the surface of any adjacent road */
for (MapWaySegment segment : node.getConnectedWaySegments()) {
if (segment.getPrimaryRepresentation() instanceof Road) {
Road road = (Road)segment.getPrimaryRepresentation();
surface = road.getSurface();
break;
}
}
}
return surface;
}
private static Material getSurfaceForRoad(TagGroup tags,
Material defaultSurface) {
Material result;
if (tags.containsKey("tracktype")) {
if (tags.contains("tracktype", "grade1")) {
result = ASPHALT;
} else if (tags.contains("tracktype", "grade2")) {
result = GRAVEL;
} else {
result = EARTH;
}
} else {
result = defaultSurface;
}
return getSurfaceMaterial(tags.getValue("surface"), result);
}
private static Material getSurfaceMiddleForRoad(TagGroup tags,
Material defaultSurface) {
Material result;
if (tags.contains("tracktype", "grade4")
|| tags.contains("tracktype", "grade5")) {
result = TERRAIN_DEFAULT;
// ideally, this would be the terrain type surrounds the track...
} else {
result = defaultSurface;
}
result = getSurfaceMaterial(tags.getValue("surface:middle"), result);
if (result == GRASS) {
result = TERRAIN_DEFAULT;
}
return result;
}
/**
* returns all roads connected to a node
* @param requireLanes only include roads that are not paths and have lanes
*/
private static List<Road> getConnectedRoads(MapNode node,
boolean requireLanes) {
List<Road> connectedRoadsWithLanes = new ArrayList<Road>();
for (MapWaySegment segment : node.getConnectedWaySegments()) {
if (segment.getPrimaryRepresentation() instanceof Road) {
Road road = (Road)segment.getPrimaryRepresentation();
if (!requireLanes ||
(road.getLaneLayout() != null && !isPath(road.tags))) {
connectedRoadsWithLanes.add(road);
}
}
}
return connectedRoadsWithLanes;
}
/**
* find matching lane pairs
* (lanes that can be connected at a junction or connector)
*/
private static Map<Integer, Integer> findMatchingLanes(
List<Lane> lanes1, List<Lane> lanes2,
boolean isJunction, boolean isCrossing) {
Map<Integer, Integer> matches = new HashMap<Integer, Integer>();
/*
* iterate from inside to outside
* (only for connectors, where it will lead to desirable connections
* between straight motorcar lanes e.g. at highway exits)
*/
if (!isJunction) {
for (int laneI = 0; laneI < lanes1.size()
&& laneI < lanes2.size(); ++laneI) {
final Lane lane1 = lanes1.get(laneI);
final Lane lane2 = lanes2.get(laneI);
if (isCrossing && !lane1.type.isConnectableAtCrossings) {
continue;
} else if (isJunction && !lane1.type.isConnectableAtJunctions) {
continue;
}
if (lane2.type.equals(lane1.type)) {
matches.put(laneI, laneI);
}
}
}
/* iterate from outside to inside.
* Mostly intended to gather sidewalks and other non-car lanes. */
for (int laneI = 0; laneI < lanes1.size()
&& laneI < lanes2.size(); ++laneI) {
int lane1Index = lanes1.size() - 1 - laneI;
int lane2Index = lanes2.size() - 1 - laneI;
final Lane lane1 = lanes1.get(lane1Index);
final Lane lane2 = lanes2.get(lane2Index);
if (isCrossing && !lane1.type.isConnectableAtCrossings) {
continue;
} else if (isJunction && !lane1.type.isConnectableAtJunctions) {
continue;
}
if (matches.containsKey(lane1Index)
|| matches.containsKey(lane2Index)) {
continue;
}
if (lane2.type.equals(lane1.type)) {
matches.put(lane1Index, lane2Index);
}
}
return matches;
}
/**
* determines connected lanes at a junction, crossing or connector
*/
private static List<LaneConnection> buildLaneConnections(
MapNode node, boolean isJunction, boolean isCrossing) {
List<Road> roads = getConnectedRoads(node, true);
/* check whether the oneway special case applies */
if (isJunction) {
boolean allOneway = true;
int firstInboundIndex = -1;
for (int i = 0; i < roads.size(); i++) {
Road road = roads.get(i);
if (!isOneway(road.tags)) {
allOneway = false;
break;
}
if (firstInboundIndex == -1 && road.line.getEndNode() == node) {
firstInboundIndex = i;
}
}
if (firstInboundIndex != -1) {
// sort into inbound and outbound oneways
// (need to be sequential blocks in the road list)
List<Road> inboundOnewayRoads = new ArrayList<Road>();
List<Road> outboundOnewayRoads = new ArrayList<Road>();
int i = 0;
for (i = firstInboundIndex; i < roads.size(); i++) {
if (roads.get(i).line.getEndNode() != node) {
break; //not inbound
}
inboundOnewayRoads.add(roads.get(i));
}
reverse(inboundOnewayRoads);
for (/* continue previous loop */;
i % roads.size() != firstInboundIndex; i++) {
outboundOnewayRoads.add(roads.get(i % roads.size()));
}
if (allOneway) {
return buildLaneConnections_allOneway(node,
inboundOnewayRoads, outboundOnewayRoads);
}
}
}
/* apply normal treatment (not oneway-specific) */
List<LaneConnection> result = new ArrayList<LaneConnection>();
for (int i = 0; i < roads.size(); i++) {
final Road road1 = roads.get(i);
final Road road2 = roads.get(
(i+1) % roads.size());
addLaneConnectionsForRoadPair(result,
node, road1, road2,
isJunction, isCrossing);
}
return result;
}
/**
* builds lane connections at a junction of just oneway roads.
* Intended to handle motorway merges and splits well.
* Inbound and outbound roads must not be mixed,
* but build two separate continuous blocks instead.
*
* @param inboundOnewayRoadsLTR inbound roads, left to right
* @param outboundOnewayRoadsLTR outbound roads, left to right
*/
private static List<LaneConnection> buildLaneConnections_allOneway(
MapNode node, List<Road> inboundOnewayRoadsLTR,
List<Road> outboundOnewayRoadsLTR) {
List<Lane> inboundLanes = new ArrayList<Lane>();
List<Lane> outboundLanes = new ArrayList<Lane>();
for (Road road : inboundOnewayRoadsLTR) {
inboundLanes.addAll(road.getLaneLayout().getLanesLeftToRight());
}
for (Road road : outboundOnewayRoadsLTR) {
outboundLanes.addAll(road.getLaneLayout().getLanesLeftToRight());
}
Map<Integer, Integer> matches = findMatchingLanes(inboundLanes,
outboundLanes, false, false);
/* build connections */
List<LaneConnection> result = new ArrayList<RoadModule.LaneConnection>();
for (int lane1Index : matches.keySet()) {
final Lane lane1 = inboundLanes.get(lane1Index);
final Lane lane2 = outboundLanes.get(matches.get(lane1Index));
result.add(buildLaneConnection(lane1, lane2,
RoadPart.LEFT, //TODO: road part is not always the same
false, true));
}
return result;
}
/**
* determines connected lanes at a junction, crossing or connector
* for a pair of two of the junction's roads.
* Only connections between the left part of road1 with the right part of
* road2 will be taken into account.
*/
private static void addLaneConnectionsForRoadPair(
List<LaneConnection> result,
MapNode node, Road road1, Road road2,
boolean isJunction, boolean isCrossing) {
/* get some basic info about the roads */
final boolean isRoad1Inbound = road1.line.getEndNode() == node;
final boolean isRoad2Inbound = road2.line.getEndNode() == node;
final List<Lane> lanes1, lanes2;
lanes1 = road1.getLaneLayout().getLanes(
isRoad1Inbound ? RoadPart.LEFT : RoadPart.RIGHT);
lanes2 = road2.getLaneLayout().getLanes(
isRoad2Inbound ? RoadPart.RIGHT : RoadPart.LEFT);
/* determine which lanes are connected */
Map<Integer, Integer> matches =
findMatchingLanes(lanes1, lanes2, isJunction, isCrossing);
/* build the lane connections */
for (int lane1Index : matches.keySet()) {
final Lane lane1 = lanes1.get(lane1Index);
final Lane lane2 = lanes2.get(matches.get(lane1Index));
result.add(buildLaneConnection(lane1, lane2, RoadPart.LEFT,
!isRoad1Inbound, !isRoad2Inbound));
}
//TODO: connect "disappearing" lanes to a point on the other side
// or draw caps (only for connectors)
}
private static LaneConnection buildLaneConnection(
Lane lane1, Lane lane2, RoadPart roadPart,
boolean atLane1Start, boolean atLane2Start) {
List<VectorXYZ> leftLaneBorder = new ArrayList<VectorXYZ>();
leftLaneBorder.add(lane1.getBorderNode(
atLane1Start, atLane1Start));
leftLaneBorder.add(lane2.getBorderNode(
atLane2Start, !atLane2Start));
List<VectorXYZ> rightLaneBorder = new ArrayList<VectorXYZ>();
rightLaneBorder.add(lane1.getBorderNode(
atLane1Start, !atLane1Start));
rightLaneBorder.add(lane2.getBorderNode(
atLane2Start, atLane2Start));
return new LaneConnection(lane1.type, RoadPart.LEFT,
leftLaneBorder, rightLaneBorder);
}
/**
* representation for junctions between roads.
*/
public static class RoadJunction
extends JunctionNodeWorldObject
implements NodeWorldObject, RenderableToAllTargets,
TerrainBoundaryWorldObject {
public RoadJunction(MapNode node) {
super(node);
}
@Override
public void renderTo(Target<?> target) {
Material material = getSurfaceForNode(node);
Collection<TriangleXYZ> triangles = super.getTriangulation();
target.drawTriangles(material, triangles,
globalTexCoordLists(triangles, material, false));
/* connect some lanes such as sidewalks between adjacent roads */
List<LaneConnection> connections = buildLaneConnections(
node, true, false);
for (LaneConnection connection : connections) {
connection.renderTo(target);
}
}
@Override
public GroundState getGroundState() {
GroundState currentGroundState = null;
checkEachLine: {
for (MapWaySegment line : this.node.getConnectedWaySegments()) {
if (line.getPrimaryRepresentation() == null) continue;
GroundState lineGroundState = line.getPrimaryRepresentation().getGroundState();
if (currentGroundState == null) {
currentGroundState = lineGroundState;
} else if (currentGroundState != lineGroundState) {
currentGroundState = GroundState.ON;
break checkEachLine;
}
}
}
return currentGroundState;
}
}
/* TODO: crossings at junctions - when there is, e.g., a footway connecting to the road!
* (ideally, this would be implemented using more flexibly configurable
* junctions which can have "preferred" segments that influence
* the junction shape more/exclusively)
*/
/**
* visible connectors where a road changes width or lane layout
*/
public static class RoadConnector
extends VisibleConnectorNodeWorldObject
implements NodeWorldObject, RenderableToAllTargets,
TerrainBoundaryWorldObject {
private static final double MAX_CONNECTOR_LENGTH = 5;
public RoadConnector(MapNode node) {
super(node);
}
@Override
public float getLength() {
// length is at most a third of the shorter road segment's length
List<Road> roads = getConnectedRoads(node, false);
return (float)Math.min(Math.min(
roads.get(0).line.getLineSegment().getLength() / 3,
roads.get(1).line.getLineSegment().getLength() / 3),
MAX_CONNECTOR_LENGTH);
}
@Override
public void renderTo(Target<?> target) {
List<LaneConnection> connections = buildLaneConnections(
node, false, false);
/* render connections */
for (LaneConnection connection : connections) {
connection.renderTo(target);
}
/* render area not covered by connections */
//TODO: subtract area covered by connections
List<TriangleXZ> trianglesXZ = triangulate(getOutlinePolygonXZ(),
Collections.<SimplePolygonXZ>emptySet());
List<TriangleXYZ> trianglesXYZ = new ArrayList<TriangleXYZ>();
for (TriangleXZ triangle : trianglesXZ) {
trianglesXYZ.add(
triangle.makeCounterclockwise().xyz(
node.getElevationProfile().getEle()));
}
Material material = getSurfaceForNode(node);
target.drawTriangles(material, trianglesXYZ,
globalTexCoordLists(trianglesXYZ, material, false));
}
@Override
public GroundState getGroundState() {
GroundState currentGroundState = null;
checkEachLine: {
for (MapWaySegment line : this.node.getConnectedWaySegments()) {
if (line.getPrimaryRepresentation() == null) continue;
GroundState lineGroundState = line.getPrimaryRepresentation().getGroundState();
if (currentGroundState == null) {
currentGroundState = lineGroundState;
} else if (currentGroundState != lineGroundState) {
currentGroundState = GroundState.ON;
break checkEachLine;
}
}
}
return currentGroundState;
}
@Override
public double getClearingAbove(VectorXZ pos) {
return 0;
}
@Override
public double getClearingBelow(VectorXZ pos) {
return 0;
}
}
/**
* representation for crossings (zebra crossing etc.) on roads
*/
public static class RoadCrossingAtConnector
extends VisibleConnectorNodeWorldObject
implements NodeWorldObject, RenderableToAllTargets,
TerrainBoundaryWorldObject {
private static final float CROSSING_WIDTH = 3f;
public RoadCrossingAtConnector(MapNode node) {
super(node);
}
@Override
public float getLength() {
return parseWidth(node.getTags(), CROSSING_WIDTH);
}
@Override
public void renderTo(Target<?> target) {
NodeElevationProfile eleProfile = node.getElevationProfile();
VectorXYZ start = eleProfile.getWithEle(startPos);
VectorXYZ end = eleProfile.getWithEle(endPos);
/* draw crossing markings */
VectorXYZ startLines1 = eleProfile.getWithEle(
interpolateBetween(startPos, endPos, 0.1f));
VectorXYZ endLines1 = eleProfile.getWithEle(
interpolateBetween(startPos, endPos, 0.2f));
VectorXYZ startLines2 = eleProfile.getWithEle(
interpolateBetween(startPos, endPos, 0.8f));
VectorXYZ endLines2 = eleProfile.getWithEle(
interpolateBetween(startPos, endPos, 0.9f));
double halfStartWidth = startWidth * 0.5;
double halfEndWidth = endWidth * 0.5;
double halfStartLines1Width = interpolateValue(startLines1.xz(),
startPos, halfStartWidth, endPos, halfEndWidth);
double halfEndLines1Width = interpolateValue(endLines1.xz(),
startPos, halfStartWidth, endPos, halfEndWidth);
double halfStartLines2Width = interpolateValue(startLines2.xz(),
startPos, halfStartWidth, endPos, halfEndWidth);
double halfEndLines2Width = interpolateValue(endLines2.xz(),
startPos, halfStartWidth, endPos, halfEndWidth);
//TODO: don't always use halfStart/EndWith - you need to interpolate!
// area outside and inside lines
Material surface = getSurfaceForNode(node);
List<VectorXYZ> vs = asList(
start.subtract(cutVector.mult(halfStartWidth)),
start.add(cutVector.mult(halfStartWidth)),
startLines1.subtract(cutVector.mult(halfStartLines1Width)),
startLines1.add(cutVector.mult(halfStartLines1Width)));
target.drawTriangleStrip(surface, vs,
globalTexCoordLists(vs, surface, false));
vs = asList(
endLines1.subtract(cutVector.mult(halfEndLines1Width)),
endLines1.add(cutVector.mult(halfEndLines1Width)),
startLines2.subtract(cutVector.mult(halfStartLines2Width)),
startLines2.add(cutVector.mult(halfStartLines2Width)));
target.drawTriangleStrip(surface, vs,
globalTexCoordLists(vs, surface, false));
vs = asList(
endLines2.subtract(cutVector.mult(halfEndLines2Width)),
endLines2.add(cutVector.mult(halfEndLines2Width)),
end.subtract(cutVector.mult(halfEndWidth)),
end.add(cutVector.mult(halfEndWidth)));
target.drawTriangleStrip(surface, vs,
globalTexCoordLists(vs, surface, false));
// lines across road
vs = asList(
startLines1.subtract(cutVector.mult(halfStartLines1Width)),
startLines1.add(cutVector.mult(halfStartLines1Width)),
endLines1.subtract(cutVector.mult(halfEndLines1Width)),
endLines1.add(cutVector.mult(halfEndLines1Width)));
target.drawTriangleStrip(ROAD_MARKING, vs,
globalTexCoordLists(vs, ROAD_MARKING, false));
vs = asList(
startLines2.subtract(cutVector.mult(halfStartLines2Width)),
startLines2.add(cutVector.mult(halfStartLines2Width)),
endLines2.subtract(cutVector.mult(halfEndLines2Width)),
endLines2.add(cutVector.mult(halfEndLines2Width)));
target.drawTriangleStrip(ROAD_MARKING, vs,
globalTexCoordLists(vs, ROAD_MARKING, false));
/* draw lane connections */
List<LaneConnection> connections = buildLaneConnections(
node, false, true);
for (LaneConnection connection : connections) {
connection.renderTo(target);
}
}
@Override
public GroundState getGroundState() {
GroundState currentGroundState = null;
checkEachLine: {
for (MapWaySegment line : this.node.getConnectedWaySegments()) {
if (line.getPrimaryRepresentation() == null) continue;
GroundState lineGroundState = line.getPrimaryRepresentation().getGroundState();
if (currentGroundState == null) {
currentGroundState = lineGroundState;
} else if (currentGroundState != lineGroundState) {
currentGroundState = GroundState.ON;
break checkEachLine;
}
}
}
return currentGroundState;
}
@Override
public double getClearingAbove(VectorXZ pos) {
return 0;
}
@Override
public double getClearingBelow(VectorXZ pos) {
return 0;
}
}
/** representation of a road */
public static class Road
extends AbstractNetworkWaySegmentWorldObject
implements WaySegmentWorldObject, RenderableToAllTargets,
TerrainBoundaryWorldObject {
protected static final float DEFAULT_LANE_WIDTH = 3.5f;
protected static final float DEFAULT_ROAD_CLEARING = 5;
protected static final float DEFAULT_PATH_CLEARING = 2;
protected static final List<VectorXYZ> HANDRAIL_SHAPE = asList(
new VectorXYZ(-0.02f, -0.05f, 0), new VectorXYZ(-0.02f, 0f, 0),
new VectorXYZ(+0.02f, 0f, 0), new VectorXYZ(+0.02f, -0.05f, 0));
public final LaneLayout laneLayout;
public final float width;
final private TagGroup tags;
final public VectorXZ startCoord, endCoord;
final private boolean steps;
public Road(MapWaySegment line, TagGroup tags) {
super(line);
this.tags = tags;
this.startCoord = line.getStartNode().getPos();
this.endCoord = line.getEndNode().getPos();
this.steps = isSteps(tags);
if (steps) {
this.laneLayout = null;
this.width = parseWidth(tags, 1.0f);
} else {
this.laneLayout = buildBasicLaneLayout();
this.width = parseWidth(tags, (float)calculateFallbackWidth());
laneLayout.setCalculatedValues(width);
}
}
/**
* creates a lane layout from several basic tags.
*/
private LaneLayout buildBasicLaneLayout() {
boolean isOneway = isOneway(tags);
/* determine which lanes exist */
String divider = tags.getValue("divider");
String sidewalk = tags.containsKey("sidewalk") ?
tags.getValue("sidewalk") : tags.getValue("footway");
boolean leftSidewalk = "left".equals(sidewalk)
|| "both".equals(sidewalk);
boolean rightSidewalk = "right".equals(sidewalk)
|| "both".equals(sidewalk);
boolean leftCycleway = tags.contains("cycleway:left", "lane")
|| tags.contains("cycleway", "lane");
boolean rightCycleway = tags.contains("cycleway:right", "lane")
|| tags.contains("cycleway", "lane");
Float lanes = null;
if (tags.containsKey("lanes")) {
lanes = parseOsmDecimal(tags.getValue("lanes"), false);
}
int vehicleLaneCount = (lanes != null)
? (int)(float)lanes : getDefaultLanes(tags);
/* create the layout */
LaneLayout layout = new LaneLayout();
for (int i = 0; i < vehicleLaneCount; ++ i) {
RoadPart roadPart = (i%2 == 0 || isOneway)
? RoadPart.RIGHT : RoadPart.LEFT;
if (i == 1 && !isOneway) {
//central divider
LaneType dividerType = DASHED_LINE;
if ("dashed_line".equals(divider)) {
dividerType = DASHED_LINE;
} else if ("solid_line".equals(divider)) {
dividerType = SOLID_LINE;
} else if ("no".equals(divider)) {
dividerType = null;
}
if (dividerType != null) {
layout.getLanes(roadPart).add(new Lane(this,
dividerType, roadPart, EMPTY_TAG_GROUP));
}
} else if (i >= 1) {
//other divider
layout.getLanes(roadPart).add(new Lane(this,
DASHED_LINE, roadPart, EMPTY_TAG_GROUP));
}
//lane itself
layout.getLanes(roadPart).add(new Lane(this,
VEHICLE_LANE, roadPart, EMPTY_TAG_GROUP));
}
if (leftCycleway) {
layout.leftLanes.add(new Lane(this,
CYCLEWAY, RoadPart.LEFT, EMPTY_TAG_GROUP));
}
if (rightCycleway) {
layout.rightLanes.add(new Lane(this,
CYCLEWAY, RoadPart.RIGHT, EMPTY_TAG_GROUP));
}
if (leftSidewalk) {
layout.leftLanes.add(new Lane(this,
KERB, RoadPart.LEFT, EMPTY_TAG_GROUP));
layout.leftLanes.add(new Lane(this,
SIDEWALK, RoadPart.LEFT, EMPTY_TAG_GROUP));
}
if (rightSidewalk) {
layout.rightLanes.add(new Lane(this,
KERB, RoadPart.RIGHT, EMPTY_TAG_GROUP));
layout.rightLanes.add(new Lane(this,
SIDEWALK, RoadPart.RIGHT, EMPTY_TAG_GROUP));
}
return layout;
}
private double calculateFallbackWidth() {
String highwayValue = tags.getValue("highway");
double width = 0;
boolean ignoreVehicleLanes = false;
/* guess the combined width of all vehicle lanes */
if (!tags.containsKey("lanes") && !tags.containsKey("divider")) {
ignoreVehicleLanes = true;
if (isPath(tags)) {
width = 1f;
}
else if ("service".equals(highwayValue)
|| "track".equals(highwayValue)) {
if (tags.contains("service", "parking_aisle")) {
width = DEFAULT_LANE_WIDTH * 0.8;
} else {
width = DEFAULT_LANE_WIDTH;
}
} else if ("primary".equals(highwayValue) || "secondary".equals(highwayValue)) {
width = 2 * DEFAULT_LANE_WIDTH;
} else if ("motorway".equals(highwayValue)) {
width = 2.5f * DEFAULT_LANE_WIDTH;
}
else if (tags.containsKey("oneway") && !tags.getValue("oneway").equals("no")) {
width = DEFAULT_LANE_WIDTH;
}
else {
width = 4;
}
}
/* calculate sum of lane widths */
for (Lane lane : laneLayout.getLanesLeftToRight()) {
if (lane.type == VEHICLE_LANE && ignoreVehicleLanes) continue;
if (lane.getAbsoluteWidth() == null) {
width += DEFAULT_LANE_WIDTH;
} else {
width += lane.getAbsoluteWidth();
}
}
return width;
}
@Override
public float getWidth() {
return width;
}
public Material getSurface() {
return getSurfaceForRoad(tags, ASPHALT);
}
public LaneLayout getLaneLayout() {
return laneLayout;
}
private void renderStepsTo(Target<?> target) {
WaySegmentElevationProfile elevationProfile = line.getElevationProfile();
final VectorXZ startWithOffset = getStartPosition();
final VectorXZ endWithOffset = getEndPosition();
List<VectorXYZ> leftOutline = getOutline(false);
List<VectorXYZ> rightOutline = getOutline(true);
double lineLength = VectorXZ.distance (
line.getStartNode().getPos(), line.getEndNode().getPos());
/* render ground first (so gaps between the steps look better) */
List<VectorXYZ> vs = createTriangleStripBetween(
leftOutline, rightOutline);
target.drawTriangleStrip(ASPHALT, vs,
globalTexCoordLists(vs, ASPHALT, false));
/* determine the length of each individual step */
float stepLength = 0.3f;
if (tags.containsKey("step_count")) {
try {
int stepCount = Integer.parseInt(tags.getValue("step_count"));
stepLength = (float)lineLength / stepCount;
} catch (NumberFormatException e) { /* don't overwrite default length */ }
}
/* locate the position on the line at the beginning/end of each step
* (positions on the line spaced by step length),
* interpolate heights between adjacent points with elevation */
List<VectorXZ> stepBorderPositionsXZ =
GeometryUtil.equallyDistributePointsAlong(
stepLength, true, startWithOffset, endWithOffset);
List<VectorXYZ> stepBorderPositions = new ArrayList<VectorXYZ>();
for (VectorXZ posXZ : stepBorderPositionsXZ) {
VectorXYZ posXYZ = posXZ.xyz(elevationProfile.getEleAt(posXZ));
stepBorderPositions.add(posXYZ);
}
/* draw steps */
for (int step = 0; step < stepBorderPositions.size() - 1; step++) {
VectorXYZ frontCenter = stepBorderPositions.get(step);
VectorXYZ backCenter = stepBorderPositions.get(step+1);
double height = abs(frontCenter.y - backCenter.y);
VectorXYZ center = (frontCenter.add(backCenter)).mult(0.5);
center = center.subtract(Y_UNIT.mult(0.5 * height));
VectorXZ faceDirection = line.getDirection();
if (frontCenter.y < backCenter.y) {
//invert if upwards
faceDirection = faceDirection.invert();
}
target.drawBox(Materials.STEPS_DEFAULT,
center, faceDirection,
height, width, backCenter.distanceToXZ(frontCenter));
}
/* draw handrails */
List<List<VectorXYZ>> handrailFootprints =
new ArrayList<List<VectorXYZ>>();
if (line.getTags().contains("handrail:left","yes")) {
handrailFootprints.add(leftOutline);
}
if (line.getTags().contains("handrail:right","yes")) {
handrailFootprints.add(rightOutline);
}
int centerHandrails = 0;
if (line.getTags().contains("handrail:center","yes")) {
centerHandrails = 1;
} else if (line.getTags().containsKey("handrail:center")) {
try {
centerHandrails = Integer.parseInt(
line.getTags().getValue("handrail:center"));
} catch (NumberFormatException e) {}
}
for (int i = 0; i < centerHandrails; i++) {
handrailFootprints.add(createLineBetween(
leftOutline, rightOutline,
(i + 1.0f) / (centerHandrails + 1)));
}
for (List<VectorXYZ> handrailFootprint : handrailFootprints) {
List<VectorXYZ> handrailLine = new ArrayList<VectorXYZ>();
for (VectorXYZ v : handrailFootprint) {
handrailLine.add(v.y(v.y + 1));
}
List<List<VectorXYZ>> strips = createShapeExtrusionAlong(
HANDRAIL_SHAPE, handrailLine,
Collections.nCopies(handrailLine.size(), VectorXYZ.Y_UNIT));
for (List<VectorXYZ> strip : strips) {
target.drawTriangleStrip(HANDRAIL_DEFAULT, strip,
wallTexCoordLists(strip, HANDRAIL_DEFAULT));
}
target.drawColumn(HANDRAIL_DEFAULT, 4,
handrailFootprint.get(0),
1, 0.03, 0.03, false, true);
target.drawColumn(HANDRAIL_DEFAULT, 4,
handrailFootprint.get(handrailFootprint.size()-1),
1, 0.03, 0.03, false, true);
}
}
private void renderLanesTo(Target<?> target) {
List<Lane> lanesLeftToRight = laneLayout.getLanesLeftToRight();
/* draw lanes themselves */
for (Lane lane : lanesLeftToRight) {
lane.renderTo(target);
}
/* close height gaps at left and right border of the road */
Lane firstLane = lanesLeftToRight.get(0);
Lane lastLane = lanesLeftToRight.get(lanesLeftToRight.size() - 1);
if (firstLane.getHeightAboveRoad() > 0) {
List<VectorXYZ> vs = createTriangleStripBetween(
getOutline(false),
addYList(getOutline(false), firstLane.getHeightAboveRoad()));
target.drawTriangleStrip(getSurface(), vs,
wallTexCoordLists(vs, getSurface()));
}
if (lastLane.getHeightAboveRoad() > 0) {
List<VectorXYZ> vs = createTriangleStripBetween(
addYList(getOutline(true), lastLane.getHeightAboveRoad()),
getOutline(true));
target.drawTriangleStrip(getSurface(), vs,
wallTexCoordLists(vs, getSurface()));
}
}
@Override
public void renderTo(Target<?> target) {
if (steps) {
renderStepsTo(target);
} else {
renderLanesTo(target);
}
}
@Override
public GroundState getGroundState() {
if (BridgeModule.isBridge(tags)) {
return GroundState.ABOVE;
} else if (TunnelModule.isTunnel(tags)) {
return GroundState.BELOW;
} else {
return GroundState.ON;
}
}
@Override
public double getClearingAbove(VectorXZ pos) {
return WorldModuleParseUtil.parseClearing(tags,
isPath(tags) ? DEFAULT_PATH_CLEARING : DEFAULT_ROAD_CLEARING);
}
@Override
public double getClearingBelow(VectorXZ pos) {
return 0;
}
}
public static class RoadArea extends NetworkAreaWorldObject
implements RenderableToAllTargets, TerrainBoundaryWorldObject {
private static final float DEFAULT_CLEARING = 5f;
public RoadArea(MapArea area) {
super(area);
}
@Override
public void renderTo(Target<?> target) {
String surface = area.getTags().getValue("surface");
Material material = getSurfaceMaterial(surface, ASPHALT);
Collection<TriangleXYZ> triangles = getTriangulation();
target.drawTriangles(material, triangles,
globalTexCoordLists(triangles, material, false));
}
@Override
public GroundState getGroundState() {
if (BridgeModule.isBridge(area.getTags())) {
return GroundState.ABOVE;
} else if (TunnelModule.isTunnel(area.getTags())) {
return GroundState.BELOW;
} else {
return GroundState.ON;
}
}
@Override
public double getClearingAbove(VectorXZ pos) {
return WorldModuleParseUtil.parseClearing(
area.getTags(), DEFAULT_CLEARING);
}
@Override
public double getClearingBelow(VectorXZ pos) {
return 0;
}
}
private static enum RoadPart {
LEFT, RIGHT
//TODO add CENTRE lane support
}
private static class LaneLayout {
public final List<Lane> leftLanes = new ArrayList<Lane>();
public final List<Lane> rightLanes = new ArrayList<Lane>();
public List<Lane> getLanes(RoadPart roadPart) {
switch (roadPart) {
case LEFT: return leftLanes;
case RIGHT: return rightLanes;
default: throw new Error("unhandled road part value");
}
}
public List<Lane> getLanesLeftToRight() {
List<Lane> result = new ArrayList<Lane>();
result.addAll(leftLanes);
Collections.reverse(result);
result.addAll(rightLanes);
return result;
}
/**
* calculates and sets all lane attributes
* that are not known during lane creation
*/
public void setCalculatedValues(double totalRoadWidth) {
/* determine width of lanes without explicitly assigned width */
int lanesWithImplicitWidth = 0;
double remainingWidth = totalRoadWidth;
for (RoadPart part : RoadPart.values()) {
for (Lane lane : getLanes(part)) {
if (lane.getAbsoluteWidth() == null) {
lanesWithImplicitWidth += 1;
} else {
remainingWidth -= lane.getAbsoluteWidth();
}
}
}
double implicitLaneWidth = remainingWidth / lanesWithImplicitWidth;
/* calculate a factor to reduce all lanes' width
* if the sum of their widths would otherwise
* be larger than that of the road */
double laneWidthScaling = 1.0;
if (remainingWidth < 0) {
double widthSum = totalRoadWidth - remainingWidth;
implicitLaneWidth = 1;
widthSum += lanesWithImplicitWidth * implicitLaneWidth;
laneWidthScaling = totalRoadWidth / widthSum;
}
/* assign values */
for (RoadPart part : asList(RoadPart.LEFT, RoadPart.RIGHT)) {
double heightAboveRoad = 0;
for (Lane lane : getLanes(part)) {
double relativeWidth;
if (lane.getAbsoluteWidth() == null) {
relativeWidth = laneWidthScaling *
(implicitLaneWidth / totalRoadWidth);
} else {
relativeWidth = laneWidthScaling *
(lane.getAbsoluteWidth() / totalRoadWidth);
}
lane.setCalculatedValues1(relativeWidth, heightAboveRoad);
heightAboveRoad += lane.getHeightOffset();
}
}
/* calculate relative lane positions based on relative width */
double accumulatedWidth = 0;
for (Lane lane : getLanesLeftToRight()) {
double relativePositionLeft = accumulatedWidth;
accumulatedWidth += lane.getRelativeWidth();
double relativePositionRight = accumulatedWidth;
lane.setCalculatedValues2(relativePositionLeft,
relativePositionRight);
}
}
/**
* calculates and sets all lane attributes
* that are not known during lane creation
*/
}
/**
* a lane or lane divider of the road segment.
*
* Field values depend on neighboring lanes and are therefore calculated
* and defined in two phases. Results are then set using
* {@link #setCalculatedValues1(double, double)} and
* {@link #setCalculatedValues2(double, double)}, respectively.
*/
private static final class Lane implements RenderableToAllTargets {
public final Road road;
public final LaneType type;
public final RoadPart roadPart;
public final TagGroup laneTags;
private int phase = 0;
private double relativeWidth;
private double heightAboveRoad;
private double relativePositionLeft;
private double relativePositionRight;
public Lane(Road road, LaneType type, RoadPart roadPart,
TagGroup laneTags) {
this.road = road;
this.type = type;
this.roadPart = roadPart;
this.laneTags = laneTags;
}
/** returns width in meters or null for undefined width */
public Double getAbsoluteWidth() {
return type.getAbsoluteWidth(road.tags, laneTags);
}
/** returns height increase relative to inner neighbor */
public double getHeightOffset() {
return type.getHeightOffset(road.tags, laneTags);
}
public void setCalculatedValues1(double relativeWidth,
double heightAboveRoad) {
assert phase == 0;
this.relativeWidth = relativeWidth;
this.heightAboveRoad = heightAboveRoad;
phase = 1;
}
public void setCalculatedValues2(double relativePositionLeft,
double relativePositionRight) {
assert phase == 1;
this.relativePositionLeft = relativePositionLeft;
this.relativePositionRight = relativePositionRight;
phase = 2;
}
public Double getRelativeWidth() {
assert phase > 0;
return relativeWidth;
}
public double getHeightAboveRoad() {
assert phase > 0;
return heightAboveRoad;
}
/**
* provides access to the first and last node
* of the lane's left and right border
*/
public VectorXYZ getBorderNode(boolean start, boolean right) {
assert phase > 1;
double relativePosition = right
? relativePositionRight
: relativePositionLeft;
VectorXYZ roadPoint = road.getPointOnCut(start, relativePosition);
return roadPoint.add(0, getHeightAboveRoad(), 0);
}
public void renderTo(Target<?> target) {
assert phase > 1;
List<VectorXYZ> leftLaneBorder = createLineBetween(
road.getOutline(false), road.getOutline(true),
(float)relativePositionLeft);
leftLaneBorder = addYList(leftLaneBorder, getHeightAboveRoad());
List<VectorXYZ> rightLaneBorder = createLineBetween(
road.getOutline(false), road.getOutline(true),
(float)relativePositionRight);
rightLaneBorder = addYList(rightLaneBorder, getHeightAboveRoad());
type.render(target, roadPart, road.tags, laneTags,
leftLaneBorder, rightLaneBorder);
}
@Override
public String toString() {
return "{" + type + ", " + roadPart + "}";
}
}
/**
* a connection between two lanes (e.g. at a junction)
*/
private static class LaneConnection implements RenderableToAllTargets {
public final LaneType type;
public final RoadPart roadPart;
private final List<VectorXYZ> leftBorder;
private final List<VectorXYZ> rightBorder;
private LaneConnection(LaneType type, RoadPart roadPart,
List<VectorXYZ> leftBorder, List<VectorXYZ> rightBorder) {
this.type = type;
this.roadPart = roadPart;
this.leftBorder = leftBorder;
this.rightBorder = rightBorder;
}
/**
* returns the outline of this connection.
* For determining the total terrain covered by junctions and connectors.
*/
public PolygonXYZ getOutline() {
List<VectorXYZ> outline = new ArrayList<VectorXYZ>();
outline.addAll(leftBorder);
List<VectorXYZ>rOutline = new ArrayList<VectorXYZ>(rightBorder);
Collections.reverse(rOutline);
outline.addAll(rOutline);
outline.add(outline.get(0));
return new PolygonXYZ(outline);
}
public void renderTo(Target<?> target) {
type.render(target, roadPart, EMPTY_TAG_GROUP, EMPTY_TAG_GROUP,
leftBorder, rightBorder);
}
}
/**
* a type of lanes. Determines visual appearance,
* and contains the intelligence for evaluating type-specific tags.
*/
private static abstract class LaneType {
private final String typeName;
public final boolean isConnectableAtCrossings;
public final boolean isConnectableAtJunctions;
private LaneType(String typeName,
boolean isConnectableAtCrossings,
boolean isConnectableAtJunctions) {
this.typeName = typeName;
this.isConnectableAtCrossings = isConnectableAtCrossings;
this.isConnectableAtJunctions = isConnectableAtJunctions;
}
public abstract void render(Target<?> target, RoadPart roadPart,
TagGroup roadTags, TagGroup laneTags,
List<VectorXYZ> leftLaneBorder,
List<VectorXYZ> rightLaneBorder);
public abstract Double getAbsoluteWidth(
TagGroup roadTags, TagGroup laneTags);
public abstract double getHeightOffset(
TagGroup roadTags, TagGroup laneTags);
@Override
public String toString() {
return typeName;
}
}
private static abstract class FlatTexturedLane extends LaneType {
private FlatTexturedLane(String typeName,
boolean isConnectableAtCrossings,
boolean isConnectableAtJunctions) {
super(typeName, isConnectableAtCrossings, isConnectableAtJunctions);
}
@Override
public void render(Target<?> target, RoadPart roadPart,
TagGroup roadTags, TagGroup laneTags,
List<VectorXYZ> leftLaneBorder,
List<VectorXYZ> rightLaneBorder) {
Material surface = getSurface(roadTags, laneTags);
Material surfaceMiddle = getSurfaceMiddle(roadTags, laneTags);
if (surfaceMiddle == null || surfaceMiddle.equals(surface)) {
List<VectorXYZ> vs = createTriangleStripBetween(
leftLaneBorder, rightLaneBorder);
target.drawTriangleStrip(surface, vs,
globalTexCoordLists(vs, surface, false));
} else {
List<VectorXYZ> leftMiddleBorder =
createLineBetween(leftLaneBorder, rightLaneBorder, 0.3f);
List<VectorXYZ> rightMiddleBorder =
createLineBetween(leftLaneBorder, rightLaneBorder, 0.7f);
List<VectorXYZ> vsLeft = createTriangleStripBetween(
leftLaneBorder, leftMiddleBorder);
List<VectorXYZ> vsMiddle = createTriangleStripBetween(
leftMiddleBorder, rightMiddleBorder);
List<VectorXYZ> vsRight = createTriangleStripBetween(
rightMiddleBorder, rightLaneBorder);
target.drawTriangleStrip(surface, vsLeft,
globalTexCoordLists(vsLeft, surface, false));
target.drawTriangleStrip(surfaceMiddle, vsMiddle,
globalTexCoordLists(vsMiddle, surfaceMiddle, false));
target.drawTriangleStrip(surface, vsRight,
globalTexCoordLists(vsRight, surface, false));
}
}
@Override
public double getHeightOffset(TagGroup roadTags, TagGroup laneTags) {
return 0;
}
protected Material getSurface(TagGroup roadTags, TagGroup laneTags) {
return getSurfaceMaterial(laneTags.getValue("surface"),
getSurfaceForRoad(roadTags, ASPHALT));
}
protected Material getSurfaceMiddle(TagGroup roadTags, TagGroup laneTags) {
return getSurfaceMaterial(laneTags.getValue("surface:middle"),
getSurfaceMiddleForRoad(roadTags, null));
}
};
private static final LaneType VEHICLE_LANE = new FlatTexturedLane(
"VEHICLE_LANE", false, false) {
public Double getAbsoluteWidth(TagGroup roadTags, TagGroup laneTags) {
return null;
};
};
private static final LaneType CYCLEWAY = new FlatTexturedLane(
"CYCLEWAY", false, false) {
public Double getAbsoluteWidth(TagGroup roadTags, TagGroup laneTags) {
return (double)parseWidth(laneTags, 0.5f);
};
@Override
protected Material getSurface(TagGroup roadTags, TagGroup laneTags) {
Material material = super.getSurface(roadTags, laneTags);
if (material == ASPHALT) return RED_ROAD_MARKING;
else return material;
};
};
private static final LaneType SIDEWALK = new FlatTexturedLane(
"SIDEWALK", true, true) {
public Double getAbsoluteWidth(TagGroup roadTags, TagGroup laneTags) {
return (double)parseWidth(laneTags, 1.0f);
};
};
private static final LaneType SOLID_LINE = new FlatTexturedLane(
"SOLID_LINE", false, false) {
@Override
public Double getAbsoluteWidth(TagGroup roadTags, TagGroup laneTags) {
return (double)parseWidth(laneTags, 0.1f);
}
@Override
protected Material getSurface(TagGroup roadTags, TagGroup laneTags) {
return ROAD_MARKING;
}
};
private static final LaneType DASHED_LINE = new FlatTexturedLane(
"DASHED_LINE", false, false) {
@Override
public Double getAbsoluteWidth(TagGroup roadTags, TagGroup laneTags) {
return (double)parseWidth(laneTags, 0.1f);
}
@Override
protected Material getSurface(TagGroup roadTags, TagGroup laneTags) {
return ROAD_MARKING;
//TODO: use a dashed texture instead
}
};
private static final LaneType KERB = new LaneType(
"KERB", true, true) {
@Override
public void render(Target<?> target, RoadPart roadPart,
TagGroup roadTags, TagGroup laneTags,
List<VectorXYZ> leftLaneBorder,
List<VectorXYZ> rightLaneBorder) {
List<VectorXYZ> border1, border2, border3;
double height = getHeightOffset(roadTags, laneTags);
if (roadPart == RoadPart.LEFT) {
border1 = addYList(leftLaneBorder, height);
border2 = addYList(rightLaneBorder, height);
border3 = rightLaneBorder;
} else {
border1 = leftLaneBorder;
border2 = addYList(leftLaneBorder, height);
border3 = addYList(rightLaneBorder, height);
}
List<VectorXYZ> vs1_2 = createTriangleStripBetween(
border1, border2);
target.drawTriangleStrip(Materials.KERB, vs1_2,
wallTexCoordLists(vs1_2, Materials.KERB));
List<VectorXYZ> vs2_3 = createTriangleStripBetween(
border2, border3);
target.drawTriangleStrip(Materials.KERB, vs2_3,
wallTexCoordLists(vs2_3, Materials.KERB));
}
@Override
public Double getAbsoluteWidth(TagGroup roadTags, TagGroup laneTags) {
return (double)parseWidth(laneTags, 0.15f);
}
@Override
public double getHeightOffset(TagGroup roadTags, TagGroup laneTags) {
return (double)parseHeight(laneTags, 0.12f);
}
};
}
| true | false | null | null |
diff --git a/src/edu/msu/cse/cse450/Test.java b/src/edu/msu/cse/cse450/Test.java
new file mode 100644
index 0000000..a6053dd
--- /dev/null
+++ b/src/edu/msu/cse/cse450/Test.java
@@ -0,0 +1,30 @@
+package edu.msu.cse.cse450;
+
+import org.antlr.runtime.*;
+
+public class Test {
+ public static void main(String[] args) throws Exception {
+ // create a CharStream that reads from standard input
+ ANTLRInputStream input = new ANTLRInputStream(System.in);
+
+ // create a lexer that feeds off of input CharStream
+ LogoTokensLexer lexer = new LogoTokensLexer(input);
+
+ // create a buffer of tokens pulled from the lexer
+ CommonTokenStream tokens = new CommonTokenStream(lexer);
+
+ // create a parser that feeds off the tokens buffer
+ LogoTokensParser parser = new LogoTokensParser(tokens);
+
+ // begin parsing at rule program
+ parser.program();
+
+ System.out.println("COMMANDS: " + lexer.commandCount);
+ System.out.println("IDS: " + lexer.idCount);
+ System.out.println("NUMBERS: " + lexer.numberCount);
+ System.out.println("MATHOPS: " + lexer.mathopCount);
+ System.out.println("REFOPS: " + lexer.refopCount);
+ System.out.println("NEWLINES: " + lexer.newlineCount);
+ System.out.println("COMMENTS: " + lexer.commentCount);
+ }
+}
| true | false | null | null |
diff --git a/framework/src/org/apache/cordova/Echo.java b/framework/src/org/apache/cordova/Echo.java
index 78146e79..5f1fed66 100644
--- a/framework/src/org/apache/cordova/Echo.java
+++ b/framework/src/org/apache/cordova/Echo.java
@@ -1,44 +1,44 @@
/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
package org.apache.cordova;
import org.apache.cordova.api.CallbackContext;
import org.apache.cordova.api.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;
public class Echo extends CordovaPlugin {
@Override
public boolean execute(String action, JSONArray args, final CallbackContext callbackContext) throws JSONException {
- final String result = args.getString(0);
+ final String result = args.isNull(0) ? null : args.getString(0);
if ("echo".equals(action)) {
callbackContext.success(result);
return true;
} else if ("echoAsync".equals(action)) {
cordova.getThreadPool().execute(new Runnable() {
public void run() {
callbackContext.success(result);
}
});
return true;
}
return false;
}
}
diff --git a/framework/src/org/apache/cordova/NativeToJsMessageQueue.java b/framework/src/org/apache/cordova/NativeToJsMessageQueue.java
index 03a69b1d..4f9f9ad1 100755
--- a/framework/src/org/apache/cordova/NativeToJsMessageQueue.java
+++ b/framework/src/org/apache/cordova/NativeToJsMessageQueue.java
@@ -1,472 +1,469 @@
/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
package org.apache.cordova;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.LinkedList;
import org.apache.cordova.api.CordovaInterface;
import org.apache.cordova.api.PluginResult;
import android.os.Message;
import android.util.Log;
import android.webkit.WebView;
/**
* Holds the list of messages to be sent to the WebView.
*/
public class NativeToJsMessageQueue {
private static final String LOG_TAG = "JsMessageQueue";
// This must match the default value in incubator-cordova-js/lib/android/exec.js
private static final int DEFAULT_BRIDGE_MODE = 2;
// Set this to true to force plugin results to be encoding as
// JS instead of the custom format (useful for benchmarking).
private static final boolean FORCE_ENCODE_USING_EVAL = false;
// Disable URL-based exec() bridge by default since it's a bit of a
// security concern.
static final boolean ENABLE_LOCATION_CHANGE_EXEC_MODE = false;
// Disable sending back native->JS messages during an exec() when the active
// exec() is asynchronous. Set this to true when running bridge benchmarks.
static final boolean DISABLE_EXEC_CHAINING = false;
// Arbitrarily chosen upper limit for how much data to send to JS in one shot.
private static final int MAX_PAYLOAD_SIZE = 50 * 1024;
/**
* The index into registeredListeners to treat as active.
*/
private int activeListenerIndex;
/**
* When true, the active listener is not fired upon enqueue. When set to false,
* the active listener will be fired if the queue is non-empty.
*/
private boolean paused;
/**
* The list of JavaScript statements to be sent to JavaScript.
*/
private final LinkedList<JsMessage> queue = new LinkedList<JsMessage>();
/**
* The array of listeners that can be used to send messages to JS.
*/
private final BridgeMode[] registeredListeners;
private final CordovaInterface cordova;
private final CordovaWebView webView;
public NativeToJsMessageQueue(CordovaWebView webView, CordovaInterface cordova) {
this.cordova = cordova;
this.webView = webView;
registeredListeners = new BridgeMode[4];
registeredListeners[0] = null; // Polling. Requires no logic.
registeredListeners[1] = new LoadUrlBridgeMode();
registeredListeners[2] = new OnlineEventsBridgeMode();
registeredListeners[3] = new PrivateApiBridgeMode();
reset();
}
/**
* Changes the bridge mode.
*/
public void setBridgeMode(int value) {
if (value < 0 || value >= registeredListeners.length) {
Log.d(LOG_TAG, "Invalid NativeToJsBridgeMode: " + value);
} else {
if (value != activeListenerIndex) {
Log.d(LOG_TAG, "Set native->JS mode to " + value);
synchronized (this) {
activeListenerIndex = value;
BridgeMode activeListener = registeredListeners[value];
if (!paused && !queue.isEmpty() && activeListener != null) {
activeListener.onNativeToJsMessageAvailable();
}
}
}
}
}
/**
* Clears all messages and resets to the default bridge mode.
*/
public void reset() {
synchronized (this) {
queue.clear();
setBridgeMode(DEFAULT_BRIDGE_MODE);
}
}
private int calculatePackedMessageLength(JsMessage message) {
int messageLen = message.calculateEncodedLength();
String messageLenStr = String.valueOf(messageLen);
return messageLenStr.length() + messageLen + 1;
}
private void packMessage(JsMessage message, StringBuilder sb) {
sb.append(message.calculateEncodedLength())
.append(' ');
message.encodeAsMessage(sb);
}
/**
* Combines and returns queued messages combined into a single string.
* Combines as many messages as possible, while staying under MAX_PAYLOAD_SIZE.
* Returns null if the queue is empty.
*/
public String popAndEncode() {
synchronized (this) {
if (queue.isEmpty()) {
return null;
}
int totalPayloadLen = 0;
int numMessagesToSend = 0;
for (JsMessage message : queue) {
int messageSize = calculatePackedMessageLength(message);
if (numMessagesToSend > 0 && totalPayloadLen + messageSize > MAX_PAYLOAD_SIZE) {
break;
}
totalPayloadLen += messageSize;
numMessagesToSend += 1;
}
StringBuilder sb = new StringBuilder(totalPayloadLen);
for (int i = 0; i < numMessagesToSend; ++i) {
JsMessage message = queue.removeFirst();
packMessage(message, sb);
}
if (!queue.isEmpty()) {
// Attach a char to indicate that there are more messages pending.
sb.append('*');
}
return sb.toString();
}
}
/**
* Same as popAndEncode(), except encodes in a form that can be executed as JS.
*/
private String popAndEncodeAsJs() {
synchronized (this) {
int length = queue.size();
if (length == 0) {
return null;
}
int totalPayloadLen = 0;
int numMessagesToSend = 0;
for (JsMessage message : queue) {
int messageSize = message.calculateEncodedLength() + 50; // overestimate.
if (numMessagesToSend > 0 && totalPayloadLen + messageSize > MAX_PAYLOAD_SIZE) {
break;
}
totalPayloadLen += messageSize;
numMessagesToSend += 1;
}
boolean willSendAllMessages = numMessagesToSend == queue.size();
StringBuilder sb = new StringBuilder(totalPayloadLen + (willSendAllMessages ? 0 : 100));
// Wrap each statement in a try/finally so that if one throws it does
// not affect the next.
for (int i = 0; i < numMessagesToSend; ++i) {
JsMessage message = queue.removeFirst();
if (willSendAllMessages && (i + 1 == numMessagesToSend)) {
message.encodeAsJsMessage(sb);
} else {
sb.append("try{");
message.encodeAsJsMessage(sb);
sb.append("}finally{");
}
}
if (!willSendAllMessages) {
sb.append("window.setTimeout(function(){cordova.require('cordova/plugin/android/polling').pollOnce();},0);");
}
for (int i = willSendAllMessages ? 1 : 0; i < numMessagesToSend; ++i) {
sb.append('}');
}
return sb.toString();
}
}
/**
* Add a JavaScript statement to the list.
*/
public void addJavaScript(String statement) {
enqueueMessage(new JsMessage(statement));
}
/**
* Add a JavaScript statement to the list.
*/
public void addPluginResult(PluginResult result, String callbackId) {
if (callbackId == null) {
Log.e(LOG_TAG, "Got plugin result with no callbackId", new Throwable());
return;
}
// Don't send anything if there is no result and there is no need to
// clear the callbacks.
boolean noResult = result.getStatus() == PluginResult.Status.NO_RESULT.ordinal();
boolean keepCallback = result.getKeepCallback();
if (noResult && keepCallback) {
return;
}
JsMessage message = new JsMessage(result, callbackId);
if (FORCE_ENCODE_USING_EVAL) {
StringBuilder sb = new StringBuilder(message.calculateEncodedLength() + 50);
message.encodeAsJsMessage(sb);
message = new JsMessage(sb.toString());
}
enqueueMessage(message);
}
private void enqueueMessage(JsMessage message) {
synchronized (this) {
queue.add(message);
if (!paused && registeredListeners[activeListenerIndex] != null) {
registeredListeners[activeListenerIndex].onNativeToJsMessageAvailable();
}
}
}
public void setPaused(boolean value) {
if (paused && value) {
// This should never happen. If a use-case for it comes up, we should
// change pause to be a counter.
Log.e(LOG_TAG, "nested call to setPaused detected.", new Throwable());
}
paused = value;
if (!value) {
synchronized (this) {
if (!queue.isEmpty() && registeredListeners[activeListenerIndex] != null) {
registeredListeners[activeListenerIndex].onNativeToJsMessageAvailable();
}
}
}
}
public boolean getPaused() {
return paused;
}
private interface BridgeMode {
void onNativeToJsMessageAvailable();
}
/** Uses webView.loadUrl("javascript:") to execute messages. */
private class LoadUrlBridgeMode implements BridgeMode {
final Runnable runnable = new Runnable() {
public void run() {
String js = popAndEncodeAsJs();
if (js != null) {
webView.loadUrlNow("javascript:" + js);
}
}
};
public void onNativeToJsMessageAvailable() {
cordova.getActivity().runOnUiThread(runnable);
}
}
/** Uses online/offline events to tell the JS when to poll for messages. */
private class OnlineEventsBridgeMode implements BridgeMode {
boolean online = true;
final Runnable runnable = new Runnable() {
public void run() {
if (!queue.isEmpty()) {
online = !online;
webView.setNetworkAvailable(online);
}
}
};
OnlineEventsBridgeMode() {
webView.setNetworkAvailable(true);
}
public void onNativeToJsMessageAvailable() {
cordova.getActivity().runOnUiThread(runnable);
}
}
/**
* Uses Java reflection to access an API that lets us eval JS.
* Requires Android 3.2.4 or above.
*/
private class PrivateApiBridgeMode implements BridgeMode {
// Message added in commit:
// http://omapzoom.org/?p=platform/frameworks/base.git;a=commitdiff;h=9497c5f8c4bc7c47789e5ccde01179abc31ffeb2
// Which first appeared in 3.2.4ish.
private static final int EXECUTE_JS = 194;
Method sendMessageMethod;
Object webViewCore;
boolean initFailed;
@SuppressWarnings("rawtypes")
private void initReflection() {
Object webViewObject = webView;
Class webViewClass = WebView.class;
try {
Field f = webViewClass.getDeclaredField("mProvider");
f.setAccessible(true);
webViewObject = f.get(webView);
webViewClass = webViewObject.getClass();
} catch (Throwable e) {
// mProvider is only required on newer Android releases.
}
try {
Field f = webViewClass.getDeclaredField("mWebViewCore");
f.setAccessible(true);
webViewCore = f.get(webViewObject);
if (webViewCore != null) {
sendMessageMethod = webViewCore.getClass().getDeclaredMethod("sendMessage", Message.class);
sendMessageMethod.setAccessible(true);
}
} catch (Throwable e) {
initFailed = true;
Log.e(LOG_TAG, "PrivateApiBridgeMode failed to find the expected APIs.", e);
}
}
public void onNativeToJsMessageAvailable() {
if (sendMessageMethod == null && !initFailed) {
initReflection();
}
// webViewCore is lazily initialized, and so may not be available right away.
if (sendMessageMethod != null) {
String js = popAndEncodeAsJs();
Message execJsMessage = Message.obtain(null, EXECUTE_JS, js);
try {
sendMessageMethod.invoke(webViewCore, execJsMessage);
} catch (Throwable e) {
Log.e(LOG_TAG, "Reflection message bridge failed.", e);
}
}
}
}
private static class JsMessage {
final String jsPayloadOrCallbackId;
final PluginResult pluginResult;
JsMessage(String js) {
if (js == null) {
throw new NullPointerException();
}
jsPayloadOrCallbackId = js;
pluginResult = null;
}
JsMessage(PluginResult pluginResult, String callbackId) {
if (callbackId == null || pluginResult == null) {
throw new NullPointerException();
}
jsPayloadOrCallbackId = callbackId;
this.pluginResult = pluginResult;
}
int calculateEncodedLength() {
if (pluginResult == null) {
return jsPayloadOrCallbackId.length() + 1;
}
int statusLen = String.valueOf(pluginResult.getStatus()).length();
int ret = 2 + statusLen + 1 + jsPayloadOrCallbackId.length() + 1;
switch (pluginResult.getMessageType()) {
- case PluginResult.MESSAGE_TYPE_BOOLEAN:
+ case PluginResult.MESSAGE_TYPE_BOOLEAN: // f or t
+ case PluginResult.MESSAGE_TYPE_NULL: // N
ret += 1;
break;
case PluginResult.MESSAGE_TYPE_NUMBER: // n
ret += 1 + pluginResult.getMessage().length();
break;
case PluginResult.MESSAGE_TYPE_STRING: // s
- if (pluginResult.getStrMessage() == null) {
- ret += 1;
- }
- else {
- ret += 1 + pluginResult.getStrMessage().length();
- }
+ ret += 1 + pluginResult.getStrMessage().length();
break;
case PluginResult.MESSAGE_TYPE_JSON:
default:
ret += pluginResult.getMessage().length();
}
return ret;
}
void encodeAsMessage(StringBuilder sb) {
if (pluginResult == null) {
sb.append('J')
.append(jsPayloadOrCallbackId);
return;
}
int status = pluginResult.getStatus();
boolean noResult = status == PluginResult.Status.NO_RESULT.ordinal();
boolean resultOk = status == PluginResult.Status.OK.ordinal();
boolean keepCallback = pluginResult.getKeepCallback();
sb.append((noResult || resultOk) ? 'S' : 'F')
.append(keepCallback ? '1' : '0')
.append(status)
.append(' ')
.append(jsPayloadOrCallbackId)
.append(' ');
switch (pluginResult.getMessageType()) {
case PluginResult.MESSAGE_TYPE_BOOLEAN:
sb.append(pluginResult.getMessage().charAt(0)); // t or f.
break;
+ case PluginResult.MESSAGE_TYPE_NULL: // N
+ sb.append('N');
+ break;
case PluginResult.MESSAGE_TYPE_NUMBER: // n
sb.append('n')
.append(pluginResult.getMessage());
break;
case PluginResult.MESSAGE_TYPE_STRING: // s
sb.append('s');
- if (pluginResult.getStrMessage() != null) {
- sb.append(pluginResult.getStrMessage());
- }
+ sb.append(pluginResult.getStrMessage());
break;
case PluginResult.MESSAGE_TYPE_JSON:
default:
sb.append(pluginResult.getMessage()); // [ or {
}
}
void encodeAsJsMessage(StringBuilder sb) {
if (pluginResult == null) {
sb.append(jsPayloadOrCallbackId);
} else {
int status = pluginResult.getStatus();
boolean success = (status == PluginResult.Status.OK.ordinal()) || (status == PluginResult.Status.NO_RESULT.ordinal());
sb.append("cordova.callbackFromNative('")
.append(jsPayloadOrCallbackId)
.append("',")
.append(success)
.append(",")
.append(status)
.append(",")
.append(pluginResult.getMessage())
.append(",")
.append(pluginResult.getKeepCallback())
.append(");");
}
}
}
}
diff --git a/framework/src/org/apache/cordova/api/PluginResult.java b/framework/src/org/apache/cordova/api/PluginResult.java
index 28c7b980..0058f375 100755
--- a/framework/src/org/apache/cordova/api/PluginResult.java
+++ b/framework/src/org/apache/cordova/api/PluginResult.java
@@ -1,162 +1,163 @@
/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
package org.apache.cordova.api;
import org.json.JSONArray;
import org.json.JSONObject;
public class PluginResult {
private final int status;
private final int messageType;
private boolean keepCallback = false;
private String strMessage;
private String encodedMessage;
public PluginResult(Status status) {
this(status, PluginResult.StatusMessages[status.ordinal()]);
}
public PluginResult(Status status, String message) {
this.status = status.ordinal();
- this.messageType = MESSAGE_TYPE_STRING;
+ this.messageType = message == null ? MESSAGE_TYPE_NULL : MESSAGE_TYPE_STRING;
this.strMessage = message;
}
public PluginResult(Status status, JSONArray message) {
this.status = status.ordinal();
this.messageType = MESSAGE_TYPE_JSON;
encodedMessage = message.toString();
}
public PluginResult(Status status, JSONObject message) {
this.status = status.ordinal();
this.messageType = MESSAGE_TYPE_JSON;
encodedMessage = message.toString();
}
public PluginResult(Status status, int i) {
this.status = status.ordinal();
this.messageType = MESSAGE_TYPE_NUMBER;
this.encodedMessage = ""+i;
}
public PluginResult(Status status, float f) {
this.status = status.ordinal();
this.messageType = MESSAGE_TYPE_NUMBER;
this.encodedMessage = ""+f;
}
public PluginResult(Status status, boolean b) {
this.status = status.ordinal();
this.messageType = MESSAGE_TYPE_BOOLEAN;
this.encodedMessage = Boolean.toString(b);
}
public void setKeepCallback(boolean b) {
this.keepCallback = b;
}
public int getStatus() {
return status;
}
public int getMessageType() {
return messageType;
}
public String getMessage() {
if (encodedMessage == null) {
encodedMessage = JSONObject.quote(strMessage);
}
return encodedMessage;
}
/**
* If messageType == MESSAGE_TYPE_STRING, then returns the message string.
* Otherwise, returns null.
*/
public String getStrMessage() {
return strMessage;
}
public boolean getKeepCallback() {
return this.keepCallback;
}
@Deprecated // Use sendPluginResult instead of sendJavascript.
public String getJSONString() {
return "{\"status\":" + this.status + ",\"message\":" + this.getMessage() + ",\"keepCallback\":" + this.keepCallback + "}";
}
@Deprecated // Use sendPluginResult instead of sendJavascript.
public String toCallbackString(String callbackId) {
// If no result to be sent and keeping callback, then no need to sent back to JavaScript
if ((status == PluginResult.Status.NO_RESULT.ordinal()) && keepCallback) {
return null;
}
// Check the success (OK, NO_RESULT & !KEEP_CALLBACK)
if ((status == PluginResult.Status.OK.ordinal()) || (status == PluginResult.Status.NO_RESULT.ordinal())) {
return toSuccessCallbackString(callbackId);
}
return toErrorCallbackString(callbackId);
}
@Deprecated // Use sendPluginResult instead of sendJavascript.
public String toSuccessCallbackString(String callbackId) {
return "cordova.callbackSuccess('"+callbackId+"',"+this.getJSONString()+");";
}
@Deprecated // Use sendPluginResult instead of sendJavascript.
public String toErrorCallbackString(String callbackId) {
return "cordova.callbackError('"+callbackId+"', " + this.getJSONString()+ ");";
}
public static final int MESSAGE_TYPE_STRING = 1;
public static final int MESSAGE_TYPE_JSON = 2;
public static final int MESSAGE_TYPE_NUMBER = 3;
public static final int MESSAGE_TYPE_BOOLEAN = 4;
+ public static final int MESSAGE_TYPE_NULL = 5;
public static String[] StatusMessages = new String[] {
"No result",
"OK",
"Class not found",
"Illegal access",
"Instantiation error",
"Malformed url",
"IO error",
"Invalid action",
"JSON error",
"Error"
};
public enum Status {
NO_RESULT,
OK,
CLASS_NOT_FOUND_EXCEPTION,
ILLEGAL_ACCESS_EXCEPTION,
INSTANTIATION_EXCEPTION,
MALFORMED_URL_EXCEPTION,
IO_EXCEPTION,
INVALID_ACTION,
JSON_EXCEPTION,
ERROR
}
}
| false | false | null | null |
diff --git a/src/main/java/com/jayway/maven/plugins/android/phase01generatesources/GenerateSourcesMojo.java b/src/main/java/com/jayway/maven/plugins/android/phase01generatesources/GenerateSourcesMojo.java
index 64d156f9..bd764257 100644
--- a/src/main/java/com/jayway/maven/plugins/android/phase01generatesources/GenerateSourcesMojo.java
+++ b/src/main/java/com/jayway/maven/plugins/android/phase01generatesources/GenerateSourcesMojo.java
@@ -1,983 +1,983 @@
/*
* Copyright (C) 2009 Jayway AB
* Copyright (C) 2007-2008 JVending Masa
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jayway.maven.plugins.android.phase01generatesources;
import com.android.builder.internal.SymbolLoader;
import com.android.builder.internal.SymbolWriter;
import com.android.manifmerger.ManifestMerger;
import com.android.manifmerger.MergerLog;
import com.android.utils.StdLogger;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;
import com.jayway.maven.plugins.android.AbstractAndroidMojo;
import com.jayway.maven.plugins.android.CommandExecutor;
import com.jayway.maven.plugins.android.ExecutionException;
import com.jayway.maven.plugins.android.common.AetherHelper;
import com.jayway.maven.plugins.android.configuration.BuildConfigConstant;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.codehaus.plexus.archiver.ArchiverException;
import org.codehaus.plexus.archiver.UnArchiver;
import org.codehaus.plexus.archiver.zip.ZipUnArchiver;
import org.codehaus.plexus.logging.Logger;
import org.codehaus.plexus.logging.console.ConsoleLogger;
import org.codehaus.plexus.util.AbstractScanner;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static com.jayway.maven.plugins.android.common.AndroidExtension.APK;
import static com.jayway.maven.plugins.android.common.AndroidExtension.APKLIB;
import static com.jayway.maven.plugins.android.common.AndroidExtension.AAR;
import static com.jayway.maven.plugins.android.common.AndroidExtension.APKSOURCES;
/**
* Generates <code>R.java</code> based on resources specified by the <code>resources</code> configuration parameter.
* Generates java files based on aidl files.
*
* @author [email protected]
* @author Manfred Moser <[email protected]>
*
* @goal generate-sources
* @phase generate-sources
* @requiresProject true
* @requiresDependencyResolution compile
*/
public class GenerateSourcesMojo extends AbstractAndroidMojo
{
/**
* <p>
* Override default merging. You must have SDK Tools r20+
* </p>
*
* <p>
* <b>IMPORTANT:</b> The resource plugin needs to be disabled for the
* <code>process-resources</code> phase, so the "default-resources"
* execution must be added. Without this the non-merged manifest will get
* re-copied to the build directory.
* </p>
*
* <p>
* The <code>androidManifestFile</code> should also be configured to pull
* from the build directory so that later phases will pull the merged
* manifest file.
* </p>
* <p>
* Example POM Setup:
* </p>
*
* <pre>
* <build>
* ...
* <plugins>
* ...
* <plugin>
* <artifactId>maven-resources-plugin</artifactId>
* <version>2.6</version>
* <executions>
* <execution>
* <phase>initialize</phase>
* <goals>
* <goal>resources</goal>
* </goals>
* </execution>
* <b><execution>
* <id>default-resources</id>
* <phase>DISABLED</phase>
* </execution></b>
* </executions>
* </plugin>
* <plugin>
* <groupId>com.jayway.maven.plugins.android.generation2</groupId>
* <artifactId>android-maven-plugin</artifactId>
* <configuration>
* <b><androidManifestFile>
* ${project.build.directory}/AndroidManifest.xml
* </androidManifestFile>
* <mergeManifests>true</mergeManifests></b>
* </configuration>
* <extensions>true</extensions>
* </plugin>
* ...
* </plugins>
* ...
* </build>
* </pre>
* <p>
* You can filter the pre-merged APK manifest. One important note about Eclipse, Eclipse will
* replace the merged manifest with a filtered pre-merged version when the project is refreshed.
* If you want to review the filtered merged version then you will need to open it outside Eclipse
* without refreshing the project in Eclipse.
* </p>
* <pre>
* <resources>
* <resource>
* <targetPath>${project.build.directory}</targetPath>
* <filtering>true</filtering>
* <directory>${basedir}</directory>
* <includes>
* <include>AndroidManifest.xml</include>
* </includes>
* </resource>
* </resources>
* </pre>
*
* @parameter expression="${android.mergeManifests}" default-value="false"
*/
protected boolean mergeManifests;
/**
* Override default generated folder containing R.java
*
* @parameter expression="${android.genDirectory}" default-value="${project.build.directory}/generated-sources/r"
*/
protected File genDirectory;
/**
* Override default generated folder containing aidl classes
*
* @parameter expression="${android.genDirectoryAidl}"
* default-value="${project.build.directory}/generated-sources/aidl"
*/
protected File genDirectoryAidl;
/**
* <p>Parameter designed to generate custom BuildConfig constants
*
* @parameter expression="${android.buildConfigConstants}"
* @readonly
*/
protected BuildConfigConstant[] buildConfigConstants;
public void execute() throws MojoExecutionException, MojoFailureException
{
// If the current POM isn't an Android-related POM, then don't do
// anything. This helps work with multi-module projects.
if ( ! isCurrentProjectAndroid() )
{
return;
}
try
{
extractSourceDependencies();
extractApkLibDependencies();
extractAarDependencies();
final String[] relativeAidlFileNames1 = findRelativeAidlFileNames( sourceDirectory );
final String[] relativeAidlFileNames2 = findRelativeAidlFileNames( extractedDependenciesJavaSources );
final Map<String, String[]> relativeApklibAidlFileNames = new HashMap<String, String[]>();
String[] apklibAidlFiles;
for ( Artifact artifact : getAllRelevantDependencyArtifacts() )
{
if ( artifact.getType().equals( APKLIB ) )
{
apklibAidlFiles = findRelativeAidlFileNames(
new File( getLibraryUnpackDirectory( artifact ) + "/src" ) );
relativeApklibAidlFileNames.put( artifact.getId(), apklibAidlFiles );
}
}
mergeManifests();
generateR();
generateApklibR();
generateAarR();
generateBuildConfig();
// When compiling AIDL for this project,
// make sure we compile AIDL for dependencies as well.
// This is so project A, which depends on project B, can
// use AIDL info from project B in its own AIDL
Map<File, String[]> files = new HashMap<File, String[]>();
files.put( sourceDirectory, relativeAidlFileNames1 );
files.put( extractedDependenciesJavaSources, relativeAidlFileNames2 );
for ( Artifact artifact : getAllRelevantDependencyArtifacts() )
{
if ( artifact.getType().equals( APKLIB ) )
{
files.put( new File( getLibraryUnpackDirectory( artifact ) + "/src" ),
relativeApklibAidlFileNames.get( artifact.getId() ) );
}
}
generateAidlFiles( files );
}
catch ( MojoExecutionException e )
{
getLog().error( "Error when generating sources.", e );
throw e;
}
}
protected void extractSourceDependencies() throws MojoExecutionException
{
for ( Artifact artifact : getRelevantDependencyArtifacts() )
{
String type = artifact.getType();
if ( type.equals( APKSOURCES ) )
{
getLog().debug( "Detected apksources dependency " + artifact + " with file " + artifact.getFile()
+ ". Will resolve and extract..." );
Artifact resolvedArtifact = AetherHelper
.resolveArtifact( artifact, repoSystem, repoSession, projectRepos );
File apksourcesFile = resolvedArtifact.getFile();
// When the artifact is not installed in local repository, but rather part of the current reactor,
// resolve from within the reactor. (i.e. ../someothermodule/target/*)
if ( ! apksourcesFile.exists() )
{
apksourcesFile = resolveArtifactToFile( artifact );
}
// When using maven under eclipse the artifact will by default point to a directory, which isn't
// correct. To work around this we'll first try to get the archive from the local repo, and only if it
// isn't found there we'll do a normal resolve.
if ( apksourcesFile.isDirectory() )
{
apksourcesFile = resolveArtifactToFile( artifact );
}
getLog().debug( "Extracting " + apksourcesFile + "..." );
extractApksources( apksourcesFile );
}
}
projectHelper.addResource( project, extractedDependenciesJavaResources.getAbsolutePath(), null, null );
project.addCompileSourceRoot( extractedDependenciesJavaSources.getAbsolutePath() );
}
private void extractApksources( File apksourcesFile ) throws MojoExecutionException
{
if ( apksourcesFile.isDirectory() )
{
getLog().warn( "The apksources artifact points to '" + apksourcesFile
+ "' which is a directory; skipping unpacking it." );
return;
}
final UnArchiver unArchiver = new ZipUnArchiver( apksourcesFile )
{
@Override
protected Logger getLogger()
{
return new ConsoleLogger( Logger.LEVEL_DEBUG, "dependencies-unarchiver" );
}
};
extractedDependenciesDirectory.mkdirs();
unArchiver.setDestDirectory( extractedDependenciesDirectory );
try
{
unArchiver.extract();
}
catch ( ArchiverException e )
{
throw new MojoExecutionException( "ArchiverException while extracting " + apksourcesFile.getAbsolutePath()
+ ". Message: " + e.getLocalizedMessage(), e );
}
}
private void extractApkLibDependencies() throws MojoExecutionException
{
for ( Artifact artifact : getAllRelevantDependencyArtifacts() )
{
String type = artifact.getType();
if ( type.equals( APKLIB ) )
{
getLog().debug( "Extracting apklib " + artifact.getArtifactId() + "..." );
extractApklib( artifact );
}
}
}
private void extractApklib( Artifact apklibArtifact ) throws MojoExecutionException
{
final Artifact resolvedArtifact = AetherHelper
.resolveArtifact( apklibArtifact, repoSystem, repoSession, projectRepos );
File apkLibFile = resolvedArtifact.getFile();
// When the artifact is not installed in local repository, but rather part of the current reactor,
// resolve from within the reactor. (i.e. ../someothermodule/target/*)
if ( ! apkLibFile.exists() )
{
apkLibFile = resolveArtifactToFile( apklibArtifact );
}
//When using maven under eclipse the artifact will by default point to a directory, which isn't correct.
//To work around this we'll first try to get the archive from the local repo, and only if it isn't found there
// we'll do a normal resolve.
if ( apkLibFile.isDirectory() )
{
apkLibFile = resolveArtifactToFile( apklibArtifact );
}
if ( apkLibFile.isDirectory() )
{
getLog().warn(
"The apklib artifact points to '" + apkLibFile + "' which is a directory; skipping unpacking it." );
return;
}
final UnArchiver unArchiver = new ZipUnArchiver( apkLibFile )
{
@Override
protected Logger getLogger()
{
return new ConsoleLogger( Logger.LEVEL_DEBUG, "dependencies-unarchiver" );
}
};
File apklibDirectory = new File( getLibraryUnpackDirectory( apklibArtifact ) );
apklibDirectory.mkdirs();
unArchiver.setDestDirectory( apklibDirectory );
try
{
unArchiver.extract();
}
catch ( ArchiverException e )
{
throw new MojoExecutionException( "ArchiverException while extracting " + apklibDirectory.getAbsolutePath()
+ ". Message: " + e.getLocalizedMessage(), e );
}
projectHelper.addResource( project, apklibDirectory.getAbsolutePath() + "/src", null,
Arrays.asList( "**/*.java", "**/*.aidl" ) );
project.addCompileSourceRoot( apklibDirectory.getAbsolutePath() + "/src" );
}
private void extractAarDependencies() throws MojoExecutionException
{
for ( Artifact artifact : getAllRelevantDependencyArtifacts() )
{
String type = artifact.getType();
if ( type.equals( AAR ) )
{
getLog().debug( "Extracting aar " + artifact.getArtifactId() + "..." );
extractAarlib( artifact );
}
}
}
private void extractAarlib( Artifact aarArtifact ) throws MojoExecutionException
{
final Artifact resolvedArtifact = AetherHelper
.resolveArtifact( aarArtifact, repoSystem, repoSession, projectRepos );
File aarFile = resolvedArtifact.getFile();
// When the artifact is not installed in local repository, but rather part of the current reactor,
// resolve from within the reactor. (i.e. ../someothermodule/target/*)
if ( ! aarFile.exists() )
{
aarFile = resolveArtifactToFile( aarArtifact );
}
//When using maven under eclipse the artifact will by default point to a directory, which isn't correct.
//To work around this we'll first try to get the archive from the local repo, and only if it isn't found there
// we'll do a normal resolve.
if ( aarFile.isDirectory() )
{
aarFile = resolveArtifactToFile( aarArtifact );
}
if ( aarFile.isDirectory() )
{
getLog().warn(
"The aar artifact points to '" + aarFile + "' which is a directory; skipping unpacking it." );
return;
}
final UnArchiver unArchiver = new ZipUnArchiver( aarFile )
{
@Override
protected Logger getLogger()
{
return new ConsoleLogger( Logger.LEVEL_DEBUG, "dependencies-unarchiver" );
}
};
File aarDirectory = new File( getLibraryUnpackDirectory( aarArtifact ) );
aarDirectory.mkdirs();
unArchiver.setDestDirectory( aarDirectory );
try
{
unArchiver.extract();
}
catch ( ArchiverException e )
{
throw new MojoExecutionException( "ArchiverException while extracting " + aarDirectory.getAbsolutePath()
+ ". Message: " + e.getLocalizedMessage(), e );
}
projectHelper.addResource( project, aarDirectory.getAbsolutePath() + "/src", null,
Arrays.asList( "**/*.aidl" ) );
//project.addCompileSourceRoot( aarDirectory.getAbsolutePath() + "/src" );
}
private void generateR() throws MojoExecutionException
{
getLog().debug( "Generating R file for " + project.getPackaging() );
genDirectory.mkdirs();
File[] overlayDirectories = getResourceOverlayDirectories();
if ( extractedDependenciesRes.exists() )
{
try
{
getLog().info( "Copying dependency resource files to combined resource directory." );
if ( ! combinedRes.exists() )
{
if ( ! combinedRes.mkdirs() )
{
throw new MojoExecutionException(
"Could not create directory for combined resources at " + combinedRes
.getAbsolutePath() );
}
}
org.apache.commons.io.FileUtils.copyDirectory( extractedDependenciesRes, combinedRes );
}
catch ( IOException e )
{
throw new MojoExecutionException( "", e );
}
}
if ( resourceDirectory.exists() && combinedRes.exists() )
{
try
{
getLog().info( "Copying local resource files to combined resource directory." );
org.apache.commons.io.FileUtils.copyDirectory( resourceDirectory, combinedRes, new FileFilter()
{
/**
* Excludes files matching one of the common file to exclude.
* The default excludes pattern are the ones from
* {org.codehaus.plexus.util.AbstractScanner#DEFAULTEXCLUDES}
* @see java.io.FileFilter#accept(java.io.File)
*/
public boolean accept( File file )
{
for ( String pattern : AbstractScanner.DEFAULTEXCLUDES )
{
if ( AbstractScanner.match( pattern, file.getAbsolutePath() ) )
{
getLog().debug(
"Excluding " + file.getName() + " from resource copy : matching " + pattern );
return false;
}
}
return true;
}
} );
}
catch ( IOException e )
{
throw new MojoExecutionException( "", e );
}
}
CommandExecutor executor = CommandExecutor.Factory.createDefaultCommmandExecutor();
executor.setLogger( this.getLog() );
List<String> commands = new ArrayList<String>();
commands.add( "package" );
if ( APKLIB.equals( project.getArtifact().getType() ) )
{
commands.add( "--non-constant-id" );
}
commands.add( "-m" );
commands.add( "-J" );
commands.add( genDirectory.getAbsolutePath() );
commands.add( "-M" );
commands.add( androidManifestFile.getAbsolutePath() );
if ( StringUtils.isNotBlank( customPackage ) )
{
commands.add( "--custom-package" );
commands.add( customPackage );
}
addResourcesDirectories( commands, overlayDirectories );
commands.add( "--auto-add-overlay" );
if ( assetsDirectory.exists() )
{
commands.add( "-A" );
commands.add( assetsDirectory.getAbsolutePath() );
}
if ( extractedDependenciesAssets.exists() )
{
commands.add( "-A" );
commands.add( extractedDependenciesAssets.getAbsolutePath() );
}
commands.add( "-I" );
commands.add( getAndroidSdk().getAndroidJar().getAbsolutePath() );
if ( StringUtils.isNotBlank( configurations ) )
{
commands.add( "-c" );
commands.add( configurations );
}
for ( String aaptExtraArg : aaptExtraArgs )
{
commands.add( aaptExtraArg );
}
if ( proguardFile != null )
{
File parentFolder = proguardFile.getParentFile();
if ( parentFolder != null )
{
parentFolder.mkdirs();
}
commands.add( "-G" );
commands.add( proguardFile.getAbsolutePath() );
}
commands.add( "--output-text-symbols" );
commands.add( project.getBuild().getDirectory() );
getLog().info( getAndroidSdk().getAaptPath() + " " + commands.toString() );
try
{
executor.executeCommand( getAndroidSdk().getAaptPath(), commands, project.getBasedir(), false );
}
catch ( ExecutionException e )
{
throw new MojoExecutionException( "", e );
}
project.addCompileSourceRoot( genDirectory.getAbsolutePath() );
}
private void addResourcesDirectories( List<String> commands, File[] overlayDirectories )
{
for ( File resOverlayDir : overlayDirectories )
{
if ( resOverlayDir != null && resOverlayDir.exists() )
{
commands.add( "-S" );
commands.add( resOverlayDir.getAbsolutePath() );
}
}
if ( combinedRes.exists() )
{
commands.add( "-S" );
commands.add( combinedRes.getAbsolutePath() );
}
else
{
if ( resourceDirectory.exists() )
{
commands.add( "-S" );
commands.add( resourceDirectory.getAbsolutePath() );
}
}
for ( Artifact artifact : getAllRelevantDependencyArtifacts() )
{
if ( artifact.getType().equals( APKLIB ) || artifact.getType().equals( AAR ) )
{
String apklibResDirectory = getLibraryUnpackDirectory( artifact ) + "/res";
if ( new File( apklibResDirectory ).exists() )
{
commands.add( "-S" );
commands.add( apklibResDirectory );
}
}
}
}
private void mergeManifests() throws MojoExecutionException
{
getLog().debug( "mergeManifests: " + mergeManifests );
if ( !mergeManifests )
{
getLog().info( "Manifest merging disabled. Using project manifest only" );
return;
}
getLog().info( "Getting manifests of dependent apklibs" );
List<File> libManifests = new ArrayList<File>();
for ( Artifact artifact : getAllRelevantDependencyArtifacts() )
{
if ( artifact.getType().equals( APKLIB ) || artifact.getType().equals( AAR ) )
{
File apklibManifeset = new File( getLibraryUnpackDirectory( artifact ), "AndroidManifest.xml" );
if ( !apklibManifeset.exists() )
{
throw new MojoExecutionException( artifact.getArtifactId() + " is missing AndroidManifest.xml" );
}
libManifests.add( apklibManifeset );
}
}
if ( !libManifests.isEmpty() )
{
final File mergedManifest = new File( androidManifestFile.getParent(), "AndroidManifest-merged.xml" );
final StdLogger stdLogger = new StdLogger( StdLogger.Level.VERBOSE );
final ManifestMerger merger = new ManifestMerger( MergerLog.wrapSdkLog( stdLogger ), null );
getLog().info( "Merging manifests of dependent apklibs" );
final boolean mergeSuccess = merger.process( mergedManifest, androidManifestFile,
libManifests.toArray( new File[libManifests.size()] ), null, null );
if ( mergeSuccess )
{
// Replace the original manifest file with the merged one so that
// the rest of the build will pick it up.
androidManifestFile.delete();
mergedManifest.renameTo( androidManifestFile );
getLog().info( "Done Merging Manifests of APKLIBs" );
}
else
{
getLog().error( "Manifests were not merged!" );
throw new MojoExecutionException( "Manifests were not merged!" );
}
}
else
{
getLog().info( "No APKLIB manifests found. Using project manifest only." );
}
}
private void generateAarR() throws MojoExecutionException
{
getLog().debug( "Generating R file for projects dependent on aar's" );
genDirectory.mkdirs();
SymbolLoader fullSymbolValues = null;
// list of all the symbol loaders per package names.
Multimap<String, SymbolLoader> libMap = ArrayListMultimap.create();
try
{
for ( Artifact artifact : getAllRelevantDependencyArtifacts() )
{
if ( !artifact.getType().equals( AAR ) )
{
continue;
}
String unpackDir = getLibraryUnpackDirectory( artifact );
String packageName = extractPackageNameFromAndroidManifest(
new File( unpackDir + "/" + "AndroidManifest.xml" ) );
File rFile = new File( unpackDir + "/R.txt" );
// if the library has no resource, this file won't exist.
if ( rFile.isFile() )
{
// load the full values if that's not already been done.
// Doing it lazily allow us to support the case where there's no
// resources anywhere.
if ( fullSymbolValues == null )
{
fullSymbolValues = new SymbolLoader(
- new File( genDirectory + "/" + packageName ), null );
+ new File( project.getBuild().getDirectory() + "/R.txt" ), null );
fullSymbolValues.load();
}
SymbolLoader libSymbols = new SymbolLoader( rFile, null );
libSymbols.load();
// store these symbols by associating them with the package name.
libMap.put( packageName, libSymbols );
}
}
// now loop on all the package name, merge all the symbols to write, and write them
for ( String packageName : libMap.keySet() )
{
Collection<SymbolLoader> symbols = libMap.get( packageName );
SymbolWriter writer = new SymbolWriter( genDirectory.getPath(), packageName,
fullSymbolValues );
for ( SymbolLoader symbolLoader : symbols )
{
writer.addSymbolsToWrite( symbolLoader );
}
writer.write();
}
}
catch ( IOException ex )
{
getLog().error( ex );
}
project.addCompileSourceRoot( genDirectory.getAbsolutePath() );
}
private void generateApklibR() throws MojoExecutionException
{
getLog().debug( "Generating R file for projects dependent on apklibs" );
genDirectory.mkdirs();
for ( Artifact artifact : getAllRelevantDependencyArtifacts() )
{
if ( artifact.getType().equals( APKLIB ) )
{
generateRForApkLibDependency( artifact );
}
}
project.addCompileSourceRoot( genDirectory.getAbsolutePath() );
}
private void generateRForApkLibDependency( Artifact apklibArtifact ) throws MojoExecutionException
{
final String unpackDir = getLibraryUnpackDirectory( apklibArtifact );
getLog().debug( "Generating R file for apklibrary: " + apklibArtifact.getGroupId() );
CommandExecutor executor = CommandExecutor.Factory.createDefaultCommmandExecutor();
executor.setLogger( this.getLog() );
List<String> commands = new ArrayList<String>();
commands.add( "package" );
commands.add( "--non-constant-id" );
commands.add( "-m" );
commands.add( "-J" );
commands.add( genDirectory.getAbsolutePath() );
commands.add( "--custom-package" );
commands.add( extractPackageNameFromAndroidManifest( new File( unpackDir + "/" + "AndroidManifest.xml" ) ) );
commands.add( "-M" );
commands.add( androidManifestFile.getAbsolutePath() );
if ( resourceDirectory.exists() )
{
commands.add( "-S" );
commands.add( resourceDirectory.getAbsolutePath() );
}
for ( Artifact artifact : getAllRelevantDependencyArtifacts() )
{
if ( artifact.getType().equals( APKLIB ) || artifact.getType().equals( AAR ) )
{
final String apkLibResDir = getLibraryUnpackDirectory( artifact ) + "/res";
if ( new File( apkLibResDir ).exists() )
{
commands.add( "-S" );
commands.add( apkLibResDir );
}
}
}
commands.add( "--auto-add-overlay" );
if ( assetsDirectory.exists() )
{
commands.add( "-A" );
commands.add( assetsDirectory.getAbsolutePath() );
}
for ( Artifact artifact : getAllRelevantDependencyArtifacts() )
{
if ( artifact.getType().equals( APKLIB ) )
{
final String apkLibAssetsDir = getLibraryUnpackDirectory( artifact ) + "/assets";
if ( new File( apkLibAssetsDir ).exists() )
{
commands.add( "-A" );
commands.add( apkLibAssetsDir );
}
}
}
commands.add( "-I" );
commands.add( getAndroidSdk().getAndroidJar().getAbsolutePath() );
if ( StringUtils.isNotBlank( configurations ) )
{
commands.add( "-c" );
commands.add( configurations );
}
for ( String aaptExtraArg : aaptExtraArgs )
{
commands.add( aaptExtraArg );
}
getLog().info( getAndroidSdk().getAaptPath() + " " + commands.toString() );
try
{
executor.executeCommand( getAndroidSdk().getAaptPath(), commands, project.getBasedir(), false );
}
catch ( ExecutionException e )
{
throw new MojoExecutionException( "", e );
}
}
private void generateBuildConfig() throws MojoExecutionException
{
getLog().debug( "Generating BuildConfig file" );
// Create the BuildConfig for our package.
String packageName = extractPackageNameFromAndroidManifest( androidManifestFile );
if ( StringUtils.isNotBlank( customPackage ) )
{
packageName = customPackage;
}
generateBuildConfigForPackage( packageName );
// Generate the BuildConfig for any apklib dependencies.
for ( Artifact artifact : getAllRelevantDependencyArtifacts() )
{
if ( artifact.getType().equals( APKLIB ) )
{
File apklibManifeset = new File( getLibraryUnpackDirectory( artifact ), "AndroidManifest.xml" );
String apklibPackageName = extractPackageNameFromAndroidManifest( apklibManifeset );
generateBuildConfigForPackage( apklibPackageName );
}
}
}
private void generateBuildConfigForPackage( String packageName ) throws MojoExecutionException
{
File outputFolder = new File( genDirectory, packageName.replace( ".", File.separator ) );
outputFolder.mkdirs();
StringBuilder buildConfig = new StringBuilder();
buildConfig.append( "package " ).append( packageName ).append( ";\n\n" );
buildConfig.append( "public final class BuildConfig {\n" );
buildConfig.append( " public static final boolean DEBUG = " ).append( !release ).append( ";\n" );
for ( BuildConfigConstant constant : buildConfigConstants )
{
String value = constant.getValue();
if ( "String".equals( constant.getType() ) )
{
value = "\"" + value + "\"";
}
buildConfig.append( " public static final " )
.append( constant.getType() )
.append( " " )
.append( constant.getName() )
.append( " = " )
.append( value )
.append( ";\n" );
}
buildConfig.append( "}\n" );
File outputFile = new File( outputFolder, "BuildConfig.java" );
try
{
FileUtils.writeStringToFile( outputFile, buildConfig.toString() );
}
catch ( IOException e )
{
getLog().error( "Error generating BuildConfig ", e );
throw new MojoExecutionException( "Error generating BuildConfig", e );
}
}
/**
* Given a map of source directories to list of AIDL (relative) filenames within each,
* runs the AIDL compiler for each, such that all source directories are available to
* the AIDL compiler.
*
* @param files Map of source directory File instances to the relative paths to all AIDL files within
* @throws MojoExecutionException If the AIDL compiler fails
*/
private void generateAidlFiles( Map<File /*sourceDirectory*/, String[] /*relativeAidlFileNames*/> files )
throws MojoExecutionException
{
List<String> protoCommands = new ArrayList<String>();
protoCommands.add( "-p" + getAndroidSdk().getPathForFrameworkAidl() );
genDirectoryAidl.mkdirs();
project.addCompileSourceRoot( genDirectoryAidl.getPath() );
Set<File> sourceDirs = files.keySet();
for ( File sourceDir : sourceDirs )
{
protoCommands.add( "-I" + sourceDir );
}
for ( File sourceDir : sourceDirs )
{
for ( String relativeAidlFileName : files.get( sourceDir ) )
{
File targetDirectory = new File( genDirectoryAidl, new File( relativeAidlFileName ).getParent() );
targetDirectory.mkdirs();
final String shortAidlFileName = new File( relativeAidlFileName ).getName();
final String shortJavaFileName = shortAidlFileName.substring( 0, shortAidlFileName.lastIndexOf( "." ) )
+ ".java";
final File aidlFileInSourceDirectory = new File( sourceDir, relativeAidlFileName );
List<String> commands = new ArrayList<String>( protoCommands );
commands.add( aidlFileInSourceDirectory.getAbsolutePath() );
commands.add( new File( targetDirectory, shortJavaFileName ).getAbsolutePath() );
try
{
CommandExecutor executor = CommandExecutor.Factory.createDefaultCommmandExecutor();
executor.setLogger( this.getLog() );
executor.executeCommand( getAndroidSdk().getAidlPath(), commands, project.getBasedir(),
false );
}
catch ( ExecutionException e )
{
throw new MojoExecutionException( "", e );
}
}
}
}
private String[] findRelativeAidlFileNames( File sourceDirectory )
{
String[] relativeAidlFileNames = findFilesInDirectory( sourceDirectory, "**/*.aidl" );
getLog().info( "ANDROID-904-002: Found aidl files: Count = " + relativeAidlFileNames.length );
return relativeAidlFileNames;
}
/**
* @return true if the pom type is APK, APKLIB, or APKSOURCES
*/
private boolean isCurrentProjectAndroid()
{
Set<String> androidArtifacts = new HashSet<String>()
{
{
addAll( Arrays.asList( APK, APKLIB, APKSOURCES, AAR ) );
}
};
return androidArtifacts.contains( project.getArtifact().getType() );
}
}
| true | false | null | null |
diff --git a/qalingo-apis/qalingo-api-core/qalingo-api-core-common/src/main/java/fr/hoteia/qalingo/core/web/util/impl/RequestUtilImpl.java b/qalingo-apis/qalingo-api-core/qalingo-api-core-common/src/main/java/fr/hoteia/qalingo/core/web/util/impl/RequestUtilImpl.java
index 6fb54f83..9942a20e 100644
--- a/qalingo-apis/qalingo-api-core/qalingo-api-core-common/src/main/java/fr/hoteia/qalingo/core/web/util/impl/RequestUtilImpl.java
+++ b/qalingo-apis/qalingo-api-core/qalingo-api-core-common/src/main/java/fr/hoteia/qalingo/core/web/util/impl/RequestUtilImpl.java
@@ -1,1598 +1,1602 @@
/**
* Most of the code in the Qalingo project is copyrighted Hoteia and licensed
* under the Apache License Version 2.0 (release version 0.7.0)
* http://www.apache.org/licenses/LICENSE-2.0
*
* Copyright (c) Hoteia, 2012-2013
* http://www.hoteia.com - http://twitter.com/hoteia - [email protected]
*
*/
package fr.hoteia.qalingo.core.web.util.impl;
import java.math.RoundingMode;
import java.security.MessageDigest;
import java.text.DateFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Currency;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang.BooleanUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.opensymphony.clickstream.Clickstream;
import com.opensymphony.clickstream.ClickstreamListener;
import com.opensymphony.clickstream.ClickstreamRequest;
import fr.hoteia.qalingo.core.Constants;
import fr.hoteia.qalingo.core.RequestConstants;
import fr.hoteia.qalingo.core.domain.Asset;
import fr.hoteia.qalingo.core.domain.Cart;
import fr.hoteia.qalingo.core.domain.CartItem;
import fr.hoteia.qalingo.core.domain.Company;
import fr.hoteia.qalingo.core.domain.Customer;
import fr.hoteia.qalingo.core.domain.EngineBoSession;
import fr.hoteia.qalingo.core.domain.EngineEcoSession;
import fr.hoteia.qalingo.core.domain.EngineSetting;
import fr.hoteia.qalingo.core.domain.EngineSettingValue;
import fr.hoteia.qalingo.core.domain.Localization;
import fr.hoteia.qalingo.core.domain.Market;
import fr.hoteia.qalingo.core.domain.MarketArea;
import fr.hoteia.qalingo.core.domain.MarketPlace;
import fr.hoteia.qalingo.core.domain.Order;
import fr.hoteia.qalingo.core.domain.ProductSku;
import fr.hoteia.qalingo.core.domain.Retailer;
import fr.hoteia.qalingo.core.domain.User;
import fr.hoteia.qalingo.core.domain.enumtype.EngineSettingWebAppContext;
import fr.hoteia.qalingo.core.service.CustomerService;
import fr.hoteia.qalingo.core.service.EngineSettingService;
import fr.hoteia.qalingo.core.service.LocalizationService;
import fr.hoteia.qalingo.core.service.MarketPlaceService;
import fr.hoteia.qalingo.core.service.MarketService;
import fr.hoteia.qalingo.core.service.ProductSkuService;
import fr.hoteia.qalingo.core.service.pojo.RequestData;
import fr.hoteia.qalingo.core.web.util.RequestUtil;
/**
* <p>
* <a href="RequestUtilImpl.java.html"><i>View Source</i></a>
* </p>
*
* @author Denis Gosset <a href="http://www.hoteia.com"><i>Hoteia.com</i></a>
*
*/
@Service("requestUtil")
@Transactional
public class RequestUtilImpl implements RequestUtil {
private final Logger LOG = LoggerFactory.getLogger(getClass());
@Autowired
protected EngineSettingService engineSettingService;
@Value("${env.name}")
protected String environmentName;
@Value("${app.name}")
protected String applicationName;
@Value("${context.name}")
protected String contextName;
@Autowired
protected MarketPlaceService marketPlaceService;
@Autowired
protected MarketService marketService;
@Autowired
protected ProductSkuService productSkuService;
@Autowired
protected CustomerService customerService;
@Autowired
protected LocalizationService localizationService;
/**
*
*/
public boolean isLocalHostMode(final HttpServletRequest request) throws Exception {
if (StringUtils.isNotEmpty(getHost(request))
&& (getHost(request).contains("localhost")
|| getHost(request).equalsIgnoreCase("127.0.0.1"))) {
return true;
}
return false;
}
/**
*
*/
public String getHost(final HttpServletRequest request) throws Exception {
return (String) request.getHeader(Constants.HOST);
}
/**
*
*/
public String getEnvironmentName() throws Exception {
return environmentName;
}
/**
*
*/
public String getApplicationName() throws Exception {
return applicationName;
}
/**
*
*/
public String getContextName() throws Exception {
return contextName;
}
/**
*
*/
public DateFormat getFormatDate(final RequestData requestData, final int dateStyle, final int timeStyle) throws Exception {
final Localization localization = requestData.getLocalization();
final Locale locale = localization.getLocale();
DateFormat formatter = DateFormat.getDateTimeInstance(dateStyle, timeStyle, locale);
return formatter;
}
/**
*
*/
public SimpleDateFormat getRssFormatDate(final RequestData requestData) throws Exception {
SimpleDateFormat formatter = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z");
return formatter;
}
/**
*
*/
public SimpleDateFormat getDataVocabularyFormatDate(final RequestData requestData) throws Exception {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
return formatter;
}
/**
*
*/
public SimpleDateFormat getAtomFormatDate(final RequestData requestData) throws Exception {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssz");
return formatter;
}
/**
*
*/
public NumberFormat getCartItemPriceNumberFormat(final RequestData requestData, final String currencyCode) throws Exception {
return getNumberFormat(requestData, currencyCode, RoundingMode.HALF_EVEN, 2, 2, 1000000, 1);
}
/**
*
*/
public NumberFormat getNumberFormat(final RequestData requestData, final String currencyCode, final RoundingMode roundingMode, final int maximumFractionDigits,
final int minimumFractionDigits, final int maximumIntegerDigits, final int minimumIntegerDigits) throws Exception {
final Localization localization = requestData.getLocalization();
final Locale locale = localization.getLocale();
NumberFormat formatter = NumberFormat.getCurrencyInstance(locale);
formatter.setGroupingUsed(true);
formatter.setParseIntegerOnly(false);
formatter.setRoundingMode(roundingMode);
Currency currency = Currency.getInstance(currencyCode);
formatter.setCurrency(currency);
formatter.setMaximumFractionDigits(maximumFractionDigits);
formatter.setMinimumFractionDigits(minimumFractionDigits);
formatter.setMaximumIntegerDigits(maximumIntegerDigits);
formatter.setMinimumIntegerDigits(minimumIntegerDigits);
return formatter;
}
/**
*
*/
public String getLastRequestUrlNotSecurity(final HttpServletRequest request) throws Exception {
final List<String> excludedPatterns = new ArrayList<String>();
excludedPatterns.add("login");
excludedPatterns.add("auth");
excludedPatterns.add("logout");
excludedPatterns.add("timeout");
excludedPatterns.add("forbidden");
return getRequestUrl(request, excludedPatterns, 1);
}
/**
*
*/
public String getCurrentRequestUrl(final HttpServletRequest request, final List<String> excludedPatterns) throws Exception {
return getRequestUrl(request, excludedPatterns, 0);
}
/**
*
*/
public String getCurrentRequestUrl(final HttpServletRequest request) throws Exception {
return getRequestUrl(request, new ArrayList<String>(), 0);
}
/**
*
*/
public String getCurrentRequestUrlNotSecurity(final HttpServletRequest request) throws Exception {
final List<String> excludedPatterns = new ArrayList<String>();
excludedPatterns.add("login");
excludedPatterns.add("auth");
excludedPatterns.add("logout");
excludedPatterns.add("timeout");
excludedPatterns.add("forbidden");
return getRequestUrl(request, excludedPatterns, 0);
}
/**
*
*/
public String getLastRequestUrl(final HttpServletRequest request, final List<String> excludedPatterns, String fallbackUrl) throws Exception {
String url = getRequestUrl(request, excludedPatterns, 1);
if(StringUtils.isEmpty(url)){
return fallbackUrl;
}
return url;
}
/**
*
*/
public String getLastRequestUrl(final HttpServletRequest request, final List<String> excludedPatterns) throws Exception {
return getRequestUrl(request, excludedPatterns, 1);
}
/**
*
*/
public String getLastRequestUrl(final HttpServletRequest request) throws Exception {
return getRequestUrl(request, new ArrayList<String>(), 1);
}
/**
*
*/
public String getRequestUrl(final HttpServletRequest request, final List<String> excludedPatterns, int position) throws Exception {
String url = Constants.EMPTY;
final List<ClickstreamRequest> clickstreams = getClickStreamRequests(request);
if(clickstreams != null
&& !clickstreams.isEmpty()) {
if(clickstreams != null
&& !clickstreams.isEmpty()) {
// Clean not html values or exluded patterns
List<ClickstreamRequest> cleanClickstreams = new ArrayList<ClickstreamRequest>();
Iterator<ClickstreamRequest> it = clickstreams.iterator();
while (it.hasNext()) {
ClickstreamRequest clickstream = (ClickstreamRequest) it.next();
String uri = clickstream.getRequestURI();
if(uri.endsWith(".html")){
// TEST IF THE URL IS EXCLUDE
CharSequence[] excludedPatternsCharSequence = excludedPatterns.toArray(new CharSequence[excludedPatterns.size()]);
boolean isExclude = false;
for (int i = 0; i < excludedPatternsCharSequence.length; i++) {
CharSequence string = excludedPatternsCharSequence[i];
if(uri.contains(string)){
isExclude = true;
}
}
if(BooleanUtils.negate(isExclude)){
cleanClickstreams.add(clickstream);
}
}
}
if(cleanClickstreams.size() == 1) {
Iterator<ClickstreamRequest> itCleanClickstreams = cleanClickstreams.iterator();
while (itCleanClickstreams.hasNext()) {
ClickstreamRequest clickstream = (ClickstreamRequest) itCleanClickstreams.next();
String uri = clickstream.getRequestURI();
url = uri;
}
} else {
Iterator<ClickstreamRequest> itCleanClickstreams = cleanClickstreams.iterator();
int countCleanClickstream = 1;
while (itCleanClickstreams.hasNext()) {
ClickstreamRequest clickstream = (ClickstreamRequest) itCleanClickstreams.next();
String uri = clickstream.getRequestURI();
// The last url is the current URI, so we need to get the url previous the last
if(countCleanClickstream == (cleanClickstreams.size() - position)) {
url = uri;
}
countCleanClickstream++;
}
}
}
}
// CLEAN CONTEXT FROM URL
if(StringUtils.isNotEmpty(url)
&& !isLocalHostMode(request)
&& url.contains(request.getContextPath())){
url = url.replace(request.getContextPath(), "");
}
return handleUrl(url);
}
/**
*
*/
public String getRootAssetFilePath(final HttpServletRequest request) throws Exception {
EngineSetting engineSetting = engineSettingService.getAssetFileRootPath();
String prefixPath = "";
if(engineSetting != null){
prefixPath = engineSetting.getDefaultValue();
}
if(prefixPath.endsWith("/")){
prefixPath = prefixPath.substring(0, prefixPath.length() - 1);
}
return prefixPath;
}
/**
*
*/
public String getRootAssetWebPath(final HttpServletRequest request) throws Exception {
EngineSetting engineSetting = engineSettingService.getAssetWebRootPath();
String prefixPath = "";
if(engineSetting != null){
prefixPath = engineSetting.getDefaultValue();
}
if(prefixPath.endsWith("/")){
prefixPath = prefixPath.substring(0, prefixPath.length() - 1);
}
return prefixPath;
}
/**
*
*/
public String getCatalogImageWebPath(final HttpServletRequest request, final Asset asset) throws Exception {
EngineSetting engineSetting = engineSettingService.getAssetCatalogFilePath();
String prefixPath = "";
if(engineSetting != null){
prefixPath = engineSetting.getDefaultValue();
}
String catalogImageWebPath = getRootAssetWebPath(request) + prefixPath + "/" + asset.getType().getPropertyKey().toLowerCase() + "/" + asset.getPath();
if(catalogImageWebPath.endsWith("/")){
catalogImageWebPath = catalogImageWebPath.substring(0, catalogImageWebPath.length() - 1);
}
return catalogImageWebPath;
}
/**
*
*/
public String getProductMarketingImageWebPath(final HttpServletRequest request, final Asset asset) throws Exception {
EngineSetting engineSetting = engineSettingService.getAssetProductMarketingFilePath();
String prefixPath = "";
if(engineSetting != null){
prefixPath = engineSetting.getDefaultValue();
}
String productMarketingImageWebPath = getRootAssetWebPath(request) + prefixPath + "/" + asset.getType().getPropertyKey().toLowerCase() + "/" + asset.getPath();
if(productMarketingImageWebPath.endsWith("/")){
productMarketingImageWebPath = productMarketingImageWebPath.substring(0, productMarketingImageWebPath.length() - 1);
}
return productMarketingImageWebPath;
}
/**
*
*/
public String getProductSkuImageWebPath(final HttpServletRequest request, final Asset asset) throws Exception {
EngineSetting engineSetting = engineSettingService.getAssetPoductSkuFilePath();
String prefixPath = "";
if(engineSetting != null){
prefixPath = engineSetting.getDefaultValue();
}
String productSkuImageWebPath = getRootAssetWebPath(request) + prefixPath + "/" + asset.getType().getPropertyKey().toLowerCase() + "/" + asset.getPath();
if(productSkuImageWebPath.endsWith("/")){
productSkuImageWebPath = productSkuImageWebPath.substring(0, productSkuImageWebPath.length() - 1);
}
return productSkuImageWebPath;
}
/**
*
*/
public String getCurrentThemeResourcePrefixPath(final HttpServletRequest request) throws Exception {
EngineSetting engineSetting = engineSettingService.getThemeResourcePrefixPath();
try {
String contextValue = getCurrentContextNameValue(request);
EngineSettingValue engineSettingValue = engineSetting.getEngineSettingValue(contextValue);
String prefixPath = engineSetting.getDefaultValue();
if(engineSettingValue != null){
prefixPath = engineSettingValue.getValue();
} else {
LOG.warn("This engine setting is request, but doesn't exist: " + engineSetting.getCode() + "/" + contextValue);
}
String currentThemeResourcePrefixPath = prefixPath + getCurrentTheme(request);
if(currentThemeResourcePrefixPath.endsWith("/")){
currentThemeResourcePrefixPath = currentThemeResourcePrefixPath.substring(0, currentThemeResourcePrefixPath.length() - 1);
}
return currentThemeResourcePrefixPath;
} catch (Exception e) {
LOG.error("Context name, " + getContextName() + " can't be resolve by EngineSettingWebAppContext class.", e);
}
return null;
}
/**
*
*/
public String getCurrentContextNameValue(final HttpServletRequest request) throws Exception {
return EngineSettingWebAppContext.valueOf(getContextName()).getPropertyKey();
}
/**
*
*/
public String getCurrentVelocityWebPrefix(final HttpServletRequest request) throws Exception {
String velocityPath = "/" + getCurrentTheme(request) + "/www/" + getCurrentDevice(request) + "/content/";
return velocityPath;
}
/**
*
*/
public String getCurrentVelocityEmailPrefix(final HttpServletRequest request) throws Exception {
String velocityPath = "/" + getCurrentTheme(request) + "/email/";
return velocityPath;
}
/**
*
*/
@SuppressWarnings("unchecked")
protected List<ClickstreamRequest> getClickStreamRequests(final HttpServletRequest request) {
- final List<ClickstreamRequest> clickstreams = getClickStream(request).getStream();
- return clickstreams;
+ Clickstream clickstream = getClickStream(request);
+ if(clickstream != null){
+ final List<ClickstreamRequest> clickstreams = getClickStream(request).getStream();
+ return clickstreams;
+ }
+ return null;
}
/**
*
*/
protected Clickstream getClickStream(final HttpServletRequest request) {
final Clickstream stream = (Clickstream) request.getSession().getAttribute(ClickstreamListener.SESSION_ATTRIBUTE_KEY);
return stream;
}
/**
*
*/
protected String handleUrl(String url) {
return url;
}
/**
*
*/
public EngineEcoSession getCurrentEcoSession(final HttpServletRequest request) throws Exception {
EngineEcoSession engineEcoSession = (EngineEcoSession) request.getSession().getAttribute(Constants.ENGINE_ECO_SESSION_OBJECT);
engineEcoSession = checkEngineEcoSession(request, engineEcoSession);
return engineEcoSession;
}
/**
*
*/
public void updateCurrentEcoSession(final HttpServletRequest request, final EngineEcoSession engineEcoSession) throws Exception {
setCurrentEcoSession(request, engineEcoSession);
}
/**
*
*/
public void setCurrentEcoSession(final HttpServletRequest request, final EngineEcoSession engineEcoSession) throws Exception {
request.getSession().setAttribute(Constants.ENGINE_ECO_SESSION_OBJECT, engineEcoSession);
}
/**
*
*/
public EngineBoSession getCurrentBoSession(final HttpServletRequest request) throws Exception {
EngineBoSession engineBoSession = (EngineBoSession) request.getSession().getAttribute(Constants.ENGINE_BO_SESSION_OBJECT);
engineBoSession = checkEngineBoSession(request, engineBoSession);
return engineBoSession;
}
/**
*
*/
public void updateCurrentBoSession(final HttpServletRequest request, final EngineBoSession engineBoSession) throws Exception {
setCurrentBoSession(request, engineBoSession);
}
/**
*
*/
public void setCurrentBoSession(final HttpServletRequest request, final EngineBoSession engineBoSession) throws Exception {
request.getSession().setAttribute(Constants.ENGINE_BO_SESSION_OBJECT, engineBoSession);
}
/**
*
*/
public Cart getCurrentCart(final HttpServletRequest request) throws Exception {
EngineEcoSession engineEcoSession = getCurrentEcoSession(request);
return engineEcoSession.getCart();
}
/**
*
*/
public void updateCurrentCart(final HttpServletRequest request, final Cart cart) throws Exception {
EngineEcoSession engineEcoSession = getCurrentEcoSession(request);
engineEcoSession.setCart(cart);
updateCurrentEcoSession(request, engineEcoSession);
}
/**
*
*/
public void updateCurrentCart(final HttpServletRequest request, final String skuCode, final int quantity) throws Exception {
// SANITY CHECK : sku code is empty or null : no sense
if (StringUtils.isEmpty(skuCode)) {
throw new Exception("");
}
// SANITY CHECK : quantity is equal zero : no sense
if (StringUtils.isEmpty(skuCode)) {
throw new Exception("");
}
Cart cart = getCurrentCart(request);
Set<CartItem> cartItems = cart.getCartItems();
boolean productSkuIsNew = true;
for (Iterator<CartItem> iterator = cartItems.iterator(); iterator.hasNext();) {
CartItem cartItem = (CartItem) iterator.next();
if (cartItem.getProductSkuCode().equalsIgnoreCase(skuCode)) {
int newQuantity = cartItem.getQuantity() + quantity;
cartItem.setQuantity(newQuantity);
productSkuIsNew = false;
}
}
if (productSkuIsNew) {
final MarketArea marketArea = getCurrentMarketArea(request);
final Retailer retailer = getCurrentRetailer(request);
CartItem cartItem = new CartItem();
ProductSku productSku = productSkuService.getProductSkuByCode(marketArea.getId(), retailer.getId(), skuCode);
cartItem.setProductSkuCode(skuCode);
cartItem.setProductSku(productSku);
cartItem.setQuantity(quantity);
cart.getCartItems().add(cartItem);
}
updateCurrentCart(request, cart);
// TODO update session/cart db ?
}
/**
*
*/
public void updateCurrentCart(final HttpServletRequest request, final Long billingAddressId, final Long shippingAddressId) throws Exception {
Cart cart = getCurrentCart(request);
cart.setBillingAddressId(billingAddressId);
cart.setShippingAddressId(shippingAddressId);
updateCurrentCart(request, cart);
// TODO update session/cart db ?
}
/**
*
*/
public void cleanCurrentCart(final HttpServletRequest request) throws Exception {
Cart cart = new Cart();
updateCurrentCart(request, cart);
// TODO update session/cart db ?
}
/**
*
*/
public Order getLastOrder(final HttpServletRequest request) throws Exception {
EngineEcoSession engineEcoSession = getCurrentEcoSession(request);
return engineEcoSession.getLastOrder();
}
/**
*
*/
public void saveLastOrder(final HttpServletRequest request, final Order order) throws Exception {
if (order != null) {
EngineEcoSession engineEcoSession = getCurrentEcoSession(request);
engineEcoSession.setLastOrder(order);
updateCurrentEcoSession(request, engineEcoSession);
}
}
/**
*
*/
public void removeCartItemFromCurrentCart(final HttpServletRequest request, final String skuCode) throws Exception {
Cart cart = getCurrentCart(request);
Set<CartItem> cartItems = cart.getCartItems();
for (Iterator<CartItem> iterator = cartItems.iterator(); iterator.hasNext();) {
CartItem cartItem = (CartItem) iterator.next();
if (cartItem.getProductSkuCode().equalsIgnoreCase(skuCode)) {
cartItems.remove(cartItem);
}
}
cart.setCartItems(cartItems);
updateCurrentCart(request, cart);
// TODO update session/cart db ?
}
/**
*
*/
public MarketPlace getCurrentMarketPlace(final HttpServletRequest request) throws Exception {
MarketPlace marketPlace = null;
if(isBackoffice()){
EngineBoSession engineBoSession = getCurrentBoSession(request);
marketPlace = engineBoSession.getCurrentMarketPlace();
if (marketPlace == null) {
initDefaultBoMarketPlace(request);
marketPlace = engineBoSession.getCurrentMarketPlace();
}
} else {
EngineEcoSession engineEcoSession = getCurrentEcoSession(request);
marketPlace = engineEcoSession.getCurrentMarketPlace();
if (marketPlace == null) {
initDefaultEcoMarketPlace(request);
marketPlace = engineEcoSession.getCurrentMarketPlace();
}
}
return marketPlace;
}
/**
*
*/
public Market getCurrentMarket(final HttpServletRequest request) throws Exception {
Market market = null;
if(isBackoffice()){
EngineBoSession engineBoSession = getCurrentBoSession(request);
market = engineBoSession.getCurrentMarket();
if (market == null) {
initDefaultEcoMarketPlace(request);
market = engineBoSession.getCurrentMarket();
}
} else {
EngineEcoSession engineEcoSession = getCurrentEcoSession(request);
market = engineEcoSession.getCurrentMarket();
if (market == null) {
initDefaultEcoMarketPlace(request);
market = engineEcoSession.getCurrentMarket();
}
}
return market;
}
/**
*
*/
public MarketArea getCurrentMarketArea(final HttpServletRequest request) throws Exception {
MarketArea marketArea = null;
if(isBackoffice()){
EngineBoSession engineBoSession = getCurrentBoSession(request);
marketArea = engineBoSession.getCurrentMarketArea();
if (marketArea == null) {
initDefaultBoMarketPlace(request);
marketArea = engineBoSession.getCurrentMarketArea();
}
} else {
EngineEcoSession engineEcoSession = getCurrentEcoSession(request);
marketArea = engineEcoSession.getCurrentMarketArea();
if (marketArea == null) {
initDefaultEcoMarketPlace(request);
marketArea = engineEcoSession.getCurrentMarketArea();
}
}
return marketArea;
}
/**
*
*/
public Localization getCurrentMarketLocalization(final HttpServletRequest request) throws Exception {
Localization localization = null;
if(isBackoffice()){
EngineBoSession engineBoSession = getCurrentBoSession(request);
localization = engineBoSession.getCurrentMarketLocalization();
} else {
EngineEcoSession engineEcoSession = getCurrentEcoSession(request);
localization = engineEcoSession.getCurrentLocalization();
}
return localization;
}
/**
*
*/
public Localization getCurrentLocalization(final HttpServletRequest request) throws Exception {
Localization localization = null;
if(isBackoffice()){
EngineBoSession engineBoSession = getCurrentBoSession(request);
localization = engineBoSession.getCurrentMarketLocalization();
} else {
EngineEcoSession engineEcoSession = getCurrentEcoSession(request);
localization = engineEcoSession.getCurrentLocalization();
}
return localization;
}
/**
*
*/
public Locale getCurrentLocale(final HttpServletRequest request) throws Exception {
Localization localization = getCurrentLocalization(request);
if (localization != null) {
return localization.getLocale();
} else {
LOG.warn("Current Locale is null and it is not possible. Need to reset session.");
if(isBackoffice()){
initDefaultBoMarketPlace(request);
} else {
initDefaultEcoMarketPlace(request);
}
localization = getCurrentLocalization(request);
return localization.getLocale();
}
}
/**
*
*/
public void updateCurrentLocalization(final HttpServletRequest request, final Localization localization) throws Exception {
if (localization != null) {
if(isBackoffice()){
EngineBoSession engineBoSession = getCurrentBoSession(request);
engineBoSession.setCurrentLocalization(localization);
updateCurrentBoSession(request, engineBoSession);
} else {
EngineEcoSession engineEcoSession = getCurrentEcoSession(request);
engineEcoSession.setCurrentLocalization(localization);
updateCurrentEcoSession(request, engineEcoSession);
}
}
}
/**
*
*/
public Retailer getCurrentRetailer(final HttpServletRequest request) throws Exception {
Retailer retailer = null;
if(isBackoffice()){
EngineBoSession engineBoSession = getCurrentBoSession(request);
retailer = engineBoSession.getCurrentRetailer();
if (retailer == null) {
initDefaultBoMarketPlace(request);
}
} else {
EngineEcoSession engineEcoSession = getCurrentEcoSession(request);
retailer = engineEcoSession.getCurrentRetailer();
if (retailer == null) {
initDefaultEcoMarketPlace(request);
}
}
return retailer;
}
/**
*
*/
public Customer getCurrentCustomer(final HttpServletRequest request) throws Exception {
EngineEcoSession engineEcoSession = getCurrentEcoSession(request);
Customer customer = engineEcoSession.getCurrentCustomer();
if (customer == null) {
// CHECK
if(SecurityContextHolder.getContext().getAuthentication() != null){
String username = SecurityContextHolder.getContext().getAuthentication().getName();
if (StringUtils.isNotEmpty(username) && !username.equalsIgnoreCase("anonymousUser")) {
customer = customerService.getCustomerByLoginOrEmail(username);
engineEcoSession.setCurrentCustomer(customer);
}
}
}
return customer;
}
/**
*
*/
public String getCustomerAvatar(final HttpServletRequest request, final Customer customer) throws Exception {
String customerAvatar = null;
if (customer != null){
if ( StringUtils.isNotEmpty(customer.getAvatarImg())) {
customerAvatar = customer.getAvatarImg();
} else {
String email = customer.getEmail().toLowerCase().trim();
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] array = md.digest(email.getBytes("CP1252"));
StringBuffer sb = new StringBuffer();
for (int i = 0; i < array.length; ++i) {
sb.append(Integer.toHexString((array[i]
& 0xFF) | 0x100).substring(1,3));
}
String gravatarId = sb.toString();
if("https".equals(request.getScheme())){
customerAvatar = "https://secure.gravatar.com/avatar/" + gravatarId;
} else {
customerAvatar = "http://www.gravatar.com/avatar/" + gravatarId;
}
}
}
return customerAvatar;
}
/**
*
*/
public boolean hasKnownCustomerLogged(final HttpServletRequest request) throws Exception {
final Customer customer = getCurrentCustomer(request);
if (customer != null) {
return true;
}
return false;
}
/**
*
*/
public Long getCurrentCustomerId(final HttpServletRequest request) throws Exception {
Customer customer = getCurrentCustomer(request);
if (customer == null) {
return null;
}
return customer.getId();
}
/**
*
*/
public String getCurrentCustomerLogin(final HttpServletRequest request) throws Exception {
EngineEcoSession engineEcoSession = getCurrentEcoSession(request);
Customer customer = engineEcoSession.getCurrentCustomer();
if (customer == null) {
return null;
}
return customer.getLogin();
}
/**
*
*/
public void updateCurrentCustomer(final HttpServletRequest request, final Customer customer) throws Exception {
if (customer != null) {
final EngineEcoSession engineEcoSession = getCurrentEcoSession(request);
engineEcoSession.setCurrentCustomer(customer);
updateCurrentEcoSession(request, engineEcoSession);
}
}
/**
*
*/
public void cleanCurrentCustomer(final HttpServletRequest request) throws Exception {
final EngineEcoSession engineEcoSession = getCurrentEcoSession(request);
engineEcoSession.setCurrentCustomer(null);
updateCurrentEcoSession(request, engineEcoSession);
}
/**
*
*/
public void handleFrontofficeUrlParameters(final HttpServletRequest request) throws Exception {
String marketPlaceCode = request.getParameter(RequestConstants.REQUEST_PARAMETER_MARKET_PLACE_CODE);
String marketCode = request.getParameter(RequestConstants.REQUEST_PARAMETER_MARKET_CODE);
String marketAreaCode = request.getParameter(RequestConstants.REQUEST_PARAMETER_MARKET_AREA_CODE);
String localeCode = request.getParameter(RequestConstants.REQUEST_PARAMETER_MARKET_LANGUAGE);
String retailerCode = request.getParameter(RequestConstants.REQUEST_PARAMETER_RETAILER_CODE);
EngineEcoSession engineEcoSession = getCurrentEcoSession(request);
MarketPlace currentMarketPlace = engineEcoSession.getCurrentMarketPlace();
if (StringUtils.isNotEmpty(marketPlaceCode) && StringUtils.isNotEmpty(marketCode) && StringUtils.isNotEmpty(marketAreaCode) && StringUtils.isNotEmpty(localeCode)) {
if (currentMarketPlace != null && !currentMarketPlace.getCode().equalsIgnoreCase(marketPlaceCode)) {
// RESET ALL SESSION AND CHANGE THE MARKET PLACE
resetCart(request);
initEcoSession(request);
MarketPlace newMarketPlace = marketPlaceService.getMarketPlaceByCode(marketPlaceCode);
if (newMarketPlace == null) {
// INIT A DEFAULT MARKET PLACE
initDefaultEcoMarketPlace(request);
} else {
// MARKET PLACE
engineEcoSession.setCurrentMarketPlace(newMarketPlace);
updateCurrentTheme(request, newMarketPlace.getTheme());
// MARKET
Market market = newMarketPlace.getMarket(marketCode);
if (market == null) {
market = newMarketPlace.getDefaultMarket();
}
engineEcoSession.setCurrentMarket(market);
// MARKET MODE
MarketArea marketArea = market.getMarketArea(marketAreaCode);
if (marketArea == null) {
marketArea = market.getDefaultMarketArea();
}
// TODO : why : SET A RELOAD OBJECT MARKET AREA -> event LazyInitializationException: could not initialize proxy - no Session
engineEcoSession.setCurrentMarketArea(marketService.getMarketAreaById(marketArea.getId().toString()));
// LOCALE
Localization localization = marketArea.getLocalization(localeCode);
if (localization == null) {
Localization defaultLocalization = marketArea.getDefaultLocalization();
engineEcoSession.setCurrentLocalization(defaultLocalization);
} else {
engineEcoSession.setCurrentLocalization(localization);
}
// RETAILER
Retailer retailer = marketArea.getRetailer(retailerCode);
if (retailer == null) {
Retailer defaultRetailer = marketArea.getDefaultRetailer();
engineEcoSession.setCurrentRetailer(defaultRetailer);
} else {
engineEcoSession.setCurrentRetailer(retailer);
}
}
} else {
Market market = engineEcoSession.getCurrentMarket();
if (market != null && !market.getCode().equalsIgnoreCase(marketCode)) {
// RESET CART
resetCart(request);
// CHANGE THE MARKET
Market newMarket = marketService.getMarketByCode(marketCode);
if (newMarket == null) {
newMarket = currentMarketPlace.getDefaultMarket();
}
engineEcoSession.setCurrentMarket(newMarket);
updateCurrentTheme(request, newMarket.getTheme());
// MARKET MODE
MarketArea marketArea = newMarket.getMarketArea(marketAreaCode);
if (marketArea == null) {
marketArea = market.getDefaultMarketArea();
}
// TODO : why : SET A RELOAD OBJECT MARKET AREA -> event LazyInitializationException: could not initialize proxy - no Session
engineEcoSession.setCurrentMarketArea(marketService.getMarketAreaById(marketArea.getId().toString()));
// LOCALE
Localization localization = marketArea.getLocalization(localeCode);
if (localization == null) {
Localization defaultLocalization = marketArea.getDefaultLocalization();
engineEcoSession.setCurrentLocalization(defaultLocalization);
} else {
engineEcoSession.setCurrentLocalization(localization);
}
// RETAILER
Retailer retailer = marketArea.getRetailer(retailerCode);
if (retailer == null) {
Retailer defaultRetailer = marketArea.getDefaultRetailer();
engineEcoSession.setCurrentRetailer(defaultRetailer);
} else {
engineEcoSession.setCurrentRetailer(retailer);
}
} else {
MarketArea marketArea = engineEcoSession.getCurrentMarketArea();
if (marketArea != null && !marketArea.getCode().equalsIgnoreCase(marketAreaCode)) {
// RESET CART
resetCart(request);
// CHANGE THE MARKET MODE
MarketArea newMarketArea = market.getMarketArea(marketAreaCode);
if (newMarketArea == null) {
newMarketArea = market.getDefaultMarketArea();
}
// TODO : why : SET A RELOAD OBJECT MARKET AREA -> event LazyInitializationException: could not initialize proxy - no Session
engineEcoSession.setCurrentMarketArea(marketService.getMarketAreaById(newMarketArea.getId().toString()));
updateCurrentTheme(request, newMarketArea.getTheme());
// LOCALE
Localization localization = newMarketArea.getLocalization(localeCode);
if (localization == null) {
Localization defaultLocalization = marketArea.getDefaultLocalization();
engineEcoSession.setCurrentLocalization(defaultLocalization);
} else {
engineEcoSession.setCurrentLocalization(localization);
}
// RETAILER
Retailer retailer = marketArea.getRetailer(retailerCode);
if (retailer == null) {
Retailer defaultRetailer = marketArea.getDefaultRetailer();
engineEcoSession.setCurrentRetailer(defaultRetailer);
} else {
engineEcoSession.setCurrentRetailer(retailer);
}
} else {
Localization localization = engineEcoSession.getCurrentLocalization();
if (localization != null && !localization.getLocale().toString().equalsIgnoreCase(localeCode)) {
// CHANGE THE LOCALE
Localization newLocalization = marketArea.getLocalization(localeCode);
if (newLocalization == null) {
Localization defaultLocalization = marketArea.getDefaultLocalization();
engineEcoSession.setCurrentLocalization(defaultLocalization);
} else {
engineEcoSession.setCurrentLocalization(newLocalization);
}
// RETAILER
Retailer retailer = marketArea.getRetailer(retailerCode);
if (retailer == null) {
Retailer defaultRetailer = marketArea.getDefaultRetailer();
engineEcoSession.setCurrentRetailer(defaultRetailer);
} else {
engineEcoSession.setCurrentRetailer(retailer);
}
} else {
Retailer retailer = engineEcoSession.getCurrentRetailer();
if (retailer != null && !retailer.getCode().toString().equalsIgnoreCase(retailerCode)) {
// CHANGE THE RETAILER
Retailer newRetailer = marketArea.getRetailer(retailerCode);
if (newRetailer == null) {
Retailer defaultRetailer = marketArea.getDefaultRetailer();
engineEcoSession.setCurrentRetailer(defaultRetailer);
} else {
engineEcoSession.setCurrentRetailer(newRetailer);
}
}
}
}
}
}
}
// THEME
final MarketArea marketArea = getCurrentMarketArea(request);
String themeFolder = "default";
if (StringUtils.isNotEmpty(marketArea.getTheme())) {
themeFolder = marketArea.getTheme();
}
updateCurrentTheme(request, themeFolder);
// SAVE THE ENGINE SESSION
updateCurrentEcoSession(request, engineEcoSession);
}
/**
*
*/
public User getCurrentUser(final HttpServletRequest request) throws Exception {
EngineBoSession engineBoSession = getCurrentBoSession(request);
return engineBoSession.getCurrentUser();
}
/**
*
*/
public Long getCurrentUserId(final HttpServletRequest request) throws Exception {
User user = getCurrentUser(request);
if(user == null){
return null;
}
return user.getId();
}
/**
*
*/
public void updateCurrentUser(final HttpServletRequest request, final User user) throws Exception {
if(user != null){
final EngineBoSession engineBoSSession = getCurrentBoSession(request);
engineBoSSession.setCurrentUser(user);
updateCurrentBoSession(request, engineBoSSession);
}
}
/**
*
*/
public void handleBackofficeUrlParameters(final HttpServletRequest request) throws Exception {
String marketPlaceCode = request.getParameter(RequestConstants.REQUEST_PARAMETER_MARKET_PLACE_CODE);
String marketCode = request.getParameter(RequestConstants.REQUEST_PARAMETER_MARKET_CODE);
String marketAreaCode = request.getParameter(RequestConstants.REQUEST_PARAMETER_MARKET_AREA_CODE);
String marketLanguageCode = request.getParameter(RequestConstants.REQUEST_PARAMETER_MARKET_LANGUAGE);
String retailerCode = request.getParameter(RequestConstants.REQUEST_PARAMETER_RETAILER_CODE);
EngineBoSession engineBoSession = getCurrentBoSession(request);
MarketPlace currentMarketPlace = engineBoSession.getCurrentMarketPlace();
if(StringUtils.isNotEmpty(marketPlaceCode)
&& StringUtils.isNotEmpty(marketCode)
&& StringUtils.isNotEmpty(marketAreaCode)
&& StringUtils.isNotEmpty(marketLanguageCode)){
if(currentMarketPlace != null
&& !currentMarketPlace.getCode().equalsIgnoreCase(marketPlaceCode)){
// RESET ALL SESSION AND CHANGE THE MARKET PLACE
initBoSession(request);
MarketPlace newMarketPlace = marketPlaceService.getMarketPlaceByCode(marketPlaceCode);
if(newMarketPlace == null){
// INIT A DEFAULT MARKET PLACE
initDefaultBoMarketPlace(request);
} else {
// MARKET PLACE
engineBoSession.setCurrentMarketPlace(newMarketPlace);
updateCurrentTheme(request, newMarketPlace.getTheme());
// MARKET
Market market = newMarketPlace.getMarket(marketCode);
if(market == null){
market = newMarketPlace.getDefaultMarket();
}
engineBoSession.setCurrentMarket(market);
// MARKET MODE
MarketArea marketArea = market.getMarketArea(marketAreaCode);
if(marketArea == null){
marketArea = market.getDefaultMarketArea();
}
// TODO : why : SET A RELOAD OBJECT MARKET AREA -> event LazyInitializationException: could not initialize proxy - no Session
engineBoSession.setCurrentMarketArea(marketService.getMarketAreaById(marketArea.getId().toString()));
// LOCALE
Localization localization = marketArea.getLocalization(marketLanguageCode);
if(localization == null){
Localization defaultLocalization = marketArea.getDefaultLocalization();
engineBoSession.setCurrentMarketLocalization(defaultLocalization);
} else {
engineBoSession.setCurrentMarketLocalization(localization);
}
// RETAILER
Retailer retailer = marketArea.getRetailer(retailerCode);
if(retailer == null){
Retailer defaultRetailer = marketArea.getDefaultRetailer();
engineBoSession.setCurrentRetailer(defaultRetailer);
} else {
engineBoSession.setCurrentRetailer(retailer);
}
}
} else {
Market market = engineBoSession.getCurrentMarket();
if(market != null
&& !market.getCode().equalsIgnoreCase(marketCode)){
// CHANGE THE MARKET
Market newMarket = marketService.getMarketByCode(marketCode);
if(newMarket == null){
newMarket = currentMarketPlace.getDefaultMarket();
}
engineBoSession.setCurrentMarket(newMarket);
updateCurrentTheme(request, newMarket.getTheme());
// MARKET MODE
MarketArea marketArea = newMarket.getMarketArea(marketAreaCode);
if(marketArea == null){
marketArea = market.getDefaultMarketArea();
}
// TODO : why : SET A RELOAD OBJECT MARKET AREA -> event LazyInitializationException: could not initialize proxy - no Session
engineBoSession.setCurrentMarketArea(marketService.getMarketAreaById(marketArea.getId().toString()));
// LOCALE
Localization localization = marketArea.getLocalization(marketLanguageCode);
if(localization == null){
Localization defaultLocalization = marketArea.getDefaultLocalization();
engineBoSession.setCurrentMarketLocalization(defaultLocalization);
} else {
engineBoSession.setCurrentMarketLocalization(localization);
}
// RETAILER
Retailer retailer = marketArea.getRetailer(retailerCode);
if(retailer == null){
Retailer defaultRetailer = marketArea.getDefaultRetailer();
engineBoSession.setCurrentRetailer(defaultRetailer);
} else {
engineBoSession.setCurrentRetailer(retailer);
}
} else {
MarketArea marketArea = engineBoSession.getCurrentMarketArea();
if(marketArea != null
&& !marketArea.getCode().equalsIgnoreCase(marketAreaCode)){
// CHANGE THE MARKET MODE
MarketArea newMarketArea = market.getMarketArea(marketAreaCode);
if(newMarketArea == null){
newMarketArea = market.getDefaultMarketArea();
}
// TODO : why : SET A RELOAD OBJECT MARKET AREA -> event LazyInitializationException: could not initialize proxy - no Session
engineBoSession.setCurrentMarketArea(marketService.getMarketAreaById(newMarketArea.getId().toString()));
updateCurrentTheme(request, newMarketArea.getTheme());
// LOCALE
Localization localization = newMarketArea.getLocalization(marketLanguageCode);
if(localization == null){
Localization defaultLocalization = marketArea.getDefaultLocalization();
engineBoSession.setCurrentMarketLocalization(defaultLocalization);
} else {
engineBoSession.setCurrentMarketLocalization(localization);
}
// RETAILER
Retailer retailer = marketArea.getRetailer(retailerCode);
if(retailer == null){
Retailer defaultRetailer = marketArea.getDefaultRetailer();
engineBoSession.setCurrentRetailer(defaultRetailer);
} else {
engineBoSession.setCurrentRetailer(retailer);
}
} else {
Localization localization = engineBoSession.getCurrentMarketLocalization();
if(localization != null
&& !localization.getLocale().toString().equalsIgnoreCase(marketLanguageCode)){
// CHANGE THE LOCALE
Localization newLocalization = marketArea.getLocalization(marketLanguageCode);
if(newLocalization == null){
Localization defaultLocalization = marketArea.getDefaultLocalization();
engineBoSession.setCurrentMarketLocalization(defaultLocalization);
} else {
engineBoSession.setCurrentMarketLocalization(newLocalization);
}
// RETAILER
Retailer retailer = marketArea.getRetailer(retailerCode);
if(retailer == null){
Retailer defaultRetailer = marketArea.getDefaultRetailer();
engineBoSession.setCurrentRetailer(defaultRetailer);
} else {
engineBoSession.setCurrentRetailer(retailer);
}
} else {
Retailer retailer = engineBoSession.getCurrentRetailer();
if(retailer != null
&& !retailer.getCode().toString().equalsIgnoreCase(retailerCode)){
// CHANGE THE RETAILER
Retailer newRetailer = marketArea.getRetailer(retailerCode);
if(newRetailer == null){
Retailer defaultRetailer = marketArea.getDefaultRetailer();
engineBoSession.setCurrentRetailer(defaultRetailer);
} else {
engineBoSession.setCurrentRetailer(newRetailer);
}
}
}
}
}
}
}
// CHECK BACKOFFICE LANGUAGES
String localeCode = request.getParameter(RequestConstants.REQUEST_PARAMETER_LOCALE_CODE);
// LOCALIZATIONS
Company company = getCurrentCompany(request);
if(company != null){
Localization localization = company.getLocalization(localeCode);
if(localization != null){
engineBoSession.setCurrentLocalization(localization);
}
}
// SAVE THE ENGINE SESSION
updateCurrentBoSession(request, engineBoSession);
}
/**
*
*/
@Override
public String getCurrentTheme(final HttpServletRequest request) throws Exception {
EngineEcoSession engineEcoSession = getCurrentEcoSession(request);
String currenTheme = engineEcoSession.getTheme();
// SANITY CHECK
if (StringUtils.isEmpty(currenTheme)) {
return "default";
}
return currenTheme;
}
/**
*
*/
@Override
public void updateCurrentTheme(final HttpServletRequest request, final String theme) throws Exception {
final EngineEcoSession engineEcoSession = getCurrentEcoSession(request);
if (StringUtils.isNotEmpty(theme)) {
engineEcoSession.setTheme(theme);
updateCurrentEcoSession(request, engineEcoSession);
}
}
/**
*
*/
@Override
public String getCurrentDevice(final HttpServletRequest request) throws Exception {
String currenDevice = "default";
if(isBackoffice()){
EngineBoSession engineBoSession = getCurrentBoSession(request);
if(StringUtils.isNotEmpty(engineBoSession.getDevice())){
currenDevice = engineBoSession.getDevice();
}
} else {
EngineEcoSession engineEcoSession = getCurrentEcoSession(request);
if(StringUtils.isNotEmpty(engineEcoSession.getDevice())){
currenDevice = engineEcoSession.getDevice();
}
}
return currenDevice;
}
/**
*
*/
@Override
public void updateCurrentDevice(final HttpServletRequest request, final String device) throws Exception {
if(isBackoffice()){
final EngineBoSession engineBoSession = getCurrentBoSession(request);
if (StringUtils.isNotEmpty(device)) {
engineBoSession.setDevice(device);
updateCurrentBoSession(request, engineBoSession);
}
} else {
final EngineEcoSession engineEcoSession = getCurrentEcoSession(request);
if (StringUtils.isNotEmpty(device)) {
engineEcoSession.setDevice(device);
updateCurrentEcoSession(request, engineEcoSession);
}
}
}
/**
*
*/
public Company getCurrentCompany(final HttpServletRequest request) throws Exception {
EngineBoSession engineBoSession = getCurrentBoSession(request);
User user = engineBoSession.getCurrentUser();
if(user == null){
return null;
}
return user.getCompany();
}
/**
*
*/
public RequestData getRequestData(final HttpServletRequest request) throws Exception {
RequestData requestData = new RequestData();
requestData.setRequest(request);
String contextPath = "";
if (request.getRequestURL().toString().contains("localhost")
|| request.getRequestURL().toString().contains("127.0.0.1")){
contextPath = contextPath + request.getContextPath() + "/";
} else {
contextPath = "/";
}
requestData.setContextPath(contextPath);
requestData.setContextNameValue(getCurrentContextNameValue(request));
requestData.setVelocityEmailPrefix(getCurrentVelocityEmailPrefix(request));
requestData.setMarketPlace(getCurrentMarketPlace(request));
requestData.setMarket(getCurrentMarket(request));
requestData.setMarketArea(getCurrentMarketArea(request));
requestData.setLocalization(getCurrentLocalization(request));
requestData.setRetailer(getCurrentRetailer(request));
if(getCurrentCustomer(request) != null){
requestData.setCustomer(getCurrentCustomer(request));
}
return requestData;
}
/**
*
*/
protected EngineEcoSession initEcoSession(final HttpServletRequest request) throws Exception {
final EngineEcoSession engineEcoSession = new EngineEcoSession();
setCurrentEcoSession(request, engineEcoSession);
String jSessionId = request.getSession().getId();
engineEcoSession.setjSessionId(jSessionId);
initCart(request);
initDefaultEcoMarketPlace(request);
updateCurrentEcoSession(request, engineEcoSession);
return engineEcoSession;
}
/**
*
*/
protected EngineEcoSession checkEngineEcoSession(final HttpServletRequest request, EngineEcoSession engineEcoSession) throws Exception {
if (engineEcoSession == null) {
engineEcoSession = initEcoSession(request);
}
String jSessionId = request.getSession().getId();
if (!engineEcoSession.getjSessionId().equals(jSessionId)) {
engineEcoSession.setjSessionId(jSessionId);
updateCurrentEcoSession(request, engineEcoSession);
}
return engineEcoSession;
}
/**
*
*/
protected EngineBoSession checkEngineBoSession(final HttpServletRequest request, EngineBoSession engineBoSession) throws Exception {
if(engineBoSession == null) {
engineBoSession = initBoSession(request);
}
String jSessionId = request.getSession().getId();
if(!engineBoSession.getjSessionId().equals(jSessionId)){
engineBoSession.setjSessionId(jSessionId);
updateCurrentBoSession(request, engineBoSession);
}
return engineBoSession;
}
/**
*
*/
protected void initDefaultBoMarketPlace(final HttpServletRequest request) throws Exception {
final EngineBoSession engineBoSession = getCurrentBoSession(request);
MarketPlace marketPlace = marketPlaceService.getDefaultMarketPlace();
engineBoSession.setCurrentMarketPlace(marketPlace);
Market market = marketPlace.getDefaultMarket();
engineBoSession.setCurrentMarket(market);
MarketArea marketArea = market.getDefaultMarketArea();
// TODO : why : SET A RELOAD OBJECT MARKET AREA -> event LazyInitializationException: could not initialize proxy - no Session
engineBoSession.setCurrentMarketArea(marketService.getMarketAreaById(marketArea.getId().toString()));
// DEFAULT LOCALE IS FROM THE REQUEST OR FROM THE MARKET AREA
String requestLocale = request.getLocale().toString();
Localization localization = marketArea.getDefaultLocalization();
if(marketArea.getLocalization(requestLocale) != null){
localization = marketArea.getLocalization(requestLocale);
} else {
if(requestLocale.length() > 2){
String localeLanguage = request.getLocale().getLanguage();
if(marketArea.getLocalization(localeLanguage) != null){
localization = marketArea.getLocalization(localeLanguage);
}
}
}
engineBoSession.setCurrentMarketLocalization(localization);
Retailer retailer = marketArea.getDefaultRetailer();
engineBoSession.setCurrentRetailer(retailer);
updateCurrentBoSession(request, engineBoSession);
}
/**
*
*/
protected EngineBoSession initBoSession(final HttpServletRequest request) throws Exception {
final EngineBoSession engineBoSession = new EngineBoSession();
setCurrentBoSession(request, engineBoSession);
String jSessionId = request.getSession().getId();
engineBoSession.setjSessionId(jSessionId);
initDefaultBoMarketPlace(request);
// Default Localization
Company company = getCurrentCompany(request);
if(company != null){
// USER IS LOGGED
engineBoSession.setCurrentLocalization(company.getDefaultLocalization());
} else {
Localization defaultLocalization = localizationService.getLocalizationByCode("en");
engineBoSession.setCurrentLocalization(defaultLocalization);
}
updateCurrentBoSession(request, engineBoSession);
return engineBoSession;
}
/**
*
*/
protected void initCart(final HttpServletRequest request) throws Exception {
final EngineEcoSession engineEcoSession = getCurrentEcoSession(request);
Cart cart = engineEcoSession.getCart();
if (cart == null) {
// Init a new empty Cart with a default configuration
cart = new Cart();
}
engineEcoSession.setCart(cart);
updateCurrentEcoSession(request, engineEcoSession);
}
/**
* @throws Exception
*
*/
protected void resetCart(final HttpServletRequest request) throws Exception {
// TODO : save the current cart
// Reset Cart
updateCurrentCart(request, new Cart());
}
/**
*
*/
protected void initDefaultEcoMarketPlace(final HttpServletRequest request) throws Exception {
final EngineEcoSession engineEcoSession = getCurrentEcoSession(request);
MarketPlace marketPlace = marketPlaceService.getDefaultMarketPlace();
engineEcoSession.setCurrentMarketPlace(marketPlace);
Market market = marketPlace.getDefaultMarket();
engineEcoSession.setCurrentMarket(market);
MarketArea marketArea = market.getDefaultMarketArea();
// TODO : why : SET A RELOAD OBJECT MARKET AREA -> event LazyInitializationException: could not initialize proxy - no Session
engineEcoSession.setCurrentMarketArea(marketService.getMarketAreaById(marketArea.getId().toString()));
// DEFAULT LOCALE IS FROM THE REQUEST OR FROM THE MARKET AREA
String requestLocale = request.getLocale().toString();
Localization localization = marketArea.getDefaultLocalization();
if(marketArea.getLocalization(requestLocale) != null){
localization = marketArea.getLocalization(requestLocale);
} else {
if(requestLocale.length() > 2){
String localeLanguage = request.getLocale().getLanguage();
if(marketArea.getLocalization(localeLanguage) != null){
localization = marketArea.getLocalization(localeLanguage);
}
}
}
engineEcoSession.setCurrentLocalization(localization);
Retailer retailer = marketArea.getDefaultRetailer();
engineEcoSession.setCurrentRetailer(retailer);
updateCurrentEcoSession(request, engineEcoSession);
}
protected boolean isBackoffice() throws Exception {
if(getContextName().contains("BO_")){
return true;
}
return false;
}
}
\ No newline at end of file
| true | false | null | null |
diff --git a/src/czshare/cz/vity/freerapid/plugins/services/czshare/CzshareRunner.java b/src/czshare/cz/vity/freerapid/plugins/services/czshare/CzshareRunner.java
index ac747319..47fa39cc 100644
--- a/src/czshare/cz/vity/freerapid/plugins/services/czshare/CzshareRunner.java
+++ b/src/czshare/cz/vity/freerapid/plugins/services/czshare/CzshareRunner.java
@@ -1,226 +1,230 @@
package cz.vity.freerapid.plugins.services.czshare;
import cz.vity.freerapid.plugins.exceptions.*;
import cz.vity.freerapid.plugins.webclient.AbstractRunner;
import cz.vity.freerapid.plugins.webclient.DownloadState;
import cz.vity.freerapid.plugins.webclient.FileState;
import cz.vity.freerapid.plugins.webclient.utils.PlugUtils;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;
import java.util.regex.Matcher;
/**
* @author Ladislav Vitasek, Ludek Zika, Jan Smejkal (edit from Hellshare to CZshare)
*/
class CzshareRunner extends AbstractRunner {
private final static Logger logger = Logger.getLogger(CzshareRunner.class.getName());
private final static Map<String, PostMethod> methodsMap = new HashMap<String, PostMethod>();
private final static int WAIT_TIME = 30;
@Override
public void runCheck() throws Exception {
super.runCheck();
if (makeRequest(getGetMethod(fileURL))) {
checkNameAndSize(getContentAsString());
checkCaptcha();
} else {
checkProblems();
makeRedirectedRequest(getGetMethod(fileURL));
checkProblems();
throw new PluginImplementationException();
}
}
@Override
public void run() throws Exception {
super.run();
logger.info("Starting download in TASK " + fileURL);
if (checkInQueue())
return;
final PostMethod postmethod = parseFirstPage();
if (makeRequest(postmethod)) {
PostMethod method = stepCaptcha();
httpFile.setState(DownloadState.GETTING);
if (!tryDownloadAndSaveFile(method)) {
boolean finish = false;
while (!finish) {
method = stepCaptcha();
finish = tryDownloadAndSaveFile(method);
}
}
} else {
checkProblems();
logger.info(getContentAsString());
throw new PluginImplementationException();
}
}
private void checkCaptcha() throws Exception {
final PostMethod postmethod = parseFirstPage();
if (makeRequest(postmethod)) {
stepCaptcha();
} else {
checkProblems();
logger.info(getContentAsString());
throw new PluginImplementationException();
}
}
private boolean checkInQueue() throws Exception {
if (!methodsMap.containsKey(fileURL))
return false;
PostMethod method = methodsMap.get(fileURL);
methodsMap.remove(fileURL);
httpFile.setState(DownloadState.GETTING);
return tryDownloadAndSaveFile(method);
}
private PostMethod parseFirstPage() throws Exception {
final GetMethod getMethod = getGetMethod(fileURL);
if (makeRedirectedRequest(getMethod)) {
String content = getContentAsString();
checkNameAndSize(content);
Matcher matcher = getMatcherAgainstContent("Bohu.el je vy.erp.na maxim.ln. kapacita FREE download.");
if (matcher.find()) {
throw new YouHaveToWaitException("Na serveru jsou vyu�ity v�echny free download sloty", WAIT_TIME);
}
client.setReferer(fileURL);
matcher = PlugUtils.matcher("<div class=\"free-download\">[ ]*\n[ ]*<form action=\"([^\"]*)\" method=\"post\">", content);
if (!matcher.find()) {
throw new PluginImplementationException();
}
String postURL = matcher.group(1);
final PostMethod method = getPostMethod(postURL);
PlugUtils.addParameters(method, getContentAsString(), new String[]{"id", "file", "ticket"});
return method;
} else
throw new PluginImplementationException();
}
private void checkNameAndSize(String content) throws Exception {
if (getContentAsString().contains("zev souboru:")) {
Matcher matcher = PlugUtils.matcher("<span class=\"text-darkred\"><strong>([^<]*)</strong></span>", content);
if (matcher.find()) {
String fn = matcher.group(1);
httpFile.setFileName(fn);
}
matcher = PlugUtils.matcher("<td class=\"text-left\">([0-9.]+ .B)</td>", content);
if (matcher.find()) {
long a = PlugUtils.getFileSizeFromString(matcher.group(1));
httpFile.setFileSize(a);
}
httpFile.setFileState(FileState.CHECKED_AND_EXISTING);
} else {
checkProblems();
logger.info(getContentAsString());
throw new PluginImplementationException();
}
}
private PostMethod stepCaptcha() throws Exception {
if ("".equals(getContentAsString())) {
throw new YouHaveToWaitException("Neur�it� omezen�", 4 * WAIT_TIME);
}
Matcher matcher;
matcher = getMatcherAgainstContent("<td class=\"kod\" colspan=\"2\"><img src=\"([^\"]*)\" /></td>");
if (!matcher.find()) {
checkProblems();
throw new PluginImplementationException();
}
String img = "http://czshare.com/" + PlugUtils.replaceEntities(matcher.group(1));
boolean emptyCaptcha;
String captcha;
do {
logger.info("Captcha image " + img);
captcha = getCaptchaSupport().getCaptcha(img);
if (captcha == null) {
throw new CaptchaEntryInputMismatchException();
}
if ("".equals(captcha)) {
emptyCaptcha = true;
img = img + "1";
} else emptyCaptcha = false;
} while (emptyCaptcha);
matcher = getMatcherAgainstContent("<form action=\"([^\"]*)\" method=\"get\">");
if (!matcher.find()) {
throw new PluginImplementationException();
}
String finalURL = matcher.group(1);
final String content = getContentAsString();
String finalID = PlugUtils.getParameter("id", content);
String finalFile = PlugUtils.getParameter("file", content);
String finalTicket = PlugUtils.getParameter("ticket", content);
finalURL = "http://czshare.com/" + finalURL + "?id=" + finalID + "&file=" + finalFile + "&ticket=" + finalTicket + "&captchastring=" + captcha;
final GetMethod method = getGetMethod(finalURL);
if (makeRequest(method)) {
return stepDownload();
} else {
checkProblems();
logger.info(getContentAsString());
throw new PluginImplementationException("Problem with a connection to service.\nCannot find requested page content");
}
}
private PostMethod stepDownload() throws Exception {
Matcher matcher = getMatcherAgainstContent("<form name=\"pre_download_form\" action=\"([^\"]*)\" method=\"post\"");
if (!matcher.find()) {
throw new PluginImplementationException();
}
String finalURL = matcher.group(1);
PostMethod method = getPostMethod(finalURL);
PlugUtils.addParameters(method, getContentAsString(), new String[]{"id", "ticket", "submit_btn"});
methodsMap.put(fileURL, method);
return method;
}
private void checkProblems() throws ServiceConnectionProblemException, YouHaveToWaitException, URLNotAvailableAnymoreException {
Matcher matcher;
matcher = getMatcherAgainstContent("Soubor nenalezen");
if (matcher.find()) {
throw new URLNotAvailableAnymoreException("<b>Soubor nenalezen</b><br>");
}
matcher = getMatcherAgainstContent("Soubor expiroval");
if (matcher.find()) {
throw new URLNotAvailableAnymoreException("<b>Soubor expiroval</b><br>");
}
matcher = getMatcherAgainstContent("Soubor byl smaz.n jeho odesilatelem</strong>");
if (matcher.find()) {
throw new URLNotAvailableAnymoreException("<b>Soubor byl smaz�n jeho odesilatelem</b><br>");
}
+ matcher = getMatcherAgainstContent("Tento soubor byl na upozorn.n. identifikov.n jako warez.</strong>");
+ if (matcher.find()) {
+ throw new URLNotAvailableAnymoreException("<b>Tento soubor byl na upozorn�n� identifikov�n jako warez</b><br>");
+ }
matcher = getMatcherAgainstContent("Bohu.el je vy.erp.na maxim.ln. kapacita FREE download.");
if (matcher.find()) {
throw new YouHaveToWaitException("Bohu�el je vy�erp�na maxim�ln� kapacita FREE download�", WAIT_TIME);
}
matcher = getMatcherAgainstContent("Nesouhlas. kontroln. kod");
if (matcher.find()) {
throw new YouHaveToWaitException("�patn� k�d", 3);
}
}
}
\ No newline at end of file
diff --git a/src/czshare_profi/cz/vity/freerapid/plugins/services/czshare_profi/CzshareRunner.java b/src/czshare_profi/cz/vity/freerapid/plugins/services/czshare_profi/CzshareRunner.java
index d521eb79..e289ff55 100644
--- a/src/czshare_profi/cz/vity/freerapid/plugins/services/czshare_profi/CzshareRunner.java
+++ b/src/czshare_profi/cz/vity/freerapid/plugins/services/czshare_profi/CzshareRunner.java
@@ -1,184 +1,188 @@
package cz.vity.freerapid.plugins.services.czshare_profi;
import cz.vity.freerapid.plugins.exceptions.*;
import cz.vity.freerapid.plugins.webclient.AbstractRunner;
import cz.vity.freerapid.plugins.webclient.DownloadState;
import cz.vity.freerapid.plugins.webclient.FileState;
import cz.vity.freerapid.plugins.webclient.hoster.PremiumAccount;
import cz.vity.freerapid.plugins.webclient.utils.PlugUtils;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author Jan Smejkal (edit from CZshare and RapidShare premium to CZshare profi)
*/
class CzshareRunner extends AbstractRunner {
private final static Logger logger = Logger.getLogger(CzshareRunner.class.getName());
private boolean badConfig = false;
private final static int WAIT_TIME = 30;
@Override
public void runCheck() throws Exception {
super.runCheck();
if (makeRequest(getGetMethod(fileURL))) {
checkNameAndSize(getContentAsString());
} else {
checkProblems();
makeRedirectedRequest(getGetMethod(fileURL));
checkProblems();
throw new PluginImplementationException();
}
}
@Override
public void run() throws Exception {
super.run();
logger.info("Starting download in TASK " + fileURL);
final GetMethod getMethod = getGetMethod(fileURL);
if (makeRedirectedRequest(getMethod)) {
String content = getContentAsString();
checkNameAndSize(content);
client.setReferer(fileURL);
Matcher matcher = PlugUtils.matcher("<div class=\"profy-download\">[ ]*\n[ ]*<form action=\"([^\"]*)\" method=\"post\">|</table>[ ]*\n[ ]*<form action=\"([^\"]*)\" method=\"post\">", content);
if (!matcher.find()) {
throw new PluginImplementationException();
}
String postURL = matcher.group(1) != null ? matcher.group(1) : matcher.group(2);
final PostMethod postmethod = getPostMethod(postURL);
PlugUtils.addParameters(postmethod, getContentAsString(), new String[]{"id", "file"});
String id = postmethod.getParameter("id").getValue();
if (makeRedirectedRequest(postmethod)) {
matcher = getMatcherAgainstContent("<span class=\"nadpis\">P.ihl..en.</span>");
if (matcher.find())
Login(getContentAsString());
content = getContentAsString();
matcher = PlugUtils.matcher("<a href=\"(.*czshare.com/" + id + "/[^\"]*)\" title=\"" + Pattern.quote(httpFile.getFileName()) + "\">" + Pattern.quote(httpFile.getFileName()) + "</a>", content);
if (matcher.find()) {
String downURL = matcher.group(1);
GetMethod method = getGetMethod(downURL);
httpFile.setState(DownloadState.GETTING);
if (!tryDownloadAndSaveFile(method)) {
if (getContentAsString().equals(""))
throw new NotRecoverableDownloadException("No credit for download this file!");
checkProblems();
logger.info(getContentAsString());
throw new PluginImplementationException();
} else {
matcher = PlugUtils.matcher("<form action=\'([^\']+)\' method=\'POST\'>", content);
if (matcher.find()) {
String delURL = "http://czshare.com/profi/" + matcher.group(1);
matcher = PlugUtils.matcher("<a href=\"" + downURL + "\" title=\"" + Pattern.quote(httpFile.getFileName()) + "\">" + Pattern.quote(httpFile.getFileName()) + "</a></td><td><input type=\'checkbox\' name=\'[^\']+\' value=\'([^\']+)\'></td>", content);
if (matcher.find()) {
String delFile = matcher.group(1);
PostMethod postMethod = getPostMethod(delURL);
postMethod.addParameter("smaz[0]", delFile);
makeRequest(postMethod);
}
}
}
} else {
checkProblems();
logger.info(getContentAsString());
throw new PluginImplementationException();
}
} else {
checkProblems();
logger.info(getContentAsString());
throw new PluginImplementationException();
}
} else
throw new PluginImplementationException();
}
private void checkNameAndSize(String content) throws Exception {
if (getContentAsString().contains("zev souboru:")) {
Matcher matcher = PlugUtils.matcher("<span class=\"text-darkred\"><strong>([^<]*)</strong></span>", content);
if (matcher.find()) {
String fn = matcher.group(1);
httpFile.setFileName(fn);
}
matcher = PlugUtils.matcher("<td class=\"text-left\">([0-9.]+ .B)</td>", content);
if (matcher.find()) {
long a = PlugUtils.getFileSizeFromString(matcher.group(1));
httpFile.setFileSize(a);
}
httpFile.setFileState(FileState.CHECKED_AND_EXISTING);
} else {
checkProblems();
logger.info(getContentAsString());
throw new PluginImplementationException();
}
}
private void Login(String content) throws Exception {
synchronized (CzshareRunner.class) {
CzshareServiceImpl service = (CzshareServiceImpl) getPluginService();
PremiumAccount pa = service.getConfig();
if (!pa.isSet() || badConfig) {
pa = service.showConfigDialog();
if (pa == null || !pa.isSet()) {
throw new NotRecoverableDownloadException("No CZshare profi account login information!");
}
badConfig = false;
}
Matcher matcher = PlugUtils.matcher("<form action=\"([^\"]*)\" method=\"post\">[ \n]+<input type=\"hidden\" name=\"step\" value=\"1\" />", content);
if (!matcher.find()) {
throw new PluginImplementationException();
}
String postURL = "http://czshare.com" + matcher.group(1);
final PostMethod postmethod = getPostMethod(postURL);
PlugUtils.addParameters(postmethod, getContentAsString(), new String[]{"id", "file", "step", "prihlasit"});
postmethod.addParameter("jmeno", pa.getUsername());
postmethod.addParameter("heslo", pa.getPassword());
if (makeRedirectedRequest(postmethod)) {
matcher = getMatcherAgainstContent("<span class=\"nadpis\">P.ihl..en.</span>");
if (matcher.find()) {
badConfig = true;
throw new NotRecoverableDownloadException("Bad CZshare profi account login information!");
}
}
}
}
private void checkProblems() throws ServiceConnectionProblemException, YouHaveToWaitException, NotRecoverableDownloadException {
Matcher matcher;
matcher = getMatcherAgainstContent("Soubor nenalezen");
if (matcher.find()) {
throw new URLNotAvailableAnymoreException("<b>Soubor nenalezen</b><br>");
}
matcher = getMatcherAgainstContent("Soubor expiroval");
if (matcher.find()) {
throw new URLNotAvailableAnymoreException("<b>Soubor expiroval</b><br>");
}
matcher = getMatcherAgainstContent("Soubor byl smaz.n jeho odesilatelem</strong>");
if (matcher.find()) {
throw new URLNotAvailableAnymoreException("<b>Soubor byl smaz�n jeho odesilatelem</b><br>");
}
+ matcher = getMatcherAgainstContent("Tento soubor byl na upozorn.n. identifikov.n jako warez\\.</strong>");
+ if (matcher.find()) {
+ throw new URLNotAvailableAnymoreException("<b>Tento soubor byl na upozorn�n� identifikov�n jako warez</b><br>");
+ }
matcher = getMatcherAgainstContent("Bohu.el je vy.erp.na maxim.ln. kapacita FREE download.");
if (matcher.find()) {
throw new YouHaveToWaitException("Bohu�el je vy�erp�na maxim�ln� kapacita FREE download�", WAIT_TIME);
}
if (badConfig || getContentAsString().equals("")) {
throw new NotRecoverableDownloadException("Bad CZshare profi account login information!");
}
}
}
\ No newline at end of file
| false | false | null | null |
diff --git a/DbstarLauncher/src/com/dbstar/guodian/GDClient.java b/DbstarLauncher/src/com/dbstar/guodian/GDClient.java
index aa977f5b..33b1e7f6 100644
--- a/DbstarLauncher/src/com/dbstar/guodian/GDClient.java
+++ b/DbstarLauncher/src/com/dbstar/guodian/GDClient.java
@@ -1,287 +1,288 @@
package com.dbstar.guodian;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.util.LinkedList;
import com.dbstar.guodian.data.LoginData;
import com.dbstar.util.GDNetworkUtil;
import android.content.Context;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.os.Process;
import android.util.Log;
public class GDClient {
private static final String TAG = "GDClient";
public static final int MSG_REQUEST = 0x1001;
public static final int MSG_RESPONSE = 0x1002;
public static final int MSG_COMMAND = 0x1003;
// Command type
public static final int CMD_CONNECT = 0x2001;
public static final int CMD_STOP = 0x2002;
// Request type
public static final int REQUEST_LOGIN = 0x3001;
class Task {
public int TaskType;
public String TaskId;
public String Command;
public String[] ResponseData;
public Object ParsedData;
}
private String mHostAddr = null;
private int mHostPort = 0;
private Socket mSocket = null;
private BufferedReader mIn = null;
private BufferedWriter mOut = null;
ReceiveThread mInThread;
HandlerThread mClientThread = null;
Handler mClientHandler = null;
Context mContext = null;
LinkedList<Task> mWaitingQueue = new LinkedList<Task>();
Handler mAppHander = null;
public GDClient(Context context, Handler handler) {
mContext = context;
mAppHander = handler;
mClientThread = new HandlerThread("GDClient",
Process.THREAD_PRIORITY_BACKGROUND);
mClientThread.start();
mClientHandler = new Handler(mClientThread.getLooper()) {
@Override
public void handleMessage(Message msg) {
int msgType = msg.what;
switch (msgType) {
case MSG_COMMAND: {
performCommand(msg.arg1, msg.obj);
break;
}
case MSG_REQUEST: {
performRequest((Task) msg.obj);
break;
}
case MSG_RESPONSE: {
handleResponse((String) msg.obj);
break;
}
}
}
};
}
public void setHostAddress(String hostAddr, int port) {
mHostAddr = hostAddr;
mHostPort = port;
}
public void connectToServer() {
Message msg = mClientHandler.obtainMessage(MSG_COMMAND);
msg.arg1 = CMD_CONNECT;
msg.sendToTarget();
}
public void login() {
Task task = new Task();
String taskId = GDCmdHelper.generateUID();
String macAddr = GDNetworkUtil.getMacAddress(mContext, true);
String cmdStr = GDCmdHelper.constructLoginCmd(taskId, macAddr);
task.TaskType = REQUEST_LOGIN;
task.TaskId = taskId;
task.Command = cmdStr;
Message msg = mClientHandler.obtainMessage(MSG_REQUEST);
msg.obj = task;
msg.sendToTarget();
}
public void stop() {
Log.d(TAG, " ============ stop GDClient thread ============");
Message msg = mClientHandler.obtainMessage(MSG_COMMAND);
msg.arg1 = CMD_STOP;
msg.sendToTarget();
}
public void destroy() {
Log.d(TAG, " ============ destroy GDClient thread ============");
mClientThread.quit();
doStop();
}
// run in client thread
private void performCommand(int cmdType, Object cmdData) {
switch (cmdType) {
case CMD_CONNECT: {
doConnectToServer();
break;
}
case CMD_STOP: {
doStop();
break;
}
}
}
private void performRequest(Task task) {
doRequest(task);
}
private void handleResponse(String response) {
Log.d(TAG, " ++++++++++++handleResponse++++++++" + response);
String[] data = GDCmdHelper.processResponse(response);
String id = data[0];
Task task = null;
for (Task t : mWaitingQueue) {
if (t.TaskId.equals(id)) {
mWaitingQueue.remove(t);
task = t;
task.ResponseData = data;
processResponse(task);
}
}
}
private void processResponse(Task task) {
Log.d(TAG, " ++++++++++++processResponse++++++++" + task.TaskType);
switch (task.TaskType) {
case REQUEST_LOGIN: {
LoginData loginData = LoginDataHandler.parse(task.ResponseData[6]);
task.ParsedData = loginData;
break;
}
}
if (mAppHander != null) {
Message msg = mAppHander
.obtainMessage(GDEngine.MSG_REQUEST_FINISHED);
msg.obj = task;
msg.sendToTarget();
}
}
private void doConnectToServer() {
try {
Log.d(TAG, " ====== doConnectToServer ===");
if (mSocket != null) {
if (mSocket.isConnected() && !mSocket.isClosed()) {
return;
}
mSocket = null;
}
Log.d(TAG, " server ip = " + mHostAddr + " port=" + mHostPort);
mSocket = new Socket(mHostAddr, mHostPort);
mSocket.setKeepAlive(true);
mIn = new BufferedReader(new InputStreamReader(
mSocket.getInputStream(), "UTF-8"));
Log.d(TAG, " ==== mIn " + mSocket.isInputShutdown());
mOut = new BufferedWriter(new OutputStreamWriter(
mSocket.getOutputStream(), "UTF-8"));
Log.d(TAG, " ==== mOut " + mSocket.isOutputShutdown());
mInThread = new ReceiveThread(mSocket, mIn, mClientHandler);
mInThread.start();
Log.d(TAG, " ====== doConnectToServer ===" + mSocket.isConnected());
if (mSocket.isConnected()) {
mAppHander.sendEmptyMessage(GDEngine.MSG_CONNECT_SUCCESSED);
}
} catch (IOException e) {
e.printStackTrace();
}
}
private boolean isConnectionSetup() {
return (mSocket != null && mSocket.isConnected());
}
private boolean isOutputAvailable() {
if (mSocket == null)
return false;
Log.d(TAG, "isOutputShutdown " + mSocket.isOutputShutdown());
return isConnectionSetup() && !mSocket.isClosed();
}
private void doRequest(Task task) {
Log.d(TAG, "======= doRequest =========");
Log.d(TAG, "task type" + task.TaskType);
Log.d(TAG, "task cmd" + task.Command);
if (!isOutputAvailable()) {
Log.d(TAG, "======= no connection to server =========");
return;
}
mWaitingQueue.add(task);
try {
mOut.write(task.Command);
+ mOut.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
// stop receive thread,
// close socket.
private void doStop() {
Log.d(TAG, " ============ doStop ============");
if (mInThread != null) {
mInThread.setExit();
mInThread = null;
}
Log.d(TAG, " ============ stop 1 ============");
try {
if (mSocket != null && (mSocket.isConnected() || !mSocket.isClosed())) {
if (!mSocket.isInputShutdown()) {
mSocket.shutdownInput();
}
if (!mSocket.isOutputShutdown()) {
mSocket.shutdownOutput();
}
mSocket.close();
}
mSocket = null;
} catch (Exception e) {
e.printStackTrace();
}
mWaitingQueue.clear();
Log.d(TAG, " ============ stop 3 ============");
}
}
diff --git a/DbstarLauncher/src/com/dbstar/guodian/GDCmdHelper.java b/DbstarLauncher/src/com/dbstar/guodian/GDCmdHelper.java
index e8df4779..6ebe7077 100644
--- a/DbstarLauncher/src/com/dbstar/guodian/GDCmdHelper.java
+++ b/DbstarLauncher/src/com/dbstar/guodian/GDCmdHelper.java
@@ -1,107 +1,107 @@
package com.dbstar.guodian;
import java.util.Random;
import org.json.JSONException;
import org.json.JSONStringer;
import com.dbstar.guodian.data.JsonTag;
import com.smartlife.mobile.service.FormatCMD;
import android.os.SystemClock;
import android.util.Log;
public class GDCmdHelper {
private static final String TAG = "GDCmdHelper";
private static final String CmdStartTag = "#!";
private static final String CmdEndTag = "!#";
private static final String CmdDelimiterTag = "#";
private static final String DeviceVersion = "v3.3.5";
private static final String DeviceId = "epg_htcm";
private static String toJson(String key, String value) {
String jsonStr = "";
try {
jsonStr = new JSONStringer().object()
.key(key).value(value)
.endObject().toString();
} catch (JSONException e) {
e.printStackTrace();
}
return jsonStr;
}
private static String toJson(String[] keys, String[] values) {
String jsonStr = null;
try {
JSONStringer jsonStringer = new JSONStringer();
jsonStringer.object();
int count = keys.length;
for(int i=0; i<count ; i++) {
jsonStringer.key(keys[i]).value(values[i]);
}
jsonStringer.endObject();
jsonStr = jsonStringer.toString();
} catch (JSONException e) {
e.printStackTrace();
}
return jsonStr;
}
public static String generateUID() {
String uid = null;
long currentTime = SystemClock.currentThreadTimeMillis();
Random random = new Random(currentTime);
long randomValue = random.nextLong();
uid = String.valueOf(currentTime) + String.valueOf(randomValue);
return uid;
}
public static String constructLoginCmd(String cmdId, String macaddr) {
String cmdStr = cmdId + CmdDelimiterTag
+ "aut" + CmdDelimiterTag
+ "m008f001" + CmdDelimiterTag
+ macaddr + CmdDelimiterTag
+ DeviceVersion + CmdDelimiterTag
+ DeviceId + CmdDelimiterTag
+ toJson("macaddr", macaddr);
Log.d(TAG, "cmd data = " + cmdStr);
String encryptStr = FormatCMD.encryptCMD(cmdStr);
cmdStr = CmdStartTag + encryptStr + CmdEndTag+"\n";
Log.d(TAG, " cmd ===== " + cmdStr);
return cmdStr;
}
public static String constructGetPowerPanelDataCmd(String cmdId, String macaddr) {
String[] keys = new String[2];
String[] values = new String[2];
keys[0]=JsonTag.TAGNumCCGuid;
keys[1]="user_type";
values[0]="";
values[1]="";
String cmdStr = CmdStartTag + cmdId + CmdDelimiterTag
+ "elc" + CmdDelimiterTag
+ "m008f001" + CmdDelimiterTag
+ macaddr + CmdDelimiterTag
+ DeviceVersion + CmdDelimiterTag
+ DeviceId + CmdDelimiterTag
- + toJson("macaddr", macaddr) + CmdEndTag;
+ + toJson("macaddr", macaddr) + CmdEndTag + "\n";
return cmdStr;
}
public static String[] processResponse(String response) {
String data = response;//response.substring(CmdStartTag.length(), response.length() - CmdEndTag.length());
Log.d(TAG, "receive rawdata = " + response);
Log.d(TAG, "receive data = " + data);
String decryptedStr = FormatCMD.decryptCMD(data);
Log.d(TAG, "decrypt data = " + decryptedStr);
return decryptedStr.split(CmdDelimiterTag);
}
}
| false | false | null | null |
diff --git a/cspi-webui/src/main/java/org/collectionspace/chain/csp/webui/authorities/AuthoritiesVocabulariesSearchList.java b/cspi-webui/src/main/java/org/collectionspace/chain/csp/webui/authorities/AuthoritiesVocabulariesSearchList.java
index 43c38926..a40bb9d0 100644
--- a/cspi-webui/src/main/java/org/collectionspace/chain/csp/webui/authorities/AuthoritiesVocabulariesSearchList.java
+++ b/cspi-webui/src/main/java/org/collectionspace/chain/csp/webui/authorities/AuthoritiesVocabulariesSearchList.java
@@ -1,375 +1,375 @@
/* Copyright 2010 University of Cambridge
* Licensed under the Educational Community License (ECL), Version 2.0. You may not use this file except in
* compliance with this License.
*
* You may obtain a copy of the ECL 2.0 License at https://source.collectionspace.org/collection-space/LICENSE.txt
*/
package org.collectionspace.chain.csp.webui.authorities;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
import org.collectionspace.chain.csp.schema.Field;
import org.collectionspace.chain.csp.schema.FieldSet;
import org.collectionspace.chain.csp.schema.Instance;
import org.collectionspace.chain.csp.schema.Record;
import org.collectionspace.chain.csp.schema.Spec;
import org.collectionspace.chain.csp.webui.main.Request;
import org.collectionspace.chain.csp.webui.main.WebMethod;
import org.collectionspace.chain.csp.webui.main.WebUI;
import org.collectionspace.csp.api.persistence.ExistException;
import org.collectionspace.csp.api.persistence.Storage;
import org.collectionspace.csp.api.persistence.UnderlyingStorageException;
import org.collectionspace.csp.api.persistence.UnimplementedException;
import org.collectionspace.csp.api.ui.UIException;
import org.collectionspace.csp.api.ui.UIRequest;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class AuthoritiesVocabulariesSearchList implements WebMethod {
private static final Logger log=LoggerFactory.getLogger(AuthoritiesVocabulariesSearchList.class);
private Record r;
private Instance n;
private boolean search;
private Map<String,String> type_to_url=new HashMap<String,String>();
//search all instances of an authority
public AuthoritiesVocabulariesSearchList(Record r,boolean search) {
this.r=r;
this.search=search;
}
//search a specific instance of an authority
public AuthoritiesVocabulariesSearchList(Instance n,boolean search) {
this.n=n;
this.r=n.getRecord();
this.search=search;
}
private JSONObject generateMiniRecord(Storage storage,String auth_type,String inst_type,String csid) throws JSONException {
JSONObject out = new JSONObject();
try{
String postfix = "list";
if(this.search){
postfix = "search";
}
out=storage.retrieveJSON(auth_type+"/"+inst_type+"/"+csid+"/view/"+postfix, new JSONObject());
out.put("csid",csid);
out.put("recordtype",inst_type);
}
catch (ExistException e) {
out.put("csid",csid);
out.put("isError", true);
JSONObject msg = new JSONObject();
msg.put("severity", "error");
msg.put("message", "Exist Exception:"+e.getMessage());
JSONArray msgs = new JSONArray();
msgs.put(msg);
out.put("messages", msgs);
} catch (UnimplementedException e) {
out.put("csid",csid);
out.put("isError", true);
JSONObject msg = new JSONObject();
msg.put("severity", "error");
msg.put("message", "Unimplemented Exception:"+e.getMessage());
JSONArray msgs = new JSONArray();
msgs.put(msg);
out.put("messages", msgs);
} catch (UnderlyingStorageException e) {
out.put("csid",csid);
out.put("isError", true);
JSONObject msg = new JSONObject();
msg.put("severity", "error");
msg.put("message", "UnderlyingStorage Exception:"+e.getMessage());
JSONArray msgs = new JSONArray();
msgs.put(msg);
out.put("messages", msgs);
}
return out;
}
private JSONObject setRestricted(UIRequest ui, String param, String pageNum, String pageSize) throws UIException, JSONException{
JSONObject returndata = new JSONObject();
JSONObject restriction=new JSONObject();
String key="results";
Set<String> args = ui.getAllRequestArgument();
for(String restrict : args){
if(!restrict.equals("_")){
if(ui.getRequestArgument(restrict)!=null){
String value = ui.getRequestArgument(restrict);
if(restrict.equals("sortDir")){
restriction.put(restrict,value);
}
else if(restrict.equals("sortKey")){////"summarylist.updatedAt"//movements_common:locationDate
String[] bits = value.split("\\.");
String fieldname = value;
if(bits.length>1){
fieldname = bits[1];
}
FieldSet fs = null;
if(fieldname.equals("number")){
fs = r.getMiniNumber();
fieldname = fs.getID();
}
else if(fieldname.equals("summary")){
fs = r.getMiniSummary();
fieldname = fs.getID();
}
else{
//convert sortKey
fs = r.getField(fieldname);
}
String tablebase = r.getServicesRecordPath(fs.getSection()).split(":",2)[0];
String newvalue = tablebase+":"+fieldname;
restriction.put(restrict,newvalue);
}
}
}
}
if(param!=null && !param.equals("")){
restriction.put("queryTerm", "kw");
restriction.put("queryString",param);
//restriction.put(r.getDisplayNameField().getID(),param);
}
if(pageNum!=null){
restriction.put("pageNum",pageNum);
}
else{
restriction.put("pageNum","0");
}
if(pageSize!=null){
restriction.put("pageSize",pageSize);
}
if(param==null){
key = "items";
}
returndata.put("key", key);
returndata.put("restriction", restriction);
return returndata;
}
private void advancedSearch(Storage storage,UIRequest ui,JSONObject restriction, String resultstring, JSONObject params) throws UIException, ExistException, UnimplementedException, UnderlyingStorageException, JSONException{
Map<String, String> dates = new HashMap<String, String>();
String operation = params.getString("operation").toUpperCase();
JSONObject fields = params.getJSONObject("fields");
String asq = "";
Iterator rit=fields.keys();
while(rit.hasNext()) {
String join = "=";
String fieldname=(String)rit.next();
Object item = fields.get(fieldname);
String value = "";
if(item instanceof JSONArray){ // this is a repeatable
JSONArray itemarray = (JSONArray)item;
for(int j=0;j<itemarray.length();j++){
JSONObject jo = itemarray.getJSONObject(j);
Iterator jit=jo.keys();
while(jit.hasNext()){
String jname=(String)jit.next();
if(!jname.equals("_primary")){
value = jo.getString(jname);
asq += getAdvancedSearch(jname,value,operation,"=");
}
}
}
}
else if(item instanceof JSONObject){ // no idea what this is
}
else if(item instanceof String){
value = (String)item;
String fieldid = fieldname;
if(this.r.hasSearchField(fieldname) && this.r.getSearchField(fieldname).getUIType().equals("date")){
if(fieldname.endsWith("Start")){
fieldid = fieldname.substring(0, (fieldname.length() - 5));
join = ">=";
}
else if(fieldname.endsWith("End")){
fieldid = fieldname.substring(0, (fieldname.length() - 3));
join = "<=";
}
if(dates.containsKey(fieldid)){
String temp = getAdvancedSearch(fieldid,value,"AND",join);
String get = dates.get(fieldid);
dates.put(fieldid, temp + get);
}
else{
String temp = getAdvancedSearch(fieldid,value,"",join);
dates.put(fieldid, temp);
}
}
else{
asq += getAdvancedSearch(fieldname,value,operation,join);
}
}
}
if(!dates.isEmpty()){
for (String key : dates.keySet()) {
asq += " ( "+dates.get(key)+" ) "+ operation;
}
}
if(!asq.equals("")){
asq = asq.substring(0, asq.length()-(operation.length() + 2));
}
String asquery = "( "+asq+" )";
resultstring="results";
restriction.put("advancedsearch", asquery);
search_or_list(storage,ui,restriction,resultstring);
}
private String getAdvancedSearch(String fieldname, String value, String operator, String join){
if(!value.equals("")){
try{
String section = this.r.getRepeatField(fieldname).getSection();
String spath=this.r.getServicesRecordPath(section);
String[] parts=spath.split(":",2);
if(value.contains("*")){
- value.replace("*", "%");
+ value = value.replace("*", "%");
join = " ilike ";
}
//backslash quotes??
return parts[0]+":"+fieldname+join+"\""+value +"\""+ " " + operator+ " ";
}
catch(Exception e){
return "";
}
}
return "";
}
private void search_or_list_vocab(JSONObject out,Instance n,Storage storage,UIRequest ui,JSONObject restriction, String resultstring, JSONObject temp ) throws ExistException, UnimplementedException, UnderlyingStorageException, JSONException, UIException {
JSONObject data = storage.getPathsJSON(r.getID()+"/"+n.getTitleRef(),restriction);
String[] paths = (String[]) data.get("listItems");
JSONObject pagination = new JSONObject();
if(data.has("pagination")){
pagination = data.getJSONObject("pagination");
}
JSONArray members = new JSONArray();
/* Get a view of each */
if(temp.has(resultstring)){
members = temp.getJSONArray(resultstring);
}
for(String result : paths) {
if(temp.has(resultstring)){
temp.getJSONArray(resultstring).put(generateMiniRecord(storage,r.getID(),n.getTitleRef(),result));
members = temp.getJSONArray(resultstring);
}
else{
members.put(generateMiniRecord(storage,r.getID(),n.getTitleRef(),result));
}
}
out.put(resultstring,members);
if(pagination!=null){
if(temp.has("pagination")){
JSONObject pag2 = temp.getJSONObject("pagination");
String itemsInPage = pag2.getString("itemsInPage");
String pagSize = pag2.getString("pageSize");
String totalItems = pag2.getString("totalItems");
String itemsInPage1 = pagination.getString("itemsInPage");
String pagSize1 = pagination.getString("pageSize");
String totalItems1 = pagination.getString("totalItems");
int iip = Integer.parseInt(itemsInPage) +Integer.parseInt(itemsInPage1);
int ps = Integer.parseInt(pagSize) +Integer.parseInt(pagSize1);
int ti = Integer.parseInt(totalItems) +Integer.parseInt(totalItems1);
pagination.put("itemsInPage", Integer.toString(iip) );
pagination.put("pageSize", Integer.toString(ps) );
pagination.put("totalItems", Integer.toString(ti) );
}
out.put("pagination",pagination);
}
log.debug(restriction.toString());
}
private void search_or_list(Storage storage,UIRequest ui,JSONObject restriction, String resultstring) throws UIException, ExistException, UnimplementedException, UnderlyingStorageException, JSONException {
JSONObject results=new JSONObject();
if(n==null) {
for(Instance n : r.getAllInstances()) {
JSONObject results2=new JSONObject();
search_or_list_vocab(results2,n,storage,ui,restriction,resultstring,results);
results = results2;
}
} else {
search_or_list_vocab(results,n,storage,ui,restriction,resultstring,new JSONObject());
}
ui.sendJSONResponse(results);
}
public void searchtype(Storage storage,UIRequest ui,String param, String pageSize, String pageNum) throws UIException{
try {
JSONObject restrictedkey = setRestricted(ui,param,pageNum,pageSize);
JSONObject restriction = restrictedkey.getJSONObject("restriction");
String resultstring = restrictedkey.getString("key");
if(ui.getBody() == null || StringUtils.isBlank(ui.getBody())){
search_or_list(storage,ui,restriction,resultstring);
}
else{
//advanced search
advancedSearch(storage,ui,restriction,resultstring, ui.getJSONBody());
}
} catch (JSONException e) {
throw new UIException("Cannot generate JSON",e);
} catch (ExistException e) {
throw new UIException("Exist exception",e);
} catch (UnimplementedException e) {
throw new UIException("Unimplemented exception",e);
} catch (UnderlyingStorageException x) {
UIException uiexception = new UIException(x.getMessage(),x.getStatus(),x.getUrl(),x);
ui.sendJSONResponse(uiexception.getJSON());
}
}
public void run(Object in, String[] tail) throws UIException {
Request q=(Request)in;
if(search)
searchtype(q.getStorage(),q.getUIRequest(),q.getUIRequest().getRequestArgument("query"),q.getUIRequest().getRequestArgument("pageSize"),q.getUIRequest().getRequestArgument("pageNum"));
else
searchtype(q.getStorage(),q.getUIRequest(),null,q.getUIRequest().getRequestArgument("pageSize"),q.getUIRequest().getRequestArgument("pageNum"));
}
public void configure(WebUI ui,Spec spec) {
for(Record r : spec.getAllRecords()) {
type_to_url.put(r.getID(),r.getWebURL());
}
}
}
diff --git a/cspi-webui/src/main/java/org/collectionspace/chain/csp/webui/record/RecordSearchList.java b/cspi-webui/src/main/java/org/collectionspace/chain/csp/webui/record/RecordSearchList.java
index 5fc37681..27979dc5 100644
--- a/cspi-webui/src/main/java/org/collectionspace/chain/csp/webui/record/RecordSearchList.java
+++ b/cspi-webui/src/main/java/org/collectionspace/chain/csp/webui/record/RecordSearchList.java
@@ -1,493 +1,493 @@
/* Copyright 2010 University of Cambridge
* Licensed under the Educational Community License (ECL), Version 2.0. You may not use this file except in
* compliance with this License.
*
* You may obtain a copy of the ECL 2.0 License at https://source.collectionspace.org/collection-space/LICENSE.txt
*/
package org.collectionspace.chain.csp.webui.record;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
import org.collectionspace.chain.csp.schema.FieldSet;
import org.collectionspace.chain.csp.schema.Record;
import org.collectionspace.chain.csp.schema.Repeat;
import org.collectionspace.chain.csp.schema.Spec;
import org.collectionspace.chain.csp.webui.main.Request;
import org.collectionspace.chain.csp.webui.main.WebMethod;
import org.collectionspace.chain.csp.webui.main.WebUI;
import org.collectionspace.chain.csp.webui.misc.Generic;
import org.collectionspace.csp.api.persistence.ExistException;
import org.collectionspace.csp.api.persistence.Storage;
import org.collectionspace.csp.api.persistence.UnderlyingStorageException;
import org.collectionspace.csp.api.persistence.UnimplementedException;
import org.collectionspace.csp.api.ui.UIException;
import org.collectionspace.csp.api.ui.UIRequest;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class RecordSearchList implements WebMethod {
private static final Logger log=LoggerFactory.getLogger(RecordSearchList.class);
private boolean search;
private String base;
private Spec spec;
private Record r;
private Map<String,String> type_to_url=new HashMap<String,String>();
public RecordSearchList(Record r,boolean search) {
this.r = r;
this.spec=r.getSpec();
this.base=r.getID();
this.search=search;
}
/**
* Retrieve the mini summary information e.g. summary and number and append the csid and recordType to it
* @param {Storage} storage Type of storage (e.g. AuthorizationStorage, RecordStorage,...)
* @param {String} type The type of record requested (e.g. permission)
* @param {String} csid The csid of the record
* @return {JSONObject} The JSON string containing the mini record
* @throws ExistException
* @throws UnimplementedException
* @throws UnderlyingStorageException
* @throws JSONException
*/
private JSONObject generateMiniRecord(Storage storage,String type,String csid) throws JSONException {
String postfix = "list";
if(this.search){
postfix = "search";
}
JSONObject restrictions = new JSONObject();
JSONObject out = new JSONObject();
try {
if(csid == null || csid.equals("")){
return out;
}
out = storage.retrieveJSON(type+"/"+csid+"/view/"+postfix,restrictions);
out.put("csid",csid);
out.put("recordtype",type_to_url.get(type));
// CSPACE-2894
if(this.r.getID().equals("permission")){
String summary = out.getString("summary");
String name = Generic.ResourceNameUI(this.r.getSpec(), summary);
if(name.endsWith("/*/workflow/")){
return null;
}
out.put("summary", name);
out.put("display", Generic.getPermissionView(this.r.getSpec(), summary));
}
} catch (ExistException e) {
out.put("csid",csid);
out.put("isError", true);
JSONObject msg = new JSONObject();
msg.put("severity", "error");
msg.put("message", "Exist Exception:"+e.getMessage());
JSONArray msgs = new JSONArray();
msgs.put(msg);
out.put("messages", msgs);
} catch (UnimplementedException e) {
out.put("csid",csid);
out.put("isError", true);
JSONObject msg = new JSONObject();
msg.put("severity", "error");
msg.put("message", "Exist Exception:"+e.getMessage());
JSONArray msgs = new JSONArray();
msgs.put(msg);
out.put("messages", msgs);
} catch (UnderlyingStorageException e) {
out.put("csid",csid);
out.put("isError", true);
JSONObject msg = new JSONObject();
msg.put("severity", "error");
msg.put("message", "Exist Exception:"+e.getMessage());
JSONArray msgs = new JSONArray();
msgs.put(msg);
out.put("messages", msgs);
}
return out;
}
/**
* Intermediate function to generateMiniRecord. This function only exists for if someone would like to create different types
* of records e.g. MiniRecordA, MiniRecordB,...
* @param {Storage} storage The type of storage (e.g. AuthorizationStorage,RecordStorage,...)
* @param {String} base The type of record (e.g. permission)
* @param {String} member The csid of the object
* @return {JSONObject} A JSONObject containing the mini record.
* @throws JSONException
* @throws ExistException
* @throws UnimplementedException
* @throws UnderlyingStorageException
*/
private JSONObject generateEntry(Storage storage,String base,String member) throws JSONException, ExistException, UnimplementedException, UnderlyingStorageException {
return generateMiniRecord(storage,base,member);
}
/**
* Creates a list of results containing:summary, number, recordType, csid
* @param {Storage} storage The type of storage (e.g. AuthorizationStorage,RecordStorage,...)
* @param {String} base The type of record (e.g. permission)
* @param {String[]} paths The list of csids from the records that were requested
* @param {String} key The surrounding key for the results (e.g. {"key":{...}})
* @return {JSONObject} The JSONObject that is sent back to the UI Layer
* @throws JSONException
* @throws ExistException
* @throws UnimplementedException
* @throws UnderlyingStorageException
*/
private JSONObject pathsToJSON(Storage storage,String base,String[] paths,String key, JSONObject pagination) throws JSONException, ExistException, UnimplementedException, UnderlyingStorageException {
JSONObject out=new JSONObject();
JSONArray members=new JSONArray();
for(String p : paths){
JSONObject temp = generateEntry(storage,base,p);
if(temp !=null){
members.put(temp);
}
}
out.put(key,members);
if(pagination!=null){
out.put("pagination",pagination);
}
return out;
}
private JSONObject setRestricted(UIRequest ui) throws UIException, JSONException{
JSONObject returndata = new JSONObject();
JSONObject restriction=new JSONObject();
String key="items";
Set<String> args = ui.getAllRequestArgument();
for(String restrict : args){
if(!restrict.equals("_")){
if(ui.getRequestArgument(restrict)!=null){
String value = ui.getRequestArgument(restrict);
if(restrict.equals("query") && search){
restrict = "keywords";
key="results";
}
if(restrict.equals("pageSize")||restrict.equals("pageNum")||restrict.equals("keywords")){
restriction.put(restrict,value);
}
else if(restrict.equals("sortDir")){
restriction.put(restrict,value);
}
else if(restrict.equals("sortKey")){////"summarylist.updatedAt"//movements_common:locationDate
String[] bits = value.split("\\.");
String fieldname = value;
if(bits.length>1){
fieldname = bits[1];
}
FieldSet fs = null;
if(fieldname.equals("number")){
fs = r.getMiniNumber();
fieldname = fs.getID();
}
else if(fieldname.equals("summary")){
fs = r.getMiniSummary();
fieldname = fs.getID();
}
else{
//convert sortKey
fs = r.getField(fieldname);
}
String tablebase = r.getServicesRecordPath(fs.getSection()).split(":",2)[0];
String newvalue = tablebase+":"+fieldname;
restriction.put(restrict,newvalue);
}
else if(restrict.equals("query")){
//ignore - someone was doing something odd
}
else{
//XXX I would so prefer not to restrict and just pass stuff up but I know it will cause issues later
restriction.put("queryTerm",restrict);
restriction.put("queryString",value);
}
}
}
}
returndata.put("key", key);
returndata.put("restriction", restriction);
return returndata;
}
/**
* This function is the general function that calls the correct funtions to get all the data that the UI requested and get it in the
* correct format for the UI.
* @param {Storage} storage The type of storage requested (e.g. RecordStorage, AuthorizationStorage,...)
* @param {UIRequest} ui The request from the ui to which we send a response.
* @param {String} param If a querystring has been added to the URL(e.g.'?query='), it will be in this param
* @param {String} pageSize The amount of results per page requested.
* @param {String} pageNum The amount of pages requested.
* @throws UIException
*/
private void search_or_list(Storage storage,UIRequest ui,String path) throws UIException {
try {
JSONObject restrictedkey = setRestricted(ui);
JSONObject restriction = restrictedkey.getJSONObject("restriction");
String key = restrictedkey.getString("key");
JSONObject returndata = new JSONObject();
if(this.r.getID().equals("permission")){
//pagination isn't properly implemented in permissions so just keep looping til we get everything
int pgnum = 0;
if(restriction.has("pageNum")){ //just get teh page specified
returndata = getJSON(storage,restriction,key,base);
}
else{ // if not specified page then loop over them all.
JSONArray newitems =new JSONArray();
returndata = getJSON(storage,restriction,key,base);
while(returndata.has(key) && returndata.getJSONArray(key).length()>0){
JSONArray items = returndata.getJSONArray(key);
for(int i=0;i<items.length();i++){
newitems.put(items.get(i));
}
pgnum++;
restriction.put("pageNum", Integer.toString(pgnum));
returndata = getJSON(storage,restriction,key,base);
}
returndata.put(key, newitems);
}
}
else if(r.getID().equals("reports")){
String type= "";
if(path!=null && !path.equals("")){
restriction.put("queryTerm", "doctype");
restriction.put("queryString", spec.getRecordByWebUrl(path).getServicesTenantSg());
}
if(restriction.has("queryTerm") && restriction.getString("queryTerm").equals("doctype")){
type = restriction.getString("queryString");
returndata = getJSON(storage,restriction,key,base);
returndata = showReports(returndata, type, key);
}
else{
JSONObject reporting = new JSONObject();
for(Record r2 : spec.getAllRecords()) {
if(r2.isInRecordList()){
type = r2.getServicesTenantSg();
restriction.put("queryTerm","doctype");
restriction.put("queryString",type);
JSONObject rdata = getJSON(storage,restriction,key,base);
JSONObject procedurereports = showReports(rdata, type, key);
reporting.put(r2.getWebURL(), procedurereports);
}
}
returndata.put("reporting", reporting);
}
}
else{
returndata = getJSON(storage,restriction,key,base);
}
ui.sendJSONResponse(returndata);
} catch (JSONException e) {
throw new UIException("JSONException during search_or_list",e);
} catch (ExistException e) {
throw new UIException("ExistException during search_or_list",e);
} catch (UnimplementedException e) {
throw new UIException("UnimplementedException during search_or_list",e);
} catch (UnderlyingStorageException x) {
UIException uiexception = new UIException(x.getMessage(),x.getStatus(),x.getUrl(),x);
ui.sendJSONResponse(uiexception.getJSON());
}
}
private JSONObject showReports(JSONObject data, String type, String key) throws JSONException{
JSONObject results = new JSONObject();
JSONArray list = new JSONArray();
JSONArray names = new JSONArray();
if(data.has(key)){
JSONArray ja = data.getJSONArray(key);
for(int j=0;j<ja.length();j++){
list.put(ja.getJSONObject(j).getString("csid"));
names.put(ja.getJSONObject(j).getString("number"));
}
results.put("reportlist", list);
results.put("reportnames", names);
}
return results;
}
private void advancedSearch(Storage storage,UIRequest ui,String path, JSONObject params) throws UIException{
try {
Map<String, String> dates = new HashMap<String, String>();
JSONObject returndata = new JSONObject();
JSONObject restrictedkey = setRestricted(ui);
JSONObject restriction = restrictedkey.getJSONObject("restriction");
String key = restrictedkey.getString("key");
String operation = params.getString("operation").toUpperCase();
JSONObject fields = params.getJSONObject("fields");
String asq = "";
Iterator rit=fields.keys();
while(rit.hasNext()) {
String join = "=";
String fieldname=(String)rit.next();
Object item = fields.get(fieldname);
String value = "";
if(item instanceof JSONArray){ // this is a repeatable
JSONArray itemarray = (JSONArray)item;
for(int j=0;j<itemarray.length();j++){
JSONObject jo = itemarray.getJSONObject(j);
Iterator jit=jo.keys();
while(jit.hasNext()){
String jname=(String)jit.next();
if(!jname.equals("_primary")){
value = jo.getString(jname);
asq += getAdvancedSearch(jname,value,operation,join);
}
}
}
}
else if(item instanceof JSONObject){ // no idea what this is
}
else if(item instanceof String){
value = (String)item;
String fieldid = fieldname;
if(this.r.hasSearchField(fieldname) && this.r.getSearchField(fieldname).getUIType().equals("date")){
if(fieldname.endsWith("Start")){
fieldid = fieldname.substring(0, (fieldname.length() - 5));
join = ">=";
}
else if(fieldname.endsWith("End")){
fieldid = fieldname.substring(0, (fieldname.length() - 3));
join = "<=";
}
if(dates.containsKey(fieldid)){
String temp = getAdvancedSearch(fieldid,value,"AND",join);
String get = dates.get(fieldid);
dates.put(fieldid, temp + get);
}
else{
String temp = getAdvancedSearch(fieldid,value,"",join);
dates.put(fieldid, temp);
}
}
else{
asq += getAdvancedSearch(fieldname,value,operation,join);
}
}
}
if(!dates.isEmpty()){
for (String keyed : dates.keySet()) {
asq += " ( "+dates.get(keyed)+" ) "+ operation;
}
}
if(!asq.equals("")){
asq = asq.substring(0, asq.length()-(operation.length() + 2));
}
String asquery = "( "+asq+" )";
key="results";
restriction.put("advancedsearch", asquery);
returndata = getJSON(storage,restriction,key,base);
ui.sendJSONResponse(returndata);
} catch (JSONException e) {
throw new UIException("JSONException during advancedSearch "+e.getMessage(),e);
} catch (ExistException e) {
throw new UIException("ExistException during search_or_list",e);
} catch (UnimplementedException e) {
throw new UIException("UnimplementedException during search_or_list",e);
} catch (UnderlyingStorageException x) {
UIException uiexception = new UIException(x.getMessage(),x.getStatus(),x.getUrl(),x);
ui.sendJSONResponse(uiexception.getJSON());
}
}
private String getAdvancedSearch(String fieldname, String value, String operator, String join){
if(!value.equals("")){
try{
String section = this.r.getRepeatField(fieldname).getSection();
String spath=this.r.getServicesRecordPath(section);
String[] parts=spath.split(":",2);
if(value.contains("*")){
- value.replace("*", "%");
+ value = value.replace("*", "%");
join = " ilike ";
}
//backslash quotes??
return parts[0]+":"+fieldname+join+"\""+value +"\""+ " " + operator+ " ";
}
catch(Exception e){
return "";
}
}
return "";
}
public void searchtype(Storage storage,UIRequest ui,String path) throws UIException{
if(ui.getBody() == null || StringUtils.isBlank(ui.getBody())){
search_or_list(storage,ui,path);
}
else{
//advanced search
advancedSearch(storage,ui,path, ui.getJSONBody());
}
}
/* Wrapper exists to be used inRead, hence not private */
public JSONObject getJSON(Storage storage,JSONObject restriction, String key, String mybase) throws JSONException, UIException, ExistException, UnimplementedException, UnderlyingStorageException{
JSONObject out = new JSONObject();
JSONObject data = storage.getPathsJSON(mybase,restriction);
String[] paths = (String[]) data.get("listItems");
JSONObject pagination = new JSONObject();
if(data.has("pagination")){
pagination = data.getJSONObject("pagination");
}
for(int i=0;i<paths.length;i++) {
if(paths[i].startsWith(mybase+"/"))
paths[i]=paths[i].substring((mybase+"/").length());
}
out = pathsToJSON(storage,mybase,paths,key,pagination);
return out;
}
public void run(Object in,String[] tail) throws UIException {
Request q=(Request)in;
searchtype(q.getStorage(),q.getUIRequest(),StringUtils.join(tail,"/"));
}
public void configure(WebUI ui,Spec spec) {
for(Record r : spec.getAllRecords()) {
type_to_url.put(r.getID(),r.getWebURL());
}
}
}
| false | false | null | null |
diff --git a/src/main/java/com/jmartin/temaki/FocusActivity.java b/src/main/java/com/jmartin/temaki/FocusActivity.java
index 3ed68af..a94f18a 100644
--- a/src/main/java/com/jmartin/temaki/FocusActivity.java
+++ b/src/main/java/com/jmartin/temaki/FocusActivity.java
@@ -1,162 +1,178 @@
package com.jmartin.temaki;
import android.app.ActionBar;
import android.app.Activity;
import android.app.FragmentManager;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.TypefaceSpan;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageButton;
import android.widget.TextView;
import com.jmartin.temaki.dialog.GenericInputDialog;
import com.jmartin.temaki.model.Constants;
import com.jmartin.temaki.model.TemakiItem;
/**
* Created by jeff on 2013-09-10.
*/
public class FocusActivity extends Activity {
private TextView focusTextView;
private ImageButton finishedFocusButton;
private TemakiItem focusItem;
private String spName = "";
+ private GenericInputDialog inputDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.focus_layout);
- String focusBundledText = getIntent().getStringExtra(Constants.FOCUS_BUNDLE_ID);
spName = getIntent().getStringExtra(Constants.SP_NAME_BUNDLE_ID);
- focusItem = new TemakiItem(focusBundledText);
+ if (savedInstanceState == null) {
+ // Then we should create from the Intent
+ String focusBundledText = getIntent().getStringExtra(Constants.FOCUS_BUNDLE_ID);
+ focusItem = new TemakiItem(focusBundledText);
+ } else {
+ // Then let's use whatever is in savedInstanceState
+ String focusSavedInstanceText = savedInstanceState.getString(Constants.FOCUS_SP_KEY);
+ focusItem = new TemakiItem(focusSavedInstanceText);
+ }
focusTextView = (TextView) findViewById(R.id.focus_text_view);
focusTextView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
editFocusText();
}
});
finishedFocusButton = (ImageButton) findViewById(R.id.focus_finished_image_button);
finishedFocusButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Cool animation showing the task is finished and delete it from the list
finishFocus();
}
});
if (!focusItem.getText().equalsIgnoreCase("")) {
focusTextView.setText(focusItem.getText());
}
initActionBar();
}
@Override
public void onBackPressed() {
super.onBackPressed();
overridePendingTransition(R.anim.focus_anim_slide_out_right, R.anim.focus_anim_slide_in_right);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Constants.EDIT_FOCUS_ID) {
String input = data.getStringExtra(Constants.INTENT_RESULT_KEY);
setFocusText(input);
focusTextView.setText(input);
}
super.onActivityResult(requestCode, resultCode, data);
}
@Override
protected void onPause() {
+ if (inputDialog != null) inputDialog.dismiss();
+
saveFocus();
super.onPause();
}
+ @Override
+ protected void onSaveInstanceState(Bundle outState) {
+ outState.putString(Constants.FOCUS_SP_KEY, focusItem.getText());
+ super.onSaveInstanceState(outState);
+ }
+
/**
* Save the user's Focus list in a separate SharedPreferences than other lists.
*/
private void saveFocus() {
SharedPreferences.Editor sharedPrefsEditor = getSharedPreferences(spName, MODE_PRIVATE).edit();
sharedPrefsEditor.putString(Constants.FOCUS_SP_KEY, focusItem.getText())
.commit();
}
private void initActionBar() {
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
SpannableString abTitle = new SpannableString(getResources().getString(R.string.focus));
abTitle.setSpan(new TypefaceSpan("sans-serif-light"), 0, abTitle.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
getActionBar().setTitle(abTitle);
}
private void editFocusText() {
FragmentManager fragManager = getFragmentManager();
- GenericInputDialog inputDialog = new GenericInputDialog(focusItem.getText());
+ inputDialog = new GenericInputDialog(focusItem.getText());
inputDialog.setActionIdentifier(Constants.EDIT_FOCUS_ID);
inputDialog.setTitle(getResources().getString(R.string.edit_focus_dialog_title));
inputDialog.show(fragManager, "generic_name_dialog_fragment");
}
public String getFocusText() {
if (focusItem == null) {
return "";
}
return focusItem.getText();
}
public void setFocusText(String newFocus) {
this.focusItem.setText(newFocus);
}
private void finishFocus() {
focusItem = new TemakiItem("");
Animation fadeOutAnimation = AnimationUtils.loadAnimation(this, R.anim.focus_text_disappear_anim);
fadeOutAnimation.setAnimationListener(finishFocusAnimationListener);
focusTextView.startAnimation(fadeOutAnimation);
}
private Animation.AnimationListener finishFocusAnimationListener = new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {}
@Override
public void onAnimationEnd(Animation animation) {
Animation fadeInAnimation = AnimationUtils.loadAnimation(FocusActivity.this, R.anim.focus_text_fade_in_anim);
focusTextView.setText(getResources().getString(R.string.focus_finished));
focusTextView.startAnimation(fadeInAnimation);
}
@Override
public void onAnimationRepeat(Animation animation) {}
};
}
| false | false | null | null |
diff --git a/src/com/android/mms/ui/ComposeMessageActivity.java b/src/com/android/mms/ui/ComposeMessageActivity.java
index 4844abf2..3f9154a6 100644
--- a/src/com/android/mms/ui/ComposeMessageActivity.java
+++ b/src/com/android/mms/ui/ComposeMessageActivity.java
@@ -1,5026 +1,5028 @@
/*
* Copyright (C) 2008 Esmertec AG.
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR 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.mms.ui;
import static android.content.res.Configuration.KEYBOARDHIDDEN_NO;
import static com.android.mms.transaction.ProgressCallbackEntity.PROGRESS_ABORT;
import static com.android.mms.transaction.ProgressCallbackEntity.PROGRESS_COMPLETE;
import static com.android.mms.transaction.ProgressCallbackEntity.PROGRESS_START;
import static com.android.mms.transaction.ProgressCallbackEntity.PROGRESS_STATUS_ACTION;
import static com.android.mms.ui.MessageListAdapter.COLUMN_ID;
import static com.android.mms.ui.MessageListAdapter.COLUMN_MSG_TYPE;
import static com.android.mms.ui.MessageListAdapter.PROJECTION;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.LoaderManager;
import android.app.ProgressDialog;
import android.app.Service;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.CursorLoader;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.Loader;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SqliteWrapper;
import android.drm.DrmStore;
import android.gesture.Gesture;
import android.gesture.GestureLibrary;
import android.gesture.GestureOverlayView;
import android.gesture.GestureOverlayView.OnGesturePerformedListener;
import android.gesture.Prediction;
import android.graphics.drawable.Drawable;
import android.hardware.SensorEventListener;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorManager;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.os.SystemProperties;
import android.preference.PreferenceManager;
import android.provider.CalendarContract;
import android.provider.CalendarContract.Events;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds;
import android.provider.ContactsContract.CommonDataKinds.Email;
import android.provider.ContactsContract.CommonDataKinds.Event;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.CommonDataKinds.StructuredPostal;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.Data;
import android.provider.ContactsContract.Intents;
import android.provider.ContactsContract.QuickContact;
import android.provider.MediaStore.Images;
import android.provider.MediaStore.Video;
import android.provider.Settings;
import android.provider.Telephony;
import android.provider.Telephony.Mms;
import android.provider.Telephony.Sms;
import android.support.v4.widget.CursorAdapter;
import android.support.v4.widget.SimpleCursorAdapter;
import android.telephony.PhoneNumberUtils;
import android.telephony.SmsMessage;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputFilter.LengthFilter;
import android.text.InputType;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.TextKeyListener;
import android.text.style.URLSpan;
import android.text.util.Linkify;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnCreateContextMenuListener;
import android.view.View.OnKeyListener;
import android.view.ViewStub;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.webkit.MimeTypeMap;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.LinearLayout;
import com.android.internal.telephony.TelephonyIntents;
import com.android.internal.telephony.TelephonyProperties;
import com.android.mms.LogTag;
import com.android.mms.MmsApp;
import com.android.mms.MmsConfig;
import com.android.mms.R;
import com.android.mms.TempFileProvider;
import com.android.mms.data.Contact;
import com.android.mms.data.ContactList;
import com.android.mms.data.Conversation;
import com.android.mms.data.Conversation.ConversationQueryHandler;
import com.android.mms.data.WorkingMessage;
import com.android.mms.data.WorkingMessage.MessageStatusListener;
import com.android.mms.drm.DrmUtils;
import com.android.mms.model.SlideModel;
import com.android.mms.model.SlideshowModel;
import com.android.mms.templates.TemplateGesturesLibrary;
import com.android.mms.templates.TemplatesProvider.Template;
import com.android.mms.transaction.MessagingNotification;
import com.android.mms.transaction.SmsReceiverService;
import com.android.mms.ui.MessageListView.OnSizeChangedListener;
import com.android.mms.ui.MessageUtils.ResizeImageResultCallback;
import com.android.mms.ui.RecipientsEditor.RecipientContextMenuInfo;
import com.android.mms.util.DateUtils;
import com.android.mms.util.DraftCache;
import com.android.mms.util.EmojiParser;
import com.android.mms.util.PhoneNumberFormatter;
import com.android.mms.util.SendingProgressTokenManager;
import com.android.mms.util.SmileyParser;
import com.android.mms.util.UnicodeFilter;
import com.android.mms.widget.MmsWidgetProvider;
import com.google.android.mms.ContentType;
import com.google.android.mms.MmsException;
import com.google.android.mms.pdu.EncodedStringValue;
import com.google.android.mms.pdu.PduBody;
import com.google.android.mms.pdu.PduPart;
import com.google.android.mms.pdu.PduPersister;
import com.google.android.mms.pdu.SendReq;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import java.text.Normalizer;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
/**
* This is the main UI for:
* 1. Composing a new message;
* 2. Viewing/managing message history of a conversation.
*
* This activity can handle following parameters from the intent
* by which it's launched.
* thread_id long Identify the conversation to be viewed. When creating a
* new message, this parameter shouldn't be present.
* msg_uri Uri The message which should be opened for editing in the editor.
* address String The addresses of the recipients in current conversation.
* exit_on_sent boolean Exit this activity after the message is sent.
*/
public class ComposeMessageActivity extends Activity
implements View.OnClickListener, TextView.OnEditorActionListener,
MessageStatusListener, Contact.UpdateListener, OnGesturePerformedListener, SensorEventListener,
LoaderManager.LoaderCallbacks<Cursor> {
public static final int REQUEST_CODE_ATTACH_IMAGE = 100;
public static final int REQUEST_CODE_TAKE_PICTURE = 101;
public static final int REQUEST_CODE_ATTACH_VIDEO = 102;
public static final int REQUEST_CODE_TAKE_VIDEO = 103;
public static final int REQUEST_CODE_ATTACH_SOUND = 104;
public static final int REQUEST_CODE_RECORD_SOUND = 105;
public static final int REQUEST_CODE_CREATE_SLIDESHOW = 106;
public static final int REQUEST_CODE_ECM_EXIT_DIALOG = 107;
public static final int REQUEST_CODE_ADD_CONTACT = 108;
public static final int REQUEST_CODE_PICK = 109;
public static final int REQUEST_CODE_INSERT_CONTACT_INFO = 110;
private static final String TAG = "Mms/compose";
private static final boolean DEBUG = false;
private static final boolean TRACE = false;
private static final boolean LOCAL_LOGV = false;
// Menu ID
private static final int MENU_ADD_SUBJECT = 0;
private static final int MENU_DELETE_THREAD = 1;
private static final int MENU_ADD_ATTACHMENT = 2;
private static final int MENU_DISCARD = 3;
private static final int MENU_SEND = 4;
private static final int MENU_CALL_RECIPIENT = 5;
private static final int MENU_CONVERSATION_LIST = 6;
private static final int MENU_DEBUG_DUMP = 7;
// Context menu ID
private static final int MENU_VIEW_CONTACT = 12;
private static final int MENU_ADD_TO_CONTACTS = 13;
private static final int MENU_EDIT_MESSAGE = 14;
private static final int MENU_INSERT_CONTACT_INFO = 15;
private static final int MENU_VIEW_SLIDESHOW = 16;
private static final int MENU_VIEW_MESSAGE_DETAILS = 17;
private static final int MENU_DELETE_MESSAGE = 18;
private static final int MENU_SEARCH = 19;
private static final int MENU_DELIVERY_REPORT = 20;
private static final int MENU_FORWARD_MESSAGE = 21;
private static final int MENU_CALL_BACK = 22;
private static final int MENU_SEND_EMAIL = 23;
private static final int MENU_COPY_MESSAGE_TEXT = 24;
private static final int MENU_COPY_TO_SDCARD = 25;
private static final int MENU_INSERT_SMILEY = 26;
private static final int MENU_ADD_ADDRESS_TO_CONTACTS = 27;
private static final int MENU_LOCK_MESSAGE = 28;
private static final int MENU_UNLOCK_MESSAGE = 29;
private static final int MENU_SAVE_RINGTONE = 30;
private static final int MENU_PREFERENCES = 31;
private static final int MENU_GROUP_PARTICIPANTS = 32;
private static final int MENU_INSERT_EMOJI = 33;
private static final int MENU_ADD_TEMPLATE = 34;
private static final int DIALOG_TEMPLATE_SELECT = 1;
private static final int DIALOG_TEMPLATE_NOT_AVAILABLE = 2;
private static final int LOAD_TEMPLATE_BY_ID = 0;
private static final int LOAD_TEMPLATES = 1;
// Add SMS to calendar reminder
private static final int MENU_ADD_TO_CALENDAR = 35;
private static final int RECIPIENTS_MAX_LENGTH = 312;
private static final int MESSAGE_LIST_QUERY_TOKEN = 9527;
private static final int MESSAGE_LIST_QUERY_AFTER_DELETE_TOKEN = 9528;
private static final int DELETE_MESSAGE_TOKEN = 9700;
private static final int CHARS_REMAINING_BEFORE_COUNTER_SHOWN = 10;
private static final long NO_DATE_FOR_DIALOG = -1L;
private static final String EXIT_ECM_RESULT = "exit_ecm_result";
// When the conversation has a lot of messages and a new message is sent, the list is scrolled
// so the user sees the just sent message. If we have to scroll the list more than 20 items,
// then a scroll shortcut is invoked to move the list near the end before scrolling.
private static final int MAX_ITEMS_TO_INVOKE_SCROLL_SHORTCUT = 20;
// Any change in height in the message list view greater than this threshold will not
// cause a smooth scroll. Instead, we jump the list directly to the desired position.
private static final int SMOOTH_SCROLL_THRESHOLD = 200;
// To reduce janky interaction when message history + draft loads and keyboard opening
// query the messages + draft after the keyboard opens. This controls that behavior.
private static final boolean DEFER_LOADING_MESSAGES_AND_DRAFT = true;
// The max amount of delay before we force load messages and draft.
// 500ms is determined empirically. We want keyboard to have a chance to be shown before
// we force loading. However, there is at least one use case where the keyboard never shows
// even if we tell it to (turning off and on the screen). So we need to force load the
// messages+draft after the max delay.
private static final int LOADING_MESSAGES_AND_DRAFT_MAX_DELAY_MS = 500;
private ContentResolver mContentResolver;
private BackgroundQueryHandler mBackgroundQueryHandler;
private Conversation mConversation; // Conversation we are working in
private boolean mExitOnSent; // Should we finish() after sending a message?
// TODO: mExitOnSent is obsolete -- remove
private View mTopPanel; // View containing the recipient and subject editors
private View mBottomPanel; // View containing the text editor, send button, ec.
private EditText mTextEditor; // Text editor to type your message into
private TextView mTextCounter; // Shows the number of characters used in text editor
private TextView mSendButtonMms; // Press to send mms
private ImageButton mSendButtonSms; // Press to send sms
private EditText mSubjectTextEditor; // Text editor for MMS subject
private ImageButton mQuickEmoji;
private AttachmentEditor mAttachmentEditor;
private View mAttachmentEditorScrollView;
private MessageListView mMsgListView; // ListView for messages in this conversation
public MessageListAdapter mMsgListAdapter; // and its corresponding ListAdapter
private RecipientsEditor mRecipientsEditor; // UI control for editing recipients
private ImageButton mRecipientsPicker; // UI control for recipients picker
// For HW keyboard, 'mIsKeyboardOpen' indicates if the HW keyboard is open.
// For SW keyboard, 'mIsKeyboardOpen' should always be true.
private boolean mIsKeyboardOpen;
private boolean mIsLandscape; // Whether we're in landscape mode
private boolean mToastForDraftSave; // Whether to notify the user that a draft is being saved
private boolean mSentMessage; // true if the user has sent a message while in this
// activity. On a new compose message case, when the first
// message is sent is a MMS w/ attachment, the list blanks
// for a second before showing the sent message. But we'd
// think the message list is empty, thus show the recipients
// editor thinking it's a draft message. This flag should
// help clarify the situation.
private WorkingMessage mWorkingMessage; // The message currently being composed.
private AlertDialog mSmileyDialog;
private AlertDialog mEmojiDialog;
private View mEmojiView;
private boolean mEnableEmojis;
private boolean mEnableQuickEmojis;
private boolean mWaitingForSubActivity;
private int mLastRecipientCount; // Used for warning the user on too many recipients.
private AttachmentTypeSelectorAdapter mAttachmentTypeSelectorAdapter;
private boolean mSendingMessage; // Indicates the current message is sending, and shouldn't send again.
private Intent mAddContactIntent; // Intent used to add a new contact
private Uri mTempMmsUri; // Only used as a temporary to hold a slideshow uri
private long mTempThreadId; // Only used as a temporary to hold a threadId
private AsyncDialog mAsyncDialog; // Used for background tasks.
private String mDebugRecipients;
private GestureLibrary mLibrary;
private SimpleCursorAdapter mTemplatesCursorAdapter;
private double mGestureSensitivity;
private int mInputMethod;
private SensorManager mSensorManager;
private int SensorOrientationY;
private int SensorProximity;
private int oldProximity;
private boolean initProx;
private boolean proxChanged;
private int mLastSmoothScrollPosition;
private boolean mScrollOnSend; // Flag that we need to scroll the list to the end.
private int mSavedScrollPosition = -1; // we save the ListView's scroll position in onPause(),
// so we can remember it after re-entering the activity.
// If the value >= 0, then we jump to that line. If the
// value is maxint, then we jump to the end.
private long mLastMessageId;
// Add SMS to calendar reminder
private static final String CALENDAR_EVENT_TYPE = "vnd.android.cursor.item/event";
/**
* Whether this activity is currently running (i.e. not paused)
*/
public static boolean mIsRunning;
// we may call loadMessageAndDraft() from a few different places. This is used to make
// sure we only load message+draft once.
private boolean mMessagesAndDraftLoaded;
// whether we should load the draft. For example, after attaching a photo and coming back
// in onActivityResult(), we should not load the draft because that will mess up the draft
// state of mWorkingMessage. Also, if we are handling a Send or Forward Message Intent,
// we should not load the draft.
private boolean mShouldLoadDraft;
private UnicodeFilter mUnicodeFilter = null;
private Handler mHandler = new Handler();
// keys for extras and icicles
public final static String THREAD_ID = "thread_id";
private final static String RECIPIENTS = "recipients";
@SuppressWarnings("unused")
public static void log(String logMsg) {
Thread current = Thread.currentThread();
long tid = current.getId();
StackTraceElement[] stack = current.getStackTrace();
String methodName = stack[3].getMethodName();
// Prepend current thread ID and name of calling method to the message.
logMsg = "[" + tid + "] [" + methodName + "] " + logMsg;
Log.d(TAG, logMsg);
}
private void editSlideshow() {
// The user wants to edit the slideshow. That requires us to persist the slideshow to
// disk as a PDU in saveAsMms. This code below does that persisting in a background
// task. If the task takes longer than a half second, a progress dialog is displayed.
// Once the PDU persisting is done, another runnable on the UI thread get executed to start
// the SlideshowEditActivity.
getAsyncDialog().runAsync(new Runnable() {
@Override
public void run() {
// This runnable gets run in a background thread.
mTempMmsUri = mWorkingMessage.saveAsMms(false);
}
}, new Runnable() {
@Override
public void run() {
// Once the above background thread is complete, this runnable is run
// on the UI thread.
if (mTempMmsUri == null) {
return;
}
Intent intent = new Intent(ComposeMessageActivity.this,
SlideshowEditActivity.class);
intent.setData(mTempMmsUri);
startActivityForResult(intent, REQUEST_CODE_CREATE_SLIDESHOW);
}
}, R.string.building_slideshow_title);
}
private final Handler mAttachmentEditorHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case AttachmentEditor.MSG_EDIT_SLIDESHOW: {
editSlideshow();
break;
}
case AttachmentEditor.MSG_SEND_SLIDESHOW: {
if (isPreparedForSending()) {
ComposeMessageActivity.this.confirmSendMessageIfNeeded();
}
break;
}
case AttachmentEditor.MSG_VIEW_IMAGE:
case AttachmentEditor.MSG_PLAY_VIDEO:
case AttachmentEditor.MSG_PLAY_AUDIO:
case AttachmentEditor.MSG_PLAY_SLIDESHOW:
viewMmsMessageAttachment(msg.what);
break;
case AttachmentEditor.MSG_REPLACE_IMAGE:
case AttachmentEditor.MSG_REPLACE_VIDEO:
case AttachmentEditor.MSG_REPLACE_AUDIO:
showAddAttachmentDialog(true);
break;
case AttachmentEditor.MSG_REMOVE_ATTACHMENT:
mWorkingMessage.removeAttachment(true);
break;
default:
break;
}
}
};
private void viewMmsMessageAttachment(final int requestCode) {
SlideshowModel slideshow = mWorkingMessage.getSlideshow();
if (slideshow == null) {
throw new IllegalStateException("mWorkingMessage.getSlideshow() == null");
}
if (slideshow.isSimple()) {
MessageUtils.viewSimpleSlideshow(this, slideshow);
} else {
// The user wants to view the slideshow. That requires us to persist the slideshow to
// disk as a PDU in saveAsMms. This code below does that persisting in a background
// task. If the task takes longer than a half second, a progress dialog is displayed.
// Once the PDU persisting is done, another runnable on the UI thread get executed to
// start the SlideshowActivity.
getAsyncDialog().runAsync(new Runnable() {
@Override
public void run() {
// This runnable gets run in a background thread.
mTempMmsUri = mWorkingMessage.saveAsMms(false);
}
}, new Runnable() {
@Override
public void run() {
// Once the above background thread is complete, this runnable is run
// on the UI thread.
if (mTempMmsUri == null) {
return;
}
MessageUtils.launchSlideshowActivity(ComposeMessageActivity.this, mTempMmsUri,
requestCode);
}
}, R.string.building_slideshow_title);
}
}
private final Handler mMessageListItemHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
MessageItem msgItem = (MessageItem) msg.obj;
if (msgItem != null) {
switch (msg.what) {
case MessageListItem.MSG_LIST_DETAILS:
showMessageDetails(msgItem);
break;
case MessageListItem.MSG_LIST_EDIT:
editMessageItem(msgItem);
drawBottomPanel();
break;
case MessageListItem.MSG_LIST_PLAY:
switch (msgItem.mAttachmentType) {
case WorkingMessage.IMAGE:
case WorkingMessage.VIDEO:
case WorkingMessage.AUDIO:
case WorkingMessage.SLIDESHOW:
MessageUtils.viewMmsMessageAttachment(ComposeMessageActivity.this,
msgItem.mMessageUri, msgItem.mSlideshow,
getAsyncDialog());
break;
}
break;
default:
Log.w(TAG, "Unknown message: " + msg.what);
return;
}
}
}
};
private boolean showMessageDetails(MessageItem msgItem) {
Cursor cursor = mMsgListAdapter.getCursorForItem(msgItem);
if (cursor == null) {
return false;
}
String messageDetails = MessageUtils.getMessageDetails(
ComposeMessageActivity.this, cursor, msgItem.mMessageSize);
new AlertDialog.Builder(ComposeMessageActivity.this)
.setTitle(R.string.message_details_title)
.setMessage(messageDetails)
.setCancelable(true)
.show();
return true;
}
private final OnKeyListener mSubjectKeyListener = new OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() != KeyEvent.ACTION_DOWN) {
return false;
}
// When the subject editor is empty, press "DEL" to hide the input field.
if ((keyCode == KeyEvent.KEYCODE_DEL) && (mSubjectTextEditor.length() == 0)) {
showSubjectEditor(false);
mWorkingMessage.setSubject(null, true);
return true;
}
return false;
}
};
/**
* Return the messageItem associated with the type ("mms" or "sms") and message id.
* @param type Type of the message: "mms" or "sms"
* @param msgId Message id of the message. This is the _id of the sms or pdu row and is
* stored in the MessageItem
* @param createFromCursorIfNotInCache true if the item is not found in the MessageListAdapter's
* cache and the code can create a new MessageItem based on the position of the current cursor.
* If false, the function returns null if the MessageItem isn't in the cache.
* @return MessageItem or null if not found and createFromCursorIfNotInCache is false
*/
private MessageItem getMessageItem(String type, long msgId,
boolean createFromCursorIfNotInCache) {
return mMsgListAdapter.getCachedMessageItem(type, msgId,
createFromCursorIfNotInCache ? mMsgListAdapter.getCursor() : null);
}
private boolean isCursorValid() {
// Check whether the cursor is valid or not.
Cursor cursor = mMsgListAdapter.getCursor();
if (cursor.isClosed() || cursor.isBeforeFirst() || cursor.isAfterLast()) {
Log.e(TAG, "Bad cursor.", new RuntimeException());
return false;
}
return true;
}
private void resetCounter() {
mTextCounter.setText("");
mTextCounter.setVisibility(View.GONE);
}
private void updateCounter(CharSequence text, int start, int before, int count) {
WorkingMessage workingMessage = mWorkingMessage;
if (workingMessage.requiresMms()) {
// If we're not removing text (i.e. no chance of converting back to SMS
// because of this change) and we're in MMS mode, just bail out since we
// then won't have to calculate the length unnecessarily.
final boolean textRemoved = (before > count);
if (!textRemoved) {
showSmsOrMmsSendButton(workingMessage.requiresMms());
return;
}
}
int[] params = SmsMessage.calculateLength(text, false);
/* SmsMessage.calculateLength returns an int[4] with:
* int[0] being the number of SMS's required,
* int[1] the number of code units used,
* int[2] is the number of code units remaining until the next message.
* int[3] is the encoding type that should be used for the message.
*/
int msgCount = params[0];
int remainingInCurrentMessage = params[2];
if (!MmsConfig.getSplitSmsEnabled() && !MmsConfig.getMultipartSmsEnabled()) {
// The provider doesn't support multi-part sms's so as soon as the user types
// an sms longer than one segment, we have to turn the message into an mms.
mWorkingMessage.setLengthRequiresMms(msgCount > 1, true);
} else {
int threshold = MmsConfig.getSmsToMmsTextThreshold();
mWorkingMessage.setLengthRequiresMms(threshold > 0 && msgCount > threshold, true);
}
// Show the counter only if:
// - We are not in MMS mode
// - We are going to send more than one message OR we are getting close
boolean showCounter = false;
if (!workingMessage.requiresMms() &&
(msgCount > 1 ||
remainingInCurrentMessage <= CHARS_REMAINING_BEFORE_COUNTER_SHOWN)) {
showCounter = true;
}
showSmsOrMmsSendButton(workingMessage.requiresMms());
if (showCounter) {
// Update the remaining characters and number of messages required.
String counterText = msgCount > 1 ? remainingInCurrentMessage + " / " + msgCount
: String.valueOf(remainingInCurrentMessage);
mTextCounter.setText(counterText);
mTextCounter.setVisibility(View.VISIBLE);
} else {
mTextCounter.setVisibility(View.GONE);
}
}
@Override
public void startActivityForResult(Intent intent, int requestCode)
{
// requestCode >= 0 means the activity in question is a sub-activity.
if (requestCode >= 0) {
mWaitingForSubActivity = true;
}
// The camera and other activities take a long time to hide the keyboard so we pre-hide
// it here. However, if we're opening up the quick contact window while typing, don't
// mess with the keyboard.
if (mIsKeyboardOpen && !QuickContact.ACTION_QUICK_CONTACT.equals(intent.getAction())) {
hideKeyboard();
}
super.startActivityForResult(intent, requestCode);
}
private void showConvertToMmsToast() {
Toast.makeText(this, R.string.converting_to_picture_message, Toast.LENGTH_SHORT).show();
}
private class DeleteMessageListener implements OnClickListener {
private final MessageItem mMessageItem;
public DeleteMessageListener(MessageItem messageItem) {
mMessageItem = messageItem;
}
@Override
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
new AsyncTask<Void, Void, Void>() {
protected Void doInBackground(Void... none) {
if (mMessageItem.isMms()) {
WorkingMessage.removeThumbnailsFromCache(mMessageItem.getSlideshow());
MmsApp.getApplication().getPduLoaderManager()
.removePdu(mMessageItem.mMessageUri);
// Delete the message *after* we've removed the thumbnails because we
// need the pdu and slideshow for removeThumbnailsFromCache to work.
}
Boolean deletingLastItem = false;
Cursor cursor = mMsgListAdapter != null ? mMsgListAdapter.getCursor() : null;
if (cursor != null) {
cursor.moveToLast();
long msgId = cursor.getLong(COLUMN_ID);
deletingLastItem = msgId == mMessageItem.mMsgId;
}
mBackgroundQueryHandler.startDelete(DELETE_MESSAGE_TOKEN,
deletingLastItem, mMessageItem.mMessageUri,
mMessageItem.mLocked ? null : "locked=0", null);
return null;
}
}.execute();
}
}
private class DiscardDraftListener implements OnClickListener {
@Override
public void onClick(DialogInterface dialog, int whichButton) {
mWorkingMessage.discard();
dialog.dismiss();
finish();
}
}
private class SendIgnoreInvalidRecipientListener implements OnClickListener {
@Override
public void onClick(DialogInterface dialog, int whichButton) {
sendMessage(true);
dialog.dismiss();
}
}
private class CancelSendingListener implements OnClickListener {
@Override
public void onClick(DialogInterface dialog, int whichButton) {
if (isRecipientsEditorVisible()) {
mRecipientsEditor.requestFocus();
}
dialog.dismiss();
}
}
private void confirmSendMessageIfNeeded() {
if (!isRecipientsEditorVisible()) {
sendMessage(true);
return;
}
boolean isMms = mWorkingMessage.requiresMms();
if (mRecipientsEditor.hasInvalidRecipient(isMms)) {
if (mRecipientsEditor.hasValidRecipient(isMms)) {
String title = getResourcesString(R.string.has_invalid_recipient,
mRecipientsEditor.formatInvalidNumbers(isMms));
new AlertDialog.Builder(this)
.setTitle(title)
.setMessage(R.string.invalid_recipient_message)
.setPositiveButton(R.string.try_to_send,
new SendIgnoreInvalidRecipientListener())
.setNegativeButton(R.string.no, new CancelSendingListener())
.show();
} else {
new AlertDialog.Builder(this)
.setTitle(R.string.cannot_send_message)
.setMessage(R.string.cannot_send_message_reason)
.setPositiveButton(R.string.yes, new CancelSendingListener())
.show();
}
} else {
// The recipients editor is still open. Make sure we use what's showing there
// as the destination.
ContactList contacts = mRecipientsEditor.constructContactsFromInput(false);
mDebugRecipients = contacts.serialize();
sendMessage(true);
}
}
private final TextWatcher mRecipientsWatcher = new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// This is a workaround for bug 1609057. Since onUserInteraction() is
// not called when the user touches the soft keyboard, we pretend it was
// called when textfields changes. This should be removed when the bug
// is fixed.
onUserInteraction();
}
@Override
public void afterTextChanged(Editable s) {
// Bug 1474782 describes a situation in which we send to
// the wrong recipient. We have been unable to reproduce this,
// but the best theory we have so far is that the contents of
// mRecipientList somehow become stale when entering
// ComposeMessageActivity via onNewIntent(). This assertion is
// meant to catch one possible path to that, of a non-visible
// mRecipientsEditor having its TextWatcher fire and refreshing
// mRecipientList with its stale contents.
if (!isRecipientsEditorVisible()) {
IllegalStateException e = new IllegalStateException(
"afterTextChanged called with invisible mRecipientsEditor");
// Make sure the crash is uploaded to the service so we
// can see if this is happening in the field.
Log.w(TAG,
"RecipientsWatcher: afterTextChanged called with invisible mRecipientsEditor");
return;
}
List<String> numbers = mRecipientsEditor.getNumbers();
mWorkingMessage.setWorkingRecipients(numbers);
boolean multiRecipients = numbers != null && numbers.size() > 1;
mMsgListAdapter.setIsGroupConversation(multiRecipients);
mWorkingMessage.setHasMultipleRecipients(multiRecipients, true);
mWorkingMessage.setHasEmail(mRecipientsEditor.containsEmail(), true);
checkForTooManyRecipients();
// Walk backwards in the text box, skipping spaces. If the last
// character is a comma, update the title bar.
for (int pos = s.length() - 1; pos >= 0; pos--) {
char c = s.charAt(pos);
if (c == ' ')
continue;
if (c == ',') {
ContactList contacts = mRecipientsEditor.constructContactsFromInput(false);
updateTitle(contacts);
}
break;
}
// If we have gone to zero recipients, disable send button.
updateSendButtonState();
}
};
private void checkForTooManyRecipients() {
final int recipientLimit = MmsConfig.getRecipientLimit();
if (recipientLimit != Integer.MAX_VALUE) {
final int recipientCount = recipientCount();
boolean tooMany = recipientCount > recipientLimit;
if (recipientCount != mLastRecipientCount) {
// Don't warn the user on every character they type when they're over the limit,
// only when the actual # of recipients changes.
mLastRecipientCount = recipientCount;
if (tooMany) {
String tooManyMsg = getString(R.string.too_many_recipients, recipientCount,
recipientLimit);
Toast.makeText(ComposeMessageActivity.this,
tooManyMsg, Toast.LENGTH_LONG).show();
}
}
}
}
private final OnCreateContextMenuListener mRecipientsMenuCreateListener =
new OnCreateContextMenuListener() {
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
if (menuInfo != null) {
Contact c = ((RecipientContextMenuInfo) menuInfo).recipient;
RecipientsMenuClickListener l = new RecipientsMenuClickListener(c);
menu.setHeaderTitle(c.getName());
if (c.existsInDatabase()) {
menu.add(0, MENU_VIEW_CONTACT, 0, R.string.menu_view_contact)
.setOnMenuItemClickListener(l);
} else if (canAddToContacts(c)){
menu.add(0, MENU_ADD_TO_CONTACTS, 0, R.string.menu_add_to_contacts)
.setOnMenuItemClickListener(l);
}
}
}
};
private final class RecipientsMenuClickListener implements MenuItem.OnMenuItemClickListener {
private final Contact mRecipient;
RecipientsMenuClickListener(Contact recipient) {
mRecipient = recipient;
}
@Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
// Context menu handlers for the recipients editor.
case MENU_VIEW_CONTACT: {
Uri contactUri = mRecipient.getUri();
Intent intent = new Intent(Intent.ACTION_VIEW, contactUri);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
startActivity(intent);
return true;
}
case MENU_ADD_TO_CONTACTS: {
mAddContactIntent = ConversationList.createAddContactIntent(
mRecipient.getNumber());
ComposeMessageActivity.this.startActivityForResult(mAddContactIntent,
REQUEST_CODE_ADD_CONTACT);
return true;
}
}
return false;
}
}
private boolean canAddToContacts(Contact contact) {
// There are some kind of automated messages, like STK messages, that we don't want
// to add to contacts. These names begin with special characters, like, "*Info".
final String name = contact.getName();
if (!TextUtils.isEmpty(contact.getNumber())) {
char c = contact.getNumber().charAt(0);
if (isSpecialChar(c)) {
return false;
}
}
if (!TextUtils.isEmpty(name)) {
char c = name.charAt(0);
if (isSpecialChar(c)) {
return false;
}
}
if (!(Mms.isEmailAddress(name) ||
Telephony.Mms.isPhoneNumber(name) ||
contact.isMe())) {
return false;
}
return true;
}
private boolean isSpecialChar(char c) {
return c == '*' || c == '%' || c == '$';
}
private void addPositionBasedMenuItems(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
AdapterView.AdapterContextMenuInfo info;
try {
info = (AdapterView.AdapterContextMenuInfo) menuInfo;
} catch (ClassCastException e) {
Log.e(TAG, "bad menuInfo");
return;
}
final int position = info.position;
addUriSpecificMenuItems(menu, v, position);
}
private Uri getSelectedUriFromMessageList(ListView listView, int position) {
// If the context menu was opened over a uri, get that uri.
MessageListItem msglistItem = (MessageListItem) listView.getChildAt(position);
if (msglistItem == null) {
// FIXME: Should get the correct view. No such interface in ListView currently
// to get the view by position. The ListView.getChildAt(position) cannot
// get correct view since the list doesn't create one child for each item.
// And if setSelection(position) then getSelectedView(),
// cannot get corrent view when in touch mode.
return null;
}
TextView textView;
CharSequence text = null;
int selStart = -1;
int selEnd = -1;
//check if message sender is selected
textView = (TextView) msglistItem.findViewById(R.id.text_view);
if (textView != null) {
text = textView.getText();
selStart = textView.getSelectionStart();
selEnd = textView.getSelectionEnd();
}
// Check that some text is actually selected, rather than the cursor
// just being placed within the TextView.
if (selStart != selEnd) {
int min = Math.min(selStart, selEnd);
int max = Math.max(selStart, selEnd);
URLSpan[] urls = ((Spanned) text).getSpans(min, max,
URLSpan.class);
if (urls.length == 1) {
return Uri.parse(urls[0].getURL());
}
}
//no uri was selected
return null;
}
private void addUriSpecificMenuItems(ContextMenu menu, View v, int position) {
Uri uri = getSelectedUriFromMessageList((ListView) v, position);
if (uri != null) {
Intent intent = new Intent(null, uri);
intent.addCategory(Intent.CATEGORY_SELECTED_ALTERNATIVE);
menu.addIntentOptions(0, 0, 0,
new android.content.ComponentName(this, ComposeMessageActivity.class),
null, intent, 0, null);
}
}
private final void addCallAndContactMenuItems(
ContextMenu menu, MsgListMenuClickListener l, MessageItem msgItem) {
if (TextUtils.isEmpty(msgItem.mBody)) {
return;
}
SpannableString msg = new SpannableString(msgItem.mBody);
Linkify.addLinks(msg, Linkify.ALL);
ArrayList<String> uris =
MessageUtils.extractUris(msg.getSpans(0, msg.length(), URLSpan.class));
// Remove any dupes so they don't get added to the menu multiple times
HashSet<String> collapsedUris = new HashSet<String>();
for (String uri : uris) {
collapsedUris.add(uri.toLowerCase());
}
for (String uriString : collapsedUris) {
String prefix = null;
int sep = uriString.indexOf(":");
if (sep >= 0) {
prefix = uriString.substring(0, sep);
uriString = uriString.substring(sep + 1);
}
Uri contactUri = null;
boolean knownPrefix = true;
if ("mailto".equalsIgnoreCase(prefix)) {
contactUri = getContactUriForEmail(uriString);
} else if ("tel".equalsIgnoreCase(prefix)) {
contactUri = getContactUriForPhoneNumber(uriString);
} else {
knownPrefix = false;
}
if (knownPrefix && contactUri == null) {
Intent intent = ConversationList.createAddContactIntent(uriString);
String addContactString = getString(R.string.menu_add_address_to_contacts,
uriString);
menu.add(0, MENU_ADD_ADDRESS_TO_CONTACTS, 0, addContactString)
.setOnMenuItemClickListener(l)
.setIntent(intent);
}
}
}
private Uri getContactUriForEmail(String emailAddress) {
Cursor cursor = SqliteWrapper.query(this, getContentResolver(),
Uri.withAppendedPath(Email.CONTENT_LOOKUP_URI, Uri.encode(emailAddress)),
new String[] { Email.CONTACT_ID, Contacts.DISPLAY_NAME }, null, null, null);
if (cursor != null) {
try {
while (cursor.moveToNext()) {
String name = cursor.getString(1);
if (!TextUtils.isEmpty(name)) {
return ContentUris.withAppendedId(Contacts.CONTENT_URI, cursor.getLong(0));
}
}
} finally {
cursor.close();
}
}
return null;
}
private Uri getContactUriForPhoneNumber(String phoneNumber) {
Contact contact = Contact.get(phoneNumber, false);
if (contact.existsInDatabase()) {
return contact.getUri();
}
return null;
}
private final OnCreateContextMenuListener mMsgListMenuCreateListener =
new OnCreateContextMenuListener() {
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
if (!isCursorValid()) {
return;
}
Cursor cursor = mMsgListAdapter.getCursor();
String type = cursor.getString(COLUMN_MSG_TYPE);
long msgId = cursor.getLong(COLUMN_ID);
addPositionBasedMenuItems(menu, v, menuInfo);
MessageItem msgItem = mMsgListAdapter.getCachedMessageItem(type, msgId, cursor);
if (msgItem == null) {
Log.e(TAG, "Cannot load message item for type = " + type
+ ", msgId = " + msgId);
return;
}
menu.setHeaderTitle(R.string.message_options);
MsgListMenuClickListener l = new MsgListMenuClickListener(msgItem);
// It is unclear what would make most sense for copying an MMS message
// to the clipboard, so we currently do SMS only.
if (msgItem.isSms()) {
// Message type is sms. Only allow "edit" if the message has a single recipient
if (getRecipients().size() == 1 &&
(msgItem.mBoxId == Sms.MESSAGE_TYPE_OUTBOX ||
msgItem.mBoxId == Sms.MESSAGE_TYPE_FAILED)) {
menu.add(0, MENU_EDIT_MESSAGE, 0, R.string.menu_edit)
.setOnMenuItemClickListener(l);
}
menu.add(0, MENU_COPY_MESSAGE_TEXT, 0, R.string.copy_message_text)
.setOnMenuItemClickListener(l);
// Add SMS to calendar reminder
menu.add(0, MENU_ADD_TO_CALENDAR, 0, R.string.menu_add_to_calendar)
.setOnMenuItemClickListener(l);
}
addCallAndContactMenuItems(menu, l, msgItem);
// Forward is not available for undownloaded messages.
if (msgItem.isDownloaded() && (msgItem.isSms() || isForwardable(msgId))) {
menu.add(0, MENU_FORWARD_MESSAGE, 0, R.string.menu_forward)
.setOnMenuItemClickListener(l);
}
if (msgItem.isMms()) {
switch (msgItem.mBoxId) {
case Mms.MESSAGE_BOX_INBOX:
break;
case Mms.MESSAGE_BOX_OUTBOX:
// Since we currently break outgoing messages to multiple
// recipients into one message per recipient, only allow
// editing a message for single-recipient conversations.
if (getRecipients().size() == 1) {
menu.add(0, MENU_EDIT_MESSAGE, 0, R.string.menu_edit)
.setOnMenuItemClickListener(l);
}
break;
}
switch (msgItem.mAttachmentType) {
case WorkingMessage.TEXT:
break;
case WorkingMessage.VIDEO:
case WorkingMessage.IMAGE:
if (haveSomethingToCopyToSDCard(msgItem.mMsgId)) {
menu.add(0, MENU_COPY_TO_SDCARD, 0, R.string.copy_to_sdcard)
.setOnMenuItemClickListener(l);
}
break;
case WorkingMessage.SLIDESHOW:
default:
menu.add(0, MENU_VIEW_SLIDESHOW, 0, R.string.view_slideshow)
.setOnMenuItemClickListener(l);
if (haveSomethingToCopyToSDCard(msgItem.mMsgId)) {
menu.add(0, MENU_COPY_TO_SDCARD, 0, R.string.copy_to_sdcard)
.setOnMenuItemClickListener(l);
}
if (isDrmRingtoneWithRights(msgItem.mMsgId)) {
menu.add(0, MENU_SAVE_RINGTONE, 0,
getDrmMimeMenuStringRsrc(msgItem.mMsgId))
.setOnMenuItemClickListener(l);
}
break;
}
}
if (msgItem.mLocked) {
menu.add(0, MENU_UNLOCK_MESSAGE, 0, R.string.menu_unlock)
.setOnMenuItemClickListener(l);
} else {
menu.add(0, MENU_LOCK_MESSAGE, 0, R.string.menu_lock)
.setOnMenuItemClickListener(l);
}
menu.add(0, MENU_VIEW_MESSAGE_DETAILS, 0, R.string.view_message_details)
.setOnMenuItemClickListener(l);
if (msgItem.mDeliveryStatus != MessageItem.DeliveryStatus.NONE || msgItem.mReadReport) {
menu.add(0, MENU_DELIVERY_REPORT, 0, R.string.view_delivery_report)
.setOnMenuItemClickListener(l);
}
menu.add(0, MENU_DELETE_MESSAGE, 0, R.string.delete_message)
.setOnMenuItemClickListener(l);
}
};
private void editMessageItem(MessageItem msgItem) {
if ("sms".equals(msgItem.mType)) {
editSmsMessageItem(msgItem);
} else {
editMmsMessageItem(msgItem);
}
if (msgItem.isFailedMessage() && mMsgListAdapter.getCount() <= 1) {
// For messages with bad addresses, let the user re-edit the recipients.
initRecipientsEditor();
}
}
private void editSmsMessageItem(MessageItem msgItem) {
// When the message being edited is the only message in the conversation, the delete
// below does something subtle. The trigger "delete_obsolete_threads_pdu" sees that a
// thread contains no messages and silently deletes the thread. Meanwhile, the mConversation
// object still holds onto the old thread_id and code thinks there's a backing thread in
// the DB when it really has been deleted. Here we try and notice that situation and
// clear out the thread_id. Later on, when Conversation.ensureThreadId() is called, we'll
// create a new thread if necessary.
synchronized(mConversation) {
if (mConversation.getMessageCount() <= 1) {
mConversation.clearThreadId();
MessagingNotification.setCurrentlyDisplayedThreadId(
MessagingNotification.THREAD_NONE);
}
}
// Delete the old undelivered SMS and load its content.
Uri uri = ContentUris.withAppendedId(Sms.CONTENT_URI, msgItem.mMsgId);
SqliteWrapper.delete(ComposeMessageActivity.this,
mContentResolver, uri, null, null);
mWorkingMessage.setText(msgItem.mBody);
}
private void editMmsMessageItem(MessageItem msgItem) {
// Load the selected message in as the working message.
WorkingMessage newWorkingMessage = WorkingMessage.load(this, msgItem.mMessageUri);
if (newWorkingMessage == null) {
return;
}
// Discard the current message in progress.
mWorkingMessage.discard();
mWorkingMessage = newWorkingMessage;
mWorkingMessage.setConversation(mConversation);
invalidateOptionsMenu();
drawTopPanel(false);
// WorkingMessage.load() above only loads the slideshow. Set the
// subject here because we already know what it is and avoid doing
// another DB lookup in load() just to get it.
mWorkingMessage.setSubject(msgItem.mSubject, false);
if (mWorkingMessage.hasSubject()) {
showSubjectEditor(true);
}
}
private void copyToClipboard(String str) {
ClipboardManager clipboard = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
clipboard.setPrimaryClip(ClipData.newPlainText(null, str));
}
// Add SMS to calendar reminder
private void addEventToCalendar(String subject, String description) {
Intent calendarIntent = new Intent(Intent.ACTION_INSERT);
Calendar calTime = Calendar.getInstance();
calendarIntent.setType(CALENDAR_EVENT_TYPE);
calendarIntent.putExtra(Events.TITLE, subject);
calendarIntent.putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, calTime.getTimeInMillis());
calTime.add(Calendar.MINUTE, 30);
calendarIntent.putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, calTime.getTimeInMillis());
calendarIntent.putExtra(Events.DESCRIPTION, description);
startActivity(calendarIntent);
}
private void forwardMessage(final MessageItem msgItem) {
mTempThreadId = 0;
// The user wants to forward the message. If the message is an mms message, we need to
// persist the pdu to disk. This is done in a background task.
// If the task takes longer than a half second, a progress dialog is displayed.
// Once the PDU persisting is done, another runnable on the UI thread get executed to start
// the ForwardMessageActivity.
getAsyncDialog().runAsync(new Runnable() {
@Override
public void run() {
// This runnable gets run in a background thread.
if (msgItem.mType.equals("mms")) {
SendReq sendReq = new SendReq();
String subject = getString(R.string.forward_prefix);
if (msgItem.mSubject != null) {
subject += msgItem.mSubject;
}
sendReq.setSubject(new EncodedStringValue(subject));
sendReq.setBody(msgItem.mSlideshow.makeCopy());
mTempMmsUri = null;
try {
PduPersister persister =
PduPersister.getPduPersister(ComposeMessageActivity.this);
// Copy the parts of the message here.
mTempMmsUri = persister.persist(sendReq, Mms.Draft.CONTENT_URI, true,
MessagingPreferenceActivity
.getIsGroupMmsEnabled(ComposeMessageActivity.this), null);
mTempThreadId = MessagingNotification.getThreadId(
ComposeMessageActivity.this, mTempMmsUri);
} catch (MmsException e) {
Log.e(TAG, "Failed to copy message: " + msgItem.mMessageUri);
Toast.makeText(ComposeMessageActivity.this,
R.string.cannot_save_message, Toast.LENGTH_SHORT).show();
return;
}
}
}
}, new Runnable() {
@Override
public void run() {
// Once the above background thread is complete, this runnable is run
// on the UI thread.
Intent intent = createIntent(ComposeMessageActivity.this, 0);
intent.putExtra("exit_on_sent", true);
intent.putExtra("forwarded_message", true);
if (mTempThreadId > 0) {
intent.putExtra(THREAD_ID, mTempThreadId);
}
if (msgItem.mType.equals("sms")) {
intent.putExtra("sms_body", msgItem.mBody);
} else {
intent.putExtra("msg_uri", mTempMmsUri);
String subject = getString(R.string.forward_prefix);
if (msgItem.mSubject != null) {
subject += msgItem.mSubject;
}
intent.putExtra("subject", subject);
}
// ForwardMessageActivity is simply an alias in the manifest for
// ComposeMessageActivity. We have to make an alias because ComposeMessageActivity
// launch flags specify singleTop. When we forward a message, we want to start a
// separate ComposeMessageActivity. The only way to do that is to override the
// singleTop flag, which is impossible to do in code. By creating an alias to the
// activity, without the singleTop flag, we can launch a separate
// ComposeMessageActivity to edit the forward message.
intent.setClassName(ComposeMessageActivity.this,
"com.android.mms.ui.ForwardMessageActivity");
startActivity(intent);
}
}, R.string.building_slideshow_title);
}
/**
* Context menu handlers for the message list view.
*/
private final class MsgListMenuClickListener implements MenuItem.OnMenuItemClickListener {
private MessageItem mMsgItem;
public MsgListMenuClickListener(MessageItem msgItem) {
mMsgItem = msgItem;
}
@Override
public boolean onMenuItemClick(MenuItem item) {
if (mMsgItem == null) {
return false;
}
switch (item.getItemId()) {
case MENU_EDIT_MESSAGE:
editMessageItem(mMsgItem);
drawBottomPanel();
return true;
case MENU_COPY_MESSAGE_TEXT:
copyToClipboard(mMsgItem.mBody);
return true;
case MENU_FORWARD_MESSAGE:
forwardMessage(mMsgItem);
return true;
case MENU_VIEW_SLIDESHOW:
MessageUtils.viewMmsMessageAttachment(ComposeMessageActivity.this,
ContentUris.withAppendedId(Mms.CONTENT_URI, mMsgItem.mMsgId), null,
getAsyncDialog());
return true;
case MENU_VIEW_MESSAGE_DETAILS:
return showMessageDetails(mMsgItem);
case MENU_DELETE_MESSAGE: {
DeleteMessageListener l = new DeleteMessageListener(mMsgItem);
confirmDeleteDialog(l, mMsgItem.mLocked);
return true;
}
case MENU_DELIVERY_REPORT:
showDeliveryReport(mMsgItem.mMsgId, mMsgItem.mType);
return true;
case MENU_COPY_TO_SDCARD: {
int resId = copyMedia(mMsgItem.mMsgId) ? R.string.copy_to_sdcard_success :
R.string.copy_to_sdcard_fail;
Toast.makeText(ComposeMessageActivity.this, resId, Toast.LENGTH_SHORT).show();
return true;
}
case MENU_SAVE_RINGTONE: {
int resId = getDrmMimeSavedStringRsrc(mMsgItem.mMsgId,
saveRingtone(mMsgItem.mMsgId));
Toast.makeText(ComposeMessageActivity.this, resId, Toast.LENGTH_SHORT).show();
return true;
}
case MENU_LOCK_MESSAGE: {
lockMessage(mMsgItem, true);
return true;
}
case MENU_UNLOCK_MESSAGE: {
lockMessage(mMsgItem, false);
return true;
}
// Add SMS to calendar reminder
case MENU_ADD_TO_CALENDAR: {
addEventToCalendar(mMsgItem.mSubject, mMsgItem.mBody);
return true;
}
default:
return false;
}
}
}
private void lockMessage(MessageItem msgItem, boolean locked) {
Uri uri;
if ("sms".equals(msgItem.mType)) {
uri = Sms.CONTENT_URI;
} else {
uri = Mms.CONTENT_URI;
}
final Uri lockUri = ContentUris.withAppendedId(uri, msgItem.mMsgId);
final ContentValues values = new ContentValues(1);
values.put("locked", locked ? 1 : 0);
new Thread(new Runnable() {
@Override
public void run() {
getContentResolver().update(lockUri,
values, null, null);
}
}, "ComposeMessageActivity.lockMessage").start();
}
/**
* Looks to see if there are any valid parts of the attachment that can be copied to a SD card.
* @param msgId
*/
private boolean haveSomethingToCopyToSDCard(long msgId) {
PduBody body = null;
try {
body = SlideshowModel.getPduBody(this,
ContentUris.withAppendedId(Mms.CONTENT_URI, msgId));
} catch (MmsException e) {
Log.e(TAG, "haveSomethingToCopyToSDCard can't load pdu body: " + msgId);
}
if (body == null) {
return false;
}
boolean result = false;
int partNum = body.getPartsNum();
for(int i = 0; i < partNum; i++) {
PduPart part = body.getPart(i);
String type = new String(part.getContentType());
if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
log("[CMA] haveSomethingToCopyToSDCard: part[" + i + "] contentType=" + type);
}
if (ContentType.isImageType(type) || ContentType.isVideoType(type) ||
ContentType.isAudioType(type) || DrmUtils.isDrmType(type)) {
result = true;
break;
}
}
return result;
}
/**
* Copies media from an Mms to the DrmProvider
* @param msgId
*/
private boolean saveRingtone(long msgId) {
boolean result = true;
PduBody body = null;
try {
body = SlideshowModel.getPduBody(this,
ContentUris.withAppendedId(Mms.CONTENT_URI, msgId));
} catch (MmsException e) {
Log.e(TAG, "copyToDrmProvider can't load pdu body: " + msgId);
}
if (body == null) {
return false;
}
int partNum = body.getPartsNum();
for(int i = 0; i < partNum; i++) {
PduPart part = body.getPart(i);
String type = new String(part.getContentType());
if (DrmUtils.isDrmType(type)) {
// All parts (but there's probably only a single one) have to be successful
// for a valid result.
result &= copyPart(part, Long.toHexString(msgId));
}
}
return result;
}
/**
* Returns true if any part is drm'd audio with ringtone rights.
* @param msgId
* @return true if one of the parts is drm'd audio with rights to save as a ringtone.
*/
private boolean isDrmRingtoneWithRights(long msgId) {
PduBody body = null;
try {
body = SlideshowModel.getPduBody(this,
ContentUris.withAppendedId(Mms.CONTENT_URI, msgId));
} catch (MmsException e) {
Log.e(TAG, "isDrmRingtoneWithRights can't load pdu body: " + msgId);
}
if (body == null) {
return false;
}
int partNum = body.getPartsNum();
for (int i = 0; i < partNum; i++) {
PduPart part = body.getPart(i);
String type = new String(part.getContentType());
if (DrmUtils.isDrmType(type)) {
String mimeType = MmsApp.getApplication().getDrmManagerClient()
.getOriginalMimeType(part.getDataUri());
if (ContentType.isAudioType(mimeType) && DrmUtils.haveRightsForAction(part.getDataUri(),
DrmStore.Action.RINGTONE)) {
return true;
}
}
}
return false;
}
/**
* Returns true if all drm'd parts are forwardable.
* @param msgId
* @return true if all drm'd parts are forwardable.
*/
private boolean isForwardable(long msgId) {
PduBody body = null;
try {
body = SlideshowModel.getPduBody(this,
ContentUris.withAppendedId(Mms.CONTENT_URI, msgId));
} catch (MmsException e) {
Log.e(TAG, "getDrmMimeType can't load pdu body: " + msgId);
}
if (body == null) {
return false;
}
int partNum = body.getPartsNum();
for (int i = 0; i < partNum; i++) {
PduPart part = body.getPart(i);
String type = new String(part.getContentType());
if (DrmUtils.isDrmType(type) && !DrmUtils.haveRightsForAction(part.getDataUri(),
DrmStore.Action.TRANSFER)) {
return false;
}
}
return true;
}
private int getDrmMimeMenuStringRsrc(long msgId) {
if (isDrmRingtoneWithRights(msgId)) {
return R.string.save_ringtone;
}
return 0;
}
private int getDrmMimeSavedStringRsrc(long msgId, boolean success) {
if (isDrmRingtoneWithRights(msgId)) {
return success ? R.string.saved_ringtone : R.string.saved_ringtone_fail;
}
return 0;
}
/**
* Copies media from an Mms to the "download" directory on the SD card. If any of the parts
* are audio types, drm'd or not, they're copied to the "Ringtones" directory.
* @param msgId
*/
private boolean copyMedia(long msgId) {
boolean result = true;
PduBody body = null;
try {
body = SlideshowModel.getPduBody(this,
ContentUris.withAppendedId(Mms.CONTENT_URI, msgId));
} catch (MmsException e) {
Log.e(TAG, "copyMedia can't load pdu body: " + msgId);
}
if (body == null) {
return false;
}
int partNum = body.getPartsNum();
for(int i = 0; i < partNum; i++) {
PduPart part = body.getPart(i);
// all parts have to be successful for a valid result.
result &= copyPart(part, Long.toHexString(msgId));
}
return result;
}
private boolean copyPart(PduPart part, String fallback) {
Uri uri = part.getDataUri();
String type = new String(part.getContentType());
boolean isDrm = DrmUtils.isDrmType(type);
if (isDrm) {
type = MmsApp.getApplication().getDrmManagerClient()
.getOriginalMimeType(part.getDataUri());
}
if (!ContentType.isImageType(type) && !ContentType.isVideoType(type) &&
!ContentType.isAudioType(type)) {
return true; // we only save pictures, videos, and sounds. Skip the text parts,
// the app (smil) parts, and other type that we can't handle.
// Return true to pretend that we successfully saved the part so
// the whole save process will be counted a success.
}
InputStream input = null;
FileOutputStream fout = null;
try {
input = mContentResolver.openInputStream(uri);
if (input instanceof FileInputStream) {
FileInputStream fin = (FileInputStream) input;
byte[] location = part.getName();
if (location == null) {
location = part.getFilename();
}
if (location == null) {
location = part.getContentLocation();
}
String fileName;
if (location == null) {
// Use fallback name.
fileName = fallback;
} else {
// For locally captured videos, fileName can end up being something like this:
// /mnt/sdcard/Android/data/com.android.mms/cache/.temp1.3gp
fileName = new String(location);
}
File originalFile = new File(fileName);
fileName = originalFile.getName(); // Strip the full path of where the "part" is
// stored down to just the leaf filename.
// Depending on the location, there may be an
// extension already on the name or not. If we've got audio, put the attachment
// in the Ringtones directory.
String dir = Environment.getExternalStorageDirectory() + "/"
+ (ContentType.isAudioType(type) ? Environment.DIRECTORY_RINGTONES :
Environment.DIRECTORY_DOWNLOADS) + "/";
String extension;
int index;
if ((index = fileName.lastIndexOf('.')) == -1) {
extension = MimeTypeMap.getSingleton().getExtensionFromMimeType(type);
} else {
extension = fileName.substring(index + 1, fileName.length());
fileName = fileName.substring(0, index);
}
if (isDrm) {
extension += DrmUtils.getConvertExtension(type);
}
File file = getUniqueDestination(dir + fileName, extension);
// make sure the path is valid and directories created for this file.
File parentFile = file.getParentFile();
if (!parentFile.exists() && !parentFile.mkdirs()) {
Log.e(TAG, "[MMS] copyPart: mkdirs for " + parentFile.getPath() + " failed!");
return false;
}
fout = new FileOutputStream(file);
byte[] buffer = new byte[8000];
int size = 0;
while ((size=fin.read(buffer)) != -1) {
fout.write(buffer, 0, size);
}
// Notify other applications listening to scanner events
// that a media file has been added to the sd card
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
Uri.fromFile(file)));
}
} catch (IOException e) {
// Ignore
Log.e(TAG, "IOException caught while opening or reading stream", e);
return false;
} finally {
if (null != input) {
try {
input.close();
} catch (IOException e) {
// Ignore
Log.e(TAG, "IOException caught while closing stream", e);
return false;
}
}
if (null != fout) {
try {
fout.close();
} catch (IOException e) {
// Ignore
Log.e(TAG, "IOException caught while closing stream", e);
return false;
}
}
}
return true;
}
private File getUniqueDestination(String base, String extension) {
File file = new File(base + "." + extension);
for (int i = 2; file.exists(); i++) {
file = new File(base + "_" + i + "." + extension);
}
return file;
}
private void showDeliveryReport(long messageId, String type) {
Intent intent = new Intent(this, DeliveryReportActivity.class);
intent.putExtra("message_id", messageId);
intent.putExtra("message_type", type);
startActivity(intent);
}
private final IntentFilter mHttpProgressFilter = new IntentFilter(PROGRESS_STATUS_ACTION);
private final BroadcastReceiver mHttpProgressReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (PROGRESS_STATUS_ACTION.equals(intent.getAction())) {
long token = intent.getLongExtra("token",
SendingProgressTokenManager.NO_TOKEN);
if (token != mConversation.getThreadId()) {
return;
}
int progress = intent.getIntExtra("progress", 0);
switch (progress) {
case PROGRESS_START:
setProgressBarVisibility(true);
break;
case PROGRESS_ABORT:
case PROGRESS_COMPLETE:
setProgressBarVisibility(false);
break;
default:
setProgress(100 * progress);
}
}
}
};
private static ContactList sEmptyContactList;
private ContactList getRecipients() {
// If the recipients editor is visible, the conversation has
// not really officially 'started' yet. Recipients will be set
// on the conversation once it has been saved or sent. In the
// meantime, let anyone who needs the recipient list think it
// is empty rather than giving them a stale one.
if (isRecipientsEditorVisible()) {
if (sEmptyContactList == null) {
sEmptyContactList = new ContactList();
}
return sEmptyContactList;
}
return mConversation.getRecipients();
}
private void updateTitle(ContactList list) {
String title = null;
String subTitle = null;
int cnt = list.size();
switch (cnt) {
case 0: {
String recipient = null;
if (mRecipientsEditor != null) {
recipient = mRecipientsEditor.getText().toString();
}
title = TextUtils.isEmpty(recipient) ? getString(R.string.new_message) : recipient;
break;
}
case 1: {
title = list.get(0).getName(); // get name returns the number if there's no
// name available.
String number = list.get(0).getNumber();
if (!title.equals(number)) {
subTitle = PhoneNumberUtils.formatNumber(number, number,
MmsApp.getApplication().getCurrentCountryIso());
}
break;
}
default: {
// Handle multiple recipients
title = list.formatNames(", ");
subTitle = getResources().getQuantityString(R.plurals.recipient_count, cnt, cnt);
break;
}
}
mDebugRecipients = list.serialize();
ActionBar actionBar = getActionBar();
actionBar.setTitle(title);
actionBar.setSubtitle(subTitle);
}
// Get the recipients editor ready to be displayed onscreen.
private void initRecipientsEditor() {
if (isRecipientsEditorVisible()) {
return;
}
// Must grab the recipients before the view is made visible because getRecipients()
// returns empty recipients when the editor is visible.
ContactList recipients = getRecipients();
ViewStub stub = (ViewStub)findViewById(R.id.recipients_editor_stub);
if (stub != null) {
View stubView = stub.inflate();
mRecipientsEditor = (RecipientsEditor) stubView.findViewById(R.id.recipients_editor);
mRecipientsPicker = (ImageButton) stubView.findViewById(R.id.recipients_picker);
} else {
mRecipientsEditor = (RecipientsEditor)findViewById(R.id.recipients_editor);
mRecipientsEditor.setVisibility(View.VISIBLE);
mRecipientsPicker = (ImageButton)findViewById(R.id.recipients_picker);
}
mRecipientsPicker.setOnClickListener(this);
mRecipientsEditor.setAdapter(new ChipsRecipientAdapter(this));
mRecipientsEditor.populate(recipients);
mRecipientsEditor.setOnCreateContextMenuListener(mRecipientsMenuCreateListener);
mRecipientsEditor.addTextChangedListener(mRecipientsWatcher);
// TODO : Remove the max length limitation due to the multiple phone picker is added and the
// user is able to select a large number of recipients from the Contacts. The coming
// potential issue is that it is hard for user to edit a recipient from hundred of
// recipients in the editor box. We may redesign the editor box UI for this use case.
// mRecipientsEditor.setFilters(new InputFilter[] {
// new InputFilter.LengthFilter(RECIPIENTS_MAX_LENGTH) });
mRecipientsEditor.setOnSelectChipRunnable(new Runnable() {
@Override
public void run() {
// After the user selects an item in the pop-up contacts list, move the
// focus to the text editor if there is only one recipient. This helps
// the common case of selecting one recipient and then typing a message,
// but avoids annoying a user who is trying to add five recipients and
// keeps having focus stolen away.
if (mRecipientsEditor.getRecipientCount() == 1) {
// if we're in extract mode then don't request focus
final InputMethodManager inputManager = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
if (inputManager == null || !inputManager.isFullscreenMode()) {
mTextEditor.requestFocus();
}
}
}
});
mRecipientsEditor.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
RecipientsEditor editor = (RecipientsEditor) v;
ContactList contacts = editor.constructContactsFromInput(false);
updateTitle(contacts);
}
}
});
PhoneNumberFormatter.setPhoneNumberFormattingTextWatcher(this, mRecipientsEditor);
mTopPanel.setVisibility(View.VISIBLE);
}
//==========================================================
// Activity methods
//==========================================================
public static boolean cancelFailedToDeliverNotification(Intent intent, Context context) {
if (MessagingNotification.isFailedToDeliver(intent)) {
// Cancel any failed message notifications
MessagingNotification.cancelNotification(context,
MessagingNotification.MESSAGE_FAILED_NOTIFICATION_ID);
return true;
}
return false;
}
public static boolean cancelFailedDownloadNotification(Intent intent, Context context) {
if (MessagingNotification.isFailedToDownload(intent)) {
// Cancel any failed download notifications
MessagingNotification.cancelNotification(context,
MessagingNotification.DOWNLOAD_FAILED_NOTIFICATION_ID);
return true;
}
return false;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
resetConfiguration(getResources().getConfiguration());
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences((Context) ComposeMessageActivity.this);
mGestureSensitivity = prefs
.getInt(MessagingPreferenceActivity.GESTURE_SENSITIVITY_VALUE, 3);
boolean showGesture = prefs.getBoolean(MessagingPreferenceActivity.SHOW_GESTURE, false);
int unicodeStripping = prefs.getInt(MessagingPreferenceActivity.UNICODE_STRIPPING_VALUE,
MessagingPreferenceActivity.UNICODE_STRIPPING_LEAVE_INTACT);
mInputMethod = Integer.parseInt(prefs.getString(MessagingPreferenceActivity.INPUT_TYPE,
Integer.toString(InputType.TYPE_TEXT_VARIATION_SHORT_MESSAGE)));
mLibrary = TemplateGesturesLibrary.getStore(this);
int layout = R.layout.compose_message_activity;
GestureOverlayView gestureOverlayView = new GestureOverlayView(this);
View inflate = getLayoutInflater().inflate(layout, null);
gestureOverlayView.addView(inflate);
gestureOverlayView.setEventsInterceptionEnabled(true);
gestureOverlayView.setGestureVisible(showGesture);
gestureOverlayView.addOnGesturePerformedListener(this);
setContentView(gestureOverlayView);
setProgressBarVisibility(false);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE |
WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
// Initialize members for UI elements.
initResourceRefs();
LengthFilter lengthFilter = new LengthFilter(MmsConfig.getMaxTextLimit());
mTextEditor.setFilters(new InputFilter[] { lengthFilter });
if (unicodeStripping != MessagingPreferenceActivity.UNICODE_STRIPPING_LEAVE_INTACT) {
boolean stripNonDecodableOnly =
unicodeStripping == MessagingPreferenceActivity.UNICODE_STRIPPING_NON_DECODABLE;
mUnicodeFilter = new UnicodeFilter(stripNonDecodableOnly);
}
mContentResolver = getContentResolver();
mBackgroundQueryHandler = new BackgroundQueryHandler(mContentResolver);
mEnableEmojis = prefs.getBoolean(MessagingPreferenceActivity.ENABLE_EMOJIS, false);
mEnableQuickEmojis = prefs.getBoolean(MessagingPreferenceActivity.ENABLE_QUICK_EMOJIS, false);
if (mEnableQuickEmojis && mEnableEmojis) {
mQuickEmoji.setVisibility(View.VISIBLE);
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams)mTextEditor.getLayoutParams();
params.setMargins(0, 0, 0, 0);
mTextEditor.setLayoutParams(params);
}
initialize(savedInstanceState, 0);
if (TRACE) {
android.os.Debug.startMethodTracing("compose");
}
}
@Override
public void onSensorChanged(SensorEvent event) {
switch (event.sensor.getType()) {
case Sensor.TYPE_ORIENTATION:
SensorOrientationY = (int) event.values[SensorManager.DATA_Y];
break;
case Sensor.TYPE_PROXIMITY:
int currentProx = (int) event.values[0];
if (initProx) {
SensorProximity = currentProx;
initProx = false;
} else {
if( SensorProximity > 0 && currentProx <= 3){
proxChanged = true;
}
}
SensorProximity = currentProx;
break;
}
if (rightOrientation(SensorOrientationY) && SensorProximity <= 3 && proxChanged ) {
if (getRecipients().isEmpty() == false) {
// unregister Listener to don't let the onSesorChanged run the
// whole time
mSensorManager.unregisterListener(this, mSensorManager
.getDefaultSensor(Sensor.TYPE_ORIENTATION));
mSensorManager.unregisterListener(this,
mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY));
// get number and attach it to an Intent.ACTION_CALL, then start
// the Intent
String number = getRecipients().get(0).getNumber();
Intent dialIntent = new Intent(Intent.ACTION_CALL);
dialIntent.setData(Uri.fromParts("tel", number, null));
dialIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(dialIntent);
}
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
public boolean rightOrientation(int orientation) {
if (orientation < -50 && orientation > -130) {
return true;
} else {
return false;
}
}
private void showSubjectEditor(boolean show) {
if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
log("" + show);
}
if (mSubjectTextEditor == null) {
// Don't bother to initialize the subject editor if
// we're just going to hide it.
if (show == false) {
return;
}
mSubjectTextEditor = (EditText)findViewById(R.id.subject);
mSubjectTextEditor.setFilters(new InputFilter[] {
new LengthFilter(MmsConfig.getMaxSubjectLength())});
}
mSubjectTextEditor.setOnKeyListener(show ? mSubjectKeyListener : null);
if (show) {
mSubjectTextEditor.addTextChangedListener(mSubjectEditorWatcher);
} else {
mSubjectTextEditor.removeTextChangedListener(mSubjectEditorWatcher);
}
mSubjectTextEditor.setText(mWorkingMessage.getSubject());
mSubjectTextEditor.setVisibility(show ? View.VISIBLE : View.GONE);
hideOrShowTopPanel();
}
private void hideOrShowTopPanel() {
boolean anySubViewsVisible = (isSubjectEditorVisible() || isRecipientsEditorVisible());
mTopPanel.setVisibility(anySubViewsVisible ? View.VISIBLE : View.GONE);
}
public void initialize(Bundle savedInstanceState, long originalThreadId) {
// Create a new empty working message.
mWorkingMessage = WorkingMessage.createEmpty(this);
// Read parameters or previously saved state of this activity. This will load a new
// mConversation
initActivityState(savedInstanceState);
if (LogTag.SEVERE_WARNING && originalThreadId != 0 &&
originalThreadId == mConversation.getThreadId()) {
LogTag.warnPossibleRecipientMismatch("ComposeMessageActivity.initialize: " +
" threadId didn't change from: " + originalThreadId, this);
}
log("savedInstanceState = " + savedInstanceState +
" intent = " + getIntent() +
" mConversation = " + mConversation);
if (cancelFailedToDeliverNotification(getIntent(), this)) {
// Show a pop-up dialog to inform user the message was
// failed to deliver.
undeliveredMessageDialog(getMessageDate(null));
}
cancelFailedDownloadNotification(getIntent(), this);
// Set up the message history ListAdapter
initMessageList();
mShouldLoadDraft = true;
// Load the draft for this thread, if we aren't already handling
// existing data, such as a shared picture or forwarded message.
boolean isForwardedMessage = false;
// We don't attempt to handle the Intent.ACTION_SEND when saveInstanceState is non-null.
// saveInstanceState is non-null when this activity is killed. In that case, we already
// handled the attachment or the send, so we don't try and parse the intent again.
if (savedInstanceState == null && (handleSendIntent() || handleForwardedMessage())) {
mShouldLoadDraft = false;
}
// Let the working message know what conversation it belongs to
mWorkingMessage.setConversation(mConversation);
// Show the recipients editor if we don't have a valid thread. Hide it otherwise.
if (mConversation.getThreadId() <= 0) {
// Hide the recipients editor so the call to initRecipientsEditor won't get
// short-circuited.
hideRecipientEditor();
initRecipientsEditor();
} else {
hideRecipientEditor();
}
updateSendButtonState();
drawTopPanel(false);
if (!mShouldLoadDraft) {
// We're not loading a draft, so we can draw the bottom panel immediately.
drawBottomPanel();
}
onKeyboardStateChanged(mIsKeyboardOpen);
if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
log("update title, mConversation=" + mConversation.toString());
}
updateTitle(mConversation.getRecipients());
if (isForwardedMessage && isRecipientsEditorVisible()) {
// The user is forwarding the message to someone. Put the focus on the
// recipient editor rather than in the message editor.
mRecipientsEditor.requestFocus();
}
mMsgListAdapter.setIsGroupConversation(mConversation.getRecipients().size() > 1);
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
Conversation conversation = null;
mSentMessage = false;
// If we have been passed a thread_id, use that to find our
// conversation.
// Note that originalThreadId might be zero but if this is a draft and we save the
// draft, ensureThreadId gets called async from WorkingMessage.asyncUpdateDraftSmsMessage
// the thread will get a threadId behind the UI thread's back.
long originalThreadId = mConversation.getThreadId();
long threadId = intent.getLongExtra(THREAD_ID, 0);
Uri intentUri = intent.getData();
boolean sameThread = false;
if (threadId > 0) {
conversation = Conversation.get(this, threadId, false);
} else {
if (mConversation.getThreadId() == 0) {
// We've got a draft. Make sure the working recipients are synched
// to the conversation so when we compare conversations later in this function,
// the compare will work.
mWorkingMessage.syncWorkingRecipients();
}
// Get the "real" conversation based on the intentUri. The intentUri might specify
// the conversation by a phone number or by a thread id. We'll typically get a threadId
// based uri when the user pulls down a notification while in ComposeMessageActivity and
// we end up here in onNewIntent. mConversation can have a threadId of zero when we're
// working on a draft. When a new message comes in for that same recipient, a
// conversation will get created behind CMA's back when the message is inserted into
// the database and the corresponding entry made in the threads table. The code should
// use the real conversation as soon as it can rather than finding out the threadId
// when sending with "ensureThreadId".
conversation = Conversation.get(this, intentUri, false);
}
if (LogTag.VERBOSE || Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
log("onNewIntent: data=" + intentUri + ", thread_id extra is " + threadId +
", new conversation=" + conversation + ", mConversation=" + mConversation);
}
// this is probably paranoid to compare both thread_ids and recipient lists,
// but we want to make double sure because this is a last minute fix for Froyo
// and the previous code checked thread ids only.
// (we cannot just compare thread ids because there is a case where mConversation
// has a stale/obsolete thread id (=1) that could collide against the new thread_id(=1),
// even though the recipient lists are different)
sameThread = ((conversation.getThreadId() == mConversation.getThreadId() ||
mConversation.getThreadId() == 0) &&
conversation.equals(mConversation));
if (sameThread) {
log("onNewIntent: same conversation");
if (mConversation.getThreadId() == 0) {
mConversation = conversation;
mWorkingMessage.setConversation(mConversation);
updateThreadIdIfRunning();
invalidateOptionsMenu();
}
} else {
if (LogTag.VERBOSE || Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
log("onNewIntent: different conversation");
}
saveDraft(false); // if we've got a draft, save it first
initialize(null, originalThreadId);
}
loadMessagesAndDraft(0);
}
private void sanityCheckConversation() {
if (mWorkingMessage.getConversation() != mConversation) {
LogTag.warnPossibleRecipientMismatch(
"ComposeMessageActivity: mWorkingMessage.mConversation=" +
mWorkingMessage.getConversation() + ", mConversation=" +
mConversation + ", MISMATCH!", this);
}
}
@Override
protected void onRestart() {
super.onRestart();
// hide the compose panel to reduce jank when re-entering this activity.
// if we don't hide it here, the compose panel will flash before the keyboard shows
// (when keyboard is suppose to be shown).
hideBottomPanel();
if (mWorkingMessage.isDiscarded()) {
// If the message isn't worth saving, don't resurrect it. Doing so can lead to
// a situation where a new incoming message gets the old thread id of the discarded
// draft. This activity can end up displaying the recipients of the old message with
// the contents of the new message. Recognize that dangerous situation and bail out
// to the ConversationList where the user can enter this in a clean manner.
if (mWorkingMessage.isWorthSaving()) {
if (LogTag.VERBOSE) {
log("onRestart: mWorkingMessage.unDiscard()");
}
mWorkingMessage.unDiscard(); // it was discarded in onStop().
sanityCheckConversation();
} else if (isRecipientsEditorVisible() && recipientCount() > 0) {
if (LogTag.VERBOSE) {
log("onRestart: goToConversationList");
}
goToConversationList();
}
}
}
@Override
protected void onStart() {
super.onStart();
initFocus();
// Register a BroadcastReceiver to listen on HTTP I/O process.
registerReceiver(mHttpProgressReceiver, mHttpProgressFilter);
registerReceiver(mDelaySentProgressReceiver, mDelaySentProgressFilter);
countDownFormat = getString(R.string.remaining_delay_time);
// figure out whether we need to show the keyboard or not.
// if there is draft to be loaded for 'mConversation', we'll show the keyboard;
// otherwise we hide the keyboard. In any event, delay loading
// message history and draft (controlled by DEFER_LOADING_MESSAGES_AND_DRAFT).
int mode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE;
if (DraftCache.getInstance().hasDraft(mConversation.getThreadId())) {
mode |= WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE;
} else if (mConversation.getThreadId() <= 0) {
// For composing a new message, bring up the softkeyboard so the user can
// immediately enter recipients. This call won't do anything on devices with
// a hard keyboard.
mode |= WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE;
} else {
mode |= WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN;
}
getWindow().setSoftInputMode(mode);
// reset mMessagesAndDraftLoaded
mMessagesAndDraftLoaded = false;
if (!DEFER_LOADING_MESSAGES_AND_DRAFT) {
loadMessagesAndDraft(1);
} else {
// HACK: force load messages+draft after max delay, if it's not already loaded.
// this is to work around when coming out of sleep mode. WindowManager behaves
// strangely and hides the keyboard when it should be shown, or sometimes initially
// shows it when we want to hide it. In that case, we never get the onSizeChanged()
// callback w/ keyboard shown, so we wouldn't know to load the messages+draft.
mHandler.postDelayed(new Runnable() {
public void run() {
loadMessagesAndDraft(2);
}
}, LOADING_MESSAGES_AND_DRAFT_MAX_DELAY_MS);
}
// Update the fasttrack info in case any of the recipients' contact info changed
// while we were paused. This can happen, for example, if a user changes or adds
// an avatar associated with a contact.
mWorkingMessage.syncWorkingRecipients();
if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
log("update title, mConversation=" + mConversation.toString());
}
updateTitle(mConversation.getRecipients());
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
}
public void loadMessageContent() {
// Don't let any markAsRead DB updates occur before we've loaded the messages for
// the thread. Unblocking occurs when we're done querying for the conversation
// items.
mConversation.blockMarkAsRead(true);
mConversation.markAsRead(true); // dismiss any notifications for this convo
startMsgListQuery();
updateSendFailedNotification();
}
/**
* Load message history and draft. This method should be called from main thread.
* @param debugFlag shows where this is being called from
*/
private void loadMessagesAndDraft(int debugFlag) {
if (!mMessagesAndDraftLoaded) {
if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
Log.v(TAG, "### CMA.loadMessagesAndDraft: flag=" + debugFlag);
}
loadMessageContent();
boolean drawBottomPanel = true;
if (mShouldLoadDraft) {
if (loadDraft()) {
drawBottomPanel = false;
}
}
if (drawBottomPanel) {
drawBottomPanel();
}
mMessagesAndDraftLoaded = true;
}
}
private void updateSendFailedNotification() {
final long threadId = mConversation.getThreadId();
if (threadId <= 0)
return;
// updateSendFailedNotificationForThread makes a database call, so do the work off
// of the ui thread.
new Thread(new Runnable() {
@Override
public void run() {
MessagingNotification.updateSendFailedNotificationForThread(
ComposeMessageActivity.this, threadId);
}
}, "ComposeMessageActivity.updateSendFailedNotification").start();
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString(RECIPIENTS, getRecipients().serialize());
mWorkingMessage.writeStateToBundle(outState);
if (mExitOnSent) {
outState.putBoolean("exit_on_sent", mExitOnSent);
}
}
@Override
protected void onResume() {
super.onResume();
// OLD: get notified of presence updates to update the titlebar.
// NEW: we are using ContactHeaderWidget which displays presence, but updating presence
// there is out of our control.
//Contact.startPresenceObserver();
addRecipientsListeners();
if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
log("update title, mConversation=" + mConversation.toString());
}
// There seems to be a bug in the framework such that setting the title
// here gets overwritten to the original title. Do this delayed as a
// workaround.
mMessageListItemHandler.postDelayed(new Runnable() {
@Override
public void run() {
ContactList recipients = isRecipientsEditorVisible() ?
mRecipientsEditor.constructContactsFromInput(false) : getRecipients();
updateTitle(recipients);
}
}, 100);
try {
TelephonyManager tm = (TelephonyManager)getSystemService(Service.TELEPHONY_SERVICE);
if(MessagingPreferenceActivity.getDirectCallEnabled(ComposeMessageActivity.this) && tm.getCallState() == TelephonyManager.CALL_STATE_IDLE) {
SensorOrientationY = 0;
SensorProximity = 0;
proxChanged = false;
initProx = true;
mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
mSensorManager.registerListener(this,
mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION),
SensorManager.SENSOR_DELAY_UI);
mSensorManager.registerListener(this,
mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY),
SensorManager.SENSOR_DELAY_UI);
}
} catch (Exception e) {
Log.w("ERROR", e.toString());
}
// Load the selected input type
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences((Context) ComposeMessageActivity.this);
mInputMethod = Integer.parseInt(prefs.getString(MessagingPreferenceActivity.INPUT_TYPE,
Integer.toString(InputType.TYPE_TEXT_VARIATION_SHORT_MESSAGE)));
mTextEditor.setInputType(InputType.TYPE_CLASS_TEXT | mInputMethod
| InputType.TYPE_TEXT_FLAG_AUTO_CORRECT
| InputType.TYPE_TEXT_FLAG_CAP_SENTENCES
| InputType.TYPE_TEXT_FLAG_MULTI_LINE);
mIsRunning = true;
updateThreadIdIfRunning();
mConversation.markAsRead(true);
}
@Override
protected void onPause() {
super.onPause();
if (DEBUG) {
Log.v(TAG, "onPause: setCurrentlyDisplayedThreadId: " +
MessagingNotification.THREAD_NONE);
}
MessagingNotification.setCurrentlyDisplayedThreadId(MessagingNotification.THREAD_NONE);
// OLD: stop getting notified of presence updates to update the titlebar.
// NEW: we are using ContactHeaderWidget which displays presence, but updating presence
// there is out of our control.
//Contact.stopPresenceObserver();
removeRecipientsListeners();
try {
if(MessagingPreferenceActivity.getDirectCallEnabled(ComposeMessageActivity.this)) {
mSensorManager.unregisterListener(this,
mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION));
mSensorManager.unregisterListener(this,
mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY));
}
} catch (Exception e) {
Log.w("ERROR", e.toString());
}
// remove any callback to display a progress spinner
if (mAsyncDialog != null) {
mAsyncDialog.clearPendingProgressDialog();
}
// Remember whether the list is scrolled to the end when we're paused so we can rescroll
// to the end when resumed.
if (mMsgListAdapter != null &&
mMsgListView.getLastVisiblePosition() >= mMsgListAdapter.getCount() - 1) {
mSavedScrollPosition = Integer.MAX_VALUE;
} else {
mSavedScrollPosition = mMsgListView.getFirstVisiblePosition();
}
if (LogTag.VERBOSE || Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
Log.v(TAG, "onPause: mSavedScrollPosition=" + mSavedScrollPosition);
}
mConversation.markAsRead(true);
mIsRunning = false;
}
@Override
protected void onStop() {
super.onStop();
// No need to do the querying when finished this activity
mBackgroundQueryHandler.cancelOperation(MESSAGE_LIST_QUERY_TOKEN);
// Allow any blocked calls to update the thread's read status.
mConversation.blockMarkAsRead(false);
if (mMsgListAdapter != null) {
// Close the cursor in the ListAdapter if the activity stopped.
Cursor cursor = mMsgListAdapter.getCursor();
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
mMsgListAdapter.changeCursor(null);
mMsgListAdapter.cancelBackgroundLoading();
}
if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
log("save draft");
}
saveDraft(true);
// set 'mShouldLoadDraft' to true, so when coming back to ComposeMessageActivity, we would
// load the draft, unless we are coming back to the activity after attaching a photo, etc,
// in which case we should set 'mShouldLoadDraft' to false.
mShouldLoadDraft = true;
// Cleanup the BroadcastReceiver.
unregisterReceiver(mHttpProgressReceiver);
unregisterReceiver(mDelaySentProgressReceiver);
}
@Override
protected void onDestroy() {
if (TRACE) {
android.os.Debug.stopMethodTracing();
}
super.onDestroy();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (resetConfiguration(newConfig)) {
// Have to re-layout the attachment editor because we have different layouts
// depending on whether we're portrait or landscape.
drawTopPanel(isSubjectEditorVisible());
}
if (LOCAL_LOGV) {
Log.v(TAG, "CMA.onConfigurationChanged: " + newConfig +
", mIsKeyboardOpen=" + mIsKeyboardOpen);
}
onKeyboardStateChanged(mIsKeyboardOpen);
}
// returns true if landscape/portrait configuration has changed
private boolean resetConfiguration(Configuration config) {
mIsKeyboardOpen = config.keyboardHidden == KEYBOARDHIDDEN_NO;
boolean isLandscape = config.orientation == Configuration.ORIENTATION_LANDSCAPE;
if (mIsLandscape != isLandscape) {
mIsLandscape = isLandscape;
return true;
}
return false;
}
private void onKeyboardStateChanged(boolean isKeyboardOpen) {
// If the keyboard is hidden, don't show focus highlights for
// things that cannot receive input.
if (isKeyboardOpen) {
if (mRecipientsEditor != null) {
mRecipientsEditor.setFocusableInTouchMode(true);
}
if (mSubjectTextEditor != null) {
mSubjectTextEditor.setFocusableInTouchMode(true);
}
mTextEditor.setFocusableInTouchMode(true);
mTextEditor.setHint(R.string.type_to_compose_text_enter_to_send);
} else {
if (mRecipientsEditor != null) {
mRecipientsEditor.setFocusable(false);
}
if (mSubjectTextEditor != null) {
mSubjectTextEditor.setFocusable(false);
}
mTextEditor.setFocusable(false);
mTextEditor.setHint(R.string.open_keyboard_to_compose_message);
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_DEL:
if ((mMsgListAdapter != null) && mMsgListView.isFocused()) {
Cursor cursor;
try {
cursor = (Cursor) mMsgListView.getSelectedItem();
} catch (ClassCastException e) {
Log.e(TAG, "Unexpected ClassCastException.", e);
return super.onKeyDown(keyCode, event);
}
if (cursor != null) {
String type = cursor.getString(COLUMN_MSG_TYPE);
long msgId = cursor.getLong(COLUMN_ID);
MessageItem msgItem = mMsgListAdapter.getCachedMessageItem(type, msgId,
cursor);
if (msgItem != null) {
DeleteMessageListener l = new DeleteMessageListener(msgItem);
confirmDeleteDialog(l, msgItem.mLocked);
}
return true;
}
}
break;
case KeyEvent.KEYCODE_DPAD_CENTER:
case KeyEvent.KEYCODE_ENTER:
if (isPreparedForSending()) {
confirmSendMessageIfNeeded();
return true;
}
break;
case KeyEvent.KEYCODE_BACK:
exitComposeMessageActivity(new Runnable() {
@Override
public void run() {
finish();
}
});
return true;
}
return super.onKeyDown(keyCode, event);
}
private void exitComposeMessageActivity(final Runnable exit) {
// If the message is empty, just quit -- finishing the
// activity will cause an empty draft to be deleted.
if (!mWorkingMessage.isWorthSaving()) {
exit.run();
return;
}
if (isRecipientsEditorVisible() &&
!mRecipientsEditor.hasValidRecipient(mWorkingMessage.requiresMms())) {
MessageUtils.showDiscardDraftConfirmDialog(this, new DiscardDraftListener());
return;
}
mToastForDraftSave = true;
exit.run();
}
private void goToConversationList() {
finish();
startActivity(new Intent(this, ConversationList.class));
}
private void hideRecipientEditor() {
if (mRecipientsEditor != null) {
mRecipientsEditor.removeTextChangedListener(mRecipientsWatcher);
mRecipientsEditor.setVisibility(View.GONE);
hideOrShowTopPanel();
}
}
private boolean isRecipientsEditorVisible() {
return (null != mRecipientsEditor)
&& (View.VISIBLE == mRecipientsEditor.getVisibility());
}
private boolean isSubjectEditorVisible() {
return (null != mSubjectTextEditor)
&& (View.VISIBLE == mSubjectTextEditor.getVisibility());
}
@Override
public void onAttachmentChanged() {
// Have to make sure we're on the UI thread. This function can be called off of the UI
// thread when we're adding multi-attachments
runOnUiThread(new Runnable() {
@Override
public void run() {
drawBottomPanel();
updateSendButtonState();
drawTopPanel(isSubjectEditorVisible());
}
});
}
@Override
public void onProtocolChanged(final boolean convertToMms) {
// Have to make sure we're on the UI thread. This function can be called off of the UI
// thread when we're adding multi-attachments
runOnUiThread(new Runnable() {
@Override
public void run() {
showSmsOrMmsSendButton(convertToMms);
if (convertToMms) {
// In the case we went from a long sms with a counter to an mms because
// the user added an attachment or a subject, hide the counter --
// it doesn't apply to mms.
mTextCounter.setVisibility(View.GONE);
showConvertToMmsToast();
}
}
});
}
// Show or hide the Sms or Mms button as appropriate. Return the view so that the caller
// can adjust the enableness and focusability.
private View showSmsOrMmsSendButton(boolean isMms) {
View showButton;
View hideButton;
if (isMms) {
showButton = mSendButtonMms;
hideButton = mSendButtonSms;
} else {
showButton = mSendButtonSms;
hideButton = mSendButtonMms;
}
showButton.setVisibility(View.VISIBLE);
hideButton.setVisibility(View.GONE);
return showButton;
}
Runnable mResetMessageRunnable = new Runnable() {
@Override
public void run() {
resetMessage();
}
};
@Override
public void onPreMessageSent() {
runOnUiThread(mResetMessageRunnable);
}
@Override
public void onMessageSent() {
// This callback can come in on any thread; put it on the main thread to avoid
// concurrency problems
runOnUiThread(new Runnable() {
@Override
public void run() {
// If we already have messages in the list adapter, it
// will be auto-requerying; don't thrash another query in.
// TODO: relying on auto-requerying seems unreliable when priming an MMS into the
// outbox. Need to investigate.
// if (mMsgListAdapter.getCount() == 0) {
if (LogTag.VERBOSE) {
log("onMessageSent");
}
startMsgListQuery();
// }
// The thread ID could have changed if this is a new message that we just inserted
// into the database (and looked up or created a thread for it)
updateThreadIdIfRunning();
}
});
}
@Override
public void onMaxPendingMessagesReached() {
saveDraft(false);
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(ComposeMessageActivity.this, R.string.too_many_unsent_mms,
Toast.LENGTH_LONG).show();
}
});
}
@Override
public void onAttachmentError(final int error) {
runOnUiThread(new Runnable() {
@Override
public void run() {
handleAddAttachmentError(error, R.string.type_picture);
onMessageSent(); // now requery the list of messages
}
});
}
// We don't want to show the "call" option unless there is only one
// recipient and it's a phone number.
private boolean isRecipientCallable() {
ContactList recipients = getRecipients();
return (recipients.size() == 1 && !recipients.containsEmail());
}
private void dialRecipient() {
if (isRecipientCallable()) {
String number = getRecipients().get(0).getNumber();
Intent dialIntent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + number));
startActivity(dialIntent);
}
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu) ;
menu.clear();
if (isRecipientCallable()) {
MenuItem item = menu.add(0, MENU_CALL_RECIPIENT, 0, R.string.menu_call)
.setIcon(R.drawable.ic_menu_call)
.setTitle(R.string.menu_call);
if (!isRecipientsEditorVisible()) {
// If we're not composing a new message, show the call icon in the actionbar
item.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
}
}
if (MmsConfig.getMmsEnabled()) {
if (!isSubjectEditorVisible()) {
menu.add(0, MENU_ADD_SUBJECT, 0, R.string.add_subject).setIcon(
R.drawable.ic_menu_edit);
}
if (!mWorkingMessage.hasAttachment()) {
menu.add(0, MENU_ADD_ATTACHMENT, 0, R.string.add_attachment)
.setIcon(R.drawable.ic_menu_attachment)
.setTitle(R.string.add_attachment)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS); // add to actionbar
}
}
menu.add(0, MENU_ADD_TEMPLATE, 0, R.string.template_insert)
.setIcon(android.R.drawable.ic_menu_add)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
if (isPreparedForSending()) {
menu.add(0, MENU_SEND, 0, R.string.send).setIcon(android.R.drawable.ic_menu_send);
}
if (!mWorkingMessage.hasSlideshow()) {
menu.add(0, MENU_INSERT_SMILEY, 0, R.string.menu_insert_smiley).setIcon(
R.drawable.ic_menu_emoticons);
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences((Context) ComposeMessageActivity.this);
if (mEnableEmojis) {
menu.add(0, MENU_INSERT_EMOJI, 0, R.string.menu_insert_emoji);
}
}
menu.add(0, MENU_INSERT_CONTACT_INFO, 0, R.string.menu_insert_contact_info)
.setIcon(android.R.drawable.ic_menu_add);
if (getRecipients().size() > 1) {
menu.add(0, MENU_GROUP_PARTICIPANTS, 0, R.string.menu_group_participants);
}
if (mMsgListAdapter.getCount() > 0) {
// Removed search as part of b/1205708
//menu.add(0, MENU_SEARCH, 0, R.string.menu_search).setIcon(
// R.drawable.ic_menu_search);
Cursor cursor = mMsgListAdapter.getCursor();
if ((null != cursor) && (cursor.getCount() > 0)) {
menu.add(0, MENU_DELETE_THREAD, 0, R.string.delete_thread).setIcon(
android.R.drawable.ic_menu_delete);
}
} else {
menu.add(0, MENU_DISCARD, 0, R.string.discard).setIcon(android.R.drawable.ic_menu_delete);
}
buildAddAddressToContactMenuItem(menu);
menu.add(0, MENU_PREFERENCES, 0, R.string.menu_preferences).setIcon(
android.R.drawable.ic_menu_preferences);
if (LogTag.DEBUG_DUMP) {
menu.add(0, MENU_DEBUG_DUMP, 0, R.string.menu_debug_dump);
}
return true;
}
private void buildAddAddressToContactMenuItem(Menu menu) {
// bug #7087793: for group of recipients, remove "Add to People" action. Rely on
// individually creating contacts for unknown phone numbers by touching the individual
// sender's avatars, one at a time
ContactList contacts = getRecipients();
if (contacts.size() != 1) {
return;
}
// if we don't have a contact for the recipient, create a menu item to add the number
// to contacts.
Contact c = contacts.get(0);
if (!c.existsInDatabase() && canAddToContacts(c)) {
Intent intent = ConversationList.createAddContactIntent(c.getNumber());
menu.add(0, MENU_ADD_ADDRESS_TO_CONTACTS, 0, R.string.menu_add_to_contacts)
.setIcon(android.R.drawable.ic_menu_add)
.setIntent(intent);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_ADD_SUBJECT:
showSubjectEditor(true);
mWorkingMessage.setSubject("", true);
updateSendButtonState();
mSubjectTextEditor.requestFocus();
break;
case MENU_ADD_ATTACHMENT:
// Launch the add-attachment list dialog
showAddAttachmentDialog(false);
break;
case MENU_DISCARD:
mWorkingMessage.discard();
finish();
break;
case MENU_SEND:
if (isPreparedForSending()) {
confirmSendMessageIfNeeded();
}
break;
case MENU_SEARCH:
onSearchRequested();
break;
case MENU_DELETE_THREAD:
confirmDeleteThread(mConversation.getThreadId());
break;
case android.R.id.home:
case MENU_CONVERSATION_LIST:
exitComposeMessageActivity(new Runnable() {
@Override
public void run() {
goToConversationList();
}
});
break;
case MENU_CALL_RECIPIENT:
dialRecipient();
break;
case MENU_INSERT_SMILEY:
showSmileyDialog();
break;
case MENU_INSERT_EMOJI:
showEmojiDialog();
break;
case MENU_INSERT_CONTACT_INFO:
Intent intentInsertContactInfo = new Intent(Intent.ACTION_PICK, Contacts.CONTENT_URI);
startActivityForResult(intentInsertContactInfo, REQUEST_CODE_INSERT_CONTACT_INFO);
break;
case MENU_GROUP_PARTICIPANTS: {
Intent intent = new Intent(this, RecipientListActivity.class);
intent.putExtra(THREAD_ID, mConversation.getThreadId());
startActivity(intent);
break;
}
case MENU_VIEW_CONTACT: {
// View the contact for the first (and only) recipient.
ContactList list = getRecipients();
if (list.size() == 1 && list.get(0).existsInDatabase()) {
Uri contactUri = list.get(0).getUri();
Intent intent = new Intent(Intent.ACTION_VIEW, contactUri);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
startActivity(intent);
}
break;
}
case MENU_ADD_ADDRESS_TO_CONTACTS:
mAddContactIntent = item.getIntent();
startActivityForResult(mAddContactIntent, REQUEST_CODE_ADD_CONTACT);
break;
case MENU_PREFERENCES: {
Intent intent = new Intent(this, MessagingPreferenceActivity.class);
startActivityIfNeeded(intent, -1);
break;
}
case MENU_DEBUG_DUMP:
mWorkingMessage.dump();
Conversation.dump();
LogTag.dumpInternalTables(this);
break;
case MENU_ADD_TEMPLATE:
startLoadingTemplates();
break;
}
return true;
}
private void confirmDeleteThread(long threadId) {
Conversation.startQueryHaveLockedMessages(mBackgroundQueryHandler,
threadId, ConversationList.HAVE_LOCKED_MESSAGES_TOKEN);
}
// static class SystemProperties { // TODO, temp class to get unbundling working
// static int getInt(String s, int value) {
// return value; // just return the default value or now
// }
// }
private void addAttachment(int type, boolean replace) {
// Calculate the size of the current slide if we're doing a replace so the
// slide size can optionally be used in computing how much room is left for an attachment.
int currentSlideSize = 0;
SlideshowModel slideShow = mWorkingMessage.getSlideshow();
if (replace && slideShow != null) {
WorkingMessage.removeThumbnailsFromCache(slideShow);
SlideModel slide = slideShow.get(0);
currentSlideSize = slide.getSlideSize();
}
switch (type) {
case AttachmentTypeSelectorAdapter.ADD_IMAGE:
MessageUtils.selectImage(this, REQUEST_CODE_ATTACH_IMAGE);
break;
case AttachmentTypeSelectorAdapter.TAKE_PICTURE: {
MessageUtils.capturePicture(this, REQUEST_CODE_TAKE_PICTURE);
break;
}
case AttachmentTypeSelectorAdapter.ADD_VIDEO:
MessageUtils.selectVideo(this, REQUEST_CODE_ATTACH_VIDEO);
break;
case AttachmentTypeSelectorAdapter.RECORD_VIDEO: {
long sizeLimit = computeAttachmentSizeLimit(slideShow, currentSlideSize);
if (sizeLimit > 0) {
MessageUtils.recordVideo(this, REQUEST_CODE_TAKE_VIDEO, sizeLimit);
} else {
Toast.makeText(this,
getString(R.string.message_too_big_for_video),
Toast.LENGTH_SHORT).show();
}
}
break;
case AttachmentTypeSelectorAdapter.ADD_SOUND:
MessageUtils.selectAudio(this, REQUEST_CODE_ATTACH_SOUND);
break;
case AttachmentTypeSelectorAdapter.RECORD_SOUND:
long sizeLimit = computeAttachmentSizeLimit(slideShow, currentSlideSize);
MessageUtils.recordSound(this, REQUEST_CODE_RECORD_SOUND, sizeLimit);
break;
case AttachmentTypeSelectorAdapter.ADD_SLIDESHOW:
editSlideshow();
break;
default:
break;
}
}
public static long computeAttachmentSizeLimit(SlideshowModel slideShow, int currentSlideSize) {
// Computer attachment size limit. Subtract 1K for some text.
long sizeLimit = MmsConfig.getMaxMessageSize() - SlideshowModel.SLIDESHOW_SLOP;
if (slideShow != null) {
sizeLimit -= slideShow.getCurrentMessageSize();
// We're about to ask the camera to capture some video (or the sound recorder
// to record some audio) which will eventually replace the content on the current
// slide. Since the current slide already has some content (which was subtracted
// out just above) and that content is going to get replaced, we can add the size of the
// current slide into the available space used to capture a video (or audio).
sizeLimit += currentSlideSize;
}
return sizeLimit;
}
private void showAddAttachmentDialog(final boolean replace) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setIcon(R.drawable.ic_dialog_attach);
builder.setTitle(R.string.add_attachment);
if (mAttachmentTypeSelectorAdapter == null) {
mAttachmentTypeSelectorAdapter = new AttachmentTypeSelectorAdapter(
this, AttachmentTypeSelectorAdapter.MODE_WITH_SLIDESHOW);
}
builder.setAdapter(mAttachmentTypeSelectorAdapter, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
addAttachment(mAttachmentTypeSelectorAdapter.buttonToCommand(which), replace);
dialog.dismiss();
}
});
builder.show();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (LogTag.VERBOSE) {
log("onActivityResult: requestCode=" + requestCode + ", resultCode=" + resultCode +
", data=" + data);
}
mWaitingForSubActivity = false; // We're back!
mShouldLoadDraft = false;
if (mWorkingMessage.isFakeMmsForDraft()) {
// We no longer have to fake the fact we're an Mms. At this point we are or we aren't,
// based on attachments and other Mms attrs.
mWorkingMessage.removeFakeMmsForDraft();
}
if (requestCode == REQUEST_CODE_PICK) {
mWorkingMessage.asyncDeleteDraftSmsMessage(mConversation);
}
if (requestCode == REQUEST_CODE_ADD_CONTACT) {
// The user might have added a new contact. When we tell contacts to add a contact
// and tap "Done", we're not returned to Messaging. If we back out to return to
// messaging after adding a contact, the resultCode is RESULT_CANCELED. Therefore,
// assume a contact was added and get the contact and force our cached contact to
// get reloaded with the new info (such as contact name). After the
// contact is reloaded, the function onUpdate() in this file will get called
// and it will update the title bar, etc.
if (mAddContactIntent != null) {
String address =
mAddContactIntent.getStringExtra(ContactsContract.Intents.Insert.EMAIL);
if (address == null) {
address =
mAddContactIntent.getStringExtra(ContactsContract.Intents.Insert.PHONE);
}
if (address != null) {
Contact contact = Contact.get(address, false);
if (contact != null) {
contact.reload();
}
}
}
}
if (resultCode != RESULT_OK){
if (LogTag.VERBOSE) log("bail due to resultCode=" + resultCode);
return;
}
switch (requestCode) {
case REQUEST_CODE_CREATE_SLIDESHOW:
if (data != null) {
WorkingMessage newMessage = WorkingMessage.load(this, data.getData());
if (newMessage != null) {
mWorkingMessage = newMessage;
mWorkingMessage.setConversation(mConversation);
updateThreadIdIfRunning();
drawTopPanel(false);
updateSendButtonState();
}
}
break;
case REQUEST_CODE_TAKE_PICTURE: {
// create a file based uri and pass to addImage(). We want to read the JPEG
// data directly from file (using UriImage) instead of decoding it into a Bitmap,
// which takes up too much memory and could easily lead to OOM.
File file = new File(TempFileProvider.getScrapPath(this));
Uri uri = Uri.fromFile(file);
// Remove the old captured picture's thumbnail from the cache
MmsApp.getApplication().getThumbnailManager().removeThumbnail(uri);
addImageAsync(uri, false);
break;
}
case REQUEST_CODE_ATTACH_IMAGE: {
if (data != null) {
addImageAsync(data.getData(), false);
}
break;
}
case REQUEST_CODE_TAKE_VIDEO:
Uri videoUri = TempFileProvider.renameScrapFile(".3gp", null, this);
// Remove the old captured video's thumbnail from the cache
MmsApp.getApplication().getThumbnailManager().removeThumbnail(videoUri);
addVideoAsync(videoUri, false); // can handle null videoUri
break;
case REQUEST_CODE_ATTACH_VIDEO:
if (data != null) {
addVideoAsync(data.getData(), false);
}
break;
case REQUEST_CODE_ATTACH_SOUND: {
Uri uri = (Uri) data.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI);
if (Settings.System.DEFAULT_RINGTONE_URI.equals(uri)) {
break;
}
addAudio(uri);
break;
}
case REQUEST_CODE_RECORD_SOUND:
if (data != null) {
addAudio(data.getData());
}
break;
case REQUEST_CODE_ECM_EXIT_DIALOG:
boolean outOfEmergencyMode = data.getBooleanExtra(EXIT_ECM_RESULT, false);
if (outOfEmergencyMode) {
sendMessage(false);
}
break;
case REQUEST_CODE_PICK:
if (data != null) {
processPickResult(data);
}
break;
case REQUEST_CODE_INSERT_CONTACT_INFO:
showContactInfoDialog(data.getData());
break;
default:
if (LogTag.VERBOSE) log("bail due to unknown requestCode=" + requestCode);
break;
}
}
private void processPickResult(final Intent data) {
// The EXTRA_PHONE_URIS stores the phone's urls that were selected by user in the
// multiple phone picker.
final Parcelable[] uris =
data.getParcelableArrayExtra(Intents.EXTRA_PHONE_URIS);
final int recipientCount = uris != null ? uris.length : 0;
final int recipientLimit = MmsConfig.getRecipientLimit();
if (recipientLimit != Integer.MAX_VALUE && recipientCount > recipientLimit) {
new AlertDialog.Builder(this)
.setMessage(getString(R.string.too_many_recipients, recipientCount, recipientLimit))
.setPositiveButton(android.R.string.ok, null)
.create().show();
return;
}
final Handler handler = new Handler();
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle(getText(R.string.pick_too_many_recipients));
progressDialog.setMessage(getText(R.string.adding_recipients));
progressDialog.setIndeterminate(true);
progressDialog.setCancelable(false);
final Runnable showProgress = new Runnable() {
@Override
public void run() {
progressDialog.show();
}
};
// Only show the progress dialog if we can not finish off parsing the return data in 1s,
// otherwise the dialog could flicker.
handler.postDelayed(showProgress, 1000);
new Thread(new Runnable() {
@Override
public void run() {
final ContactList list;
try {
list = ContactList.blockingGetByUris(uris);
} finally {
handler.removeCallbacks(showProgress);
progressDialog.dismiss();
}
// TODO: there is already code to update the contact header widget and recipients
// editor if the contacts change. we can re-use that code.
final Runnable populateWorker = new Runnable() {
@Override
public void run() {
mRecipientsEditor.populate(list);
updateTitle(list);
}
};
handler.post(populateWorker);
}
}, "ComoseMessageActivity.processPickResult").start();
}
private final ResizeImageResultCallback mResizeImageCallback = new ResizeImageResultCallback() {
// TODO: make this produce a Uri, that's what we want anyway
@Override
public void onResizeResult(PduPart part, boolean append) {
if (part == null) {
handleAddAttachmentError(WorkingMessage.UNKNOWN_ERROR, R.string.type_picture);
return;
}
Context context = ComposeMessageActivity.this;
PduPersister persister = PduPersister.getPduPersister(context);
int result;
Uri messageUri = mWorkingMessage.saveAsMms(true);
if (messageUri == null) {
result = WorkingMessage.UNKNOWN_ERROR;
} else {
try {
Uri dataUri = persister.persistPart(part,
ContentUris.parseId(messageUri), null);
result = mWorkingMessage.setAttachment(WorkingMessage.IMAGE, dataUri, append);
if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
log("ResizeImageResultCallback: dataUri=" + dataUri);
}
} catch (MmsException e) {
result = WorkingMessage.UNKNOWN_ERROR;
}
}
handleAddAttachmentError(result, R.string.type_picture);
}
};
private void handleAddAttachmentError(final int error, final int mediaTypeStringId) {
if (error == WorkingMessage.OK) {
return;
}
Log.d(TAG, "handleAddAttachmentError: " + error);
runOnUiThread(new Runnable() {
@Override
public void run() {
Resources res = getResources();
String mediaType = res.getString(mediaTypeStringId);
String title, message;
switch(error) {
case WorkingMessage.UNKNOWN_ERROR:
message = res.getString(R.string.failed_to_add_media, mediaType);
Toast.makeText(ComposeMessageActivity.this, message, Toast.LENGTH_SHORT).show();
return;
case WorkingMessage.UNSUPPORTED_TYPE:
title = res.getString(R.string.unsupported_media_format, mediaType);
message = res.getString(R.string.select_different_media, mediaType);
break;
case WorkingMessage.MESSAGE_SIZE_EXCEEDED:
title = res.getString(R.string.exceed_message_size_limitation, mediaType);
message = res.getString(R.string.failed_to_add_media, mediaType);
break;
case WorkingMessage.IMAGE_TOO_LARGE:
title = res.getString(R.string.failed_to_resize_image);
message = res.getString(R.string.resize_image_error_information);
break;
default:
throw new IllegalArgumentException("unknown error " + error);
}
MessageUtils.showErrorDialog(ComposeMessageActivity.this, title, message);
}
});
}
private void addImageAsync(final Uri uri, final boolean append) {
getAsyncDialog().runAsync(new Runnable() {
@Override
public void run() {
addImage(uri, append);
}
}, null, R.string.adding_attachments_title);
}
private void addImage(Uri uri, boolean append) {
if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
log("addImage: append=" + append + ", uri=" + uri);
}
int result = mWorkingMessage.setAttachment(WorkingMessage.IMAGE, uri, append);
if (result == WorkingMessage.IMAGE_TOO_LARGE ||
result == WorkingMessage.MESSAGE_SIZE_EXCEEDED) {
if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
log("resize image " + uri);
}
MessageUtils.resizeImageAsync(ComposeMessageActivity.this,
uri, mAttachmentEditorHandler, mResizeImageCallback, append);
return;
}
handleAddAttachmentError(result, R.string.type_picture);
}
private void addVideoAsync(final Uri uri, final boolean append) {
getAsyncDialog().runAsync(new Runnable() {
@Override
public void run() {
addVideo(uri, append);
}
}, null, R.string.adding_attachments_title);
}
private void addVideo(Uri uri, boolean append) {
if (uri != null) {
int result = mWorkingMessage.setAttachment(WorkingMessage.VIDEO, uri, append);
handleAddAttachmentError(result, R.string.type_video);
}
}
private void addAudio(Uri uri) {
int result = mWorkingMessage.setAttachment(WorkingMessage.AUDIO, uri, false);
handleAddAttachmentError(result, R.string.type_audio);
}
AsyncDialog getAsyncDialog() {
if (mAsyncDialog == null) {
mAsyncDialog = new AsyncDialog(this);
}
return mAsyncDialog;
}
private boolean handleForwardedMessage() {
Intent intent = getIntent();
// If this is a forwarded message, it will have an Intent extra
// indicating so. If not, bail out.
if (intent.getBooleanExtra("forwarded_message", false) == false) {
return false;
}
Uri uri = intent.getParcelableExtra("msg_uri");
if (Log.isLoggable(LogTag.APP, Log.DEBUG)) {
log("" + uri);
}
if (uri != null) {
mWorkingMessage = WorkingMessage.load(this, uri);
mWorkingMessage.setSubject(intent.getStringExtra("subject"), false);
} else {
mWorkingMessage.setText(intent.getStringExtra("sms_body"));
}
// let's clear the message thread for forwarded messages
mMsgListAdapter.changeCursor(null);
return true;
}
// Handle send actions, where we're told to send a picture(s) or text.
private boolean handleSendIntent() {
Intent intent = getIntent();
Bundle extras = intent.getExtras();
if (extras == null) {
return false;
}
final String mimeType = intent.getType();
String action = intent.getAction();
if (Intent.ACTION_SEND.equals(action)) {
if (extras.containsKey(Intent.EXTRA_STREAM)) {
final Uri uri = (Uri)extras.getParcelable(Intent.EXTRA_STREAM);
getAsyncDialog().runAsync(new Runnable() {
@Override
public void run() {
addAttachment(mimeType, uri, false);
}
}, null, R.string.adding_attachments_title);
return true;
} else if (extras.containsKey(Intent.EXTRA_TEXT)) {
mWorkingMessage.setText(extras.getString(Intent.EXTRA_TEXT));
return true;
}
} else if (Intent.ACTION_SEND_MULTIPLE.equals(action) &&
extras.containsKey(Intent.EXTRA_STREAM)) {
SlideshowModel slideShow = mWorkingMessage.getSlideshow();
final ArrayList<Parcelable> uris = extras.getParcelableArrayList(Intent.EXTRA_STREAM);
int currentSlideCount = slideShow != null ? slideShow.size() : 0;
int importCount = uris.size();
if (importCount + currentSlideCount > SlideshowEditor.MAX_SLIDE_NUM) {
importCount = Math.min(SlideshowEditor.MAX_SLIDE_NUM - currentSlideCount,
importCount);
Toast.makeText(ComposeMessageActivity.this,
getString(R.string.too_many_attachments,
SlideshowEditor.MAX_SLIDE_NUM, importCount),
Toast.LENGTH_LONG).show();
}
// Attach all the pictures/videos asynchronously off of the UI thread.
// Show a progress dialog if adding all the slides hasn't finished
// within half a second.
final int numberToImport = importCount;
getAsyncDialog().runAsync(new Runnable() {
@Override
public void run() {
for (int i = 0; i < numberToImport; i++) {
Parcelable uri = uris.get(i);
addAttachment(mimeType, (Uri) uri, true);
}
}
}, null, R.string.adding_attachments_title);
return true;
}
return false;
}
// mVideoUri will look like this: content://media/external/video/media
private static final String mVideoUri = Video.Media.getContentUri("external").toString();
// mImageUri will look like this: content://media/external/images/media
private static final String mImageUri = Images.Media.getContentUri("external").toString();
private void addAttachment(String type, Uri uri, boolean append) {
if (uri != null) {
// When we're handling Intent.ACTION_SEND_MULTIPLE, the passed in items can be
// videos, and/or images, and/or some other unknown types we don't handle. When
// a single attachment is "shared" the type will specify an image or video. When
// there are multiple types, the type passed in is "*/*". In that case, we've got
// to look at the uri to figure out if it is an image or video.
boolean wildcard = "*/*".equals(type);
if (type.startsWith("image/") || (wildcard && uri.toString().startsWith(mImageUri))) {
addImage(uri, append);
} else if (type.startsWith("video/") ||
(wildcard && uri.toString().startsWith(mVideoUri))) {
addVideo(uri, append);
}
}
}
private String getResourcesString(int id, String mediaName) {
Resources r = getResources();
return r.getString(id, mediaName);
}
/**
* draw the compose view at the bottom of the screen.
*/
private void drawBottomPanel() {
// Reset the counter for text editor.
resetCounter();
if (mWorkingMessage.hasSlideshow()) {
mBottomPanel.setVisibility(View.GONE);
mAttachmentEditor.requestFocus();
return;
}
if (LOCAL_LOGV) {
Log.v(TAG, "CMA.drawBottomPanel");
}
mBottomPanel.setVisibility(View.VISIBLE);
CharSequence text = mWorkingMessage.getText();
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences((Context) ComposeMessageActivity.this);
// TextView.setTextKeepState() doesn't like null input.
if (text != null) {
// Restore the emojis if necessary
if (mEnableEmojis) {
mTextEditor.setTextKeepState(EmojiParser.getInstance().addEmojiSpans(text));
} else {
mTextEditor.setTextKeepState(text);
}
// Set the edit caret to the end of the text.
mTextEditor.setSelection(mTextEditor.length());
} else {
mTextEditor.setText("");
}
}
private void hideBottomPanel() {
if (LOCAL_LOGV) {
Log.v(TAG, "CMA.hideBottomPanel");
}
mBottomPanel.setVisibility(View.INVISIBLE);
}
private void drawTopPanel(boolean showSubjectEditor) {
boolean showingAttachment = mAttachmentEditor.update(mWorkingMessage);
mAttachmentEditorScrollView.setVisibility(showingAttachment ? View.VISIBLE : View.GONE);
showSubjectEditor(showSubjectEditor || mWorkingMessage.hasSubject());
invalidateOptionsMenu();
}
//==========================================================
// Interface methods
//==========================================================
@Override
public void onClick(View v) {
if ((v == mSendButtonSms || v == mSendButtonMms) && isPreparedForSending()) {
confirmSendMessageIfNeeded();
} else if ((v == mRecipientsPicker)) {
launchMultiplePhonePicker();
}
else if((v == mQuickEmoji)) {
showEmojiDialog();
}
}
private void launchMultiplePhonePicker() {
Intent intent = new Intent(Intents.ACTION_GET_MULTIPLE_PHONES);
intent.addCategory("android.intent.category.DEFAULT");
intent.setType(Phone.CONTENT_TYPE);
// We have to wait for the constructing complete.
ContactList contacts = mRecipientsEditor.constructContactsFromInput(true);
int urisCount = 0;
Uri[] uris = new Uri[contacts.size()];
urisCount = 0;
for (Contact contact : contacts) {
if (Contact.CONTACT_METHOD_TYPE_PHONE == contact.getContactMethodType()) {
uris[urisCount++] = contact.getPhoneUri();
}
}
if (urisCount > 0) {
intent.putExtra(Intents.EXTRA_PHONE_URIS, uris);
}
startActivityForResult(intent, REQUEST_CODE_PICK);
}
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (event != null) {
boolean sendNow;
if (mInputMethod == InputType.TYPE_TEXT_VARIATION_LONG_MESSAGE) {
//if the user has selected enter
//for a new line the shift key must be pressed to send
sendNow = event.isShiftPressed();
} else {
//otherwise enter sends and shift must be pressed for a new line
sendNow = !event.isShiftPressed();
}
if (sendNow && event.getAction() == KeyEvent.ACTION_DOWN) {
if (isPreparedForSending()) {
confirmSendMessageIfNeeded();
}
return true;
}
return false;
}
if (isPreparedForSending()) {
confirmSendMessageIfNeeded();
}
return true;
}
private final TextWatcher mTextEditorWatcher = new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// This is a workaround for bug 1609057. Since onUserInteraction() is
// not called when the user touches the soft keyboard, we pretend it was
// called when textfields changes. This should be removed when the bug
// is fixed.
onUserInteraction();
mWorkingMessage.setText(s);
updateSendButtonState();
// strip unicode for counting characters
s = stripUnicodeIfRequested(s);
updateCounter(s, start, before, count);
ensureCorrectButtonHeight();
}
@Override
public void afterTextChanged(Editable s) {
}
};
/**
* Ensures that if the text edit box extends past two lines then the
* button will be shifted up to allow enough space for the character
* counter string to be placed beneath it.
*/
private void ensureCorrectButtonHeight() {
int currentTextLines = mTextEditor.getLineCount();
if (currentTextLines <= 2) {
mTextCounter.setVisibility(View.GONE);
}
else if (currentTextLines > 2 && mTextCounter.getVisibility() == View.GONE) {
// Making the counter invisible ensures that it is used to correctly
// calculate the position of the send button even if we choose not to
// display the text.
mTextCounter.setVisibility(View.INVISIBLE);
}
}
private final TextWatcher mSubjectEditorWatcher = new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
mWorkingMessage.setSubject(s, true);
updateSendButtonState();
}
@Override
public void afterTextChanged(Editable s) { }
};
//==========================================================
// Private methods
//==========================================================
/**
* Initialize all UI elements from resources.
*/
private void initResourceRefs() {
mMsgListView = (MessageListView) findViewById(R.id.history);
mMsgListView.setDivider(null); // no divider so we look like IM conversation.
// called to enable us to show some padding between the message list and the
// input field but when the message list is scrolled that padding area is filled
// in with message content
mMsgListView.setClipToPadding(false);
mMsgListView.setOnSizeChangedListener(new OnSizeChangedListener() {
public void onSizeChanged(int width, int height, int oldWidth, int oldHeight) {
if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
Log.v(TAG, "onSizeChanged: w=" + width + " h=" + height +
" oldw=" + oldWidth + " oldh=" + oldHeight);
}
if (!mMessagesAndDraftLoaded && (oldHeight-height > SMOOTH_SCROLL_THRESHOLD)) {
// perform the delayed loading now, after keyboard opens
loadMessagesAndDraft(3);
}
// The message list view changed size, most likely because the keyboard
// appeared or disappeared or the user typed/deleted chars in the message
// box causing it to change its height when expanding/collapsing to hold more
// lines of text.
smoothScrollToEnd(false, height - oldHeight);
}
});
mBottomPanel = findViewById(R.id.bottom_panel);
mTextEditor = (EditText) findViewById(R.id.embedded_text_editor);
mTextEditor.setOnEditorActionListener(this);
mTextEditor.addTextChangedListener(mTextEditorWatcher);
mTextEditor.setFilters(new InputFilter[] {
new LengthFilter(MmsConfig.getMaxTextLimit())});
mTextCounter = (TextView) findViewById(R.id.text_counter);
mSendButtonMms = (TextView) findViewById(R.id.send_button_mms);
mSendButtonSms = (ImageButton) findViewById(R.id.send_button_sms);
mSendButtonMms.setOnClickListener(this);
mSendButtonSms.setOnClickListener(this);
mTopPanel = findViewById(R.id.recipients_subject_linear);
mTopPanel.setFocusable(false);
mAttachmentEditor = (AttachmentEditor) findViewById(R.id.attachment_editor);
mAttachmentEditor.setHandler(mAttachmentEditorHandler);
mAttachmentEditorScrollView = findViewById(R.id.attachment_editor_scroll_view);
mQuickEmoji = (ImageButton) mBottomPanel.findViewById(R.id.quick_emoji_button_mms);
mQuickEmoji.setOnClickListener(this);
}
private void confirmDeleteDialog(OnClickListener listener, boolean locked) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setMessage(locked ? R.string.confirm_delete_locked_message :
R.string.confirm_delete_message);
builder.setPositiveButton(R.string.delete, listener);
builder.setNegativeButton(R.string.no, null);
builder.show();
}
void undeliveredMessageDialog(long date) {
String body;
if (date >= 0) {
body = getString(R.string.undelivered_msg_dialog_body,
MessageUtils.formatTimeStampString(this, date));
} else {
// FIXME: we can not get sms retry time.
body = getString(R.string.undelivered_sms_dialog_body);
}
Toast.makeText(this, body, Toast.LENGTH_LONG).show();
}
private void startMsgListQuery() {
startMsgListQuery(MESSAGE_LIST_QUERY_TOKEN);
}
private void startMsgListQuery(int token) {
Uri conversationUri = mConversation.getUri();
if (conversationUri == null) {
log("##### startMsgListQuery: conversationUri is null, bail!");
return;
}
long threadId = mConversation.getThreadId();
if (LogTag.VERBOSE || Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
log("startMsgListQuery for " + conversationUri + ", threadId=" + threadId +
" token: " + token + " mConversation: " + mConversation);
}
// Cancel any pending queries
mBackgroundQueryHandler.cancelOperation(token);
try {
// Kick off the new query
mBackgroundQueryHandler.startQuery(
token,
threadId /* cookie */,
conversationUri,
PROJECTION,
null, null, null);
} catch (SQLiteException e) {
SqliteWrapper.checkSQLiteException(this, e);
}
}
private void initMessageList() {
if (mMsgListAdapter != null) {
return;
}
String highlightString = getIntent().getStringExtra("highlight");
Pattern highlight = highlightString == null
? null
: Pattern.compile("\\b" + Pattern.quote(highlightString), Pattern.CASE_INSENSITIVE);
// Initialize the list adapter with a null cursor.
mMsgListAdapter = new MessageListAdapter(this, null, mMsgListView, true, highlight);
mMsgListAdapter.setOnDataSetChangedListener(mDataSetChangedListener);
mMsgListAdapter.setMsgListItemHandler(mMessageListItemHandler);
mMsgListView.setAdapter(mMsgListAdapter);
mMsgListView.setItemsCanFocus(false);
mMsgListView.setVisibility(View.VISIBLE);
mMsgListView.setOnCreateContextMenuListener(mMsgListMenuCreateListener);
mMsgListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (view != null) {
((MessageListItem) view).onMessageListItemClick();
}
}
});
}
/**
* Load the draft
*
* If mWorkingMessage has content in memory that's worth saving, return false.
* Otherwise, call the async operation to load draft and return true.
*/
private boolean loadDraft() {
if (mWorkingMessage.isWorthSaving()) {
Log.w(TAG, "CMA.loadDraft: called with non-empty working message, bail");
return false;
}
if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
log("CMA.loadDraft");
}
mWorkingMessage = WorkingMessage.loadDraft(this, mConversation,
new Runnable() {
@Override
public void run() {
drawTopPanel(false);
drawBottomPanel();
updateSendButtonState();
}
});
// WorkingMessage.loadDraft() can return a new WorkingMessage object that doesn't
// have its conversation set. Make sure it is set.
mWorkingMessage.setConversation(mConversation);
return true;
}
private void saveDraft(boolean isStopping) {
if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
LogTag.debug("saveDraft");
}
// TODO: Do something better here. Maybe make discard() legal
// to call twice and make isEmpty() return true if discarded
// so it is caught in the clause above this one?
if (mWorkingMessage.isDiscarded()) {
return;
}
if (!mWaitingForSubActivity &&
!mWorkingMessage.isWorthSaving() &&
(!isRecipientsEditorVisible() || recipientCount() == 0)) {
if (LogTag.VERBOSE || Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
log("not worth saving, discard WorkingMessage and bail");
}
mWorkingMessage.discard();
return;
}
mWorkingMessage.saveDraft(isStopping);
if (mToastForDraftSave) {
Toast.makeText(this, R.string.message_saved_as_draft,
Toast.LENGTH_SHORT).show();
}
}
private boolean isPreparedForSending() {
int recipientCount = recipientCount();
return recipientCount > 0 && recipientCount <= MmsConfig.getRecipientLimit() &&
(mWorkingMessage.hasAttachment() ||
mWorkingMessage.hasText() ||
mWorkingMessage.hasSubject());
}
private int recipientCount() {
int recipientCount;
// To avoid creating a bunch of invalid Contacts when the recipients
// editor is in flux, we keep the recipients list empty. So if the
// recipients editor is showing, see if there is anything in it rather
// than consulting the empty recipient list.
if (isRecipientsEditorVisible()) {
recipientCount = mRecipientsEditor.getRecipientCount();
} else {
recipientCount = getRecipients().size();
}
return recipientCount;
}
private void sendMessage(boolean bCheckEcmMode) {
if (bCheckEcmMode) {
// TODO: expose this in telephony layer for SDK build
String inEcm = SystemProperties.get(TelephonyProperties.PROPERTY_INECM_MODE);
if (Boolean.parseBoolean(inEcm)) {
try {
startActivityForResult(
new Intent(TelephonyIntents.ACTION_SHOW_NOTICE_ECM_BLOCK_OTHERS, null),
REQUEST_CODE_ECM_EXIT_DIALOG);
return;
} catch (ActivityNotFoundException e) {
// continue to send message
Log.e(TAG, "Cannot find EmergencyCallbackModeExitDialog", e);
}
}
}
if (!mSendingMessage) {
if (LogTag.SEVERE_WARNING) {
String sendingRecipients = mConversation.getRecipients().serialize();
if (!sendingRecipients.equals(mDebugRecipients)) {
String workingRecipients = mWorkingMessage.getWorkingRecipients();
if (!mDebugRecipients.equals(workingRecipients)) {
LogTag.warnPossibleRecipientMismatch("ComposeMessageActivity.sendMessage" +
" recipients in window: \"" +
mDebugRecipients + "\" differ from recipients from conv: \"" +
sendingRecipients + "\" and working recipients: " +
workingRecipients, this);
}
}
sanityCheckConversation();
}
// send can change the recipients. Make sure we remove the listeners first and then add
// them back once the recipient list has settled.
removeRecipientsListeners();
// strip unicode chars before sending (if applicable)
mWorkingMessage.setText(stripUnicodeIfRequested(mWorkingMessage.getText()));
mWorkingMessage.send(mDebugRecipients);
mSentMessage = true;
mSendingMessage = true;
addRecipientsListeners();
mScrollOnSend = true; // in the next onQueryComplete, scroll the list to the end.
}
// But bail out if we are supposed to exit after the message is sent.
if (mExitOnSent) {
finish();
}
}
private void resetMessage() {
if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
log("resetMessage");
}
// Make the attachment editor hide its view.
mAttachmentEditor.hideView();
mAttachmentEditorScrollView.setVisibility(View.GONE);
// Hide the subject editor.
showSubjectEditor(false);
// Focus to the text editor.
mTextEditor.requestFocus();
// We have to remove the text change listener while the text editor gets cleared and
// we subsequently turn the message back into SMS. When the listener is listening while
// doing the clearing, it's fighting to update its counts and itself try and turn
// the message one way or the other.
mTextEditor.removeTextChangedListener(mTextEditorWatcher);
// Clear the text box.
TextKeyListener.clear(mTextEditor.getText());
mWorkingMessage.clearConversation(mConversation, false);
mWorkingMessage = WorkingMessage.createEmpty(this);
mWorkingMessage.setConversation(mConversation);
hideRecipientEditor();
drawBottomPanel();
// "Or not", in this case.
updateSendButtonState();
// Our changes are done. Let the listener respond to text changes once again.
mTextEditor.addTextChangedListener(mTextEditorWatcher);
// Close the soft on-screen keyboard if we're in landscape mode so the user can see the
// conversation.
if (mIsLandscape) {
hideKeyboard();
}
mLastRecipientCount = 0;
mSendingMessage = false;
invalidateOptionsMenu();
}
private void hideKeyboard() {
InputMethodManager inputMethodManager =
(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(mTextEditor.getWindowToken(), 0);
}
private void updateSendButtonState() {
boolean enable = false;
if (isPreparedForSending()) {
// When the type of attachment is slideshow, we should
// also hide the 'Send' button since the slideshow view
// already has a 'Send' button embedded.
if (!mWorkingMessage.hasSlideshow()) {
enable = true;
} else {
mAttachmentEditor.setCanSend(true);
}
} else if (null != mAttachmentEditor){
mAttachmentEditor.setCanSend(false);
}
boolean requiresMms = mWorkingMessage.requiresMms();
View sendButton = showSmsOrMmsSendButton(requiresMms);
sendButton.setEnabled(enable);
sendButton.setFocusable(enable);
}
private long getMessageDate(Uri uri) {
if (uri != null) {
Cursor cursor = SqliteWrapper.query(this, mContentResolver,
uri, new String[] { Mms.DATE }, null, null, null);
if (cursor != null) {
try {
if ((cursor.getCount() == 1) && cursor.moveToFirst()) {
return cursor.getLong(0) * 1000L;
}
} finally {
cursor.close();
}
}
}
return NO_DATE_FOR_DIALOG;
}
private void initActivityState(Bundle bundle) {
Intent intent = getIntent();
if (bundle != null) {
setIntent(getIntent().setAction(Intent.ACTION_VIEW));
String recipients = bundle.getString(RECIPIENTS);
if (LogTag.VERBOSE) log("get mConversation by recipients " + recipients);
mConversation = Conversation.get(this,
ContactList.getByNumbers(recipients,
false /* don't block */, true /* replace number */), false);
addRecipientsListeners();
mExitOnSent = bundle.getBoolean("exit_on_sent", false);
mWorkingMessage.readStateFromBundle(bundle);
return;
}
// If we have been passed a thread_id, use that to find our conversation.
long threadId = intent.getLongExtra(THREAD_ID, 0);
if (threadId > 0) {
if (LogTag.VERBOSE) log("get mConversation by threadId " + threadId);
mConversation = Conversation.get(this, threadId, false);
} else {
Uri intentData = intent.getData();
if (intentData != null) {
// try to get a conversation based on the data URI passed to our intent.
if (LogTag.VERBOSE) log("get mConversation by intentData " + intentData);
mConversation = Conversation.get(this, intentData, false);
mWorkingMessage.setText(getBody(intentData));
} else {
// special intent extra parameter to specify the address
String address = intent.getStringExtra("address");
if (!TextUtils.isEmpty(address)) {
if (LogTag.VERBOSE) log("get mConversation by address " + address);
mConversation = Conversation.get(this, ContactList.getByNumbers(address,
false /* don't block */, true /* replace number */), false);
} else {
if (LogTag.VERBOSE) log("create new conversation");
mConversation = Conversation.createNew(this);
}
}
}
addRecipientsListeners();
updateThreadIdIfRunning();
mExitOnSent = intent.getBooleanExtra("exit_on_sent", false);
if (intent.hasExtra("sms_body")) {
mWorkingMessage.setText(intent.getStringExtra("sms_body"));
}
mWorkingMessage.setSubject(intent.getStringExtra("subject"), false);
}
private void initFocus() {
if (!mIsKeyboardOpen) {
return;
}
// If the recipients editor is visible, there is nothing in it,
// and the text editor is not already focused, focus the
// recipients editor.
if (isRecipientsEditorVisible()
&& TextUtils.isEmpty(mRecipientsEditor.getText())
&& !mTextEditor.isFocused()) {
mRecipientsEditor.requestFocus();
return;
}
// If we decided not to focus the recipients editor, focus the text editor.
mTextEditor.requestFocus();
}
private final MessageListAdapter.OnDataSetChangedListener
mDataSetChangedListener = new MessageListAdapter.OnDataSetChangedListener() {
@Override
public void onDataSetChanged(MessageListAdapter adapter) {
}
@Override
public void onContentChanged(MessageListAdapter adapter) {
startMsgListQuery();
}
};
/**
* smoothScrollToEnd will scroll the message list to the bottom if the list is already near
* the bottom. Typically this is called to smooth scroll a newly received message into view.
* It's also called when sending to scroll the list to the bottom, regardless of where it is,
* so the user can see the just sent message. This function is also called when the message
* list view changes size because the keyboard state changed or the compose message field grew.
*
* @param force always scroll to the bottom regardless of current list position
* @param listSizeChange the amount the message list view size has vertically changed
*/
private void smoothScrollToEnd(boolean force, int listSizeChange) {
int lastItemVisible = mMsgListView.getLastVisiblePosition();
int lastItemInList = mMsgListAdapter.getCount() - 1;
if (lastItemVisible < 0 || lastItemInList < 0) {
if (LogTag.VERBOSE || Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
Log.v(TAG, "smoothScrollToEnd: lastItemVisible=" + lastItemVisible +
", lastItemInList=" + lastItemInList +
", mMsgListView not ready");
}
return;
}
View lastChildVisible =
mMsgListView.getChildAt(lastItemVisible - mMsgListView.getFirstVisiblePosition());
int lastVisibleItemBottom = 0;
int lastVisibleItemHeight = 0;
if (lastChildVisible != null) {
lastVisibleItemBottom = lastChildVisible.getBottom();
lastVisibleItemHeight = lastChildVisible.getHeight();
}
if (LogTag.VERBOSE || Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
Log.v(TAG, "smoothScrollToEnd newPosition: " + lastItemInList +
" mLastSmoothScrollPosition: " + mLastSmoothScrollPosition +
" first: " + mMsgListView.getFirstVisiblePosition() +
" lastItemVisible: " + lastItemVisible +
" lastVisibleItemBottom: " + lastVisibleItemBottom +
" lastVisibleItemBottom + listSizeChange: " +
(lastVisibleItemBottom + listSizeChange) +
" mMsgListView.getHeight() - mMsgListView.getPaddingBottom(): " +
(mMsgListView.getHeight() - mMsgListView.getPaddingBottom()) +
" listSizeChange: " + listSizeChange);
}
// Only scroll if the list if we're responding to a newly sent message (force == true) or
// the list is already scrolled to the end. This code also has to handle the case where
// the listview has changed size (from the keyboard coming up or down or the message entry
// field growing/shrinking) and it uses that grow/shrink factor in listSizeChange to
// compute whether the list was at the end before the resize took place.
// For example, when the keyboard comes up, listSizeChange will be negative, something
// like -524. The lastChild listitem's bottom value will be the old value before the
// keyboard became visible but the size of the list will have changed. The test below
// add listSizeChange to bottom to figure out if the old position was already scrolled
// to the bottom. We also scroll the list if the last item is taller than the size of the
// list. This happens when the keyboard is up and the last item is an mms with an
// attachment thumbnail, such as picture. In this situation, we want to scroll the list so
// the bottom of the thumbnail is visible and the top of the item is scroll off the screen.
int listHeight = mMsgListView.getHeight();
boolean lastItemTooTall = lastVisibleItemHeight > listHeight;
boolean willScroll = force ||
((listSizeChange != 0 || lastItemInList != mLastSmoothScrollPosition) &&
lastVisibleItemBottom + listSizeChange <=
listHeight - mMsgListView.getPaddingBottom());
if (willScroll || (lastItemTooTall && lastItemInList == lastItemVisible)) {
if (Math.abs(listSizeChange) > SMOOTH_SCROLL_THRESHOLD) {
// When the keyboard comes up, the window manager initiates a cross fade
// animation that conflicts with smooth scroll. Handle that case by jumping the
// list directly to the end.
if (LogTag.VERBOSE || Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
Log.v(TAG, "keyboard state changed. setSelection=" + lastItemInList);
}
if (lastItemTooTall) {
// If the height of the last item is taller than the whole height of the list,
// we need to scroll that item so that its top is negative or above the top of
// the list. That way, the bottom of the last item will be exposed above the
// keyboard.
mMsgListView.setSelectionFromTop(lastItemInList,
listHeight - lastVisibleItemHeight);
} else {
mMsgListView.setSelection(lastItemInList);
}
} else if (lastItemInList - lastItemVisible > MAX_ITEMS_TO_INVOKE_SCROLL_SHORTCUT) {
if (LogTag.VERBOSE || Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
Log.v(TAG, "too many to scroll, setSelection=" + lastItemInList);
}
mMsgListView.setSelection(lastItemInList);
} else {
if (LogTag.VERBOSE || Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
Log.v(TAG, "smooth scroll to " + lastItemInList);
}
if (lastItemTooTall) {
// If the height of the last item is taller than the whole height of the list,
// we need to scroll that item so that its top is negative or above the top of
// the list. That way, the bottom of the last item will be exposed above the
// keyboard. We should use smoothScrollToPositionFromTop here, but it doesn't
// seem to work -- the list ends up scrolling to a random position.
mMsgListView.setSelectionFromTop(lastItemInList,
listHeight - lastVisibleItemHeight);
} else {
mMsgListView.smoothScrollToPosition(lastItemInList);
}
mLastSmoothScrollPosition = lastItemInList;
}
}
}
private final class BackgroundQueryHandler extends ConversationQueryHandler {
public BackgroundQueryHandler(ContentResolver contentResolver) {
super(contentResolver);
}
@Override
protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
switch(token) {
case MESSAGE_LIST_QUERY_TOKEN:
mConversation.blockMarkAsRead(false);
// check consistency between the query result and 'mConversation'
long tid = (Long) cookie;
if (LogTag.VERBOSE || Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
log("##### onQueryComplete: msg history result for threadId " + tid);
}
if (tid != mConversation.getThreadId()) {
log("onQueryComplete: msg history query result is for threadId " +
tid + ", but mConversation has threadId " +
mConversation.getThreadId() + " starting a new query");
if (cursor != null) {
cursor.close();
}
startMsgListQuery();
return;
}
// check consistency b/t mConversation & mWorkingMessage.mConversation
ComposeMessageActivity.this.sanityCheckConversation();
int newSelectionPos = -1;
long targetMsgId = getIntent().getLongExtra("select_id", -1);
if (targetMsgId != -1) {
if (cursor != null) {
cursor.moveToPosition(-1);
while (cursor.moveToNext()) {
long msgId = cursor.getLong(COLUMN_ID);
if (msgId == targetMsgId) {
newSelectionPos = cursor.getPosition();
break;
}
}
}
} else if (mSavedScrollPosition != -1) {
// mSavedScrollPosition is set when this activity pauses. If equals maxint,
// it means the message list was scrolled to the end. Meanwhile, messages
// could have been received. When the activity resumes and we were
// previously scrolled to the end, jump the list so any new messages are
// visible.
if (mSavedScrollPosition == Integer.MAX_VALUE) {
int cnt = mMsgListAdapter.getCount();
if (cnt > 0) {
// Have to wait until the adapter is loaded before jumping to
// the end.
newSelectionPos = cnt - 1;
mSavedScrollPosition = -1;
}
} else {
// remember the saved scroll position before the activity is paused.
// reset it after the message list query is done
newSelectionPos = mSavedScrollPosition;
mSavedScrollPosition = -1;
}
}
mMsgListAdapter.changeCursor(cursor);
if (newSelectionPos != -1) {
mMsgListView.setSelection(newSelectionPos); // jump the list to the pos
} else {
int count = mMsgListAdapter.getCount();
long lastMsgId = 0;
if (cursor != null && count > 0) {
cursor.moveToLast();
lastMsgId = cursor.getLong(COLUMN_ID);
}
// mScrollOnSend is set when we send a message. We always want to scroll
// the message list to the end when we send a message, but have to wait
// until the DB has changed. We also want to scroll the list when a
// new message has arrived.
smoothScrollToEnd(mScrollOnSend || lastMsgId != mLastMessageId, 0);
mLastMessageId = lastMsgId;
mScrollOnSend = false;
}
// Adjust the conversation's message count to match reality. The
// conversation's message count is eventually used in
// WorkingMessage.clearConversation to determine whether to delete
// the conversation or not.
mConversation.setMessageCount(mMsgListAdapter.getCount());
// Once we have completed the query for the message history, if
// there is nothing in the cursor and we are not composing a new
// message, we must be editing a draft in a new conversation (unless
// mSentMessage is true).
// Show the recipients editor to give the user a chance to add
// more people before the conversation begins.
if (cursor != null && cursor.getCount() == 0
&& !isRecipientsEditorVisible() && !mSentMessage) {
initRecipientsEditor();
}
// FIXME: freshing layout changes the focused view to an unexpected
// one, set it back to TextEditor forcely.
mTextEditor.requestFocus();
invalidateOptionsMenu(); // some menu items depend on the adapter's count
return;
case ConversationList.HAVE_LOCKED_MESSAGES_TOKEN:
@SuppressWarnings("unchecked")
ArrayList<Long> threadIds = (ArrayList<Long>)cookie;
ConversationList.confirmDeleteThreadDialog(
new ConversationList.DeleteThreadListener(threadIds,
mBackgroundQueryHandler, ComposeMessageActivity.this),
threadIds,
cursor != null && cursor.getCount() > 0,
ComposeMessageActivity.this);
if (cursor != null) {
cursor.close();
}
break;
case MESSAGE_LIST_QUERY_AFTER_DELETE_TOKEN:
// check consistency between the query result and 'mConversation'
tid = (Long) cookie;
if (LogTag.VERBOSE || Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
log("##### onQueryComplete (after delete): msg history result for threadId "
+ tid);
}
if (cursor == null) {
return;
}
if (tid > 0 && cursor.getCount() == 0) {
// We just deleted the last message and the thread will get deleted
// by a trigger in the database. Clear the threadId so next time we
// need the threadId a new thread will get created.
log("##### MESSAGE_LIST_QUERY_AFTER_DELETE_TOKEN clearing thread id: "
+ tid);
Conversation conv = Conversation.get(ComposeMessageActivity.this, tid,
false);
if (conv != null) {
conv.clearThreadId();
conv.setDraftState(false);
}
// The last message in this converation was just deleted. Send the user
// to the conversation list.
exitComposeMessageActivity(new Runnable() {
@Override
public void run() {
goToConversationList();
}
});
}
cursor.close();
}
}
@Override
protected void onDeleteComplete(int token, Object cookie, int result) {
super.onDeleteComplete(token, cookie, result);
switch(token) {
case ConversationList.DELETE_CONVERSATION_TOKEN:
mConversation.setMessageCount(0);
// fall through
case DELETE_MESSAGE_TOKEN:
if (cookie instanceof Boolean && ((Boolean)cookie).booleanValue()) {
// If we just deleted the last message, reset the saved id.
mLastMessageId = 0;
}
// Update the notification for new messages since they
// may be deleted.
MessagingNotification.nonBlockingUpdateNewMessageIndicator(
ComposeMessageActivity.this, MessagingNotification.THREAD_NONE, false);
// Update the notification for failed messages since they
// may be deleted.
updateSendFailedNotification();
break;
}
// If we're deleting the whole conversation, throw away
// our current working message and bail.
if (token == ConversationList.DELETE_CONVERSATION_TOKEN) {
ContactList recipients = mConversation.getRecipients();
mWorkingMessage.discard();
// Remove any recipients referenced by this single thread from the
// contacts cache. It's possible for two or more threads to reference
// the same contact. That's ok if we remove it. We'll recreate that contact
// when we init all Conversations below.
if (recipients != null) {
for (Contact contact : recipients) {
contact.removeFromCache();
}
}
// Make sure the conversation cache reflects the threads in the DB.
Conversation.init(ComposeMessageActivity.this);
finish();
} else if (token == DELETE_MESSAGE_TOKEN) {
// Check to see if we just deleted the last message
startMsgListQuery(MESSAGE_LIST_QUERY_AFTER_DELETE_TOKEN);
}
MmsWidgetProvider.notifyDatasetChanged(getApplicationContext());
}
}
private void showSmileyDialog() {
if (mSmileyDialog == null) {
int[] icons = SmileyParser.DEFAULT_SMILEY_RES_IDS;
String[] names = getResources().getStringArray(
SmileyParser.DEFAULT_SMILEY_NAMES);
final String[] texts = getResources().getStringArray(
SmileyParser.DEFAULT_SMILEY_TEXTS);
final int N = names.length;
List<Map<String, ?>> entries = new ArrayList<Map<String, ?>>();
for (int i = 0; i < N; i++) {
// We might have different ASCII for the same icon, skip it if
// the icon is already added.
boolean added = false;
for (int j = 0; j < i; j++) {
if (icons[i] == icons[j]) {
added = true;
break;
}
}
if (!added) {
HashMap<String, Object> entry = new HashMap<String, Object>();
entry.put("icon", icons[i]);
entry.put("name", names[i]);
entry.put("text", texts[i]);
entries.add(entry);
}
}
final SimpleAdapter a = new SimpleAdapter(
this,
entries,
R.layout.smiley_menu_item,
new String[] {"icon", "name", "text"},
new int[] {R.id.smiley_icon, R.id.smiley_name, R.id.smiley_text});
SimpleAdapter.ViewBinder viewBinder = new SimpleAdapter.ViewBinder() {
@Override
public boolean setViewValue(View view, Object data, String textRepresentation) {
if (view instanceof ImageView) {
Drawable img = getResources().getDrawable((Integer)data);
((ImageView)view).setImageDrawable(img);
return true;
}
return false;
}
};
a.setViewBinder(viewBinder);
AlertDialog.Builder b = new AlertDialog.Builder(this);
b.setTitle(getString(R.string.menu_insert_smiley));
b.setCancelable(true);
b.setAdapter(a, new DialogInterface.OnClickListener() {
@Override
@SuppressWarnings("unchecked")
public final void onClick(DialogInterface dialog, int which) {
HashMap<String, Object> item = (HashMap<String, Object>) a.getItem(which);
EditText mToInsert;
String smiley = (String)item.get("text");
// tag EditText to insert to
if (mSubjectTextEditor != null && mSubjectTextEditor.hasFocus()) {
mToInsert = mSubjectTextEditor;
} else {
mToInsert = mTextEditor;
}
// Insert the smiley text at current cursor position in editText
// math funcs deal with text selected in either direction
//
int start = mToInsert.getSelectionStart();
int end = mToInsert.getSelectionEnd();
mToInsert.getText().replace(Math.min(start, end), Math.max(start, end), smiley);
dialog.dismiss();
}
});
mSmileyDialog = b.create();
}
mSmileyDialog.show();
}
private void showEmojiDialog() {
if (mEmojiDialog == null) {
int[] icons = EmojiParser.DEFAULT_EMOJI_RES_IDS;
int layout = R.layout.emoji_insert_view;
mEmojiView = getLayoutInflater().inflate(layout, null);
final GridView gridView = (GridView) mEmojiView.findViewById(R.id.emoji_grid_view);
gridView.setAdapter(new ImageAdapter(this, icons));
final EditText editText = (EditText) mEmojiView.findViewById(R.id.emoji_edit_text);
final Button button = (Button) mEmojiView.findViewById(R.id.emoji_button);
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences((Context) ComposeMessageActivity.this);
final boolean useSoftBankEmojiEncoding = prefs.getBoolean(MessagingPreferenceActivity.SOFTBANK_EMOJIS, false);
gridView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
// We use the new unified Unicode 6.1 emoji code points by default
CharSequence emoji;
if (useSoftBankEmojiEncoding) {
emoji = EmojiParser.getInstance().addEmojiSpans(EmojiParser.mSoftbankEmojiTexts[position]);
} else {
emoji = EmojiParser.getInstance().addEmojiSpans(EmojiParser.mEmojiTexts[position]);
}
editText.append(emoji);
}
});
gridView.setOnItemLongClickListener(new OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position,
long id) {
// We use the new unified Unicode 6.1 emoji code points by default
CharSequence emoji;
if (useSoftBankEmojiEncoding) {
emoji = EmojiParser.getInstance().addEmojiSpans(EmojiParser.mSoftbankEmojiTexts[position]);
} else {
emoji = EmojiParser.getInstance().addEmojiSpans(EmojiParser.mEmojiTexts[position]);
}
EditText mToInsert;
// tag edit text to insert to
if (mSubjectTextEditor != null && mSubjectTextEditor.hasFocus()) {
mToInsert = mSubjectTextEditor;
} else {
mToInsert = mTextEditor;
}
// insert the emoji at the cursor location or replace selected
int start = mToInsert.getSelectionStart();
int end = mToInsert.getSelectionEnd();
mToInsert.getText().replace(Math.min(start, end), Math.max(start, end), emoji);
mEmojiDialog.dismiss();
return true;
}
});
button.setOnClickListener(new android.view.View.OnClickListener() {
@Override
public void onClick(View v) {
EditText mToInsert;
// tag edit text to insert to
if (mSubjectTextEditor != null && mSubjectTextEditor.hasFocus()) {
mToInsert = mSubjectTextEditor;
} else {
mToInsert = mTextEditor;
}
// insert the emoji at the cursor location or replace selected
int start = mToInsert.getSelectionStart();
int end = mToInsert.getSelectionEnd();
mToInsert.getText().replace(Math.min(start, end), Math.max(start, end),
editText.getText());
mEmojiDialog.dismiss();
}
});
AlertDialog.Builder b = new AlertDialog.Builder(this);
b.setTitle(getString(R.string.menu_insert_emoji));
b.setCancelable(true);
b.setView(mEmojiView);
mEmojiDialog = b.create();
}
final EditText editText = (EditText) mEmojiView.findViewById(R.id.emoji_edit_text);
editText.setText("");
mEmojiDialog.show();
}
private CharSequence[] getContactInfoData(long contactId) {
final String[] projection = new String[] {
Data.DATA1, Data.DATA2, Data.DATA3, Data.MIMETYPE
};
final String where = Data.CONTACT_ID + "=? AND ("
+ Data.MIMETYPE + "=? OR "
+ Data.MIMETYPE + "=? OR "
+ Data.MIMETYPE + "=? OR "
+ Data.MIMETYPE + "=? OR "
+ Data.MIMETYPE + "=?)";
final String[] whereArgs = new String[] {
String.valueOf(contactId),
CommonDataKinds.Phone.CONTENT_ITEM_TYPE,
CommonDataKinds.Email.CONTENT_ITEM_TYPE,
CommonDataKinds.Event.CONTENT_ITEM_TYPE,
CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE,
CommonDataKinds.Website.CONTENT_ITEM_TYPE
};
final Cursor cursor = getContentResolver().query(Data.CONTENT_URI,
projection, where, whereArgs, Data.MIMETYPE);
if (cursor == null) {
return null;
}
final int count = cursor.getCount();
final int dataIndex = cursor.getColumnIndex(Data.DATA1);
final int typeIndex = cursor.getColumnIndex(Data.DATA2);
final int labelIndex = cursor.getColumnIndex(Data.DATA3);
final int mimeTypeIndex = cursor.getColumnIndex(Data.MIMETYPE);
if (count == 0) {
cursor.close();
return null;
}
final CharSequence[] entries = new CharSequence[count];
for (int i = 0; i < count; i++) {
cursor.moveToPosition(i);
String data = cursor.getString(dataIndex);
int type = cursor.getInt(typeIndex);
String label = cursor.getString(labelIndex);
String mimeType = cursor.getString(mimeTypeIndex);
if (mimeType.equals(Phone.CONTENT_ITEM_TYPE)) {
entries[i] = Phone.getTypeLabel(getResources(), type, label) + ": " + data;
} else if (mimeType.equals(Email.CONTENT_ITEM_TYPE)) {
entries[i] = Email.getTypeLabel(getResources(), type, label) + ": " + data;
} else if (mimeType.equals(Event.CONTENT_ITEM_TYPE)) {
data = DateUtils.formatDate(getApplicationContext(), data);
int typeResource = Event.getTypeResource(type);
if (typeResource != com.android.internal.R.string.eventTypeCustom) {
label = getString(typeResource);
}
entries[i] = label + ": " + data;
} else if (mimeType.equals(StructuredPostal.CONTENT_ITEM_TYPE)) {
entries[i] = StructuredPostal.getTypeLabel(getResources(), type, label)
+ ": " + data;
} else {
entries[i] = data;
}
}
cursor.close();
return entries;
}
private void showContactInfoDialog(Uri contactUri) {
long contactId = -1;
String displayName = null;
final String[] projection = new String[] {
Contacts._ID, Contacts.DISPLAY_NAME
};
final Cursor cursor = getContentResolver().query(contactUri,
projection, null, null, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
contactId = cursor.getLong(0);
displayName = cursor.getString(1);
}
cursor.close();
}
final CharSequence[] entries = (contactId >= 0) ? getContactInfoData(contactId) : null;
if (contactId < 0 || entries == null) {
Toast.makeText(this, R.string.cannot_find_contact, Toast.LENGTH_SHORT).show();
return;
}
final boolean[] itemsChecked = new boolean[entries.length];
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setIcon(R.drawable.ic_contact_picture);
builder.setTitle(displayName);
builder.setMultiChoiceItems(entries, null, new DialogInterface.OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
itemsChecked[which] = isChecked;
}
});
builder.setPositiveButton(R.string.insert_contact_info_positive_button,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
for (int i = 0; i < entries.length; i++) {
if (itemsChecked[i]) {
int start = mTextEditor.getSelectionStart();
int end = mTextEditor.getSelectionEnd();
mTextEditor.getText().replace(
Math.min(start, end), Math.max(start, end), entries[i] + "\n");
}
}
}
});
builder.setNegativeButton(android.R.string.cancel, null);
builder.show();
}
@Override
public void onUpdate(final Contact updated) {
// Using an existing handler for the post, rather than conjuring up a new one.
mMessageListItemHandler.post(new Runnable() {
@Override
public void run() {
ContactList recipients = isRecipientsEditorVisible() ?
mRecipientsEditor.constructContactsFromInput(false) : getRecipients();
if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
log("[CMA] onUpdate contact updated: " + updated);
log("[CMA] onUpdate recipients: " + recipients);
}
updateTitle(recipients);
// The contact information for one (or more) of the recipients has changed.
// Rebuild the message list so each MessageItem will get the last contact info.
ComposeMessageActivity.this.mMsgListAdapter.notifyDataSetChanged();
// Don't do this anymore. When we're showing chips, we don't want to switch from
// chips to text.
// if (mRecipientsEditor != null) {
// mRecipientsEditor.populate(recipients);
// }
}
});
}
private void addRecipientsListeners() {
Contact.addListener(this);
}
private void removeRecipientsListeners() {
Contact.removeListener(this);
}
public static Intent createIntent(Context context, long threadId) {
Intent intent = new Intent(context, ComposeMessageActivity.class);
if (threadId > 0) {
intent.setData(Conversation.getUri(threadId));
}
return intent;
}
private String getBody(Uri uri) {
if (uri == null) {
return null;
}
String urlStr = uri.getSchemeSpecificPart();
if (!urlStr.contains("?")) {
return null;
}
urlStr = urlStr.substring(urlStr.indexOf('?') + 1);
String[] params = urlStr.split("&");
for (String p : params) {
if (p.startsWith("body=")) {
try {
return URLDecoder.decode(p.substring(5), "UTF-8");
} catch (UnsupportedEncodingException e) { }
}
}
return null;
}
private void updateThreadIdIfRunning() {
if (mIsRunning && mConversation != null) {
if (DEBUG) {
Log.v(TAG, "updateThreadIdIfRunning: threadId: " +
mConversation.getThreadId());
}
MessagingNotification.setCurrentlyDisplayedThreadId(mConversation.getThreadId());
}
// If we're not running, but resume later, the current thread ID will be set in onResume()
}
private void startLoadingTemplates() {
setProgressBarIndeterminateVisibility(true);
getLoaderManager().restartLoader(LOAD_TEMPLATES, null, this);
}
private CharSequence stripUnicodeIfRequested(CharSequence text) {
if (mUnicodeFilter != null) {
text = mUnicodeFilter.filter(text);
}
return text;
}
@Override
public void onGesturePerformed(GestureOverlayView overlay, Gesture gesture) {
ArrayList<Prediction> predictions = mLibrary.recognize(gesture);
for (Prediction prediction : predictions) {
if (prediction.score > mGestureSensitivity) {
Bundle b = new Bundle();
b.putLong("id", Long.parseLong(prediction.name));
getLoaderManager().initLoader(LOAD_TEMPLATE_BY_ID, b, this);
}
}
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
if (id == LOAD_TEMPLATE_BY_ID) {
long rowID = args.getLong("id");
Uri uri = ContentUris.withAppendedId(Template.CONTENT_URI, rowID);
return new CursorLoader(this, uri, null, null, null, null);
} else {
return new CursorLoader(this, Template.CONTENT_URI, null, null, null, null);
}
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
if (loader.getId() == LOAD_TEMPLATE_BY_ID) {
if (data != null && data.getCount() > 0) {
data.moveToFirst();
// insert template text from gesture at cursor
String text = data.getString(data.getColumnIndex(Template.TEXT));
int start = mTextEditor.getSelectionStart();
int end = mTextEditor.getSelectionEnd();
mTextEditor.getText().replace(Math.min(start, end),
Math.max(start, end), text);
}
}else{
setProgressBarIndeterminateVisibility(false);
if(data != null && data.getCount() > 0){
showDialog(DIALOG_TEMPLATE_SELECT);
mTemplatesCursorAdapter.swapCursor(data);
}else{
showDialog(DIALOG_TEMPLATE_NOT_AVAILABLE);
}
}
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
}
@Override
protected Dialog onCreateDialog(int id, Bundle args) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
switch (id) {
case DIALOG_TEMPLATE_NOT_AVAILABLE:
builder.setTitle(R.string.template_not_present_error_title);
builder.setMessage(R.string.template_not_present_error);
return builder.create();
case DIALOG_TEMPLATE_SELECT:
builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.template_select);
mTemplatesCursorAdapter = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_1, null, new String[] {
Template.TEXT
}, new int[] {
android.R.id.text1
}, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
builder.setAdapter(mTemplatesCursorAdapter, new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface dialog, int which) {
Cursor c = (Cursor) mTemplatesCursorAdapter.getItem(which);
String text = c.getString(c.getColumnIndex(Template.TEXT));
// insert selected template text at the cursor location or replace selected
int start = mTextEditor.getSelectionStart();
int end = mTextEditor.getSelectionEnd();
mTextEditor.getText().replace(Math.min(start, end),
Math.max(start, end), text);
}
});
return builder.create();
}
return super.onCreateDialog(id, args);
}
private static String countDownFormat = "";
private final IntentFilter mDelaySentProgressFilter = new IntentFilter(
SmsReceiverService.ACTION_SENT_COUNT_DOWN);
private final BroadcastReceiver mDelaySentProgressReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (SmsReceiverService.ACTION_SENT_COUNT_DOWN.equals(intent.getAction())) {
int countDown = intent.getIntExtra(SmsReceiverService.DATA_COUNT_DOWN, 0);
Uri msgUri = (Uri) intent.getExtra(SmsReceiverService.DATA_MESSAGE_URI);
long msgId = ContentUris.parseId(msgUri);
MessageItem item = getMessageItem(msgUri.getAuthority(),
msgId, false);
if (item != null) {
item.setCountDown(countDown);
int iTotal = mMsgListView.getCount();
int index = 0;
while(index < iTotal) {
MessageListItem v = (MessageListItem) mMsgListView.getChildAt(index);
+ if(v == null)
+ break;
MessageItem listItem = v.getMessageItem();
if (item.equals(listItem)) {
v.updateDelayCountDown();
break;
}
index++;
}
}
}
}
};
}
| true | false | null | null |
diff --git a/de.jutzig.jabylon.properties/src/main/java/de/jutzig/jabylon/properties/impl/ProjectImpl.java b/de.jutzig.jabylon.properties/src/main/java/de/jutzig/jabylon/properties/impl/ProjectImpl.java
index 2dc12898..09bead33 100644
--- a/de.jutzig.jabylon.properties/src/main/java/de/jutzig/jabylon/properties/impl/ProjectImpl.java
+++ b/de.jutzig.jabylon.properties/src/main/java/de/jutzig/jabylon/properties/impl/ProjectImpl.java
@@ -1,395 +1,399 @@
/**
* <copyright>
* </copyright>
*
* $Id$
*/
package de.jutzig.jabylon.properties.impl;
import java.io.File;
import java.util.Collection;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.eclipse.emf.common.notify.NotificationChain;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.util.InternalEList;
import org.eclipse.emf.internal.cdo.CDOObjectImpl;
import de.jutzig.jabylon.properties.Project;
import de.jutzig.jabylon.properties.ProjectStats;
import de.jutzig.jabylon.properties.PropertiesFactory;
import de.jutzig.jabylon.properties.PropertiesPackage;
import de.jutzig.jabylon.properties.PropertyBag;
import de.jutzig.jabylon.properties.PropertyFileDescriptor;
import de.jutzig.jabylon.properties.Workspace;
import de.jutzig.jabylon.properties.util.scanner.PropertyFileAcceptor;
import de.jutzig.jabylon.properties.util.scanner.WorkspaceScanner;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Project</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* <ul>
* <li>{@link de.jutzig.jabylon.properties.impl.ProjectImpl#getName <em>Name</em>}</li>
* <li>{@link de.jutzig.jabylon.properties.impl.ProjectImpl#getPropertyBags <em>Property Bags</em>}</li>
* <li>{@link de.jutzig.jabylon.properties.impl.ProjectImpl#getWorkspace <em>Workspace</em>}</li>
* <li>{@link de.jutzig.jabylon.properties.impl.ProjectImpl#getBase <em>Base</em>}</li>
* <li>{@link de.jutzig.jabylon.properties.impl.ProjectImpl#getStats <em>Stats</em>}</li>
* </ul>
* </p>
*
* @generated
*/
public class ProjectImpl extends CDOObjectImpl implements Project {
/**
* The default value of the '{@link #getName() <em>Name</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getName()
* @generated
* @ordered
*/
protected static final String NAME_EDEFAULT = null;
/**
* The default value of the '{@link #getBase() <em>Base</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getBase()
* @generated
* @ordered
*/
protected static final URI BASE_EDEFAULT = null;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected ProjectImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return PropertiesPackage.Literals.PROJECT;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected int eStaticFeatureCount() {
return 0;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getName() {
return (String)eDynamicGet(PropertiesPackage.PROJECT__NAME, PropertiesPackage.Literals.PROJECT__NAME, true, true);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setName(String newName) {
eDynamicSet(PropertiesPackage.PROJECT__NAME, PropertiesPackage.Literals.PROJECT__NAME, newName);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@SuppressWarnings("unchecked")
public EList<PropertyBag> getPropertyBags() {
return (EList<PropertyBag>)eDynamicGet(PropertiesPackage.PROJECT__PROPERTY_BAGS, PropertiesPackage.Literals.PROJECT__PROPERTY_BAGS, true, true);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Workspace getWorkspace() {
return (Workspace)eDynamicGet(PropertiesPackage.PROJECT__WORKSPACE, PropertiesPackage.Literals.PROJECT__WORKSPACE, true, true);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NotificationChain basicSetWorkspace(Workspace newWorkspace, NotificationChain msgs) {
msgs = eBasicSetContainer((InternalEObject)newWorkspace, PropertiesPackage.PROJECT__WORKSPACE, msgs);
return msgs;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setWorkspace(Workspace newWorkspace) {
eDynamicSet(PropertiesPackage.PROJECT__WORKSPACE, PropertiesPackage.Literals.PROJECT__WORKSPACE, newWorkspace);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated NOT
*/
public URI getBase() {
+ if(getWorkspace()==null)
+ return null;
+ if(getWorkspace().getRoot()==null)
+ return null;
return getWorkspace().getRoot().appendSegment(getName());
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public ProjectStats getStats() {
return (ProjectStats)eDynamicGet(PropertiesPackage.PROJECT__STATS, PropertiesPackage.Literals.PROJECT__STATS, true, true);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NotificationChain basicSetStats(ProjectStats newStats, NotificationChain msgs) {
msgs = eDynamicInverseAdd((InternalEObject)newStats, PropertiesPackage.PROJECT__STATS, msgs);
return msgs;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setStats(ProjectStats newStats) {
eDynamicSet(PropertiesPackage.PROJECT__STATS, PropertiesPackage.Literals.PROJECT__STATS, newStats);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated NOT
*/
public void fullScan() {
getPropertyBags().clear();
WorkspaceScanner scanner = new WorkspaceScanner();
scanner.fullScan(new FileAcceptor(), this);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@SuppressWarnings("unchecked")
@Override
public NotificationChain eInverseAdd(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
switch (featureID) {
case PropertiesPackage.PROJECT__PROPERTY_BAGS:
return ((InternalEList<InternalEObject>)(InternalEList<?>)getPropertyBags()).basicAdd(otherEnd, msgs);
case PropertiesPackage.PROJECT__WORKSPACE:
if (eInternalContainer() != null)
msgs = eBasicRemoveFromContainer(msgs);
return basicSetWorkspace((Workspace)otherEnd, msgs);
}
return super.eInverseAdd(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
switch (featureID) {
case PropertiesPackage.PROJECT__PROPERTY_BAGS:
return ((InternalEList<?>)getPropertyBags()).basicRemove(otherEnd, msgs);
case PropertiesPackage.PROJECT__WORKSPACE:
return basicSetWorkspace(null, msgs);
case PropertiesPackage.PROJECT__STATS:
return basicSetStats(null, msgs);
}
return super.eInverseRemove(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public NotificationChain eBasicRemoveFromContainerFeature(NotificationChain msgs) {
switch (eContainerFeatureID()) {
case PropertiesPackage.PROJECT__WORKSPACE:
return eInternalContainer().eInverseRemove(this, PropertiesPackage.WORKSPACE__PROJECTS, Workspace.class, msgs);
}
return super.eBasicRemoveFromContainerFeature(msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case PropertiesPackage.PROJECT__NAME:
return getName();
case PropertiesPackage.PROJECT__PROPERTY_BAGS:
return getPropertyBags();
case PropertiesPackage.PROJECT__WORKSPACE:
return getWorkspace();
case PropertiesPackage.PROJECT__BASE:
return getBase();
case PropertiesPackage.PROJECT__STATS:
return getStats();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@SuppressWarnings("unchecked")
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case PropertiesPackage.PROJECT__NAME:
setName((String)newValue);
return;
case PropertiesPackage.PROJECT__PROPERTY_BAGS:
getPropertyBags().clear();
getPropertyBags().addAll((Collection<? extends PropertyBag>)newValue);
return;
case PropertiesPackage.PROJECT__WORKSPACE:
setWorkspace((Workspace)newValue);
return;
case PropertiesPackage.PROJECT__STATS:
setStats((ProjectStats)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case PropertiesPackage.PROJECT__NAME:
setName(NAME_EDEFAULT);
return;
case PropertiesPackage.PROJECT__PROPERTY_BAGS:
getPropertyBags().clear();
return;
case PropertiesPackage.PROJECT__WORKSPACE:
setWorkspace((Workspace)null);
return;
case PropertiesPackage.PROJECT__STATS:
setStats((ProjectStats)null);
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case PropertiesPackage.PROJECT__NAME:
return NAME_EDEFAULT == null ? getName() != null : !NAME_EDEFAULT.equals(getName());
case PropertiesPackage.PROJECT__PROPERTY_BAGS:
return !getPropertyBags().isEmpty();
case PropertiesPackage.PROJECT__WORKSPACE:
return getWorkspace() != null;
case PropertiesPackage.PROJECT__BASE:
return BASE_EDEFAULT == null ? getBase() != null : !BASE_EDEFAULT.equals(getBase());
case PropertiesPackage.PROJECT__STATS:
return getStats() != null;
}
return super.eIsSet(featureID);
}
class FileAcceptor implements PropertyFileAcceptor
{
@Override
public void newMatch(File file) {
PropertyBag propertyBag = PropertiesFactory.eINSTANCE.createPropertyBag();
PropertyFileDescriptor descriptor = PropertiesFactory.eINSTANCE.createPropertyFileDescriptor();
descriptor.setName(file.getName());
propertyBag.getDescriptors().add(descriptor);
String absolutePath = file.getParentFile().getAbsolutePath();
URI bagURI = URI.createFileURI(absolutePath);
bagURI = bagURI.deresolve(getBase());
propertyBag.setPath(bagURI);
Pattern pattern = buildPatternFrom(file);
File folder = file.getParentFile();
String[] childNames = folder.list();
for (String child : childNames) {
if(child.equals(file.getName()))
continue;
Matcher matcher = pattern.matcher(child);
if(matcher.matches())
{
PropertyFileDescriptor fileDescriptor = PropertiesFactory.eINSTANCE.createPropertyFileDescriptor();
fileDescriptor.setBag(propertyBag);
fileDescriptor.setName(child);
Locale locale = createVariant(matcher.group(1).substring(1));
fileDescriptor.setVariant(locale);
}
}
getPropertyBags().add(propertyBag);
}
private Locale createVariant(String localeString) {
return (Locale) PropertiesFactory.eINSTANCE.createFromString(PropertiesPackage.Literals.LOCALE, localeString);
}
private Pattern buildPatternFrom(File file) {
int separator = file.getName().lastIndexOf(".");
String prefix = file.getName().substring(0,separator);
String suffix = file.getName().substring(separator);
return Pattern.compile(Pattern.quote(prefix) + "((_\\w\\w){1,3})"+Pattern.quote(suffix)); //messages.properties => messages_de_DE.properties
}
}
} //ProjectImpl
| true | false | null | null |
diff --git a/morphia/src/test/java/com/google/code/morphia/TestMapping.java b/morphia/src/test/java/com/google/code/morphia/TestMapping.java
index d3bbe0b..93985e8 100644
--- a/morphia/src/test/java/com/google/code/morphia/TestMapping.java
+++ b/morphia/src/test/java/com/google/code/morphia/TestMapping.java
@@ -1,811 +1,840 @@
/**
* Copyright (C) 2010 Olafur Gauti Gudmundsson
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.code.morphia;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.io.Serializable;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
+import java.util.Set;
import java.util.UUID;
import java.util.Vector;
import org.bson.types.ObjectId;
import org.junit.Ignore;
import org.junit.Test;
import com.google.code.morphia.annotations.AlsoLoad;
import com.google.code.morphia.annotations.Embedded;
import com.google.code.morphia.annotations.Entity;
import com.google.code.morphia.annotations.Id;
import com.google.code.morphia.annotations.Serialized;
import com.google.code.morphia.mapping.Mapper;
import com.google.code.morphia.mapping.MappingException;
import com.google.code.morphia.mapping.cache.DefaultEntityCache;
import com.google.code.morphia.testmodel.Address;
import com.google.code.morphia.testmodel.Article;
import com.google.code.morphia.testmodel.Circle;
import com.google.code.morphia.testmodel.Hotel;
import com.google.code.morphia.testmodel.PhoneNumber;
import com.google.code.morphia.testmodel.Rectangle;
import com.google.code.morphia.testmodel.RecursiveChild;
import com.google.code.morphia.testmodel.RecursiveParent;
import com.google.code.morphia.testmodel.Translation;
import com.google.code.morphia.testmodel.TravelAgency;
import com.google.code.morphia.testutil.AssertedFailure;
import com.mongodb.BasicDBObject;
import com.mongodb.BasicDBObjectBuilder;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.DBRef;
/**
* @author Olafur Gauti Gudmundsson
* @author Scott Hernandez
*/
@SuppressWarnings({"unchecked", "rawtypes", "unused"})
public class TestMapping extends TestBase {
@Entity
private static class MissingId {
String id;
}
private static class MissingIdStill {
String id;
}
@Entity("no-id")
private static class MissingIdRenamed {
String id;
}
@Embedded
public static class IdOnEmbedded {
@Id ObjectId id;
}
@Embedded("no-id")
public static class RenamedEmbedded {
String name;
}
private static class ContainsEmbeddedArray {
@Id ObjectId id = new ObjectId();
RenamedEmbedded[] res;
}
public static class NotEmbeddable {
String noImNot = "no, I'm not";
}
public static class SerializableClass implements Serializable {
private static final long serialVersionUID = 1L;
String someString = "hi, from the ether.";
}
public static class ContainsRef {
public @Id ObjectId id;
public DBRef rect;
}
public static class HasFinalFieldId{
public final @Id long id;
public String name = "some string";
//only called when loaded by the persistence framework.
protected HasFinalFieldId() {
id = -1;
}
public HasFinalFieldId(long id) {
this.id = id;
}
}
public static class ContainsFinalField{
public @Id ObjectId id;
public final String name;
protected ContainsFinalField() {
name = "foo";
}
public ContainsFinalField(String name) {
this.name = name;
}
}
public static class ContainsTimestamp {
@Id ObjectId id;
Timestamp ts = new Timestamp(System.currentTimeMillis());
}
public static class ContainsbyteArray {
@Id ObjectId id;
byte[] bytes = "Scott".getBytes();
}
public static class ContainsSerializedData{
@Id ObjectId id;
@Serialized SerializableClass data = new SerializableClass();
}
public static class ContainsLongAndStringArray {
@Id ObjectId id;
private Long[] longs = {0L, 1L, 2L};
String[] strings = {"Scott", "Rocks"};
}
public static class ContainsCollection {
@Id ObjectId id;
Collection<String> coll = new ArrayList<String>();
private ContainsCollection() {
coll.add("hi"); coll.add("Scott");
}
}
public static class ContainsPrimitiveMap{
@Id ObjectId id;
@Embedded public Map<String, Long> embeddedValues = new HashMap();
public Map<String, Long> values = new HashMap();
}
public static class ContainsEmbeddedEntity{
@Id ObjectId id = new ObjectId();
@Embedded ContainsIntegerList cil = new ContainsIntegerList();
}
public enum Enum1 { A, B }
@Entity(value="cil", noClassnameStored=true)
public static class ContainsIntegerList {
@Id ObjectId id;
List<Integer> intList = new ArrayList<Integer>();
}
public static class ContainsIntegerListNewAndOld {
@Id ObjectId id;
List<Integer> intList = new ArrayList<Integer>();
List<Integer> ints = new ArrayList<Integer>();
}
@Entity(value="cil", noClassnameStored=true)
public static class ContainsIntegerListNew {
@Id ObjectId id;
@AlsoLoad("intList") List<Integer> ints = new ArrayList<Integer>();
}
@Entity(noClassnameStored=true)
private static class ContainsUUID {
@Id ObjectId id;
UUID uuid = UUID.randomUUID();
}
@Entity(noClassnameStored=true)
private static class ContainsUuidId {
@Id UUID id = UUID.randomUUID();
}
public static class ContainsEnum1KeyMap{
@Id ObjectId id;
public Map<Enum1, String> values = new HashMap<Enum1,String>();
@Embedded
public Map<Enum1, String> embeddedValues = new HashMap<Enum1,String>();
}
- public static class ContainsIntKeyMap{
+ public static class ContainsIntKeyMap {
@Id ObjectId id;
public Map<Integer, String> values = new HashMap<Integer,String>();
}
+
+ public static class ContainsIntKeySetStringMap {
+ @Id ObjectId id;
+ @Embedded
+ public Map<Integer, Set<String>> values = new HashMap<Integer,Set<String>>();
+ }
public static class ContainsObjectIdKeyMap{
@Id ObjectId id;
public Map<ObjectId, String> values = new HashMap<ObjectId,String>();
}
public static class ContainsXKeyMap<T>{
@Id ObjectId id;
public Map<T, String> values = new HashMap<T,String>();
}
public static abstract class BaseEntity implements Serializable{
private static final long serialVersionUID = 1L;
public BaseEntity() {}
@Id ObjectId id;
public String getId() {
return id.toString();
}
public void setId(String id) {
this.id = new ObjectId(id);
}
}
@Entity
public static class UsesBaseEntity extends BaseEntity{
private static final long serialVersionUID = 1L;
}
public static class MapSubclass extends LinkedHashMap<String, Object> {
private static final long serialVersionUID = 1L;
@Id ObjectId id;
}
@Test
public void testUUID() throws Exception {
morphia.map(ContainsUUID.class);
ContainsUUID cuuid = new ContainsUUID();
UUID before = cuuid.uuid;
ds.save(cuuid);
ContainsUUID loaded = ds.find(ContainsUUID.class).get();
assertNotNull(loaded);
assertNotNull(loaded.id);
assertNotNull(loaded.uuid);
assertEquals(before, loaded.uuid);
}
@Test
public void testUuidId() throws Exception {
morphia.map(ContainsUuidId.class);
ContainsUuidId cuuidId = new ContainsUuidId();
UUID before = cuuidId.id;
Key<ContainsUuidId> key = ds.save(cuuidId);
ContainsUuidId loaded = ds.get(ContainsUuidId.class, before);
assertNotNull(loaded);
assertNotNull(loaded.id);
assertEquals(before, loaded.id);
}
@Test
public void testEmbeddedEntity() throws Exception {
morphia.map(ContainsEmbeddedEntity.class);
ContainsEmbeddedEntity cee = new ContainsEmbeddedEntity();
ds.save(cee);
ContainsEmbeddedEntity ceeLoaded = ds.find(ContainsEmbeddedEntity.class).get();
assertNotNull(ceeLoaded);
assertNotNull(ceeLoaded.id);
assertNotNull(ceeLoaded.cil);
assertNull(ceeLoaded.cil.id);
}
@Test
public void testEmbeddedArrayElementHasNoClassname() throws Exception {
morphia.map(ContainsEmbeddedArray.class);
ContainsEmbeddedArray cea = new ContainsEmbeddedArray();
cea.res = new RenamedEmbedded[] { new RenamedEmbedded() };
DBObject dbObj = morphia.toDBObject(cea);
assertTrue(!((DBObject)((List)dbObj.get("res")).get(0)).containsField(Mapper.CLASS_NAME_FIELDNAME));
}
@Test
public void testEmbeddedEntityDBObjectHasNoClassname() throws Exception {
morphia.map(ContainsEmbeddedEntity.class);
ContainsEmbeddedEntity cee = new ContainsEmbeddedEntity();
cee.cil = new ContainsIntegerList();
cee.cil.intList = Collections.singletonList(1);
DBObject dbObj = morphia.toDBObject(cee);
assertTrue(!((DBObject)dbObj.get("cil")).containsField(Mapper.CLASS_NAME_FIELDNAME));
}
@Test
public void testEnumKeyedMap() throws Exception {
ContainsEnum1KeyMap map = new ContainsEnum1KeyMap();
map.values.put(Enum1.A,"I'm a");
map.values.put(Enum1.B,"I'm b");
map.embeddedValues.put(Enum1.A,"I'm a");
map.embeddedValues.put(Enum1.B,"I'm b");
Key<?> mapKey = ds.save(map);
ContainsEnum1KeyMap mapLoaded = ds.get(ContainsEnum1KeyMap.class, mapKey.getId());
assertNotNull(mapLoaded);
assertEquals(2,mapLoaded.values.size());
assertNotNull(mapLoaded.values.get(Enum1.A));
assertNotNull(mapLoaded.values.get(Enum1.B));
assertEquals(2,mapLoaded.embeddedValues.size());
assertNotNull(mapLoaded.embeddedValues.get(Enum1.A));
assertNotNull(mapLoaded.embeddedValues.get(Enum1.B));
}
@Test
public void testAlsoLoad() throws Exception {
ContainsIntegerList cil = new ContainsIntegerList();
cil.intList.add(1);
ds.save(cil);
ContainsIntegerList cilLoaded = ds.get(cil);
assertNotNull(cilLoaded);
assertNotNull(cilLoaded.intList);
assertEquals(cilLoaded.intList.size(), cil.intList.size());
assertEquals(cilLoaded.intList.get(0), cil.intList.get(0));
ContainsIntegerListNew cilNew = ds.get(ContainsIntegerListNew.class, cil.id);
assertNotNull(cilNew);
assertNotNull(cilNew.ints);
assertEquals(cilNew.ints.size(), 1);
assertEquals(1, (int)cil.intList.get(0));
}
@Test
public void testIntLists() throws Exception {
ContainsIntegerList cil = new ContainsIntegerList();
ds.save(cil);
ContainsIntegerList cilLoaded = ds.get(cil);
assertNotNull(cilLoaded);
assertNotNull(cilLoaded.intList);
assertEquals(cilLoaded.intList.size(), cil.intList.size());
cil = new ContainsIntegerList();
cil.intList = null;
ds.save(cil);
cilLoaded = ds.get(cil);
assertNotNull(cilLoaded);
assertNotNull(cilLoaded.intList);
assertEquals(cilLoaded.intList.size(), 0);
cil = new ContainsIntegerList();
cil.intList.add(1);
ds.save(cil);
cilLoaded = ds.get(cil);
assertNotNull(cilLoaded);
assertNotNull(cilLoaded.intList);
assertEquals(cilLoaded.intList.size(), 1);
assertEquals(1,(int)cilLoaded.intList.get(0));
}
@Test
public void testObjectIdKeyedMap() throws Exception {
ContainsObjectIdKeyMap map = new ContainsObjectIdKeyMap();
ObjectId o1 = new ObjectId("111111111111111111111111");
ObjectId o2 = new ObjectId("222222222222222222222222");
map.values.put(o1,"I'm 1s");
map.values.put(o2,"I'm 2s");
Key<?> mapKey = ds.save(map);
ContainsObjectIdKeyMap mapLoaded = ds.get(ContainsObjectIdKeyMap.class, mapKey.getId());
assertNotNull(mapLoaded);
assertEquals(2,mapLoaded.values.size());
assertNotNull(mapLoaded.values.get(o1));
assertNotNull(mapLoaded.values.get(o2));
assertNotNull(ds.find(ContainsIntKeyMap.class).field("values.111111111111111111111111").exists());
assertEquals(0, ds.find(ContainsIntKeyMap.class).field("values.111111111111111111111111").doesNotExist().countAll());
assertNotNull(ds.find(ContainsIntKeyMap.class).field("values.4").doesNotExist());
assertEquals(0, ds.find(ContainsIntKeyMap.class).field("values.4").exists().countAll());
}
@Test
public void testIntKeyedMap() throws Exception {
ContainsIntKeyMap map = new ContainsIntKeyMap ();
map.values.put(1,"I'm 1");
map.values.put(2,"I'm 2");
Key<?> mapKey = ds.save(map);
ContainsIntKeyMap mapLoaded = ds.get(ContainsIntKeyMap.class, mapKey.getId());
assertNotNull(mapLoaded);
assertEquals(2,mapLoaded.values.size());
assertNotNull(mapLoaded.values.get(1));
assertNotNull(mapLoaded.values.get(2));
assertNotNull(ds.find(ContainsIntKeyMap.class).field("values.2").exists());
assertEquals(0, ds.find(ContainsIntKeyMap.class).field("values.2").doesNotExist().countAll());
assertNotNull(ds.find(ContainsIntKeyMap.class).field("values.4").doesNotExist());
assertEquals(0, ds.find(ContainsIntKeyMap.class).field("values.4").exists().countAll());
}
+ @Test
+ public void testIntKeySetStringMap() throws Exception {
+ ContainsIntKeySetStringMap map = new ContainsIntKeySetStringMap();
+ map.values.put(1, Collections.singleton("I'm 1"));
+ map.values.put(2, Collections.singleton("I'm 2"));
+
+ Key<?> mapKey = ds.save(map);
+
+ ContainsIntKeySetStringMap mapLoaded = ds.get(ContainsIntKeySetStringMap.class, mapKey.getId());
+
+ assertNotNull(mapLoaded);
+ assertEquals(2,mapLoaded.values.size());
+ assertNotNull(mapLoaded.values.get(1));
+ assertNotNull(mapLoaded.values.get(2));
+ assertEquals(1,mapLoaded.values.get(1).size());
+
+ assertNotNull(ds.find(ContainsIntKeyMap.class).field("values.2").exists());
+ assertEquals(0, ds.find(ContainsIntKeyMap.class).field("values.2").doesNotExist().countAll());
+ assertNotNull(ds.find(ContainsIntKeyMap.class).field("values.4").doesNotExist());
+ assertEquals(0, ds.find(ContainsIntKeyMap.class).field("values.4").exists().countAll());
+ }
+
@Test @Ignore("need to add this feature; closer after changes in 0.97")
public void testGenericKeyedMap() throws Exception {
ContainsXKeyMap<Integer> map = new ContainsXKeyMap<Integer>();
map.values.put(1,"I'm 1");
map.values.put(2,"I'm 2");
Key<?> mapKey = ds.save(map);
ContainsXKeyMap<Integer> mapLoaded = ds.get(ContainsXKeyMap.class, mapKey.getId());
assertNotNull(mapLoaded);
assertEquals(2,mapLoaded.values.size());
assertNotNull(mapLoaded.values.get(1));
assertNotNull(mapLoaded.values.get(2));
}
@Test
public void testPrimMap() throws Exception {
ContainsPrimitiveMap primMap = new ContainsPrimitiveMap();
primMap.embeddedValues.put("first",1L);
primMap.embeddedValues.put("second",2L);
primMap.values.put("first",1L);
primMap.values.put("second",2L);
Key<ContainsPrimitiveMap> primMapKey = ds.save(primMap);
ContainsPrimitiveMap primMapLoaded = ds.get(ContainsPrimitiveMap.class, primMapKey.getId());
assertNotNull(primMapLoaded);
assertEquals(2,primMapLoaded.embeddedValues.size());
assertEquals(2,primMapLoaded.values.size());
}
@Test
public void testFinalIdField() throws Exception {
morphia.map(HasFinalFieldId.class);
Key<HasFinalFieldId> savedKey = ds.save(new HasFinalFieldId(12));
HasFinalFieldId loaded = ds.get(HasFinalFieldId.class, savedKey.getId());
assertNotNull(loaded);
assertNotNull(loaded.id);
assertEquals(loaded.id, 12);
}
@Test
public void testFinalField() throws Exception {
morphia.map(ContainsFinalField.class);
Key<ContainsFinalField> savedKey = ds.save(new ContainsFinalField("blah"));
ContainsFinalField loaded = ds.get(ContainsFinalField.class, savedKey.getId());
assertNotNull(loaded);
assertNotNull(loaded.name);
assertEquals("blah",loaded.name);
}
@Test
public void testFinalFieldNotPersisted() throws Exception {
((DatastoreImpl)ds).getMapper().getOptions().ignoreFinals = true;
morphia.map(ContainsFinalField.class);
Key<ContainsFinalField> savedKey = ds.save(new ContainsFinalField("blah"));
ContainsFinalField loaded = ds.get(ContainsFinalField.class, savedKey.getId());
assertNotNull(loaded);
assertNotNull(loaded.name);
assertEquals("foo", loaded.name);
}
@Test
public void testTimestampMapping() throws Exception {
morphia.map(ContainsTimestamp.class);
ContainsTimestamp cts = new ContainsTimestamp();
Key<ContainsTimestamp> savedKey = ds.save(cts);
ContainsTimestamp loaded = ds.get(ContainsTimestamp.class, savedKey.getId());
assertNotNull(loaded.ts);
assertEquals(loaded.ts.getTime(), cts.ts.getTime());
}
@Test
public void testCollectionMapping() throws Exception {
morphia.map(ContainsCollection.class);
Key<ContainsCollection> savedKey = ds.save(new ContainsCollection());
ContainsCollection loaded = ds.get(ContainsCollection.class, savedKey.getId());
assertEquals(loaded.coll, (new ContainsCollection()).coll);
assertNotNull(loaded.id);
}
@Test
public void testbyteArrayMapping() throws Exception {
morphia.map(ContainsbyteArray.class);
Key<ContainsbyteArray> savedKey = ds.save(new ContainsbyteArray());
ContainsbyteArray loaded = ds.get(ContainsbyteArray.class, savedKey.getId());
assertEquals(new String(loaded.bytes), new String((new ContainsbyteArray()).bytes));
assertNotNull(loaded.id);
}
@Test
public void testBaseEntityValidity() throws Exception {
morphia.map(UsesBaseEntity.class);
}
@Test
public void testSerializedMapping() throws Exception {
morphia.map(ContainsSerializedData.class);
Key<ContainsSerializedData> savedKey = ds.save(new ContainsSerializedData());
ContainsSerializedData loaded = ds.get(ContainsSerializedData.class, savedKey.getId());
assertNotNull(loaded.data);
assertEquals(loaded.data.someString, (new ContainsSerializedData()).data.someString);
assertNotNull(loaded.id);
}
@SuppressWarnings("deprecation")
@Test
public void testLongArrayMapping() throws Exception {
morphia.map(ContainsLongAndStringArray.class);
ds.save(new ContainsLongAndStringArray());
ContainsLongAndStringArray loaded = ds.<ContainsLongAndStringArray>find(ContainsLongAndStringArray.class).get();
assertEquals(loaded.longs, (new ContainsLongAndStringArray()).longs);
assertEquals(loaded.strings, (new ContainsLongAndStringArray()).strings);
ContainsLongAndStringArray clasa = new ContainsLongAndStringArray();
clasa.strings = new String[] {"a", "B","c"};
clasa.longs = new Long[] {4L, 5L, 4L};
Key<ContainsLongAndStringArray> k1 = ds.save(clasa);
loaded = ds.getByKey(ContainsLongAndStringArray.class, k1);
assertEquals(loaded.longs, clasa.longs);
assertEquals(loaded.strings, clasa.strings);
assertNotNull(loaded.id);
}
@Test
public void testDbRefMapping() throws Exception {
morphia.map(ContainsRef.class).map(Rectangle.class);
DBCollection stuff = db.getCollection("stuff");
DBCollection rectangles = db.getCollection("rectangles");
assertTrue("'ne' field should not be persisted!", !morphia.getMapper().getMCMap().get(ContainsRef.class.getName()).containsJavaFieldName("ne"));
Rectangle r = new Rectangle(1,1);
DBObject rDbObject = morphia.toDBObject(r);
rDbObject.put("_ns", rectangles.getName());
rectangles.save(rDbObject);
ContainsRef cRef = new ContainsRef();
cRef.rect = new DBRef(null, (String)rDbObject.get("_ns"), rDbObject.get("_id"));
DBObject cRefDbOject = morphia.toDBObject(cRef);
stuff.save(cRefDbOject);
BasicDBObject cRefDbObjectLoaded =(BasicDBObject)stuff.findOne(BasicDBObjectBuilder.start("_id", cRefDbOject.get("_id")).get());
ContainsRef cRefLoaded = morphia.fromDBObject(ContainsRef.class, cRefDbObjectLoaded, new DefaultEntityCache());
assertNotNull(cRefLoaded);
assertNotNull(cRefLoaded.rect);
assertNotNull(cRefLoaded.rect.getId());
assertNotNull(cRefLoaded.rect.getRef());
assertEquals(cRefLoaded.rect.getId(), cRef.rect.getId());
assertEquals(cRefLoaded.rect.getRef(), cRef.rect.getRef());
}
@Test
public void testBadMappings() throws Exception {
boolean allGood=false;
try {
morphia.map(MissingId.class);
} catch (MappingException e) {
allGood = true;
}
assertTrue("Validation: Missing @Id field not caught", allGood);
allGood = false;
try {
morphia.map(IdOnEmbedded.class);
} catch (MappingException e) {
allGood = true;
}
assertTrue("Validation: @Id field on @Embedded not caught", allGood);
allGood = false;
try {
morphia.map(RenamedEmbedded.class);
} catch (MappingException e) {
allGood = true;
}
assertTrue("Validation: @Embedded(\"name\") not caught on Class", allGood);
allGood = false;
try {
morphia.map(MissingIdStill.class);
} catch (MappingException e) {
allGood = true;
}
assertTrue("Validation: Missing @Id field not not caught", allGood);
allGood = false;
try {
morphia.map(MissingIdRenamed.class);
} catch (MappingException e) {
allGood = true;
}
assertTrue("Validation: Missing @Id field not not caught", allGood);
}
@Test
public void testBasicMapping() throws Exception {
try {
DBCollection hotels = db.getCollection("hotels");
DBCollection agencies = db.getCollection("agencies");
morphia.map(Hotel.class);
morphia.map(TravelAgency.class);
Hotel borg = Hotel.create();
borg.setName("Hotel Borg");
borg.setStars(4);
borg.setTakesCreditCards(true);
borg.setStartDate(new Date());
borg.setType(Hotel.Type.LEISURE);
borg.getTags().add("Swimming pool");
borg.getTags().add("Room service");
borg.setTemp("A temporary transient value");
borg.getPhoneNumbers().add(new PhoneNumber(354,5152233,PhoneNumber.Type.PHONE));
borg.getPhoneNumbers().add(new PhoneNumber(354,5152244,PhoneNumber.Type.FAX));
Address borgAddr = new Address();
borgAddr.setStreet("Posthusstraeti 11");
borgAddr.setPostCode("101");
borg.setAddress(borgAddr);
BasicDBObject hotelDbObj = (BasicDBObject) morphia.toDBObject(borg);
assertTrue( !( ((DBObject)((List)hotelDbObj.get("phoneNumbers")).get(0)).containsField(Mapper.CLASS_NAME_FIELDNAME)) );
hotels.save(hotelDbObj);
Hotel borgLoaded = morphia.fromDBObject(Hotel.class, hotelDbObj, new DefaultEntityCache());
assertEquals(borg.getName(), borgLoaded.getName());
assertEquals(borg.getStars(), borgLoaded.getStars());
assertEquals(borg.getStartDate(), borgLoaded.getStartDate());
assertEquals(borg.getType(), borgLoaded.getType());
assertEquals(borg.getAddress().getStreet(), borgLoaded.getAddress().getStreet());
assertEquals(borg.getTags().size(), borgLoaded.getTags().size());
assertEquals(borg.getTags(), borgLoaded.getTags());
assertEquals(borg.getPhoneNumbers().size(), borgLoaded.getPhoneNumbers().size());
assertEquals(borg.getPhoneNumbers().get(1), borgLoaded.getPhoneNumbers().get(1));
assertNull(borgLoaded.getTemp());
assertTrue(borgLoaded.getPhoneNumbers() instanceof Vector);
assertNotNull(borgLoaded.getId());
TravelAgency agency = new TravelAgency();
agency.setName("Lastminute.com");
agency.getHotels().add(borgLoaded);
BasicDBObject agencyDbObj = (BasicDBObject) morphia.toDBObject(agency);
agencies.save(agencyDbObj);
TravelAgency agencyLoaded = morphia.fromDBObject(TravelAgency.class,
(BasicDBObject) agencies.findOne(new BasicDBObject(Mapper.ID_KEY, agencyDbObj.get(Mapper.ID_KEY))),
new DefaultEntityCache());
assertEquals(agency.getName(), agencyLoaded.getName());
assertEquals(agency.getHotels().size(), 1);
assertEquals(agency.getHotels().get(0).getName(), borg.getName());
// try clearing values
borgLoaded.setAddress(null);
borgLoaded.getPhoneNumbers().clear();
borgLoaded.setName(null);
hotelDbObj = (BasicDBObject) morphia.toDBObject(borgLoaded);
hotels.save(hotelDbObj);
hotelDbObj = (BasicDBObject)hotels.findOne(new BasicDBObject(Mapper.ID_KEY, hotelDbObj.get(Mapper.ID_KEY)));
borgLoaded = morphia.fromDBObject(Hotel.class, hotelDbObj, new DefaultEntityCache());
assertNull(borgLoaded.getAddress());
assertEquals(0, borgLoaded.getPhoneNumbers().size());
assertNull(borgLoaded.getName());
} finally {
db.dropDatabase();
}
}
@Test
public void testMaps() throws Exception {
try {
DBCollection articles = db.getCollection("articles");
morphia.map(Article.class).map(Translation.class).map(Circle.class);
Article related = new Article();
BasicDBObject relatedDbObj = (BasicDBObject) morphia.toDBObject(related);
articles.save(relatedDbObj);
Article relatedLoaded = morphia
.fromDBObject(Article.class, (BasicDBObject) articles.findOne(new BasicDBObject(Mapper.ID_KEY,
relatedDbObj.get(Mapper.ID_KEY))), new DefaultEntityCache());
Article article = new Article();
article.setTranslation("en", new Translation("Hello World", "Just a test"));
article.setTranslation("is", new Translation("Halló heimur", "Bara að prófa"));
article.setAttribute("myDate", new Date());
article.setAttribute("myString", "Test");
article.setAttribute("myInt", 123);
article.putRelated("test", relatedLoaded);
BasicDBObject articleDbObj = (BasicDBObject) morphia.toDBObject(article);
articles.save(articleDbObj);
Article articleLoaded = morphia
.fromDBObject(Article.class, (BasicDBObject) articles.findOne(new BasicDBObject(Mapper.ID_KEY,
articleDbObj.get(Mapper.ID_KEY))), new DefaultEntityCache());
assertEquals(article.getTranslations().size(), articleLoaded.getTranslations().size());
assertEquals(article.getTranslation("en").getTitle(), articleLoaded.getTranslation("en").getTitle());
assertEquals(article.getTranslation("is").getBody(), articleLoaded.getTranslation("is").getBody());
assertEquals(article.getAttributes().size(), articleLoaded.getAttributes().size());
assertEquals(article.getAttribute("myDate"), articleLoaded.getAttribute("myDate"));
assertEquals(article.getAttribute("myString"), articleLoaded.getAttribute("myString"));
assertEquals(article.getAttribute("myInt"), articleLoaded.getAttribute("myInt"));
assertEquals(article.getRelated().size(), articleLoaded.getRelated().size());
assertEquals(article.getRelated("test").getId(), articleLoaded.getRelated("test").getId());
} finally {
db.dropDatabase();
}
}
@Test
public void testReferenceWithoutIdValue() throws Exception {
new AssertedFailure(MappingException.class) {
public void thisMustFail() throws Throwable {
RecursiveParent parent = new RecursiveParent();
RecursiveChild child = new RecursiveChild();
child.setId(null);
parent.setChild(child);
ds.save(parent);
}
};
}
@Test
public void testRecursiveReference() throws Exception {
DBCollection stuff = db.getCollection("stuff");
morphia.map(RecursiveParent.class).map(RecursiveChild.class);
RecursiveParent parent = new RecursiveParent();
BasicDBObject parentDbObj = (BasicDBObject) morphia.toDBObject(parent);
stuff.save(parentDbObj);
RecursiveChild child = new RecursiveChild();
BasicDBObject childDbObj = (BasicDBObject) morphia.toDBObject(child);
stuff.save(childDbObj);
RecursiveParent parentLoaded = morphia.fromDBObject(RecursiveParent.class,
(BasicDBObject) stuff.findOne(new BasicDBObject(Mapper.ID_KEY, parentDbObj.get(Mapper.ID_KEY))),
new DefaultEntityCache());
RecursiveChild childLoaded = morphia.fromDBObject(RecursiveChild.class,
(BasicDBObject) stuff.findOne(new BasicDBObject(Mapper.ID_KEY, childDbObj.get(Mapper.ID_KEY))),
new DefaultEntityCache());
parentLoaded.setChild(childLoaded);
childLoaded.setParent(parentLoaded);
stuff.save(morphia.toDBObject(parentLoaded));
stuff.save(morphia.toDBObject(childLoaded));
RecursiveParent finalParentLoaded = morphia.fromDBObject(RecursiveParent.class,
(BasicDBObject) stuff.findOne(new BasicDBObject(Mapper.ID_KEY, parentDbObj.get(Mapper.ID_KEY))),
new DefaultEntityCache());
RecursiveChild finalChildLoaded = morphia.fromDBObject(RecursiveChild.class,
(BasicDBObject) stuff.findOne(new BasicDBObject(Mapper.ID_KEY, childDbObj.get(Mapper.ID_KEY))),
new DefaultEntityCache());
assertNotNull(finalParentLoaded.getChild());
assertNotNull(finalChildLoaded.getParent());
}
}
| false | false | null | null |
diff --git a/modules/activiti-engine/src/main/java/org/activiti/engine/impl/bpmn/diagram/ProcessDiagramCanvas.java b/modules/activiti-engine/src/main/java/org/activiti/engine/impl/bpmn/diagram/ProcessDiagramCanvas.java
index 2a22798e..7d7ec960 100644
--- a/modules/activiti-engine/src/main/java/org/activiti/engine/impl/bpmn/diagram/ProcessDiagramCanvas.java
+++ b/modules/activiti-engine/src/main/java/org/activiti/engine/impl/bpmn/diagram/ProcessDiagramCanvas.java
@@ -1,593 +1,593 @@
/* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.activiti.engine.impl.bpmn.diagram;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Paint;
import java.awt.Polygon;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.Stroke;
import java.awt.geom.AffineTransform;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import org.activiti.engine.ActivitiException;
import org.activiti.engine.impl.util.IoUtil;
import org.activiti.engine.impl.util.ReflectUtil;
/**
* Represents a canvas on which BPMN 2.0 constructs can be drawn.
*
* Some of the icons used are licenced under a Creative Commons Attribution 2.5
* License, see http://www.famfamfam.com/lab/icons/silk/
*
* @see ProcessDiagramGenerator
* @author Joram Barrez
*/
public class ProcessDiagramCanvas {
protected static final Logger LOGGER = Logger.getLogger(ProcessDiagramCanvas.class.getName());
// Predefined sized
protected static final int ARROW_WIDTH = 5;
protected static final int CONDITIONAL_INDICATOR_WIDTH = 16;
protected static final int MARKER_WIDTH = 12;
// Colors
protected static Color TASK_COLOR = new Color(255, 255, 204);
protected static Color BOUNDARY_EVENT_COLOR = new Color(255, 255, 255);
protected static Color CONDITIONAL_INDICATOR_COLOR = new Color(255, 255, 255);
protected static Color HIGHLIGHT_COLOR = Color.RED;
// Strokes
protected static Stroke THICK_TASK_BORDER_STROKE = new BasicStroke(3.0f);
protected static Stroke GATEWAY_TYPE_STROKE = new BasicStroke(3.0f);
protected static Stroke END_EVENT_STROKE = new BasicStroke(3.0f);
protected static Stroke MULTI_INSTANCE_STROKE = new BasicStroke(1.3f);
protected static Stroke EVENT_SUBPROCESS_STROKE = new BasicStroke(1.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 1.0f, new float[] { 1.0f }, 0.0f);
// icons
protected static int ICON_SIZE = 16;
protected static Image USERTASK_IMAGE;
protected static Image SCRIPTTASK_IMAGE;
protected static Image SERVICETASK_IMAGE;
protected static Image RECEIVETASK_IMAGE;
protected static Image SENDTASK_IMAGE;
protected static Image MANUALTASK_IMAGE;
protected static Image BUSINESS_RULE_TASK_IMAGE;
protected static Image TIMER_IMAGE;
protected static Image ERROR_THROW_IMAGE;
protected static Image ERROR_CATCH_IMAGE;
protected static Image SIGNAL_CATCH_IMAGE;
protected static Image SIGNAL_THROW_IMAGE;
// icons are statically loaded for performace
static {
try {
USERTASK_IMAGE = ImageIO.read(ReflectUtil.getResourceAsStream("org/activiti/engine/impl/bpmn/deployer/user.png"));
SCRIPTTASK_IMAGE = ImageIO.read(ReflectUtil.getResourceAsStream("org/activiti/engine/impl/bpmn/deployer/script.png"));
SERVICETASK_IMAGE = ImageIO.read(ReflectUtil.getResourceAsStream("org/activiti/engine/impl/bpmn/deployer/service.png"));
RECEIVETASK_IMAGE = ImageIO.read(ReflectUtil.getResourceAsStream("org/activiti/engine/impl/bpmn/deployer/receive.png"));
SENDTASK_IMAGE = ImageIO.read(ReflectUtil.getResourceAsStream("org/activiti/engine/impl/bpmn/deployer/send.png"));
MANUALTASK_IMAGE = ImageIO.read(ReflectUtil.getResourceAsStream("org/activiti/engine/impl/bpmn/deployer/manual.png"));
BUSINESS_RULE_TASK_IMAGE = ImageIO.read(ReflectUtil.getResourceAsStream("org/activiti/engine/impl/bpmn/deployer/business_rule.png"));
TIMER_IMAGE = ImageIO.read(ReflectUtil.getResourceAsStream("org/activiti/engine/impl/bpmn/deployer/timer.png"));
ERROR_THROW_IMAGE = ImageIO.read(ReflectUtil.getResourceAsStream("org/activiti/engine/impl/bpmn/deployer/error_throw.png"));
ERROR_CATCH_IMAGE = ImageIO.read(ReflectUtil.getResourceAsStream("org/activiti/engine/impl/bpmn/deployer/error_catch.png"));
SIGNAL_CATCH_IMAGE = ImageIO.read(ReflectUtil.getResourceAsStream("org/activiti/engine/impl/bpmn/deployer/signal_catch.png"));
SIGNAL_THROW_IMAGE = ImageIO.read(ReflectUtil.getResourceAsStream("org/activiti/engine/impl/bpmn/deployer/signal_throw.png"));
} catch (IOException e) {
LOGGER.warning("Could not load image for process diagram creation: " + e.getMessage());
}
}
protected int canvasWidth = -1;
protected int canvasHeight = -1;
protected int minX = -1;
protected int minY = -1;
protected BufferedImage processDiagram;
protected Graphics2D g;
protected FontMetrics fontMetrics;
protected boolean closed;
/**
* Creates an empty canvas with given width and height.
*/
public ProcessDiagramCanvas(int width, int height) {
this.canvasWidth = width;
this.canvasHeight = height;
this.processDiagram = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
this.g = processDiagram.createGraphics();
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setPaint(Color.black);
Font font = new Font("Arial", Font.BOLD, 11);
g.setFont(font);
this.fontMetrics = g.getFontMetrics();
}
/**
* Creates an empty canvas with given width and height.
*
* Allows to specify minimal boundaries on the left and upper side of the
* canvas. This is useful for diagrams that have white space there (eg
* Signavio). Everything beneath these minimum values will be cropped.
*
* @param minX
* Hint that will be used when generating the image. Parts that fall
* below minX on the horizontal scale will be cropped.
* @param minY
* Hint that will be used when generating the image. Parts that fall
* below minX on the horizontal scale will be cropped.
*/
public ProcessDiagramCanvas(int width, int height, int minX, int minY) {
this(width, height);
this.minX = minX;
this.minY = minY;
}
/**
* Generates an image of what currently is drawn on the canvas.
*
* Throws an {@link ActivitiException} when {@link #close()} is already
* called.
*/
public InputStream generateImage(String imageType) {
if (closed) {
throw new ActivitiException("ProcessDiagramGenerator already closed");
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
// Try to remove white space
minX = (minX <= 5) ? 5 : minX;
minY = (minY <= 5) ? 5 : minY;
BufferedImage imageToSerialize = processDiagram;
if (minX >= 0 && minY >= 0) {
imageToSerialize = processDiagram.getSubimage(minX - 5, minY - 5, canvasWidth - minX + 5, canvasHeight - minY + 5);
}
ImageIO.write(imageToSerialize, imageType, out);
} catch (IOException e) {
throw new ActivitiException("Error while generating process image", e);
} finally {
IoUtil.closeSilently(out);
}
return new ByteArrayInputStream(out.toByteArray());
}
/**
* Closes the canvas which dissallows further drawing and releases graphical
* resources.
*/
public void close() {
g.dispose();
closed = true;
}
public void drawNoneStartEvent(int x, int y, int width, int height) {
drawStartEvent(x, y, width, height, null);
}
public void drawTimerStartEvent(int x, int y, int width, int height) {
drawStartEvent(x, y, width, height, TIMER_IMAGE);
}
public void drawStartEvent(int x, int y, int width, int height, Image image) {
g.draw(new Ellipse2D.Double(x, y, width, height));
if (image != null) {
g.drawImage(image, x, y, width, height, null);
}
}
public void drawNoneEndEvent(int x, int y, int width, int height) {
Stroke originalStroke = g.getStroke();
g.setStroke(END_EVENT_STROKE);
g.draw(new Ellipse2D.Double(x, y, width, height));
g.setStroke(originalStroke);
}
public void drawErrorEndEvent(int x, int y, int width, int height) {
drawNoneEndEvent(x, y, width, height);
g.drawImage(ERROR_THROW_IMAGE, x + 3, y + 3, width - 6, height - 6, null);
}
public void drawErrorStartEvent(int x, int y, int width, int height) {
drawNoneStartEvent(x, y, width, height);
g.drawImage(ERROR_CATCH_IMAGE, x + 3, y + 3, width - 6, height - 6, null);
}
public void drawCatchingEvent(int x, int y, int width, int height, Image image) {
// event circles
Ellipse2D outerCircle = new Ellipse2D.Double(x, y, width, height);
int innerCircleX = x + 3;
int innerCircleY = y + 3;
int innerCircleWidth = width - 6;
int innerCircleHeight = height - 6;
Ellipse2D innerCircle = new Ellipse2D.Double(innerCircleX, innerCircleY, innerCircleWidth, innerCircleHeight);
Paint originalPaint = g.getPaint();
g.setPaint(BOUNDARY_EVENT_COLOR);
g.fill(outerCircle);
g.setPaint(originalPaint);
g.draw(outerCircle);
g.draw(innerCircle);
g.drawImage(image, innerCircleX, innerCircleY, innerCircleWidth, innerCircleHeight, null);
}
public void drawCatchingTimerEvent(int x, int y, int width, int height) {
drawCatchingEvent(x, y, width, height, TIMER_IMAGE);
}
public void drawCatchingErroEvent(int x, int y, int width, int height) {
drawCatchingEvent(x, y, width, height, ERROR_CATCH_IMAGE);
}
public void drawCatchingSignalEvent(int x, int y, int width, int height) {
drawCatchingEvent(x, y, width, height, SIGNAL_CATCH_IMAGE);
}
public void drawThrowingSignalEvent(int x, int y, int width, int height) {
drawCatchingEvent(x, y, width, height, SIGNAL_THROW_IMAGE);
}
public void drawSequenceflow(int srcX, int srcY, int targetX, int targetY, boolean conditional) {
Line2D.Double line = new Line2D.Double(srcX, srcY, targetX, targetY);
g.draw(line);
drawArrowHead(line);
if (conditional) {
drawConditionalSequenceFlowIndicator(line);
}
}
public void drawSequenceflowWithoutArrow(int srcX, int srcY, int targetX, int targetY, boolean conditional) {
Line2D.Double line = new Line2D.Double(srcX, srcY, targetX, targetY);
g.draw(line);
if (conditional) {
drawConditionalSequenceFlowIndicator(line);
}
}
public void drawArrowHead(Line2D.Double line) {
int doubleArrowWidth = 2 * ARROW_WIDTH;
Polygon arrowHead = new Polygon();
arrowHead.addPoint(0, 0);
arrowHead.addPoint(-ARROW_WIDTH, -doubleArrowWidth);
arrowHead.addPoint(ARROW_WIDTH, -doubleArrowWidth);
AffineTransform transformation = new AffineTransform();
transformation.setToIdentity();
double angle = Math.atan2(line.y2 - line.y1, line.x2 - line.x1);
transformation.translate(line.x2, line.y2);
transformation.rotate((angle - Math.PI / 2d));
AffineTransform originalTransformation = g.getTransform();
g.setTransform(transformation);
g.fill(arrowHead);
g.setTransform(originalTransformation);
}
public void drawConditionalSequenceFlowIndicator(Line2D.Double line) {
int horizontal = (int) (CONDITIONAL_INDICATOR_WIDTH * 0.7);
int halfOfHorizontal = horizontal / 2;
int halfOfVertical = CONDITIONAL_INDICATOR_WIDTH / 2;
Polygon conditionalIndicator = new Polygon();
conditionalIndicator.addPoint(0, 0);
conditionalIndicator.addPoint(-halfOfHorizontal, halfOfVertical);
conditionalIndicator.addPoint(0, CONDITIONAL_INDICATOR_WIDTH);
conditionalIndicator.addPoint(halfOfHorizontal, halfOfVertical);
AffineTransform transformation = new AffineTransform();
transformation.setToIdentity();
double angle = Math.atan2(line.y2 - line.y1, line.x2 - line.x1);
transformation.translate(line.x1, line.y1);
transformation.rotate((angle - Math.PI / 2d));
AffineTransform originalTransformation = g.getTransform();
g.setTransform(transformation);
g.draw(conditionalIndicator);
Paint originalPaint = g.getPaint();
g.setPaint(CONDITIONAL_INDICATOR_COLOR);
g.fill(conditionalIndicator);
g.setPaint(originalPaint);
g.setTransform(originalTransformation);
}
public void drawTask(String name, int x, int y, int width, int height) {
drawTask(name, x, y, width, height, false);
}
public void drawPoolOrLane(String name, int x, int y, int width, int height) {
g.drawRect(x, y, width, height);
// Add the name as text, vertical
if(name != null && name.length() > 0) {
// Include some padding
int availableTextSpace = height - 6;
// Create rotation for derived font
AffineTransform transformation = new AffineTransform();
transformation.setToIdentity();
transformation.rotate(270 * Math.PI/180);
Font currentFont = g.getFont();
Font theDerivedFont = currentFont.deriveFont(transformation);
g.setFont(theDerivedFont);
String truncated = fitTextToWidth(name, availableTextSpace);
int realWidth = fontMetrics.stringWidth(truncated);
g.drawString(truncated, x + 2 + fontMetrics.getHeight(), 3 + y + availableTextSpace - (availableTextSpace - realWidth) / 2);
g.setFont(currentFont);
}
}
protected void drawTask(String name, int x, int y, int width, int height, boolean thickBorder) {
Paint originalPaint = g.getPaint();
g.setPaint(TASK_COLOR);
// shape
RoundRectangle2D rect = new RoundRectangle2D.Double(x, y, width, height, 20, 20);
g.fill(rect);
g.setPaint(originalPaint);
if (thickBorder) {
Stroke originalStroke = g.getStroke();
g.setStroke(THICK_TASK_BORDER_STROKE);
g.draw(rect);
g.setStroke(originalStroke);
} else {
g.draw(rect);
}
// text
if (name != null) {
String text = fitTextToWidth(name, width);
int textX = x + ((width - fontMetrics.stringWidth(text)) / 2);
int textY = y + ((height - fontMetrics.getHeight()) / 2) + fontMetrics.getHeight();
g.drawString(text, textX, textY);
}
}
protected String fitTextToWidth(String original, int width) {
String text = original;
// remove length for "..."
int maxWidth = width - 10;
while (fontMetrics.stringWidth(text + "...") > maxWidth && text.length() > 0) {
text = text.substring(0, text.length() - 1);
}
if (!text.equals(original)) {
text = text + "...";
}
return text;
}
public void drawUserTask(String name, int x, int y, int width, int height) {
drawTask(name, x, y, width, height);
g.drawImage(USERTASK_IMAGE, x + 7, y + 7, ICON_SIZE, ICON_SIZE, null);
}
public void drawScriptTask(String name, int x, int y, int width, int height) {
drawTask(name, x, y, width, height);
g.drawImage(SCRIPTTASK_IMAGE, x + 7, y + 7, ICON_SIZE, ICON_SIZE, null);
}
public void drawServiceTask(String name, int x, int y, int width, int height) {
drawTask(name, x, y, width, height);
g.drawImage(SERVICETASK_IMAGE, x + 7, y + 7, ICON_SIZE, ICON_SIZE, null);
}
public void drawReceiveTask(String name, int x, int y, int width, int height) {
drawTask(name, x, y, width, height);
g.drawImage(RECEIVETASK_IMAGE, x + 7, y + 7, ICON_SIZE, ICON_SIZE, null);
}
public void drawSendTask(String name, int x, int y, int width, int height) {
drawTask(name, x, y, width, height);
g.drawImage(SENDTASK_IMAGE, x + 7, y + 7, ICON_SIZE, ICON_SIZE, null);
}
public void drawManualTask(String name, int x, int y, int width, int height) {
drawTask(name, x, y, width, height);
g.drawImage(MANUALTASK_IMAGE, x + 7, y + 7, ICON_SIZE, ICON_SIZE, null);
}
public void drawBusinessRuleTask(String name, int x, int y, int width, int height) {
drawTask(name, x, y, width, height);
g.drawImage(BUSINESS_RULE_TASK_IMAGE, x + 7, y + 7, ICON_SIZE, ICON_SIZE, null);
}
public void drawExpandedSubProcess(String name, int x, int y, int width, int height, Boolean isTriggeredByEvent) {
RoundRectangle2D rect = new RoundRectangle2D.Double(x, y, width, height, 20, 20);
// Use different stroke (dashed)
if(isTriggeredByEvent) {
Stroke originalStroke = g.getStroke();
g.setStroke(EVENT_SUBPROCESS_STROKE);
g.draw(rect);
g.setStroke(originalStroke);
} else {
g.draw(rect);
}
String text = fitTextToWidth(name, width);
g.drawString(text, x + 10, y + 15);
}
public void drawCollapsedSubProcess(String name, int x, int y, int width, int height, Boolean isTriggeredByEvent) {
drawCollapsedTask(name, x, y, width, height, false);
}
public void drawCollapsedCallActivity(String name, int x, int y, int width, int height) {
drawCollapsedTask(name, x, y, width, height, true);
}
protected void drawCollapsedTask(String name, int x, int y, int width, int height, boolean thickBorder) {
// The collapsed marker is now visualized separately
drawTask(name, x, y, width, height, thickBorder);
}
public void drawCollapsedMarker(int x, int y, int width, int height) {
// rectangle
int rectangleWidth = MARKER_WIDTH;
int rectangleHeight = MARKER_WIDTH;
Rectangle rect = new Rectangle(x + (width - rectangleWidth) / 2, y + height - rectangleHeight - 3, rectangleWidth, rectangleHeight);
g.draw(rect);
// plus inside rectangle
Line2D.Double line = new Line2D.Double(rect.getCenterX(), rect.getY() + 2, rect.getCenterX(), rect.getMaxY() - 2);
g.draw(line);
line = new Line2D.Double(rect.getMinX() + 2, rect.getCenterY(), rect.getMaxX() - 2, rect.getCenterY());
g.draw(line);
}
public void drawActivityMarkers(int x, int y, int width, int height, boolean multiInstanceSequential, boolean multiInstanceParallel, boolean collapsed) {
if (collapsed) {
if (!multiInstanceSequential && !multiInstanceParallel) {
drawCollapsedMarker(x, y, width, height);
} else {
drawCollapsedMarker(x - MARKER_WIDTH / 2 - 2, y, width, height);
if (multiInstanceSequential) {
drawMultiInstanceMarker(true, x + MARKER_WIDTH / 2 + 2, y, width, height);
} else if (multiInstanceParallel) {
drawMultiInstanceMarker(false, x + MARKER_WIDTH / 2 + 2, y, width, height);
}
}
} else {
if (multiInstanceSequential) {
- drawMultiInstanceMarker(false, x, y, width, height);
- } else if (multiInstanceParallel) {
drawMultiInstanceMarker(true, x, y, width, height);
+ } else if (multiInstanceParallel) {
+ drawMultiInstanceMarker(false, x, y, width, height);
}
}
}
public void drawGateway(int x, int y, int width, int height) {
Polygon rhombus = new Polygon();
rhombus.addPoint(x, y + (height / 2));
rhombus.addPoint(x + (width / 2), y + height);
rhombus.addPoint(x + width, y + (height / 2));
rhombus.addPoint(x + (width / 2), y);
g.draw(rhombus);
}
public void drawParallelGateway(int x, int y, int width, int height) {
// rhombus
drawGateway(x, y, width, height);
// plus inside rhombus
Stroke orginalStroke = g.getStroke();
g.setStroke(GATEWAY_TYPE_STROKE);
Line2D.Double line = new Line2D.Double(x + 10, y + height / 2, x + width - 10, y + height / 2); // horizontal
g.draw(line);
line = new Line2D.Double(x + width / 2, y + height - 10, x + width / 2, y + 10); // vertical
g.draw(line);
g.setStroke(orginalStroke);
}
public void drawExclusiveGateway(int x, int y, int width, int height) {
// rhombus
drawGateway(x, y, width, height);
int quarterWidth = width / 4;
int quarterHeight = height / 4;
// X inside rhombus
Stroke orginalStroke = g.getStroke();
g.setStroke(GATEWAY_TYPE_STROKE);
Line2D.Double line = new Line2D.Double(x + quarterWidth + 3, y + quarterHeight + 3, x + 3 * quarterWidth - 3, y + 3 * quarterHeight - 3);
g.draw(line);
line = new Line2D.Double(x + quarterWidth + 3, y + 3 * quarterHeight - 3, x + 3 * quarterWidth - 3, y + quarterHeight + 3);
g.draw(line);
g.setStroke(orginalStroke);
}
public void drawInclusiveGateway(int x, int y, int width, int height) {
// rhombus
drawGateway(x, y, width, height);
int diameter = width / 2;
// circle inside rhombus
Stroke orginalStroke = g.getStroke();
g.setStroke(GATEWAY_TYPE_STROKE);
Ellipse2D.Double circle = new Ellipse2D.Double(((width - diameter) / 2) + x, ((height - diameter) / 2) + y, diameter, diameter);
g.draw(circle);
g.setStroke(orginalStroke);
}
public void drawMultiInstanceMarker(boolean sequential, int x, int y, int width, int height) {
int rectangleWidth = MARKER_WIDTH;
int rectangleHeight = MARKER_WIDTH;
int lineX = x + (width - rectangleWidth) / 2;
int lineY = y + height - rectangleHeight - 3;
Stroke orginalStroke = g.getStroke();
g.setStroke(MULTI_INSTANCE_STROKE);
if (sequential) {
g.draw(new Line2D.Double(lineX, lineY, lineX + rectangleWidth, lineY));
g.draw(new Line2D.Double(lineX, lineY + rectangleHeight / 2, lineX + rectangleWidth, lineY + rectangleHeight / 2));
g.draw(new Line2D.Double(lineX, lineY + rectangleHeight, lineX + rectangleWidth, lineY + rectangleHeight));
} else {
g.draw(new Line2D.Double(lineX, lineY, lineX, lineY + rectangleHeight));
g.draw(new Line2D.Double(lineX + rectangleWidth / 2, lineY, lineX + rectangleWidth / 2, lineY + rectangleHeight));
g.draw(new Line2D.Double(lineX + rectangleWidth, lineY, lineX + rectangleWidth, lineY + rectangleHeight));
}
g.setStroke(orginalStroke);
}
public void drawHighLight(int x, int y, int width, int height) {
Paint originalPaint = g.getPaint();
Stroke originalStroke = g.getStroke();
g.setPaint(HIGHLIGHT_COLOR);
g.setStroke(THICK_TASK_BORDER_STROKE);
RoundRectangle2D rect = new RoundRectangle2D.Double(x, y, width, height, 20, 20);
g.draw(rect);
g.setPaint(originalPaint);
g.setStroke(originalStroke);
}
}
| false | false | null | null |
diff --git a/src/com/android/alarmclock/AnalogDefaultAppWidgetProvider.java b/src/com/android/alarmclock/AnalogDefaultAppWidgetProvider.java
index 6796d41..a13f2fb 100644
--- a/src/com/android/alarmclock/AnalogDefaultAppWidgetProvider.java
+++ b/src/com/android/alarmclock/AnalogDefaultAppWidgetProvider.java
@@ -1,55 +1,55 @@
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR 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.alarmclock;
import com.android.deskclock.AlarmClock;
import com.android.deskclock.R;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.RemoteViews;
/**
* Simple widget to show analog clock.
*/
public class AnalogDefaultAppWidgetProvider extends BroadcastReceiver {
static final String TAG = "AnalogDefaultAppWidgetProvider";
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (AppWidgetManager.ACTION_APPWIDGET_UPDATE.equals(action)) {
RemoteViews views = new RemoteViews(context.getPackageName(),
- R.layout.analogdefault_appwidget);
+ R.layout.analogsecond_appwidget);
- views.setOnClickPendingIntent(R.id.analogdefault_appwidget,
+ views.setOnClickPendingIntent(R.id.analogsecond_appwidget,
PendingIntent.getActivity(context, 0,
new Intent(context, AlarmClock.class),
PendingIntent.FLAG_CANCEL_CURRENT));
int[] appWidgetIds = intent.getIntArrayExtra(
AppWidgetManager.EXTRA_APPWIDGET_IDS);
AppWidgetManager gm = AppWidgetManager.getInstance(context);
gm.updateAppWidget(appWidgetIds, views);
}
}
}
| false | true | public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (AppWidgetManager.ACTION_APPWIDGET_UPDATE.equals(action)) {
RemoteViews views = new RemoteViews(context.getPackageName(),
R.layout.analogdefault_appwidget);
views.setOnClickPendingIntent(R.id.analogdefault_appwidget,
PendingIntent.getActivity(context, 0,
new Intent(context, AlarmClock.class),
PendingIntent.FLAG_CANCEL_CURRENT));
int[] appWidgetIds = intent.getIntArrayExtra(
AppWidgetManager.EXTRA_APPWIDGET_IDS);
AppWidgetManager gm = AppWidgetManager.getInstance(context);
gm.updateAppWidget(appWidgetIds, views);
}
}
| public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (AppWidgetManager.ACTION_APPWIDGET_UPDATE.equals(action)) {
RemoteViews views = new RemoteViews(context.getPackageName(),
R.layout.analogsecond_appwidget);
views.setOnClickPendingIntent(R.id.analogsecond_appwidget,
PendingIntent.getActivity(context, 0,
new Intent(context, AlarmClock.class),
PendingIntent.FLAG_CANCEL_CURRENT));
int[] appWidgetIds = intent.getIntArrayExtra(
AppWidgetManager.EXTRA_APPWIDGET_IDS);
AppWidgetManager gm = AppWidgetManager.getInstance(context);
gm.updateAppWidget(appWidgetIds, views);
}
}
|
diff --git a/core/src/main/java/tripleplay/ui/layout/BorderLayout.java b/core/src/main/java/tripleplay/ui/layout/BorderLayout.java
index 576d2a77..d318943d 100644
--- a/core/src/main/java/tripleplay/ui/layout/BorderLayout.java
+++ b/core/src/main/java/tripleplay/ui/layout/BorderLayout.java
@@ -1,338 +1,338 @@
//
// Triple Play - utilities for use in PlayN-based games
// Copyright (c) 2011, Three Rings Design, Inc. - All rights reserved.
// http://github.com/threerings/tripleplay/blob/master/LICENSE
package tripleplay.ui.layout;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import pythagoras.f.Dimension;
import pythagoras.f.IDimension;
import pythagoras.f.Rectangle;
import tripleplay.ui.Element;
import tripleplay.ui.Elements;
import tripleplay.ui.Layout;
import tripleplay.ui.Style;
/**
* Arranges up to 5 elements, one central and one on each edge. Added elements must have a
* constraint from the class' listing (e.g. {@link BorderLayout#CENTER}), which determines the
* position in the layout and stretching.
* <p>This is how the layout looks. Note north/south and east/west behavior is not quite symmetric
* because east and west fit between the bottom of the north and top of the south:</p>
* <p><pre>
* |-----------------------------|
* | north |
* |-----------------------------|
* | | | |
* | | | |
* | | | |
* | west | center | east |
* | | | |
* | | | |
* |-----------------------------|
* | south |
* |-----------------------------|
* </pre></p>
* When an element is not stretched, it obeys the {@link Style.HAlign} and {@link Style.VAlign}
* bindings.
*/
public class BorderLayout extends Layout
{
/** Constraint to position an element in the center of its parent. The element is stretched
* in both directions to take up available space. If {@link Constraint#unstretched()} is
* used, the element will be aligned in both directions using its preferred size and the
* {@link Style.HAlign} and {@link Style.VAlign} bindings. */
public static final Constraint CENTER = Position.CENTER.stretched;
/** Constraint to position an element along the top edge of its parent. The element is
* stretched horizontally and uses its preferred height. If {@link Constraint#unstretched()} is
* used, the element will be aligned horizontally using its preferred size according to the
* {@link Style.HAlign} binding. */
public static final Constraint NORTH = Position.NORTH.stretched;
/** Constraint to position an element along the bottom edge of its parent. The element is
* stretched horizontally and uses its preferred height. If {@link Constraint#unstretched()} is
* used, the element will be aligned horizontally using its preferred size according to the
* {@link Style.HAlign} binding. */
public static final Constraint SOUTH = Position.SOUTH.stretched;
/** Constraint to position an element along the right edge of its parent. The element is
* stretched vertically and uses its preferred width. If {@link Constraint#unstretched()} is
* used, the element will be aligned vertically using its preferred size according to the
* {@link Style.VAlign} binding. */
public static final Constraint EAST = Position.EAST.stretched;
/** Constraint to position an element along the right edge of its parent. The element is
* stretched vertically and uses its preferred width. If {@link Constraint#unstretched()} is
* used, the element will be aligned vertically using its preferred size according to the
* {@link Style.VAlign} binding. */
public static final Constraint WEST = Position.WEST.stretched;
/**
* Implements the constraints. Callers do not need to construct instances, but instead use the
* declared constants and select or deselect the stretching option.
*/
public static class Constraint extends Layout.Constraint {
/**
* Returns a new constraint specifying the same position as this, and with stretching.
*/
public Constraint stretched () {
return _pos.stretched;
}
/**
* Returns a new constraint specifying the same position as this, and with no stretching.
* The element's preferred size will be used and an appropriate alignment.
*/
public Constraint unstretched () {
return _pos.unstretched;
}
protected Constraint (Position pos, boolean stretch) {
_pos = pos;
_stretch = stretch;
}
protected Dimension adjust (IDimension pref, Rectangle boundary) {
Dimension dim = new Dimension(pref);
if (_stretch) {
if ((_pos.orient & 1) != 0) {
dim.width = boundary.width;
}
if ((_pos.orient & 2) != 0) {
dim.height = boundary.height;
}
}
dim.width = Math.min(dim.width, boundary.width);
dim.height = Math.min(dim.height, boundary.height);
return dim;
}
protected float align (float origin, float offset) {
return _stretch ? origin : origin + offset;
}
protected final Position _pos;
protected final boolean _stretch;
}
/** The horizontal gap between components. */
public final float hgap;
/** The vertical gap between components. */
public final float vgap;
/**
* Constructs a new border layout with no gaps.
*/
public BorderLayout () {
this(0);
}
/**
* Constructs a new border layout with the specified gap between components.
*/
public BorderLayout (float gaps) {
this(gaps, gaps);
}
/**
* Constructs a new border layout with the specified horizontal and vertical gaps between
* components.
*/
public BorderLayout (float hgap, float vgap) {
this.hgap = hgap;
this.vgap = vgap;
}
@Override
public Dimension computeSize (Elements<?> elems, float hintX, float hintY) {
return new Slots(elems).computeSize(hintX, hintY);
}
@Override
public void layout (Elements<?> elems, float left, float top, float width, float height) {
Style.HAlign halign = resolveStyle(elems, Style.HALIGN);
Style.VAlign valign = resolveStyle(elems, Style.VALIGN);
Slots slots = new Slots(elems);
Rectangle bounds = new Rectangle(left, top, width, height);
slots.layoutNs(Position.NORTH, halign, bounds);
slots.layoutNs(Position.SOUTH, halign, bounds);
slots.layoutWe(Position.WEST, valign, bounds);
slots.layoutWe(Position.EAST, valign, bounds);
Position p = Position.CENTER;
IDimension dim = slots.size(p, bounds.width, bounds.height);
if (dim == null) {
return;
}
Constraint c = slots.constraint(p);
dim = c.adjust(dim, bounds);
slots.setBounds(p,
c.align(bounds.x, halign.offset(dim.width(), bounds.width)),
c.align(bounds.y, valign.offset(dim.height(), bounds.height)), dim);
}
protected class Slots
{
final Map<Position, Element<?>> elements = new HashMap<Position, Element<?>>();
Slots (Elements<?> elems) {
for (Element<?> elem : elems) {
Position p = Position.positionOf(elem.constraint());
if (p == null) {
throw new IllegalStateException("Element with a non-BorderLayout constraint");
}
if (elements.put(p, elem) != null) {
throw new IllegalStateException(
"Multiple elements with the same constraint: " + p);
}
}
// remove invisibles
for (Iterator<Element<?>> it = elements.values().iterator(); it.hasNext(); ) {
if (!it.next().isVisible()) {
it.remove();
}
}
}
Dimension computeSize (float hintX, float hintY) {
int wce = count(WCE);
Dimension nsSize = new Dimension();
for (Position pos : NS) {
IDimension dim = size(pos, hintX, 0);
if (dim == null) {
continue;
}
nsSize.height += dim.height();
nsSize.width = Math.max(nsSize.width, dim.width());
if (wce > 0) {
nsSize.height += vgap;
}
}
float ehintY = Math.max(0, hintY - nsSize.height);
Dimension weSize = new Dimension();
for (Position pos : WE) {
IDimension dim = size(pos, 0, ehintY);
if (dim == null) {
continue;
}
weSize.width += dim.width();
weSize.height = Math.max(weSize.height, dim.height());
}
weSize.width += Math.max(wce - 1, 0) * hgap;
float ehintX = Math.max(0, hintX - weSize.width);
IDimension csize = size(Position.CENTER, ehintX, ehintY);
if (csize != null) {
weSize.width += csize.width();
nsSize.height += csize.height();
}
return new Dimension(
Math.max(weSize.width, nsSize.width),
Math.max(weSize.height, nsSize.height));
}
void layoutNs (Position p, Style.HAlign halign, Rectangle bounds) {
IDimension dim = size(p, bounds.width, 0);
if (dim == null) {
return;
}
+ Constraint c = constraint(p);
+ dim = c.adjust(dim, bounds);
float y = bounds.y;
if (p == Position.NORTH) {
bounds.y += dim.height() + vgap;
} else {
y += bounds.height - dim.height();
}
bounds.height -= dim.height() + vgap;
- Constraint c = constraint(p);
- dim = c.adjust(dim, bounds);
setBounds(p, c.align(bounds.x, halign.offset(dim.width(), bounds.width)), y, dim);
}
void layoutWe (Position p, Style.VAlign valign, Rectangle bounds) {
IDimension dim = size(p, 0, bounds.height);
if (dim == null) {
return;
}
+ Constraint c = constraint(p);
+ dim = c.adjust(dim, bounds);
float x = bounds.x;
if (p == Position.WEST) {
bounds.x += dim.width() + hgap;
} else {
x += bounds.width - dim.width();
}
bounds.width -= dim.width() + hgap;
- Constraint c = constraint(p);
- dim = c.adjust(dim, bounds);
setBounds(p, x, c.align(bounds.y, valign.offset(dim.height(), bounds.height)), dim);
}
void setBounds (Position p, float x, float y, IDimension dim) {
BorderLayout.this.setBounds(get(p), x, y, dim.width(), dim.height());
}
int count (Position ...ps) {
int count = 0;
for (Position p : ps) {
if (elements.containsKey(p)) {
count++;
}
}
return count;
}
boolean stretch (Position p) {
return ((Constraint)get(p).constraint())._stretch;
}
Element<?> get (Position p) {
return elements.get(p);
}
Constraint constraint (Position p) {
return (Constraint)get(p).constraint();
}
IDimension size (Position p, float hintX, float hintY) {
Element<?> e = elements.get(p);
return e == null ? null : preferredSize(e, hintX, hintY);
}
}
protected static enum Position
{
CENTER(3), NORTH(1), SOUTH(1), EAST(2), WEST(2);
static Position positionOf (Layout.Constraint c) {
for (Position p : values()) {
if (p.unstretched == c || p.stretched == c) {
return p;
}
}
return null;
}
final Constraint unstretched;
final Constraint stretched;
final int orient;
Position (int orient) {
this.orient = orient;
unstretched = new Constraint(this, false);
stretched = new Constraint(this, true);
}
}
protected static final Position[] NS = {Position.NORTH, Position.SOUTH};
protected static final Position[] WE = {Position.WEST, Position.EAST};
protected static final Position[] WCE = {Position.WEST, Position.CENTER, Position.EAST};
}
| false | false | null | null |
diff --git a/esmska/src/esmska/data/Contact.java b/esmska/src/esmska/data/Contact.java
index fabe63a4..940cdef5 100644
--- a/esmska/src/esmska/data/Contact.java
+++ b/esmska/src/esmska/data/Contact.java
@@ -1,160 +1,159 @@
/*
* Contact.java
*
* Created on 21. červenec 2007, 0:57
*/
package esmska.data;
-import esmska.data.Operator;
import java.beans.*;
import java.text.Collator;
import org.apache.commons.lang.builder.CompareToBuilder;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
/** SMS Contact entity
* @author ripper
*/
public class Contact extends Object implements Comparable<Contact> {
private String name;
/** full phone number including the country code (starting with "+") */
private String number;
private String operator;
// <editor-fold defaultstate="collapsed" desc="PropertyChange support">
private PropertyChangeSupport changeSupport = new PropertyChangeSupport(this);
public void addPropertyChangeListener(PropertyChangeListener listener) {
changeSupport.addPropertyChangeListener(listener);
}
public void removePropertyChangeListener(PropertyChangeListener listener) {
changeSupport.removePropertyChangeListener(listener);
}
// </editor-fold>
/** Create new contact with properties copied from provided contact */
public Contact(Contact c) {
this(c.getName(), c.getNumber(), c.getOperator());
}
/** Create new contact. */
public Contact(String name, String number, String operator) {
setName(name);
setNumber(number);
setOperator(operator);
}
/** Copy all contact properties from provided contact to current contact */
public void copyFrom(Contact c) {
setName(c.getName());
setNumber(c.getNumber());
setOperator(c.getOperator());
}
// <editor-fold defaultstate="collapsed" desc="Get Methods">
/** Get contact name. Never null. */
public String getName() {
return this.name;
}
/** Get full phone number including the country code (starting with "+")
or empty string. Never null. */
public String getNumber() {
return this.number;
}
/** Get operator. Never null. */
public String getOperator() {
return this.operator;
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="Set Methods">
/** Set contact name.
* @param name contact name. Null value is changed to empty string.
*/
public void setName(String name) {
if (name == null) {
name = "";
}
String oldName = this.name;
this.name = name;
if (!name.equals(oldName)) {
changeSupport.firePropertyChange("name", oldName, name);
}
}
/** Set full phone number.
* @param number new contact number including the country code (starting with "+").
* Alternatively it can be an empty string. Null value is changed to empty string.
*/
public void setNumber(String number) {
if (number == null) {
number = "";
}
if (number.length() > 0 && !number.startsWith("+")) {
throw new IllegalArgumentException("Number does not start with '+': " + number);
}
String oldNumber = this.number;
this.number = number;
if (!number.equals(oldNumber)) {
changeSupport.firePropertyChange("number", oldNumber, number);
}
}
/** Set contact operator
* @param operator new operator. Null value is changed to "unknown" operator.
*/
public void setOperator(String operator) {
if (operator == null) {
operator = Operator.UNKNOWN;
}
String oldOperator = this.operator;
this.operator = operator;
if (!operator.equals(oldOperator)) {
changeSupport.firePropertyChange("operator", oldOperator, operator);
}
}
// </editor-fold>
@Override
public int compareTo(Contact c) {
Collator collator = Collator.getInstance();
return new CompareToBuilder().append(name, c.name, collator).
append(number, c.number, collator).
append(operator, c.operator, collator).toComparison();
}
@Override
public String toString() {
return getName();
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof Contact)) {
return false;
}
Contact c = (Contact) obj;
return new EqualsBuilder().append(name, c.name).append(number, c.number).
append(operator, c.operator).isEquals();
}
@Override
public int hashCode() {
return new HashCodeBuilder(337, 139).append(name).append(number).
append(operator).toHashCode();
}
}
diff --git a/esmska/src/esmska/data/Envelope.java b/esmska/src/esmska/data/Envelope.java
index 24da05a3..024cc41c 100644
--- a/esmska/src/esmska/data/Envelope.java
+++ b/esmska/src/esmska/data/Envelope.java
@@ -1,184 +1,183 @@
/*
* Envelope.java
*
* Created on 14. srpen 2007, 20:18
*
*/
package esmska.data;
-import esmska.data.Operator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.text.Normalizer;
import java.util.logging.Logger;
/** Class for preparing attributes of sms (single or multiple)
*
* @author ripper
*/
public class Envelope {
private static final Config config = Config.getInstance();
private static final Logger logger = Logger.getLogger(Envelope.class.getName());
private String text;
private Set<Contact> contacts = new HashSet<Contact>();
// <editor-fold defaultstate="collapsed" desc="PropertyChange support">
private PropertyChangeSupport changeSupport = new PropertyChangeSupport(this);
public void addPropertyChangeListener(PropertyChangeListener listener) {
changeSupport.addPropertyChangeListener(listener);
}
public void removePropertyChangeListener(PropertyChangeListener listener) {
changeSupport.removePropertyChangeListener(listener);
}
// </editor-fold>
/** get text of sms */
public String getText() {
return text;
}
/** set text of sms */
public void setText(String text) {
String oldText = this.text;
if (config.isRemoveAccents()) {
text = removeAccents(text);
}
this.text = text;
changeSupport.firePropertyChange("text", oldText, text);
}
/** get all recipients */
public Set<Contact> getContacts() {
return Collections.unmodifiableSet(contacts);
}
/** set all recipients */
public void setContacts(Set<Contact> contacts) {
Set<Contact> oldContacts = this.contacts;
this.contacts = contacts;
changeSupport.firePropertyChange("contacts", oldContacts, contacts);
}
/** get maximum length of sendable message */
public int getMaxTextLength() {
int min = Integer.MAX_VALUE;
for (Contact c : contacts) {
Operator operator = Operators.getOperator(c.getOperator());
if (operator == null) {
continue;
}
int value = operator.getMaxChars() * operator.getMaxParts();
value -= getSignatureLength(c); //subtract signature length
min = Math.min(min,value);
}
return min;
}
/** get length of one sms */
public int getSMSLength() {
int min = Integer.MAX_VALUE;
for (Contact c : contacts) {
Operator operator = Operators.getOperator(c.getOperator());
if (operator == null) {
continue;
}
min = Math.min(min, operator.getSMSLength());
}
return min;
}
/** get number of sms from these characters */
public int getSMSCount(int chars) {
int worstOperator = Integer.MAX_VALUE;
for (Contact c : contacts) {
Operator operator = Operators.getOperator(c.getOperator());
if (operator == null) {
continue;
}
worstOperator = Math.min(worstOperator,
operator.getSMSLength());
}
chars += getSignatureLength();
int count = chars / worstOperator;
if (chars % worstOperator != 0) {
count++;
}
return count;
}
/** Get maximum signature length of the contact operators in the envelope */
public int getSignatureLength() {
String senderName = config.getSenderName();
//user has no signature
if (!config.isUseSenderID() || senderName == null || senderName.length() <= 0) {
return 0;
}
int worstSignature = 0;
//find maximum signature length
for (Contact c : contacts) {
Operator operator = Operators.getOperator(c.getOperator());
if (operator == null) {
continue;
}
worstSignature = Math.max(worstSignature,
operator.getSignatureExtraLength());
}
//no operator supports signature
if (worstSignature == 0) {
return 0;
} else {
//add the signature length itself
return worstSignature + senderName.length();
}
}
/** generate list of sms's to send */
public ArrayList<SMS> generate() {
ArrayList<SMS> list = new ArrayList<SMS>();
for (Contact c : contacts) {
Operator operator = Operators.getOperator(c.getOperator());
int limit = (operator != null ? operator.getMaxChars() : Integer.MAX_VALUE);
for (int i=0;i<text.length();i+=limit) {
String cutText = text.substring(i,Math.min(i+limit,text.length()));
SMS sms = new SMS(c.getNumber(), cutText, c.getOperator());
sms.setName(c.getName());
if (config.isUseSenderID()) { //append signature if requested
sms.setSenderNumber(config.getSenderNumber());
sms.setSenderName(config.getSenderName());
}
list.add(sms);
}
}
logger.fine("Envelope specified for " + contacts.size() +
" contact(s) generated " + list.size() + " SMS(s)");
return list;
}
/** get length of signature needed to be substracted from message length */
private int getSignatureLength(Contact c) {
Operator operator = Operators.getOperator(c.getOperator());
if (operator != null && config.isUseSenderID() &&
config.getSenderName() != null &&
config.getSenderName().length() > 0) {
return operator.getSignatureExtraLength() + config.getSenderName().length();
} else {
return 0;
}
}
/** remove diacritical marks from text */
private static String removeAccents(String text) {
return Normalizer.normalize(text, Normalizer.Form.NFD).
replaceAll("\\p{InCombiningDiacriticalMarks}+", "");
}
}
diff --git a/esmska/src/esmska/data/Queue.java b/esmska/src/esmska/data/Queue.java
index ce2e97a8..ed52124e 100644
--- a/esmska/src/esmska/data/Queue.java
+++ b/esmska/src/esmska/data/Queue.java
@@ -1,570 +1,571 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package esmska.data;
import esmska.data.event.ValuedEventSupport;
import esmska.data.event.ValuedListener;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Logger;
import javax.swing.Timer;
import org.apache.commons.lang.Validate;
/** Class representing queue of SMS
*
* @author ripper
*/
public class Queue {
public static enum Events {
/** New sms added.
* Event value: added sms. */
SMS_ADDED,
/** Existing sms removed.
* Event value: removed sms. */
SMS_REMOVED,
/** All sms's removed.
* Event value: null. */
QUEUE_CLEARED,
/** The postition of sms in the queue changed.
* Event value: moved sms. */
SMS_POSITION_CHANGED,
/** Existing sms is now ready for sending.
* Event value: ready sms. */
NEW_SMS_READY,
/** Existing sms is now being sent.
* Event value: sms being sent. */
SENDING_SMS,
/** Existing sms has been sent.
* Event value: sent sms. */
SMS_SENT,
/** Existing sms failed to be sent.
* Event value: failed sms. */
SMS_SENDING_FAILED,
/** Queue has been paused.
* Event value: null. */
QUEUE_PAUSED,
/** Queue has been resumed.
* Event value: null. */
QUEUE_RESUMED
}
/** Internal tick interval of the queue in milliseconds.
After each tick the current delay of all messages is recomputed. */
public static final int TIMER_TICK = 250;
/** shared instance */
private static final Queue instance = new Queue();
private static final Logger logger = Logger.getLogger(Queue.class.getName());
private static final History history = History.getInstance();
+ /** map of [operator name;SMS[*]] */
private final SortedMap<String,List<SMS>> queue = Collections.synchronizedSortedMap(new TreeMap<String,List<SMS>>());
private final AtomicBoolean paused = new AtomicBoolean();
//map of <operator name, current delay in seconds>
private final Map<String, Long> operatorDelay = Collections.synchronizedMap(new HashMap<String, Long>());
//every second check the queue
private final Timer timer = new Timer(TIMER_TICK, new TimerListener());
// <editor-fold defaultstate="collapsed" desc="ValuedEvent support">
private ValuedEventSupport<Events, SMS> valuedSupport = new ValuedEventSupport<Events, SMS>(this);
public void addValuedListener(ValuedListener<Events, SMS> valuedListener) {
valuedSupport.addValuedListener(valuedListener);
}
public void removeValuedListener(ValuedListener<Events, SMS> valuedListener) {
valuedSupport.removeValuedListener(valuedListener);
}
// </editor-fold>
/** Disabled contructor */
private Queue() {
}
/** Get shared instance */
public static Queue getInstance() {
return instance;
}
/** Get all SMS in the queue.
* This is a shortcut for getAll(null). */
public List<SMS> getAll() {
return getAll(null);
}
/** Get all SMS in the queue for specified operator.
* The queue is always sorted by the operator name, the messages are not sorted.
* @param operatorName name of the operator. May be null for any operator.
* @return unmodifiable list of SMS for specified operator.
*/
public List<SMS> getAll(String operatorName) {
List<SMS> list = new ArrayList<SMS>();
synchronized(queue) {
if (operatorName == null) { //take all messages
for (Collection<SMS> col : queue.values()) {
list.addAll(col);
}
} else if (queue.containsKey(operatorName)) { //take messages of that operator
list = queue.get(operatorName);
} else {
//operator not found, therefore empty list
}
}
return Collections.unmodifiableList(list);
}
/** Get a collection of SMS with particular status.
* This a shortcut for getAllWithStatus(status, null).
*/
public List<SMS> getAllWithStatus(SMS.Status status) {
return getAllWithStatus(status, null);
}
/** Get a collection of SMS with particular status and operator.
* The queue is always sorted by the operator name, the messages are not sorted.
* @param status SMS status, not null
* @param operatorName name of the operator of the SMS, may be null for any operator
* @return unmodifiable list of SMS with that status in the queue
*/
public List<SMS> getAllWithStatus(SMS.Status status, String operatorName) {
Validate.notNull(status, "status is null");
List<SMS> list = new ArrayList<SMS>();
synchronized(queue) {
if (operatorName == null) { //take every operator
for (Collection<SMS> col : queue.values()) {
for (SMS sms : col) {
if (sms.getStatus() == status) {
list.add(sms);
}
}
}
} else if (queue.containsKey(operatorName)) { //only one operator
for (SMS sms : queue.get(operatorName)) {
if (sms.getStatus() == status) {
list.add(sms);
}
}
} else {
//operator not found, therefore empty list
}
}
return Collections.unmodifiableList(list);
}
/** Add new SMS to the queue. May not be null.
* @return See {@link Collection#add}.
*/
public boolean add(SMS sms) {
Validate.notNull(sms);
sms.setStatus(SMS.Status.WAITING);
String operator = sms.getOperator();
boolean added = false;
synchronized(queue) {
if (queue.containsKey(operator)) { //this operator was already in the queue
if (!queue.get(operator).contains(sms)) { //sms not already present
added = queue.get(operator).add(sms);
}
} else { //new operator
List<SMS> list = new ArrayList<SMS>();
list.add(sms);
queue.put(operator, list);
added = true;
}
}
if (added) {
logger.fine("Added new SMS to queue: " + sms.toDebugString());
valuedSupport.fireEventOccured(Events.SMS_ADDED, sms);
markIfReady(sms);
timer.start();
}
return added;
}
/** Add collection of new SMS to the queue.
* @param collection Collection of SMS. May not be null, may not contain null element.
* @return See {@link Collection#addAll(java.util.Collection)}
*/
public boolean addAll(Collection<SMS> collection) {
Validate.notNull(collection, "collection is null");
Validate.noNullElements(collection);
logger.fine("Adding " + collection.size() + " new SMS to the queue");
boolean added = false;
for (SMS sms : collection) {
if (add(sms)) {
added = true;
}
}
return added;
}
/** Remove SMS from the queue. If the SMS is not present nothing happens.
* @param sms SMS to be removed. Not null.
* @return See {@link Collection#remove(java.lang.Object) }
*/
public boolean remove(SMS sms) {
Validate.notNull(sms);
String operator = sms.getOperator();
boolean removed = false;
synchronized(queue) {
if (queue.containsKey(operator)) { //only if we have this operator
removed = queue.get(operator).remove(sms);
}
if (removed && queue.get(operator).size() == 0) {
//if there are no more sms from that operator, delete it from map
queue.remove(operator);
operatorDelay.remove(operator);
}
}
if (removed) {
logger.fine("Removed SMS from queue: " + sms.toDebugString());
valuedSupport.fireEventOccured(Events.SMS_REMOVED, sms);
markAllIfReady();
}
return removed;
}
/** Remove all SMS from the queue. */
public void clear() {
logger.fine("Clearing the queue.");
synchronized(queue) {
queue.clear();
operatorDelay.clear();
}
valuedSupport.fireEventOccured(Events.QUEUE_CLEARED, null);
}
/** Checks whether the SMS is in the queue.
* @param sms SMS, not null
* @return See {@link Collection#contains(java.lang.Object) }
*/
public boolean contains(SMS sms) {
Validate.notNull(sms);
String operator = sms.getOperator();
synchronized(queue) {
if (queue.containsKey(operator)) {
return queue.get(operator).contains(sms);
} else {
//nowhere in the queue
return false;
}
}
}
/** Get the number of SMS in the queue */
public int size() {
int size = 0;
synchronized(queue) {
for (Collection<SMS> col : queue.values()) {
size += col.size();
}
}
return size;
}
/** Check if the queue is empty */
public boolean isEmpty() {
synchronized(queue) {
for (Collection<SMS> col : queue.values()) {
if (col.size() > 0) {
return false;
}
}
}
return true;
}
/** Whether queue is currently paused */
public boolean isPaused() {
return paused.get();
}
/** Sets whether queue is currently paused */
public void setPaused(boolean paused) {
this.paused.set(paused);
if (paused) {
logger.fine("Queue is now paused");
valuedSupport.fireEventOccured(Events.QUEUE_PAUSED, null);
} else {
logger.fine("Queue is now resumed");
valuedSupport.fireEventOccured(Events.QUEUE_RESUMED, null);
}
}
/** Move SMS in the queue to another position.
* Queue is always sorted by operator, therefore SMS may be moved only within
* section of its operator.
* @param sms sms to be moved, not null
* @param positionDelta direction and amount of movement. Positive number moves
* to the back of the queue, negative number moves to the front of the queue.
* The number corresponds to the number of positions to change. If the number
* is larger than current queue dimensions, the element will simply stop as the
* first or as the last element.
*/
public void movePosition(SMS sms, int positionDelta) {
Validate.notNull(sms, "sms is null");
String operator = sms.getOperator();
synchronized(queue) {
if (positionDelta == 0 || !queue.containsKey(operator) ||
!queue.get(operator).contains(sms)) {
//nothing to move
return;
}
logger.fine("Moving sms " + sms.toDebugString() + "with delta " + positionDelta);
List<SMS> list = queue.get(operator);
int currentPos = list.indexOf(sms);
int newPos = currentPos + positionDelta;
//check the boundaries of the queue
if (newPos < 0) {
newPos = 0;
}
if (newPos > list.size() - 1) {
newPos = list.size() - 1;
}
if (currentPos == newPos) {
return;
}
list.remove(currentPos);
list.add(newPos, sms);
}
valuedSupport.fireEventOccured(Events.SMS_POSITION_CHANGED, sms);
//if sms is currently ready, reset it to waiting and do another search
//(now different sms may be ready instead of this)
if (sms.getStatus() == SMS.Status.READY) {
sms.setStatus(SMS.Status.WAITING);
markAllIfReady();
}
}
/** Return current delay for specified operator.
* @param operatorName name of the operator. May be null.
* @return number of milliseconds next message from the operator must wait.
* If no such operator found, return 0.
*/
public long getOperatorDelay(String operatorName) {
Long del = operatorDelay.get(operatorName);
if (del != null) {
return del;
}
Operator operator = Operators.getOperator(operatorName);
long delay = 0;
if (operator == null) { //unknown operator
delay = 0;
} else if (operator.getDelayBetweenMessages() <= 0) { //operator without delay
delay = 0;
} else { //search in history
History.Record record = history.findLastRecord(operatorName);
if (record == null) { //no previous record
delay = 0;
} else { //compute the delay
//FIXME: does not take various daylight saving time etc into account
//A more complex library (eg. Joda Time) is needed to calculate true time differences.
long difference = (new Date().getTime() - record.getDate().getTime()); //in milliseconds
delay = Math.max(operator.getDelayBetweenMessages() * 1000 - difference, 0);
}
}
operatorDelay.put(operatorName, delay);
return delay;
}
/** Return current delay for specified sms.
* The delay is taking into account all previous messages from the same operator
* which are waiting to be sent. If sms is not found in the queue, it is
* considered to be at the end of the queue.
* @param sms sms, not null
* @return number of milliseconds a message must wait
*/
public long getSMSDelay(SMS sms) {
Validate.notNull(sms);
String operatorName = sms.getOperator();
long delay = getOperatorDelay(operatorName);
List<SMS> list = queue.get(operatorName);
if (list == null) { //no such operator in the queue
return delay; //therefore operator delay is sms delay
}
int index = list.indexOf(sms);
Operator operator = Operators.getOperator(operatorName);
int opDelay = operator != null ? operator.getDelayBetweenMessages() * 1000 : 0;
if (index >= 0) { //in the queue
delay = delay + (index * opDelay);
} else { //not in the queue, therefore after all sms's in the queue
delay = delay + (list.size() * opDelay);
}
return delay;
}
/** Mark the SMS as successfully sent.
* @param sms sent SMS, not null
*/
public void setSMSSent(SMS sms) {
Validate.notNull(sms);
logger.fine("Marking sms as successfully sent: " + sms.toDebugString());
sms.setStatus(SMS.Status.SENT);
valuedSupport.fireEventOccured(Events.SMS_SENT, sms);
updateOperatorDelay(sms.getOperator());
remove(sms); //remove it from the queue
timer.start();
}
/** Mark SMS as currently being sent.
* @param sms SMS that is currently being sent, not null
*/
public void setSMSSending(SMS sms) {
Validate.notNull(sms);
logger.fine("Marking SMS as currently being sent: " + sms.toDebugString());
sms.setStatus(SMS.Status.SENDING);
valuedSupport.fireEventOccured(Events.SENDING_SMS, sms);
}
/** Mark SMS as failed during sending. Pauses the queue.
* @param sms SMS that has failed, not null
*/
public void setSMSFailed(SMS sms) {
Validate.notNull(sms);
logger.fine("Marking SMS as failed during sending: " + sms.toDebugString());
//pause the queue when sms fail
setPaused(true);
//set sms to be waiting again
sms.setStatus(SMS.Status.WAITING);
valuedSupport.fireEventOccured(Events.SMS_SENDING_FAILED, sms);
updateOperatorDelay(sms.getOperator());
timer.start();
markIfReady(sms);
}
/** Check if sms is ready and set status if it is */
private void markIfReady(SMS sms) {
Validate.notNull(sms);
long delay = getSMSDelay(sms);
if (sms.getStatus() == SMS.Status.WAITING && delay <= 0) {
logger.finer("Marking SMS as ready: " + sms.toDebugString());
sms.setStatus(SMS.Status.READY);
valuedSupport.fireEventOccured(Events.NEW_SMS_READY, sms);
}
}
/** Check all sms for that which are ready and set their status */
private void markAllIfReady() {
ArrayList<SMS> ready = new ArrayList<SMS>();
synchronized(queue) {
for (String operator : queue.keySet()) {
long delay = getOperatorDelay(operator);
if (delay > 0) { //any new sms can't be ready
continue;
}
for (SMS sms : queue.get(operator)) {
long smsDelay = getSMSDelay(sms);
if (smsDelay > 0) {
break;
}
if (sms.getStatus() == SMS.Status.WAITING) {
logger.finer("Marking SMS as ready: " + sms.toDebugString());
sms.setStatus(SMS.Status.READY);
ready.add(sms);
}
}
}
}
for (SMS sms : ready) {
valuedSupport.fireEventOccured(Events.NEW_SMS_READY, sms);
}
}
/** Remove operator from delay cache and compute its delay again */
private void updateOperatorDelay(String operatorName) {
Validate.notEmpty(operatorName);
operatorDelay.remove(operatorName);
getOperatorDelay(operatorName);
}
/** Update the information about current message delays */
private class TimerListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
boolean timerNeeded = false;
boolean checkSMSReady = false;
synchronized(operatorDelay) {
//for every delay substract one second
for (Iterator<Entry<String, Long>> iter = operatorDelay.entrySet().iterator(); iter.hasNext(); ) {
Entry<String, Long> delay = iter.next();
if (!queue.containsKey(delay.getKey())) {
//if there is some operator which is no longer in the queue, we don't need it anymore
iter.remove();
continue;
}
if (delay.getValue() > 0) {
long newDelay = Math.max(delay.getValue() - TIMER_TICK, 0);
delay.setValue(newDelay);
timerNeeded = true; //stil counting down for someone
if (delay.getValue() <= 0) {
//new operator delay just dropped to 0
checkSMSReady = true;
}
}
}
}
if (!timerNeeded) {
//when everything is on 0, no need for timer to run, let's stop it
timer.stop();
}
if (checkSMSReady) {
//we may have new ready sms, check it
markAllIfReady();
}
}
}
}
diff --git a/esmska/src/esmska/gui/SMSPanel.java b/esmska/src/esmska/gui/SMSPanel.java
index 3043b203..150cab16 100644
--- a/esmska/src/esmska/gui/SMSPanel.java
+++ b/esmska/src/esmska/gui/SMSPanel.java
@@ -1,949 +1,948 @@
/*
* SMSPanel.java
*
* Created on 8. říjen 2007, 16:19
*/
package esmska.gui;
-import esmska.gui.ThemeManager;
import esmska.data.Config;
import esmska.data.Contact;
import esmska.data.Contacts;
import esmska.data.CountryPrefix;
import esmska.data.Envelope;
import esmska.data.Queue;
import esmska.data.SMS;
import esmska.data.event.AbstractDocumentListener;
import esmska.utils.L10N;
import java.awt.Color;
import java.awt.Component;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.text.MessageFormat;
import java.util.Collection;
import java.util.HashSet;
import java.util.ResourceBundle;
import java.util.Set;
import java.util.SortedSet;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.BorderFactory;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.KeyStroke;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.event.DocumentEvent;
import javax.swing.event.UndoableEditEvent;
import javax.swing.event.UndoableEditListener;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.DocumentFilter;
import javax.swing.text.Element;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;
import javax.swing.text.StyledDocument;
import javax.swing.undo.UndoManager;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.Validate;
import org.jvnet.substance.SubstanceLookAndFeel;
import org.jvnet.substance.skin.SkinChangeListener;
import org.openide.awt.Mnemonics;
/** Panel for writing and sending sms, and for setting immediate contact
*
* @author ripper
*/
public class SMSPanel extends javax.swing.JPanel {
private static final Logger logger = Logger.getLogger(SMSPanel.class.getName());
private static final String RES = "/esmska/resources/";
private static final ResourceBundle l10n = L10N.l10nBundle;
/** box for messages */
private Envelope envelope = new Envelope();
/** support for undo and redo in sms text pane */
private UndoManager smsTextUndoManager = new UndoManager();
private SortedSet<Contact> contacts = Contacts.getInstance().getAll();
private Config config = Config.getInstance();
private MainFrame mainFrame = MainFrame.getInstance();
private UndoAction undoAction = new UndoAction();
private RedoAction redoAction = new RedoAction();
private CompressAction compressAction = new CompressAction();
private SendAction sendAction = new SendAction();
private SMSTextPaneListener smsTextPaneListener = new SMSTextPaneListener();
private SMSTextPaneDocumentFilter smsTextPaneDocumentFilter;
private RecipientTextField recipientField;
private boolean disableContactListeners;
/** Creates new form SMSPanel */
public SMSPanel() {
initComponents();
recipientField = (RecipientTextField) recipientTextField;
//if not Substance LaF, add clipboard popup menu to text components
if (!config.getLookAndFeel().equals(ThemeManager.LAF.SUBSTANCE)) {
ClipboardPopupMenu.register(smsTextPane);
ClipboardPopupMenu.register(recipientTextField);
}
}
/** validates sms form and returns status */
private boolean validateForm(boolean transferFocus) {
if (StringUtils.isEmpty(envelope.getText())) {
if (transferFocus) {
smsTextPane.requestFocusInWindow();
}
return false;
}
if (envelope.getText().length() > envelope.getMaxTextLength()) {
if (transferFocus) {
smsTextPane.requestFocusInWindow();
}
return false;
}
if (envelope.getContacts().size() <= 0) {
if (transferFocus) {
recipientTextField.requestFocusInWindow();
}
return false;
}
for (Contact c : envelope.getContacts()) {
if (!FormChecker.checkSMSNumber(c.getNumber())) {
if (transferFocus) {
recipientTextField.requestFocusInWindow();
}
return false;
}
}
return true;
}
/** Find contact according to filled name/number and operator
* @param onlyFullMatch whether to look only for full match (name/number and operator)
* or even partial match (name/number only)
* @return found contact or null if none found
*/
private Contact lookupContact(boolean onlyFullMatch) {
String number = recipientField.getNumber();
String id = recipientTextField.getText(); //name or number
String operatorName = operatorComboBox.getSelectedOperatorName();
if (StringUtils.isEmpty(id)) {
return null;
}
Contact contact = null; //match on id
Contact fullContact = null; //match on id and operator
//search in contact numbers
if (number != null) {
for (Contact c : contacts) {
if (ObjectUtils.equals(c.getNumber(), number)) {
if (ObjectUtils.equals(c.getOperator(), operatorName)) {
fullContact = c;
break;
}
if (!onlyFullMatch && contact == null) {
contact = c; //remember only first partial match, but search further
}
}
}
} else {
//search in contact names if not number
for (Contact c : contacts) {
if (id.equalsIgnoreCase(c.getName())) {
if (ObjectUtils.equals(c.getOperator(), operatorName)) {
fullContact = c;
break;
}
if (!onlyFullMatch && contact == null) {
contact = c; //remember only first partial match, but search further
}
}
}
}
return (fullContact != null ? fullContact : contact);
}
/** Request a contact to be selected in contact list. Use null for clearing
* the selection.
*/
private void requestSelectContact(Contact contact) {
if (contact != null) {
mainFrame.getContactPanel().setSelectedContact(contact);
} else {
mainFrame.getContactPanel().clearSelection();
}
}
/** set selected contacts in contact list or contact to display */
public void setContacts(Collection<Contact> contacts) {
Validate.notNull(contacts);
disableContactListeners = true;
int count = contacts.size();
if (count == 1) {
Contact c = contacts.iterator().next();
recipientField.setContact(c);
operatorComboBox.setSelectedOperator(c.getOperator());
}
boolean multiSendMode = (count > 1);
if (multiSendMode) {
recipientTextField.setText(l10n.getString("Multiple_sending"));
}
recipientTextField.setEnabled(! multiSendMode);
operatorComboBox.setEnabled(! multiSendMode);
//update envelope
Set<Contact> set = new HashSet<Contact>();
set.addAll(contacts);
if (count < 1) {
Contact contact = recipientField.getContact();
set.add(new Contact(contact != null ? contact.getName() : null,
recipientField.getNumber(),
operatorComboBox.getSelectedOperatorName()));
}
envelope.setContacts(set);
// update components
sendAction.updateStatus();
smsTextPaneDocumentFilter.requestUpdate();
disableContactListeners = false;
}
/** set sms to display and edit */
public void setSMS(final SMS sms) {
recipientField.setNumber(sms.getNumber());
smsTextPane.setText(sms.getText());
//recipient textfield will change operator, must wait and change operator back
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
operatorComboBox.setSelectedOperator(sms.getOperator());
smsTextPane.requestFocusInWindow();
}
});
}
/** get currently written sms text
* @return currently written sms text or empty string; never null
*/
public String getText() {
String text = smsTextPane.getText();
return text != null ? text : "";
}
/** get undo action used in sms text pane */
public Action getUndoAction() {
return undoAction;
}
/** get redo action used in sms text pane */
public Action getRedoAction() {
return redoAction;
}
/** get compress action used for compressing sms text */
public Action getCompressAction() {
return compressAction;
}
/** get send action used for sending the sms */
public Action getSendAction() {
return sendAction;
}
/** updates values on progress bars according to currently written message chars*/
private void updateProgressBars() {
int smsLength = smsTextPane.getText().length();
//set maximums
singleProgressBar.setMaximum(envelope.getSMSLength());
fullProgressBar.setMaximum(envelope.getMaxTextLength());
//if we are at the end of the whole message, the current message length
//can be lesser than usual
int remainder = envelope.getMaxTextLength() % envelope.getSMSLength();
if (envelope.getMaxTextLength() - smsLength < remainder) {
//we have crossed the remainder border, let's update maximum on progress bar
singleProgressBar.setMaximum(remainder);
}
//set values
fullProgressBar.setValue(smsLength);
singleProgressBar.setValue(smsLength % envelope.getSMSLength());
//on the border counts we want progress bar full instead of empty
if (singleProgressBar.getValue() == 0 && smsLength > 0) {
singleProgressBar.setValue(singleProgressBar.getMaximum());
}
//set tooltips
int current = singleProgressBar.getValue();
int max = singleProgressBar.getMaximum();
singleProgressBar.setToolTipText(MessageFormat.format(
l10n.getString("SMSPanel.singleProgressBar"),
current, max, (max - current)));
current = fullProgressBar.getValue();
max = fullProgressBar.getMaximum();
fullProgressBar.setToolTipText(MessageFormat.format(
l10n.getString("SMSPanel.fullProgressBar"),
current, max, (max - current)));
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
operatorComboBox = new OperatorComboBox();
fullProgressBar = new JProgressBar();
jScrollPane1 = new JScrollPane();
smsTextPane = new JTextPane();
textLabel = new JLabel();
sendButton = new JButton();
smsCounterLabel = new JLabel();
singleProgressBar = new JProgressBar();
gatewayLabel = new JLabel();
recipientTextField = new SMSPanel.RecipientTextField();
recipientLabel = new JLabel();
setBorder(BorderFactory.createTitledBorder(l10n.getString("SMSPanel.border.title"))); // NOI18N
addFocusListener(new FocusAdapter() {
public void focusGained(FocusEvent evt) {
formFocusGained(evt);
}
});
operatorComboBox.addActionListener(new OperatorComboBoxActionListener());
fullProgressBar.setMaximum(1000);
smsTextPane.getDocument().addDocumentListener(smsTextPaneListener);
smsTextPaneDocumentFilter = new SMSTextPaneDocumentFilter();
((AbstractDocument)smsTextPane.getStyledDocument()).setDocumentFilter(smsTextPaneDocumentFilter);
//bind actions and listeners
smsTextUndoManager.setLimit(-1);
smsTextPane.getDocument().addUndoableEditListener(new UndoableEditListener() {
public void undoableEditHappened(UndoableEditEvent e) {
if (e.getEdit().getPresentationName().contains("style"))
return;
smsTextUndoManager.addEdit(e.getEdit());
}
});
//this mapping is here bcz of some weird performance improvements when holding undo key stroke
int menuMask = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
String command = "undo";
smsTextPane.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_Z, menuMask), command);
smsTextPane.getActionMap().put(command,undoAction);
command = "redo";
smsTextPane.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_Y, menuMask), command);
smsTextPane.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_Z,
menuMask|KeyEvent.SHIFT_DOWN_MASK), command);
smsTextPane.getActionMap().put(command, redoAction);
//ctrl+enter
command = "send";
smsTextPane.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, menuMask), command);
smsTextPane.getActionMap().put(command, sendAction);
jScrollPane1.setViewportView(smsTextPane);
textLabel.setLabelFor(smsTextPane);
Mnemonics.setLocalizedText(textLabel, l10n.getString("SMSPanel.textLabel.text")); // NOI18N
textLabel.setToolTipText(l10n.getString("SMSPanel.textLabel.toolTipText")); // NOI18N
sendButton.setAction(sendAction);
sendButton.setToolTipText(l10n.getString("SMSPanel.sendButton.toolTipText")); // NOI18N
Mnemonics.setLocalizedText(smsCounterLabel, l10n.getString("SMSPanel.smsCounterLabel.text")); // NOI18N
singleProgressBar.setMaximum(1000);
gatewayLabel.setLabelFor(operatorComboBox);
Mnemonics.setLocalizedText(gatewayLabel, l10n.getString("SMSPanel.gatewayLabel.text")); // NOI18N
gatewayLabel.setToolTipText(operatorComboBox.getToolTipText());
recipientLabel.setLabelFor(recipientTextField);
Mnemonics.setLocalizedText(recipientLabel, l10n.getString("SMSPanel.recipientLabel.text")); // NOI18N
recipientLabel.setToolTipText(recipientTextField.getToolTipText());
GroupLayout layout = new GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(Alignment.LEADING)
.addGroup(Alignment.TRAILING, layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(Alignment.LEADING)
.addComponent(textLabel)
.addComponent(singleProgressBar, GroupLayout.PREFERRED_SIZE, 33, GroupLayout.PREFERRED_SIZE)
.addComponent(fullProgressBar, GroupLayout.PREFERRED_SIZE, 33, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addComponent(smsCounterLabel, GroupLayout.DEFAULT_SIZE, 141, Short.MAX_VALUE)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(sendButton))
.addComponent(jScrollPane1, GroupLayout.DEFAULT_SIZE, 175, Short.MAX_VALUE)))
.addGroup(Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(recipientLabel)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(recipientTextField, GroupLayout.DEFAULT_SIZE, 175, Short.MAX_VALUE))
.addGroup(Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(gatewayLabel)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(operatorComboBox, GroupLayout.DEFAULT_SIZE, 175, Short.MAX_VALUE)))
.addContainerGap())
);
layout.linkSize(SwingConstants.HORIZONTAL, new Component[] {fullProgressBar, singleProgressBar});
layout.linkSize(SwingConstants.HORIZONTAL, new Component[] {gatewayLabel, recipientLabel, textLabel});
layout.setVerticalGroup(
layout.createParallelGroup(Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(Alignment.BASELINE)
.addComponent(recipientLabel)
.addComponent(recipientTextField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(Alignment.BASELINE)
.addComponent(gatewayLabel)
.addComponent(operatorComboBox, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jScrollPane1, GroupLayout.DEFAULT_SIZE, 129, Short.MAX_VALUE)
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(Alignment.LEADING, false)
.addComponent(sendButton)
.addComponent(smsCounterLabel)))
.addGroup(layout.createSequentialGroup()
.addComponent(textLabel)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(singleProgressBar, GroupLayout.PREFERRED_SIZE, 10, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(fullProgressBar, GroupLayout.PREFERRED_SIZE, 10, GroupLayout.PREFERRED_SIZE)))
.addContainerGap())
);
layout.linkSize(SwingConstants.VERTICAL, new Component[] {fullProgressBar, singleProgressBar});
}// </editor-fold>//GEN-END:initComponents
private void formFocusGained(FocusEvent evt) {//GEN-FIRST:event_formFocusGained
smsTextPane.requestFocusInWindow();
}//GEN-LAST:event_formFocusGained
/** Send sms to queue */
private class SendAction extends AbstractAction {
public SendAction() {
L10N.setLocalizedText(this, l10n.getString("Send_"));
putValue(SMALL_ICON, new ImageIcon(getClass().getResource(RES + "send-16.png")));
putValue(LARGE_ICON_KEY, new ImageIcon(getClass().getResource(RES + "send-22.png")));
putValue(SHORT_DESCRIPTION,l10n.getString("Send_message"));
putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,
Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
setEnabled(false);
}
@Override
public void actionPerformed(ActionEvent e) {
if (!validateForm(true)) {
return;
}
logger.fine("Sending new message to queue");
Queue.getInstance().addAll(envelope.generate());
smsTextPane.setText(null);
smsTextUndoManager.discardAllEdits();
smsTextPane.requestFocusInWindow();
}
/** update status according to current conditions */
public void updateStatus() {
this.setEnabled(validateForm(false));
}
}
/** undo in sms text pane */
private class UndoAction extends AbstractAction {
public UndoAction() {
L10N.setLocalizedText(this, l10n.getString("Undo_"));
putValue(SMALL_ICON, new ImageIcon(getClass().getResource(RES + "undo-16.png")));
putValue(LARGE_ICON_KEY, new ImageIcon(getClass().getResource(RES + "undo-32.png")));
putValue(SHORT_DESCRIPTION, l10n.getString("SMSPanel.Undo_change_in_message_text"));
putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_Z,
Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
}
@Override
public void actionPerformed(ActionEvent e) {
if (smsTextUndoManager.canUndo()) {
smsTextUndoManager.undo();
smsTextPaneDocumentFilter.requestUpdate();
}
}
/** update status according to current conditions */
public void updateStatus() {
setEnabled(smsTextUndoManager.canUndo());
}
}
/** redo in sms text pane */
private class RedoAction extends AbstractAction {
public RedoAction() {
L10N.setLocalizedText(this, l10n.getString("Redo_"));
putValue(SMALL_ICON, new ImageIcon(getClass().getResource(RES + "redo-16.png")));
putValue(LARGE_ICON_KEY, new ImageIcon(getClass().getResource(RES + "redo-32.png")));
putValue(SHORT_DESCRIPTION, l10n.getString("SMSPanel.Redo_change_in_message_text"));
putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_Y,
Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
}
@Override
public void actionPerformed(ActionEvent e) {
if (smsTextUndoManager.canRedo()) {
smsTextUndoManager.redo();
smsTextPaneDocumentFilter.requestUpdate();
}
}
/** update status according to current conditions */
public void updateStatus() {
setEnabled(smsTextUndoManager.canRedo());
}
}
/** compress current sms text by rewriting it to CamelCase */
private class CompressAction extends AbstractAction {
public CompressAction() {
L10N.setLocalizedText(this, l10n.getString("Compress_"));
putValue(SMALL_ICON, new ImageIcon(getClass().getResource(RES + "compress-16.png")));
putValue(LARGE_ICON_KEY, new ImageIcon(getClass().getResource(RES + "compress-32.png")));
putValue(SHORT_DESCRIPTION,l10n.getString("SMSPanel.compress"));
putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_K,
Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
}
@Override
public void actionPerformed(ActionEvent e) {
logger.fine("Compressing message");
String text = smsTextPane.getText();
if (text == null || text.equals("")) {
return;
}
text = text.replaceAll("\\s", " "); //all whitespace to spaces
text = Pattern.compile("(\\s)\\s+", Pattern.DOTALL).matcher(text).replaceAll("$1"); //remove duplicate whitespaces
Pattern pattern = Pattern.compile("\\s+(.)", Pattern.DOTALL);
Matcher matcher = pattern.matcher(text);
while (matcher.find()) { //find next space+character
text = matcher.replaceFirst(matcher.group(1).toUpperCase()); //replace by upper character
matcher = pattern.matcher(text);
}
text = text.replaceAll(" $", ""); //remove trailing space
if (!text.equals(smsTextPane.getText())) { //do not replace if already compressed
smsTextPane.setText(text);
}
}
/** update status according to current conditions */
public void updateStatus() {
setEnabled(getText().length() > 0);
}
}
/** Another operator selected */
private class OperatorComboBoxActionListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
if (disableContactListeners) {
return;
}
//update text editor listeners
DocumentEvent event = new DocumentEvent() {
@Override
public ElementChange getChange(Element elem) {
return null;
}
@Override
public Document getDocument() {
return smsTextPane.getDocument();
}
@Override
public int getLength() {
return 0;
}
@Override
public int getOffset() {
return 0;
}
@Override
public EventType getType() {
return EventType.INSERT;
}
};
smsTextPaneListener.onUpdate(event);
//select contact only if full match found
Contact contact = lookupContact(true);
if (contact != null) {
requestSelectContact(contact);
}
//update envelope
Set<Contact> set = new HashSet<Contact>();
Contact c = recipientField.getContact();
set.add(new Contact(c != null ? c.getName() : null,
recipientField.getNumber(),
operatorComboBox.getSelectedOperatorName()));
envelope.setContacts(set);
//update components
smsTextPaneDocumentFilter.requestUpdate();
}
}
/** Listener for sms text pane */
private class SMSTextPaneListener extends AbstractDocumentListener {
/** count number of chars in sms and take action */
private void countChars(DocumentEvent e) {
int chars = e.getDocument().getLength();
int smsCount = envelope.getSMSCount(chars);
smsCounterLabel.setText(MessageFormat.format(l10n.getString("SMSPanel.smsCounterLabel.1"),
chars, smsCount));
if (chars > envelope.getMaxTextLength()) { //chars more than max
smsCounterLabel.setForeground(Color.RED);
smsCounterLabel.setText(MessageFormat.format(l10n.getString("SMSPanel.smsCounterLabel.2"),
chars));
} else { //chars ok
smsCounterLabel.setForeground(UIManager.getColor("Label.foreground"));
}
}
/** update form components */
private void updateUI(DocumentEvent e) {
try {
envelope.setText(e.getDocument().getText(0,e.getDocument().getLength()));
} catch (BadLocationException ex) {
logger.log(Level.SEVERE, "Error getting sms text", ex);
}
}
@Override
public void onUpdate(DocumentEvent e) {
countChars(e);
updateUI(e);
}
}
/** Limit maximum sms length and color it */
private class SMSTextPaneDocumentFilter extends DocumentFilter {
private StyledDocument doc;
private Style regular, highlight;
//updating after each event is slow, therefore there is timer
private Timer timer = new Timer(100, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
colorDocument(0,doc.getLength());
updateUI();
}
});
public SMSTextPaneDocumentFilter() {
super();
timer.setRepeats(false);
//set styles
doc = smsTextPane.getStyledDocument();
Style def = StyleContext.getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE);
regular = doc.addStyle("regular", def);
StyleConstants.setForeground(regular, UIManager.getColor("TextArea.foreground"));
highlight = doc.addStyle("highlight", def);
StyleConstants.setForeground(highlight, Color.BLUE);
// listen for changes in Look and Feel and change color of regular text
UIManager.addPropertyChangeListener(new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
if ("lookAndFeel".equals(evt.getPropertyName())) {
lafChanged();
}
}
});
// the same for substance skins (they do not notify UIManager from some reason)
SubstanceLookAndFeel.registerSkinChangeListener(new SkinChangeListener() {
@Override
public void skinChanged() {
lafChanged();
}
});
}
/** update components and actions */
private void updateUI() {
compressAction.updateStatus();
undoAction.updateStatus();
redoAction.updateStatus();
sendAction.updateStatus();
updateProgressBars();
}
/** color parts of sms */
private void colorDocument(int from, int length) {
while (from < length) {
int to = ((from / envelope.getSMSLength()) + 1) * envelope.getSMSLength() - 1;
to = to<length-1?to:length-1;
doc.setCharacterAttributes(from,to-from+1,getStyle(from),false);
from = to + 1;
}
}
/** calculate which style is appropriate for given position */
private Style getStyle(int offset) {
if ((offset / envelope.getSMSLength()) % 2 == 0) { //even sms
return regular;
} else {
return highlight;
}
}
@Override
public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
//if reached size limit, crop the text and show a warning
if ((fb.getDocument().getLength() + (text!=null?text.length():0) - length)
> envelope.getMaxTextLength()) {
MainFrame.getInstance().getStatusPanel().setStatusMessage(
l10n.getString("SMSPanel.Text_is_too_long!"), null, null);
MainFrame.getInstance().getStatusPanel().hideStatusMessageAfter(5000);
int maxlength = envelope.getMaxTextLength() - fb.getDocument().getLength() + length;
maxlength = Math.max(maxlength, 0);
text = text.substring(0, maxlength);
}
super.replace(fb, offset, length, text, getStyle(offset));
timer.restart();
}
@Override
public void insertString(DocumentFilter.FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException {
super.insertString(fb, offset, string, attr);
timer.restart();
}
@Override
public void remove(DocumentFilter.FilterBypass fb, int offset, int length) throws BadLocationException {
super.remove(fb, offset, length);
timer.restart();
}
/** request recoloring externally */
public void requestUpdate() {
timer.restart();
}
/** update text color on LaF change */
private void lafChanged() {
StyleConstants.setForeground(regular, UIManager.getColor("TextArea.foreground"));
SMSTextPaneDocumentFilter.this.requestUpdate();
}
}
/** Textfield for entering contact name or number */
public class RecipientTextField extends JTextField {
/** currently selected contact */
private Contact contact;
private RecipientDocumentChange recipientDocumentChange = new RecipientDocumentChange();
private String tooltip = l10n.getString("SMSPanel.recipientTextField.tooltip");
private String tooltipTip = l10n.getString("SMSPanel.recipientTextField.tooltip.tip");
public RecipientTextField() {
//set tooltip
if (StringUtils.isEmpty(config.getCountryPrefix())) {
setToolTipText(tooltip + tooltipTip + "</html>");
} else {
setToolTipText(tooltip + "</html>");
}
//focus listener
addFocusListener(new FocusListener() {
@Override
public void focusGained(FocusEvent e) {
selectAll();
}
@Override
public void focusLost(FocusEvent e) {
select(0, 0);
//try to rewrite phone number to contact name if possible
redrawContactName();
}
});
//key listener
addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent evt) {
//on Enter just focus the text area
if (evt != null && evt.getKeyCode() == KeyEvent.VK_ENTER) {
smsTextPane.requestFocusInWindow();
return;
}
}
});
//document listener
getDocument().addDocumentListener(new AbstractDocumentListener() {
@Override
public void onUpdate(DocumentEvent evt) {
if (disableContactListeners) {
return;
}
SwingUtilities.invokeLater(recipientDocumentChange);
}
});
}
/** Set contact to display. Will display contact name. Will not change
displayed text if user is currently editing it. */
public void setContact(Contact contact) {
this.contact = contact;
if (!hasFocus()) {
super.setText(contact != null ? contact.getName() : null);
}
}
/** Get currently chosen contact. May be null. */
public Contact getContact() {
return contact;
}
/** Return visible text. May be contact name or phone number (will include prefix).
May be null. */
@Override
public String getText() {
if (contact != null) {
return contact.getNumber();
}
String text = super.getText();
if (StringUtils.isNotEmpty(text) && !text.startsWith("+")) {
text = config.getCountryPrefix() + text;
}
//prepend country prefix if not present and text is a number
if (FormChecker.checkSMSNumber(text)) {
return text;
} else { //text is a name
return super.getText();
}
}
/** Set text to display. Will erase any internally remembered contact. */
@Override
public void setText(String text) {
contact = null;
super.setText(text);
}
/** Rewrite phone number to contact name. Used after user finished editing
the field. */
public void redrawContactName() {
if (contact == null) {
return;
}
boolean old = disableContactListeners;
disableContactListeners = true;
super.setText(contact.getName());
disableContactListeners = old;
}
/** Get phone number of chosen contact or typed phone number. May be null. */
public String getNumber() {
if (contact != null) {
return contact.getNumber();
}
String text = getText();
if (FormChecker.checkSMSNumber(text)) {
return text;
} else {
return null;
}
}
/** Set phone number to display. Handles country prefix correctly. */
public void setNumber(String number) {
if (StringUtils.isEmpty(number)) {
setText("");
}
setText(CountryPrefix.stripCountryPrefix(number));
}
/** Listener for changes in the recipient field */
private class RecipientDocumentChange implements Runnable {
@Override
public void run() {
//search for contact
contact = null;
contact = lookupContact(false);
requestSelectContact(null); //ensure contact selection will fire
requestSelectContact(contact); //event even if the same contact
//if not found and is number, guess operator
if (contact == null && getNumber() != null) {
operatorComboBox.selectSuggestedOperator(getNumber());
}
//update envelope
Set<Contact> set = new HashSet<Contact>();
set.add(new Contact(contact != null ? contact.getName() : null,
getNumber(), operatorComboBox.getSelectedOperatorName()));
envelope.setContacts(set);
//update send action
sendAction.updateStatus();
}
}
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private JProgressBar fullProgressBar;
private JLabel gatewayLabel;
private JScrollPane jScrollPane1;
private OperatorComboBox operatorComboBox;
private JLabel recipientLabel;
private JTextField recipientTextField;
private JButton sendButton;
private JProgressBar singleProgressBar;
private JLabel smsCounterLabel;
private JTextPane smsTextPane;
private JLabel textLabel;
// End of variables declaration//GEN-END:variables
}
| false | false | null | null |
diff --git a/src/com/ichi2/anki/DeckPicker.java b/src/com/ichi2/anki/DeckPicker.java
index b0c35f66..cf477c87 100644
--- a/src/com/ichi2/anki/DeckPicker.java
+++ b/src/com/ichi2/anki/DeckPicker.java
@@ -1,223 +1,225 @@
package com.ichi2.anki;
import java.io.File;
import java.io.FileFilter;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.TreeSet;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
import android.app.Activity;
import android.content.Intent;
import android.database.SQLException;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
/**
* Allows the user to choose a deck from the filesystem.
*
* @author Andrew Dubya
*
*/
public class DeckPicker extends Activity implements Runnable {
private DeckPicker mSelf;
private SimpleAdapter mDeckListAdapter;
private ArrayList<HashMap<String, String>> mDeckList;
private ListView mDeckListView;
private File[] mFileList;
private ReentrantLock mLock = new ReentrantLock();
private Condition mCondFinished = mLock.newCondition();
private boolean mFinished = true;
AdapterView.OnItemClickListener mDeckSelHandler = new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int p, long id) {
mSelf.handleDeckSelection(p);
}
};
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) throws SQLException {
super.onCreate(savedInstanceState);
mSelf = this;
String deckPath = getIntent().getStringExtra("com.ichi2.anki.Ankidroid.DeckPath");
setContentView(R.layout.main);
mDeckList = new ArrayList<HashMap<String,String>>();
mDeckListView = (ListView)findViewById(R.id.files);
mDeckListAdapter = new SimpleAdapter(this,
mDeckList,
R.layout.deck_picker_list,
new String [] {"name","due","new"},
new int [] {R.id.DeckPickerName, R.id.DeckPickerDue, R.id.DeckPickerNew});
mDeckListView.setOnItemClickListener(mDeckSelHandler);
mDeckListView.setAdapter(mDeckListAdapter);
populateDeckList(deckPath);
}
public void populateDeckList(String location)
{
int len = 0;
File[] fileList;
TreeSet<HashMap<String,String>> tree = new TreeSet<HashMap<String,String>>(new HashMapCompare());
File dir = new File(location);
fileList = dir.listFiles(new AnkiFilter());
if (dir.exists() && dir.isDirectory() && fileList != null) {
len = fileList.length;
}
mFileList = fileList;
if (len > 0 && fileList != null) {
for (int i=0; i<len; i++) {
String absPath = fileList[i].getAbsolutePath();
HashMap<String,String> data = new HashMap<String,String>();
data.put("name", fileList[i].getName().replaceAll(".anki", ""));
data.put("due", "Loading deck...");
data.put("new", "");
data.put("mod", String.valueOf(i));
+ data.put("filepath", absPath);
tree.add(data);
}
+
+ Thread thread = new Thread(this);
+ thread.start();
}
else {
HashMap<String,String> data = new HashMap<String,String>();
data.put("name", "No decks found.");
data.put("cards", "");
data.put("due", "");
data.put("mod", "1");
tree.add(data);
}
mDeckList.clear();
mDeckList.addAll(tree);
- mDeckListView.clearChoices();
-
- Thread thread = new Thread(this);
- thread.start();
+ mDeckListView.clearChoices();
}
public static final class AnkiFilter implements FileFilter {
public boolean accept(File pathname) {
if (pathname.isFile() && pathname.getName().endsWith(".anki"))
return true;
return false;
}
}
public static final class HashMapCompare implements Comparator<HashMap<String,String>> {
public int compare(HashMap<String, String> object1,
HashMap<String, String> object2) {
return (int) (Float.parseFloat(object2.get("mod")) - Float.parseFloat(object1.get("mod")));
}
}
public void handleDeckSelection(int id) {
String deckFilename = null;
mLock.lock();
try {
while (!mFinished)
mCondFinished.await();
@SuppressWarnings("unchecked")
HashMap<String,String> data = (HashMap<String,String>) mDeckListAdapter.getItem(id);
deckFilename = data.get("filepath");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
mLock.unlock();
}
if (deckFilename != null) {
Log.i("anki", "Selected " + deckFilename);
Intent intent = this.getIntent();
intent.putExtra(Ankidroid.OPT_DB, deckFilename);
setResult(RESULT_OK, intent);
finish();
}
}
public void run() {
int len = 0;
if (mFileList != null)
len = mFileList.length;
if (len > 0 && mFileList != null) {
mLock.lock();
try {
mFinished = false;
for (int i = 0; i < len; i++) {
String path = mFileList[i].getAbsolutePath();
Deck deck;
try {
deck = Deck.openDeck(path);
} catch (SQLException e) {
Log.w("anki", "Could not open database " + path);
continue;
}
int dueCards = deck.failedSoonCount + deck.revCount;
int totalCards = deck.cardCount;
int newCards = deck.newCountToday;
deck.closeDeck();
Bundle data = new Bundle();
data.putString("absPath", path);
data.putInt("due", dueCards);
data.putInt("total", totalCards);
data.putInt("new", newCards);
Message msg = Message.obtain();
msg.setData(data);
handler.sendMessage(msg);
}
mFinished = true;
mCondFinished.signal();
} finally {
mLock.unlock();
}
}
}
private Handler handler = new Handler() {
public void handleMessage(Message msg) {
Bundle data = msg.getData();
+
+ String path = data.getString("absPath");
String dueString = String.valueOf(data.getInt("due")) +
" of " +
String.valueOf(data.getInt("total")) +
" due";
String newString = String.valueOf(data.getInt("new")) +
- " new today ";
- String path = data.getString("absPath");
+ " new today";
int count = mDeckList.size();
for (int i = 0; i < count; i++) {
HashMap<String,String> map = (HashMap<String,String>) mDeckList.remove(i);
if (map.get("filepath").equals(path)) {
map.put("due", dueString);
map.put("new", newString);
}
mDeckList.add(i, map);
}
mDeckListAdapter.notifyDataSetChanged();
}
};
}
| false | false | null | null |
diff --git a/app/KryonetServerApplication.java b/app/KryonetServerApplication.java
index 3098e7f..6c53917 100644
--- a/app/KryonetServerApplication.java
+++ b/app/KryonetServerApplication.java
@@ -1,28 +1,30 @@
import java.io.IOException;
+import net.dlogic.kryonet.common.manager.RoomManagerInstance;
import net.dlogic.kryonet.server.KryonetServer;
import net.dlogic.kryonet.server.KryonetServerException;
import net.dlogic.kryonet.server.KryonetServerInstance;
public class KryonetServerApplication {
public static void main(String[] args) {
try {
int writeBufferSize = Integer.parseInt(args[0]);
int objectBufferSize = Integer.parseInt(args[1]);
int tcpPort = Integer.parseInt(args[2]);
int udpPort = Integer.parseInt(args[3]);
KryonetServerInstance.initialize(writeBufferSize, objectBufferSize);
KryonetServer server = KryonetServerInstance.getInstance();
server.listener.setConnectionEventHandler(MyConnectionEventHandler.class);
- server.listener.setLoginOrLogoutEventHandler(MyLoginOrLogoutEventHandler.class);
+ server.listener.setLoginOrLogoutEventHandler(MyUserEventHandler.class);
server.start(tcpPort, udpPort);
+ //RoomManagerInstance.roomManager.put(1, value);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (KryonetServerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| false | false | null | null |
diff --git a/src/com/voracious/dragons/server/DBHandler.java b/src/com/voracious/dragons/server/DBHandler.java
index c53a885..19fa84d 100644
--- a/src/com/voracious/dragons/server/DBHandler.java
+++ b/src/com/voracious/dragons/server/DBHandler.java
@@ -1,299 +1,304 @@
package com.voracious.dragons.server;
import java.io.File;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.PreparedStatement;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Arrays;
import org.apache.log4j.Logger;
public class DBHandler {
public static final String dbfile = "game_data.sqlite";
private static final String[] tableNames = { "Game", "Player", "Winner", "Turn", "Spectator" };
private static Logger logger = Logger.getLogger(DBHandler.class);
private Connection conn;
private PreparedStatement checkHash;
private PreparedStatement registerUser;
private PreparedStatement numGames,numWins,aveTurn,numTuples,times;
private PreparedStatement storeTurn,storeSpect,storeWinner,storeGame;
public void init() {
try {
Class.forName("org.sqlite.JDBC");
conn = DriverManager.getConnection("jdbc:sqlite:" + dbfile);
// Check if the tables are already there or not
DatabaseMetaData meta = conn.getMetaData();
ResultSet tableResults = meta.getTables(null, null, "%", null);
ArrayList<String> tables = new ArrayList<String>();
while (tableResults.next()) {
tables.add(tableResults.getString("TABLE_NAME"));
}
String[] tablesInDb = {null};
tablesInDb = tables.toArray(tablesInDb);
Arrays.sort(tablesInDb);
Arrays.sort(tableNames);
if (!tablesInDb.equals(tableNames)) {
conn.close();
new File(dbfile).delete();
conn = DriverManager.getConnection("jdbc:sqlite:" + dbfile);
createDatabase();
}
prepareStatements();
} catch (ClassNotFoundException e) {
logger.error("Could not load database", e);
} catch (SQLException e) {
logger.error("Could not load database", e);
}
}
private void prepareStatements(){
try {
checkHash = conn.prepareStatement("SELECT passhash" +
"FROM Player" +
"WHERE pid = ?");
registerUser = conn.prepareStatement("INSERT INTO Player VALUES(?, ?)");
numGames = conn.prepareStatement(
"SELECT count(gid) AS answer" +
"FROM Game" +
"WHERE (pid1=? OR pid2=?) AND inProgress=?" +
"GROUP BY gid;");
numWins=conn.prepareStatement(
"SELECT count(gid) AS answer" +
"FROM Winner" +
"WHERE pid=?" +
"GROUP BY gid;");
aveTurn=conn.prepareStatement(
"SELECT count(*) AS answer" +
"FROM Turn" +
"WHERE pid=?" +
"GROUP BY gid, tnum;");
numTuples=conn.prepareStatement(
"SELECT count(*) AS answer" +
"FROM Turn" +
"WHERE pid=?" +
"GROUP BY gid,tnum;");
times=conn.prepareStatement(
"SELECT gid AS GID, tNUM as TNUM, timeStamp AS TIMESTAMP" +
"FROM Turn" +
"WHERE pid=?" +
"ORDER BY gid ASC,tNum ASC;");
//possible to sort the time stamps also, so each games is in order from top to bottom
//g0 t0
//g0 t1
//g1 t0
//g2 t0
//g2 t1
//g2 t2
storeTurn=conn.prepareStatement(
"INSERT INTO Turn VALUES(?,?,?,?,?);");
storeSpect=conn.prepareStatement(
"INSERT INTO Spectator VALUES(?,?);");
storeWinner=conn.prepareStatement(
"INSERT INTO Winner VALUES(?,?);");
storeGame=conn.prepareStatement(
"INSERT INTO Game (pid1,pid2,gameState) VALUES(?,?,?)");
//assuming a game inserted will be inprogress
} catch (SQLException e) {
logger.error("Error preparing statements", e);
}
}
private void createDatabase() {
Statement query;
try {
query = conn.createStatement();
query.executeUpdate("CREATE TABLE Player (pid VARCHAR(15) PRIMARY KEY NOT NULL," +
"\n passhash CHAR(60) NOT NULL)");
query.executeUpdate("CREATE TABLE Game (gid INTEGER PRIMARY KEY AUTOINCREMENT," +
"\n pid1 VARCHAR(15) NOT NULL REFERENCES Player(pid), " +
"\n pid2 VARCHAR(15) NOT NULL REFERENCES Player(pid)," +
"\n inProgress BOOLEAN NOT NULL," +
"\n gameState VARCHAR(20))");
query.executeUpdate("CREATE TABLE Winner (gid INTEGER PRIMARY KEY NOT NULL REFERENCES Game(gid)," +
"\n pid VARCHAR(15) NOT NULL REFERENCES Player(pid))");
query.executeUpdate("CREATE TABLE Spectator (gid INTEGER PRIMARY KEY NOT NULL REFERENCES Game(gid)," +
"\n pid VARCHAR(15) NOT NULL REFERENCES Player(pid))");
query.executeUpdate("CREATE TABLE Turn (gid INTEGER NOT NULL REFERENCES Game(gid)," +
"\n tnum INTEGER NOT NULL," +
"\n timeStamp DATETIME NOT NULL DEFAULT CURRENT_TIME," +
"\n pid VARCHAR(15) NOT NULL REFERENCES Player(pid)," +
"\n turnString VARCHAR(60) NOT NULL," +
"\n PRIMARY KEY(gid, pid, tnum))");
} catch (SQLException e) {
logger.error("Could not create tables", e);
}
}
public void insertGame(String PID1,String PID2,String GAMESTATE){
try {
storeGame.setString(1, PID1);
storeGame.setString(2, PID2);
storeGame.setString(3, GAMESTATE);
storeGame.executeUpdate();
} catch (SQLException e) {
logger.error("Could not add to the game table",e);
}
}
public void insertWinner(int GID,String PID){
try {
storeWinner.setInt(1, GID);
storeWinner.setString(2, PID);
storeWinner.executeUpdate();
} catch (SQLException e) {
logger.error("Coud not add to the winner table",e);
}
}
public void insertSpectator(int GID,String PID){
try {
storeSpect.setInt(1, GID);
storeSpect.setString(2, PID);
storeSpect.executeUpdate();
} catch (SQLException e) {
logger.error("Could not add to teh specatator table",e);
}
}
public void insertTurn(int GID,int TNUM,Timestamp TIME,String PID,String TURNSTRING){
try{
storeTurn.setInt(1,GID);
storeTurn.setInt(2, TNUM);
storeTurn.setTimestamp(3, TIME);
storeTurn.setString(4, PID);
storeTurn.setString(5, TURNSTRING);
storeTurn.executeUpdate();
}
catch(SQLException e){
logger.error("Coul not add to the turn table", e);
}
}
public String getPasswordHash(String pid){
try {
checkHash.setString(1, pid);
ResultSet rs = checkHash.executeQuery();
return rs.getString("passhash");
} catch (SQLException e) {
logger.error("Could not check hash", e);
return null;
}
}
public void registerUser(String uid, String passhash){
try {
registerUser.setString(1, uid);
registerUser.setString(2, passhash);
registerUser.executeUpdate();
} catch (SQLException e) {
logger.error("Could not register user", e);
}
}
public int numGames(String PID, boolean inPlay){
//the boolean is to know if the games being counted are over or still occurring
try{
numGames.setString(1, PID);
numGames.setString(2, PID);
numGames.setString(3,inPlay+"");//does "true" == true+"" ?
ResultSet ret=numGames.executeQuery();
return ret.getInt("answer");
}
catch(SQLException e){
logger.error("Could not count the number of games",e);
return -1;
}
}
public int countWins(String PID){
try{
numWins.setString(1,PID);
ResultSet ret=numWins.executeQuery();
return ret.getInt("answer");
}
catch(SQLException e){
logger.error("Could not count the number of wins",e);
return -1;
}
}
public double aveTurns(String PID,int totalNumGames) {
//the totalNumGames = done + current games, so it needs the other qureies to be done first
+ if(totalNumGames==0)
+ return 0.0;
try {
aveTurn.setString(1, PID);
ResultSet ret=aveTurn.executeQuery();
int numTurns=ret.getInt("answer");
return numTurns/totalNumGames;
} catch (SQLException e) {
logger.error("Could not count the ave number of turns", e);
return -1.0;
}
}
public long aveTime(String PID){
//the group by is only there to have an arrogate query
try {
numTuples.setString(1, PID);
ResultSet tuples=numTuples.executeQuery();
int numberTuples=tuples.getInt("answer");
+ if(numberTuples==0)
+ return 0;
+
times.setString(1, PID);
ResultSet timeRes=times.executeQuery();
long sum=0;
//calculates the total time
Timestamp temp=new Timestamp(0),current;
while(timeRes.next()){
int turnCounter=timeRes.getInt("TNUM");//readin's turn num
if(turnCounter==0){
//set that reading's timestamp as the temp
temp=timeRes.getTimestamp("TIMESTAMP");
}
else {
current=timeRes.getTimestamp("TIMESTAMP");
sum+=current.getTime()-temp.getTime();
temp=current;
}
}
sum/=numberTuples;
return sum;
} catch (SQLException e) {
logger.error("Could not count the ave time between turns", e);
return -1;
}
}
}
| false | false | null | null |
diff --git a/site/src/main/java/org/onehippo/forge/weblogdemo/components/Search.java b/site/src/main/java/org/onehippo/forge/weblogdemo/components/Search.java
index 4c2abff..fc5937b 100644
--- a/site/src/main/java/org/onehippo/forge/weblogdemo/components/Search.java
+++ b/site/src/main/java/org/onehippo/forge/weblogdemo/components/Search.java
@@ -1,113 +1,113 @@
/*
* Copyright 2010 Jasha Joachimsthal
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onehippo.forge.weblogdemo.components;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;
import org.hippoecm.hst.content.beans.query.HstQuery;
import org.hippoecm.hst.content.beans.query.HstQueryResult;
import org.hippoecm.hst.content.beans.query.exceptions.QueryException;
import org.hippoecm.hst.content.beans.query.filter.Filter;
import org.hippoecm.hst.content.beans.standard.HippoBean;
import org.hippoecm.hst.content.beans.standard.HippoBeanIterator;
import org.hippoecm.hst.core.component.HstComponentException;
import org.hippoecm.hst.core.component.HstRequest;
import org.hippoecm.hst.core.component.HstResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.onehippo.forge.weblogdemo.beans.BaseDocument;
/**
* Simple search component. Excludes construction
* @author Jasha Joachimsthal
*
*/
public class Search extends BaseSiteComponent {
private static final String SEARCHFOR_PARAM = "searchfor";
private static final String PAGEPARAM = "page";
public static final Logger log = LoggerFactory.getLogger(Search.class);
public static final int PAGESIZE = 10;
@Override
public void doBeforeRender(HstRequest request, HstResponse response) throws HstComponentException {
super.doBeforeRender(request, response);
List<BaseDocument> documents = new ArrayList<BaseDocument>();
String pageStr = request.getParameter(PAGEPARAM);
String query = getPublicRequestParameter(request, SEARCHFOR_PARAM);
if (StringUtils.isBlank(query)) {
query = request.getParameter(SEARCHFOR_PARAM);
}
int page = 0;
if (StringUtils.isNotBlank(pageStr)) {
try {
page = Integer.parseInt(pageStr);
} catch (NumberFormatException e) {
// empty ignore
}
}
request.setAttribute(PAGEPARAM, page);
try {
List<HippoBean> excludes = new ArrayList<HippoBean>();
HippoBean construction = this.getSiteContentBaseBean(request).getBean("construction");
if (construction != null) {
excludes.add(construction);
}
HstQuery hstQuery = getQueryManager().createQuery(getSiteContentBaseBean(request));
hstQuery.excludeScopes(excludes);
if (StringUtils.isNotBlank(query)) {
Filter filter = hstQuery.createFilter();
filter.addContains(".", query);
hstQuery.setFilter(filter);
request.setAttribute(SEARCHFOR_PARAM, StringEscapeUtils.escapeHtml(query));
}
HstQueryResult result = hstQuery.execute();
HippoBeanIterator beans = result.getHippoBeans();
if (beans == null) {
return;
}
long beansSize = beans.getSize();
- long pages = beansSize / PAGESIZE;
+ long pages = beansSize % PAGESIZE > 0L ? beansSize / PAGESIZE + 1L : beansSize / PAGESIZE;
request.setAttribute("nrhits", beansSize > 0 ? beansSize : 0);
request.setAttribute("pages", pages);
int results = 0;
if (beansSize > page * PAGESIZE) {
beans.skip(page * PAGESIZE);
}
while (beans.hasNext() && results < PAGESIZE) {
HippoBean bean = beans.next();
if (bean != null && bean instanceof BaseDocument) {
documents.add((BaseDocument) bean);
results++;
}
}
} catch (QueryException e) {
log.warn("Error in search", e);
}
request.setAttribute("documents", documents);
}
}
| true | true | public void doBeforeRender(HstRequest request, HstResponse response) throws HstComponentException {
super.doBeforeRender(request, response);
List<BaseDocument> documents = new ArrayList<BaseDocument>();
String pageStr = request.getParameter(PAGEPARAM);
String query = getPublicRequestParameter(request, SEARCHFOR_PARAM);
if (StringUtils.isBlank(query)) {
query = request.getParameter(SEARCHFOR_PARAM);
}
int page = 0;
if (StringUtils.isNotBlank(pageStr)) {
try {
page = Integer.parseInt(pageStr);
} catch (NumberFormatException e) {
// empty ignore
}
}
request.setAttribute(PAGEPARAM, page);
try {
List<HippoBean> excludes = new ArrayList<HippoBean>();
HippoBean construction = this.getSiteContentBaseBean(request).getBean("construction");
if (construction != null) {
excludes.add(construction);
}
HstQuery hstQuery = getQueryManager().createQuery(getSiteContentBaseBean(request));
hstQuery.excludeScopes(excludes);
if (StringUtils.isNotBlank(query)) {
Filter filter = hstQuery.createFilter();
filter.addContains(".", query);
hstQuery.setFilter(filter);
request.setAttribute(SEARCHFOR_PARAM, StringEscapeUtils.escapeHtml(query));
}
HstQueryResult result = hstQuery.execute();
HippoBeanIterator beans = result.getHippoBeans();
if (beans == null) {
return;
}
long beansSize = beans.getSize();
long pages = beansSize / PAGESIZE;
request.setAttribute("nrhits", beansSize > 0 ? beansSize : 0);
request.setAttribute("pages", pages);
int results = 0;
if (beansSize > page * PAGESIZE) {
beans.skip(page * PAGESIZE);
}
while (beans.hasNext() && results < PAGESIZE) {
HippoBean bean = beans.next();
if (bean != null && bean instanceof BaseDocument) {
documents.add((BaseDocument) bean);
results++;
}
}
} catch (QueryException e) {
log.warn("Error in search", e);
}
request.setAttribute("documents", documents);
}
| public void doBeforeRender(HstRequest request, HstResponse response) throws HstComponentException {
super.doBeforeRender(request, response);
List<BaseDocument> documents = new ArrayList<BaseDocument>();
String pageStr = request.getParameter(PAGEPARAM);
String query = getPublicRequestParameter(request, SEARCHFOR_PARAM);
if (StringUtils.isBlank(query)) {
query = request.getParameter(SEARCHFOR_PARAM);
}
int page = 0;
if (StringUtils.isNotBlank(pageStr)) {
try {
page = Integer.parseInt(pageStr);
} catch (NumberFormatException e) {
// empty ignore
}
}
request.setAttribute(PAGEPARAM, page);
try {
List<HippoBean> excludes = new ArrayList<HippoBean>();
HippoBean construction = this.getSiteContentBaseBean(request).getBean("construction");
if (construction != null) {
excludes.add(construction);
}
HstQuery hstQuery = getQueryManager().createQuery(getSiteContentBaseBean(request));
hstQuery.excludeScopes(excludes);
if (StringUtils.isNotBlank(query)) {
Filter filter = hstQuery.createFilter();
filter.addContains(".", query);
hstQuery.setFilter(filter);
request.setAttribute(SEARCHFOR_PARAM, StringEscapeUtils.escapeHtml(query));
}
HstQueryResult result = hstQuery.execute();
HippoBeanIterator beans = result.getHippoBeans();
if (beans == null) {
return;
}
long beansSize = beans.getSize();
long pages = beansSize % PAGESIZE > 0L ? beansSize / PAGESIZE + 1L : beansSize / PAGESIZE;
request.setAttribute("nrhits", beansSize > 0 ? beansSize : 0);
request.setAttribute("pages", pages);
int results = 0;
if (beansSize > page * PAGESIZE) {
beans.skip(page * PAGESIZE);
}
while (beans.hasNext() && results < PAGESIZE) {
HippoBean bean = beans.next();
if (bean != null && bean instanceof BaseDocument) {
documents.add((BaseDocument) bean);
results++;
}
}
} catch (QueryException e) {
log.warn("Error in search", e);
}
request.setAttribute("documents", documents);
}
|
diff --git a/project-model-maven-tests/src/test/java/org/jboss/forge/maven/facets/MavenDependencyFacetTest.java b/project-model-maven-tests/src/test/java/org/jboss/forge/maven/facets/MavenDependencyFacetTest.java
index 9e7ebfa32..98c5cb68f 100644
--- a/project-model-maven-tests/src/test/java/org/jboss/forge/maven/facets/MavenDependencyFacetTest.java
+++ b/project-model-maven-tests/src/test/java/org/jboss/forge/maven/facets/MavenDependencyFacetTest.java
@@ -1,192 +1,192 @@
/*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat, Inc., and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.forge.maven.facets;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-
import java.util.List;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.forge.maven.util.ProjectModelTest;
import org.jboss.forge.project.Project;
import org.jboss.forge.project.dependencies.Dependency;
import org.jboss.forge.project.dependencies.DependencyBuilder;
import org.jboss.forge.project.facets.DependencyFacet;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
/**
* @author <a href="mailto:[email protected]">Lincoln Baxter, III</a>
*/
@RunWith(Arquillian.class)
public class MavenDependencyFacetTest extends ProjectModelTest
{
@Deployment
public static JavaArchive createTestArchive()
{
return ProjectModelTest.createTestArchive()
.addAsManifestResource(
"META-INF/services/org.jboss.forge.project.dependencies.DependencyResolverProvider");
}
@Test
public void testHasDependency() throws Exception
{
DependencyFacet deps = getProject().getFacet(DependencyFacet.class);
DependencyBuilder prettyfaces = DependencyBuilder.create("com.ocpsoft:prettyfaces-jsf2:${pf.version}");
deps.setProperty("pf.version", "3.3.2");
deps.addDirectDependency(prettyfaces);
assertTrue(deps.hasDirectDependency(prettyfaces));
assertTrue(deps.hasEffectiveDependency(prettyfaces));
assertEquals("3.3.2", deps.getEffectiveDependency(prettyfaces).getVersion());
assertEquals("3.3.2", deps.getDirectDependency(prettyfaces).getVersion());
}
@Test
public void testHasImportedManagedDependency() throws Exception
{
DependencyFacet deps = getProject().getFacet(DependencyFacet.class);
DependencyBuilder javaeeSpec = DependencyBuilder.create("org.jboss.spec:jboss-javaee-6.0:1.0.0.Final:import:pom");
assertFalse(deps.hasDirectManagedDependency(javaeeSpec));
deps.addDirectManagedDependency(javaeeSpec);
assertTrue(deps.hasDirectManagedDependency(javaeeSpec));
DependencyBuilder ejb = DependencyBuilder.create("org.jboss.spec.javax.ejb:jboss-ejb-api_3.1_spec:1.0.0.Final");
assertTrue(deps.hasEffectiveManagedDependency(ejb));
}
@Test
public void testAddDependency() throws Exception
{
Dependency dependency =
DependencyBuilder.create("org.jboss:test-dependency:1.0.0.Final");
Project project = getProject();
DependencyFacet deps = project.getFacet(DependencyFacet.class);
assertFalse(deps.hasEffectiveDependency(dependency));
deps.addDirectDependency(dependency);
assertTrue(deps.hasEffectiveDependency(dependency));
assertTrue(deps.hasDirectDependency(dependency));
}
@Test
public void testRemoveDependency() throws Exception
{
Dependency dependency =
DependencyBuilder.create("org.jboss:test-dependency2:1.0.1.Final");
Project project = getProject();
DependencyFacet deps = project.getFacet(DependencyFacet.class);
assertFalse(deps.hasEffectiveDependency(dependency));
deps.addDirectDependency(dependency);
assertTrue(deps.hasDirectDependency(dependency));
assertTrue(deps.hasEffectiveDependency(dependency));
deps.removeDependency(dependency);
assertFalse(deps.hasDirectDependency(dependency));
assertFalse(deps.hasEffectiveDependency(dependency));
}
@Test
public void testAddProperty() throws Exception
{
String version = "1.0.2.Final";
Project project = getProject();
DependencyFacet deps = project.getFacet(DependencyFacet.class);
deps.setProperty("version", version);
assertEquals(version, deps.getProperty("version"));
}
@Test
@Ignore
public void testDoResolveVersions() throws Exception
{
Project project = getProject();
DependencyFacet deps = project.getFacet(DependencyFacet.class);
List<Dependency> versions = deps.resolveAvailableVersions("com.ocpsoft:prettyfaces-jsf2");
assertTrue(versions.size() > 4);
}
@Test
public void testHasManagedDependencyImport() throws Exception
{
DependencyFacet deps = getProject().getFacet(DependencyFacet.class);
DependencyBuilder javaeeSpec = DependencyBuilder.create("org.jboss.spec:jboss-javaee-6.0:1.0.0.Final:import:pom");
assertFalse(deps.hasDirectManagedDependency(javaeeSpec));
deps.addDirectManagedDependency(javaeeSpec);
assertTrue(deps.hasDirectManagedDependency(javaeeSpec));
}
@Test
public void testAddManagedDependency() throws Exception
{
Dependency dependency =
DependencyBuilder.create("org.jboss.seam:seam-bom:3.0.0.Final:import:pom");
Project project = getProject();
DependencyFacet manDeps = project.getFacet(DependencyFacet.class);
assertFalse(manDeps.hasDirectManagedDependency(dependency));
manDeps.addManagedDependency(dependency);
assertTrue(manDeps.hasDirectManagedDependency(dependency));
}
@Test
public void testRemoveManagedDependency() throws Exception
{
Dependency dependency =
DependencyBuilder.create("org.jboss.seam:seam-bom:3.0.0.Final:import:pom");
Project project = getProject();
DependencyFacet deps = project.getFacet(DependencyFacet.class);
assertFalse(deps.hasDirectManagedDependency(dependency));
deps.addDirectManagedDependency(dependency);
assertTrue(deps.hasDirectManagedDependency(dependency));
deps.removeManagedDependency(dependency);
assertFalse(deps.hasDirectManagedDependency(dependency));
}
@Test
public void testHasDependencyBehavior() throws Exception
{
DependencyFacet dependencyFacet = getProject().getFacet(DependencyFacet.class);
DependencyBuilder forgeShellApiDependency = DependencyBuilder.create().setGroupId("org.jboss.forge")
- .setArtifactId("forge-shell-api").setVersion("1.0.0-SNAPSHOT");
+ .setArtifactId("forge-shell-api").setVersion("[1.0.0-SNAPSHOT,)");
DependencyBuilder cdiDependency = DependencyBuilder.create().setGroupId("javax.enterprise")
.setArtifactId("cdi-api");
assertFalse(dependencyFacet.hasEffectiveDependency(cdiDependency));
assertFalse(dependencyFacet.hasDirectDependency(cdiDependency));
dependencyFacet.addDirectDependency(forgeShellApiDependency);
assertTrue(dependencyFacet.hasEffectiveDependency(cdiDependency));
assertFalse(dependencyFacet.hasDirectDependency(cdiDependency));
}
}
| false | false | null | null |
diff --git a/src/com/android/browser/homepages/RequestHandler.java b/src/com/android/browser/homepages/RequestHandler.java
index e0a0eac4..defda612 100644
--- a/src/com/android/browser/homepages/RequestHandler.java
+++ b/src/com/android/browser/homepages/RequestHandler.java
@@ -1,146 +1,151 @@
/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR 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.browser.homepages;
-import com.android.browser.R;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
import android.content.Context;
import android.content.UriMatcher;
import android.content.res.Resources;
import android.database.Cursor;
import android.net.Uri;
import android.provider.Browser;
+import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
+import com.android.browser.R;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
public class RequestHandler extends Thread {
private static final String TAG = "RequestHandler";
private static final int INDEX = 1;
private static final int RESOURCE = 2;
private static final UriMatcher sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
Uri mUri;
Context mContext;
OutputStream mOutput;
static {
sUriMatcher.addURI(HomeProvider.AUTHORITY, "/", INDEX);
sUriMatcher.addURI(HomeProvider.AUTHORITY, "res/*/*", RESOURCE);
}
public RequestHandler(Context context, Uri uri, OutputStream out) {
mUri = uri;
mContext = context.getApplicationContext();
mOutput = out;
}
@Override
public void run() {
super.run();
try {
doHandleRequest();
} catch (Exception e) {
Log.e(TAG, "Failed to handle request: " + mUri, e);
} finally {
cleanup();
}
}
void doHandleRequest() throws IOException {
int match = sUriMatcher.match(mUri);
switch (match) {
case INDEX:
writeTemplatedIndex();
break;
case RESOURCE:
writeResource(getUriResourcePath());
break;
}
}
+ byte[] htmlEncode(String s) {
+ return TextUtils.htmlEncode(s).getBytes();
+ }
+
void writeTemplatedIndex() throws IOException {
Template t = Template.getCachedTemplate(mContext, R.raw.most_visited);
Cursor cursor = mContext.getContentResolver().query(Browser.BOOKMARKS_URI,
new String[] { "DISTINCT url", "title", "thumbnail" },
"(visits > 0 OR bookmark = 1) AND url NOT LIKE 'content:%' AND thumbnail IS NOT NULL", null, "visits DESC LIMIT 12");
t.assignLoop("most_visited", new Template.CursorListEntityWrapper(cursor) {
@Override
public void writeValue(OutputStream stream, String key) throws IOException {
Cursor cursor = getCursor();
if (key.equals("url")) {
- stream.write(cursor.getString(0).getBytes());
+ stream.write(htmlEncode(cursor.getString(0)));
} else if (key.equals("title")) {
- stream.write(cursor.getString(1).getBytes());
+ stream.write(htmlEncode(cursor.getString(1)));
} else if (key.equals("thumbnail")) {
stream.write("data:image/png;base64,".getBytes());
byte[] thumb = cursor.getBlob(2);
stream.write(Base64.encode(thumb, Base64.DEFAULT));
}
}
});
t.write(mOutput);
}
String getUriResourcePath() {
final Pattern pattern = Pattern.compile("/?res/([\\w/]+)");
Matcher m = pattern.matcher(mUri.getPath());
if (m.matches()) {
return m.group(1);
} else {
return mUri.getPath();
}
}
void writeResource(String fileName) throws IOException {
Resources res = mContext.getResources();
String packageName = R.class.getPackage().getName();
int id = res.getIdentifier(fileName, null, packageName);
if (id != 0) {
InputStream in = res.openRawResource(id);
byte[] buf = new byte[4096];
int read;
while ((read = in.read(buf)) > 0) {
mOutput.write(buf, 0, read);
}
}
}
void writeString(String str) throws IOException {
mOutput.write(str.getBytes());
}
void writeString(String str, int offset, int count) throws IOException {
mOutput.write(str.getBytes(), offset, count);
}
void cleanup() {
try {
mOutput.close();
} catch (Exception e) {
Log.e(TAG, "Failed to close pipe!", e);
}
}
}
| false | false | null | null |
diff --git a/plugins/reportal/src/azkaban/viewer/reportal/ReportalMailCreator.java b/plugins/reportal/src/azkaban/viewer/reportal/ReportalMailCreator.java
index dcff9b8..088f1c6 100644
--- a/plugins/reportal/src/azkaban/viewer/reportal/ReportalMailCreator.java
+++ b/plugins/reportal/src/azkaban/viewer/reportal/ReportalMailCreator.java
@@ -1,231 +1,231 @@
/*
* Copyright 2012 LinkedIn Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package azkaban.viewer.reportal;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
import org.apache.commons.io.IOUtils;
import azkaban.executor.ExecutableFlow;
import azkaban.executor.ExecutionOptions;
import azkaban.executor.mail.DefaultMailCreator;
import azkaban.executor.mail.MailCreator;
import azkaban.project.Project;
import azkaban.reportal.util.IStreamProvider;
import azkaban.reportal.util.ReportalHelper;
import azkaban.reportal.util.ReportalUtil;
import azkaban.reportal.util.StreamProviderHDFS;
import azkaban.security.commons.HadoopSecurityManager;
import azkaban.utils.EmailMessage;
import azkaban.webapp.AzkabanWebServer;
public class ReportalMailCreator implements MailCreator {
public static AzkabanWebServer azkaban = null;
public static HadoopSecurityManager hadoopSecurityManager = null;
public static String outputLocation = "";
public static String outputFileSystem = "";
public static String reportalStorageUser = "";
public static File reportalMailDirectory;
public static final String REPORTAL_MAIL_CREATOR = "ReportalMailCreator";
public static final int NUM_PREVIEW_ROWS = 50;
static {
DefaultMailCreator.registerCreator(REPORTAL_MAIL_CREATOR, new ReportalMailCreator());
}
@Override
public boolean createFirstErrorMessage(ExecutableFlow flow, EmailMessage message, String azkabanName, String clientHostname, String clientPortNumber, String... vars) {
ExecutionOptions option = flow.getExecutionOptions();
List<String> emailList = option.getFailureEmails();
return createEmail(flow, emailList, message, "failed", azkabanName, clientHostname, clientPortNumber, false);
}
@Override
public boolean createErrorEmail(ExecutableFlow flow, EmailMessage message, String azkabanName, String clientHostname, String clientPortNumber, String... vars) {
ExecutionOptions option = flow.getExecutionOptions();
List<String> emailList = option.getFailureEmails();
return createEmail(flow, emailList, message, "failed", azkabanName, clientHostname, clientPortNumber, false);
}
@Override
public boolean createSuccessEmail(ExecutableFlow flow, EmailMessage message, String azkabanName, String clientHostname, String clientPortNumber, String... vars) {
ExecutionOptions option = flow.getExecutionOptions();
List<String> emailList = option.getSuccessEmails();
return createEmail(flow, emailList, message, "succeeded", azkabanName, clientHostname, clientPortNumber, true);
}
private boolean createEmail(ExecutableFlow flow, List<String> emailList, EmailMessage message, String status, String azkabanName, String clientHostname, String clientPortNumber, boolean printData) {
Project project = azkaban.getProjectManager().getProject(flow.getProjectId());
if (emailList != null && !emailList.isEmpty()) {
message.addAllToAddress(emailList);
message.setMimeType("text/html");
message.setSubject("Report '" + project.getMetadata().get("title") + "' has " + status + " on " + azkabanName);
String urlPrefix = "https://" + clientHostname + ":" + clientPortNumber + "/reportal";
try {
createMessage(project, flow, message, urlPrefix, printData);
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
return false;
}
private void createMessage(Project project, ExecutableFlow flow, EmailMessage message, String urlPrefix, boolean printData) throws Exception {
message.println("<html>");
message.println("<head></head>");
message.println("<body style='font-family: verdana; color: #000000; background-color: #cccccc; padding: 20px;'>");
message.println("<div style='background-color: #ffffff; border: 1px solid #aaaaaa; padding: 20px;-webkit-border-radius: 15px; -moz-border-radius: 15px; border-radius: 15px;'>");
// Title
message.println("<b>" + project.getMetadata().get("title") + "</b>");
message.println("<div style='font-size: .8em; margin-top: .5em; margin-bottom: .5em;'>");
// Status
message.println(flow.getStatus().name());
// Link to logs
message.println("(<a href='" + urlPrefix + "?view&logs&id=" + flow.getProjectId() + "&execid=" + flow.getExecutionId() + "'>Logs</a>)");
// Link to Data
message.println("(<a href='" + urlPrefix + "?view&id=" + flow.getProjectId() + "&execid=" + flow.getExecutionId() + "'>Result data</a>)");
// Link to Edit
message.println("(<a href='" + urlPrefix + "?edit&id=" + flow.getProjectId() + "'>Edit</a>)");
message.println("</div>");
message.println("<div style='margin-top: .5em; margin-bottom: .5em;'>");
// Description
message.println(project.getDescription());
message.println("</div>");
// message.println("{% if queue.vars|length > 0 %}");
// message.println("<div style='margin-top: 10px; margin-bottom: 10px; border-bottom: 1px solid #ccc; padding-bottom: 5px; font-weight: bold;'>");
// message.println("Variables");
// message.println("</div>");
// message.println("");
// message.println("<div>");
// message.println("{% for qv in queue.vars %}");
// message.println("{{ qv.var.title }}: {{ qv.value}}<br/>");
// message.println("{% endfor %}");
// message.println("</div>");
// message.println("{% endif %}");
if (printData) {
String locationFull = (outputLocation + "/" + flow.getExecutionId()).replace("//", "/");
IStreamProvider streamProvider = ReportalUtil.getStreamProvider(outputFileSystem);
if (streamProvider instanceof StreamProviderHDFS) {
StreamProviderHDFS hdfsStreamProvider = (StreamProviderHDFS) streamProvider;
hdfsStreamProvider.setHadoopSecurityManager(hadoopSecurityManager);
hdfsStreamProvider.setUser(reportalStorageUser);
}
// Get file list
String[] fileList = ReportalHelper.filterCSVFile(streamProvider.getFileList(locationFull));
Arrays.sort(fileList);
File tempFolder = new File(reportalMailDirectory + "/" + flow.getExecutionId());
tempFolder.mkdirs();
for (String file : fileList) {
String filePath = locationFull + "/" + file;
InputStream csvInputStream = null;
OutputStream tempOutputStream = null;
File tempOutputFile = new File(tempFolder, file);
tempOutputFile.createNewFile();
try {
csvInputStream = streamProvider.getFileInputStream(filePath);
tempOutputStream = new BufferedOutputStream(new FileOutputStream(tempOutputFile));
IOUtils.copy(csvInputStream, tempOutputStream);
} finally {
IOUtils.closeQuietly(tempOutputStream);
IOUtils.closeQuietly(csvInputStream);
}
}
try {
streamProvider.cleanUp();
} catch (IOException e) {
e.printStackTrace();
}
for (String file : fileList) {
message.println("<div style='margin-top: 10px; margin-bottom: 10px; border-bottom: 1px solid #ccc; padding-bottom: 5px; font-weight: bold;'>");
message.println(file);
message.println("</div>");
message.println("<div>");
message.println("<table border='1' cellspacing='0' cellpadding='2' style='font-size: 14px;'>");
File tempOutputFile = new File(tempFolder, file);
InputStream csvInputStream = null;
try {
csvInputStream = new BufferedInputStream(new FileInputStream(tempOutputFile));
Scanner rowScanner = new Scanner(csvInputStream);
int lineNumber = 0;
while (rowScanner.hasNextLine() && lineNumber <= NUM_PREVIEW_ROWS) {
String csvLine = rowScanner.nextLine();
- String[] data = csvLine.split(",");
+ String[] data = csvLine.split("\",\"");
message.println("<tr>");
for (String item : data) {
message.println("<td>" + item.replace("\"", "") + "</td>");
}
message.println("</tr>");
if (lineNumber == NUM_PREVIEW_ROWS && rowScanner.hasNextLine()) {
message.println("<tr>");
message.println("<td colspan=\"" + data.length + "\">...</td>");
message.println("</tr>");
}
lineNumber++;
}
rowScanner.close();
message.println("</table>");
message.println("</div>");
} finally {
IOUtils.closeQuietly(csvInputStream);
}
message.addAttachment(file, tempOutputFile);
}
}
message.println("</div>").println("</body>").println("</html>");
// message.println("<h2> Execution '" + flow.getExecutionId() + "' of flow '" + flow.getFlowId() + "' has succeeded on " + azkabanName + "</h2>");
// message.println("<table>");
// message.println("<tr><td>Start Time</td><td>" + flow.getStartTime() + "</td></tr>");
// message.println("<tr><td>End Time</td><td>" + flow.getEndTime() + "</td></tr>");
// message.println("<tr><td>Duration</td><td>" + Utils.formatDuration(flow.getStartTime(), flow.getEndTime()) + "</td></tr>");
// message.println("</table>");
// message.println("");
// String executionUrl = "https://" + clientHostname + ":" + clientPortNumber + "/" + "executor?" + "execid=" + execId;
// message.println("<a href=\"" + executionUrl + "\">" + flow.getFlowId() + " Execution Link</a>");
}
}
diff --git a/plugins/reportal/src/azkaban/viewer/reportal/ReportalServlet.java b/plugins/reportal/src/azkaban/viewer/reportal/ReportalServlet.java
index 7aff266..c8f0aee 100644
--- a/plugins/reportal/src/azkaban/viewer/reportal/ReportalServlet.java
+++ b/plugins/reportal/src/azkaban/viewer/reportal/ReportalServlet.java
@@ -1,992 +1,992 @@
/*
* Copyright 2012 LinkedIn Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package azkaban.viewer.reportal;
import java.io.File;
import java.io.FileFilter;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.joda.time.DateTime;
import azkaban.executor.ExecutableFlow;
import azkaban.executor.ExecutableNode;
import azkaban.executor.ExecutionOptions;
import azkaban.executor.ExecutorManager;
import azkaban.executor.ExecutorManagerAdapter;
import azkaban.executor.ExecutorManagerException;
import azkaban.flow.Flow;
import azkaban.project.Project;
import azkaban.project.ProjectManager;
import azkaban.project.ProjectManagerException;
import azkaban.reportal.util.IStreamProvider;
import azkaban.reportal.util.Reportal;
import azkaban.reportal.util.Reportal.Query;
import azkaban.reportal.util.Reportal.Variable;
import azkaban.reportal.util.ReportalHelper;
import azkaban.reportal.util.ReportalUtil;
import azkaban.reportal.util.StreamProviderHDFS;
import azkaban.scheduler.ScheduleManager;
import azkaban.scheduler.ScheduleManagerException;
import azkaban.security.commons.HadoopSecurityManager;
import azkaban.user.Permission.Type;
import azkaban.user.User;
import azkaban.utils.FileIOUtils.LogData;
import azkaban.utils.Props;
import azkaban.webapp.AzkabanWebServer;
import azkaban.webapp.servlet.LoginAbstractAzkabanServlet;
import azkaban.webapp.servlet.Page;
import azkaban.webapp.session.Session;
public class ReportalServlet extends LoginAbstractAzkabanServlet {
private static final String REPORTAL_VARIABLE_PREFIX = "reportal.variable.";
private static final String HADOOP_SECURITY_MANAGER_CLASS_PARAM = "hadoop.security.manager.class";
private static final long serialVersionUID = 1L;
private static Logger logger = Logger.getLogger(ReportalServlet.class);
private CleanerThread cleanerThread;
private File reportalMailDirectory;
private AzkabanWebServer server;
private Props props;
private boolean shouldProxy;
private String viewerName;
private String reportalStorageUser;
private File webResourcesFolder;
private int itemsPerPage = 20;
private boolean showNav;
// private String viewerPath;
private HadoopSecurityManager hadoopSecurityManager;
public ReportalServlet(Props props) {
this.props = props;
viewerName = props.getString("viewer.name");
reportalStorageUser = props.getString("reportal.storage.user", "reportal");
itemsPerPage = props.getInt("reportal.items_per_page", 20);
showNav = props.getBoolean("reportal.show.navigation", false);
reportalMailDirectory = new File(props.getString("reportal.mail.temp.directory", "/tmp/reportal"));
reportalMailDirectory.mkdirs();
ReportalMailCreator.reportalMailDirectory = reportalMailDirectory;
ReportalMailCreator.outputLocation = props.getString("reportal.output.location", "/tmp/reportal");
ReportalMailCreator.outputFileSystem = props.getString("reportal.output.filesystem", "local");
ReportalMailCreator.reportalStorageUser = reportalStorageUser;
webResourcesFolder = new File(new File(props.getSource()).getParentFile().getParentFile(), "web");
webResourcesFolder.mkdirs();
setResourceDirectory(webResourcesFolder);
System.out.println("Reportal web resources: " + webResourcesFolder.getAbsolutePath());
}
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
server = (AzkabanWebServer)getApplication();
cleanerThread = new CleanerThread();
cleanerThread.start();
ReportalMailCreator.azkaban = server;
shouldProxy = props.getBoolean("azkaban.should.proxy", false);
logger.info("Hdfs browser should proxy: " + shouldProxy);
try {
hadoopSecurityManager = loadHadoopSecurityManager(props, logger);
ReportalMailCreator.hadoopSecurityManager = hadoopSecurityManager;
} catch (RuntimeException e) {
e.printStackTrace();
throw new RuntimeException("Failed to get hadoop security manager!" + e.getCause());
}
}
private HadoopSecurityManager loadHadoopSecurityManager(Props props, Logger logger) throws RuntimeException {
Class<?> hadoopSecurityManagerClass = props.getClass(HADOOP_SECURITY_MANAGER_CLASS_PARAM, true, ReportalServlet.class.getClassLoader());
logger.info("Initializing hadoop security manager " + hadoopSecurityManagerClass.getName());
HadoopSecurityManager hadoopSecurityManager = null;
try {
Method getInstanceMethod = hadoopSecurityManagerClass.getMethod("getInstance", Props.class);
hadoopSecurityManager = (HadoopSecurityManager)getInstanceMethod.invoke(hadoopSecurityManagerClass, props);
} catch (InvocationTargetException e) {
logger.error("Could not instantiate Hadoop Security Manager " + hadoopSecurityManagerClass.getName() + e.getCause());
throw new RuntimeException(e.getCause());
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e.getCause());
}
return hadoopSecurityManager;
}
@Override
protected void handleGet(HttpServletRequest req, HttpServletResponse resp, Session session) throws ServletException, IOException {
if (hasParam(req, "ajax")) {
handleAJAXAction(req, resp, session);
}
else {
if (hasParam(req, "view")) {
try {
handleViewReportal(req, resp, session);
} catch (Exception e) {
e.printStackTrace();
}
}
else if (hasParam(req, "new")) {
handleNewReportal(req, resp, session);
}
else if (hasParam(req, "edit")) {
handleEditReportal(req, resp, session);
}
else if (hasParam(req, "run")) {
handleRunReportal(req, resp, session);
}
else {
handleListReportal(req, resp, session);
}
}
}
private void handleAJAXAction(HttpServletRequest req, HttpServletResponse resp, Session session) throws ServletException, IOException {
HashMap<String, Object> ret = new HashMap<String, Object>();
String ajaxName = getParam(req, "ajax");
User user = session.getUser();
int id = getIntParam(req, "id");
ProjectManager projectManager = server.getProjectManager();
Project project = projectManager.getProject(id);
Reportal reportal = Reportal.loadFromProject(project);
// Delete reportal
if (ajaxName.equals("delete")) {
if (!project.hasPermission(user, Type.ADMIN)) {
ret.put("error", "You do not have permissions to delete this reportal.");
}
else {
try {
ScheduleManager scheduleManager = server.getScheduleManager();
reportal.removeSchedules(scheduleManager);
projectManager.removeProject(project, user);
} catch (Exception e) {
e.printStackTrace();
ret.put("error", "An exception occured while deleting this reportal.");
}
ret.put("result", "success");
}
}
// Bookmark reportal
else if (ajaxName.equals("bookmark")) {
boolean wasBookmarked = ReportalHelper.isBookmarkProject(project, user);
try {
if (wasBookmarked) {
ReportalHelper.unBookmarkProject(server, project, user);
ret.put("result", "success");
ret.put("bookmark", false);
}
else {
ReportalHelper.bookmarkProject(server, project, user);
ret.put("result", "success");
ret.put("bookmark", true);
}
} catch (ProjectManagerException e) {
e.printStackTrace();
ret.put("error", "Error bookmarking reportal. " + e.getMessage());
}
}
// Subscribe reportal
else if (ajaxName.equals("subscribe")) {
boolean wasSubscribed = ReportalHelper.isSubscribeProject(project, user);
if (!wasSubscribed && !project.hasPermission(user, Type.READ)) {
ret.put("error", "You do not have permissions to view this reportal.");
}
else {
try {
if (wasSubscribed) {
ReportalHelper.unSubscribeProject(server, project, user);
ret.put("result", "success");
ret.put("subscribe", false);
}
else {
ReportalHelper.subscribeProject(server, project, user, user.getEmail());
ret.put("result", "success");
ret.put("subscribe", true);
}
} catch (ProjectManagerException e) {
e.printStackTrace();
ret.put("error", "Error subscribing to reportal. " + e.getMessage());
}
}
}
// Set graph
else if (ajaxName.equals("graph")) {
if (!project.hasPermission(user, Type.READ)) {
ret.put("error", "You do not have permissions to view this reportal.");
}
else {
String hash = getParam(req, "hash");
project.getMetadata().put("graphHash", hash);
try {
server.getProjectManager().updateProjectSetting(project);
ret.put("result", "success");
ret.put("message", "Default graph saved.");
} catch (ProjectManagerException e) {
e.printStackTrace();
ret.put("error", "Error saving graph. " + e.getMessage());
}
}
}
// Get a portion of logs
else if (ajaxName.equals("log")) {
int execId = getIntParam(req, "execId");
String jobId = getParam(req, "jobId");
int offset = getIntParam(req, "offset");
int length = getIntParam(req, "length");
ExecutableFlow exec;
ExecutorManagerAdapter executorManager = server.getExecutorManager();
try {
exec = executorManager.getExecutableFlow(execId);
} catch (Exception e) {
ret.put("error", "Log does not exist or isn't created yet.");
return;
}
LogData data;
try {
data = executorManager.getExecutionJobLog(exec, jobId, offset, length, exec.getExecutableNode(jobId).getAttempt());
} catch (Exception e) {
e.printStackTrace();
ret.put("error", "Log does not exist or isn't created yet.");
return;
}
if (data != null) {
ret.put("result", "success");
ret.put("log", data.getData());
ret.put("offset", data.getOffset());
ret.put("length", data.getLength());
ret.put("completed", exec.getEndTime() != -1);
}
else {
// Return an empty result to indicate the end
ret.put("result", "success");
ret.put("log", "");
ret.put("offset", offset);
ret.put("length", 0);
ret.put("completed", exec.getEndTime() != -1);
}
}
if (ret != null) {
this.writeJSON(resp, ret);
}
}
private void handleListReportal(HttpServletRequest req, HttpServletResponse resp, Session session) throws ServletException, IOException {
Page page = newPage(req, resp, session, "azkaban/viewer/reportal/reportallistpage.vm");
preparePage(page, session);
List<Project> projects = ReportalHelper.getReportalProjects(server);
page.add("ReportalHelper", ReportalHelper.class);
page.add("user", session.getUser());
String startDate = DateTime.now().minusWeeks(1).toString("yyyy-MM-dd");
String endDate = DateTime.now().toString("yyyy-MM-dd");
page.add("startDate", startDate);
page.add("endDate", endDate);
if (!projects.isEmpty()) {
page.add("projects", projects);
}
else {
page.add("projects", false);
}
page.render();
}
private void handleViewReportal(HttpServletRequest req, HttpServletResponse resp, Session session) throws ServletException, Exception {
int id = getIntParam(req, "id");
Page page = newPage(req, resp, session, "azkaban/viewer/reportal/reportaldatapage.vm");
preparePage(page, session);
ProjectManager projectManager = server.getProjectManager();
ExecutorManagerAdapter executorManager = server.getExecutorManager();
Project project = projectManager.getProject(id);
Reportal reportal = Reportal.loadFromProject(project);
Flow flow = project.getFlows().get(0);
if (reportal == null) {
page.add("errorMsg", "Report not found");
page.render();
return;
}
if (!project.hasPermission(session.getUser(), Type.READ)) {
page.add("errorMsg", "You are not allowed to view this report.");
page.render();
return;
}
page.add("project", project);
page.add("title", project.getMetadata().get("title"));
if (hasParam(req, "execid")) {
int execId = getIntParam(req, "execid");
page.add("execid", execId);
// Show logs
if (hasParam(req, "logs")) {
ExecutableFlow exec;
try {
exec = executorManager.getExecutableFlow(execId);
} catch (ExecutorManagerException e) {
e.printStackTrace();
page.add("errorMsg", "ExecutableFlow not found. " + e.getMessage());
page.render();
return;
}
// View single log
if (hasParam(req, "log")) {
page.add("view-log", true);
String jobId = getParam(req, "log");
page.add("execid", execId);
page.add("jobId", jobId);
}
// List files
else {
page.add("view-logs", true);
List<ExecutableNode> jobs = exec.getExecutableNodes();
// Sort list of jobs by level (which is the same as execution order
// since Reportal flows are all linear).
Collections.sort(jobs, new Comparator<ExecutableNode>() {
public int compare(ExecutableNode a, ExecutableNode b) {
return a.getLevel() < b.getLevel() ? -1 : 1;
}
public boolean equals(Object obj) {
return this.equals(obj);
}
});
List<String> logList = new ArrayList<String>();
boolean showDataCollector = hasParam(req, "debug");
for (ExecutableNode node: jobs) {
String jobId = node.getJobId();
if (!showDataCollector && !jobId.equals("data-collector")) {
logList.add(jobId);
}
}
if (logList.size() == 1) {
resp.sendRedirect("/reportal?view&logs&id=" + project.getId() + "&execid=" + execId + "&log=" + logList.get(0));
}
page.add("logs", logList);
}
}
// Show data files
else {
String outputFileSystem = props.getString("reportal.output.filesystem", "local");
String outputBase = props.getString("reportal.output.location", "/tmp/reportal");
String locationFull = (outputBase + "/" + execId).replace("//", "/");
IStreamProvider streamProvider = ReportalUtil.getStreamProvider(outputFileSystem);
if (streamProvider instanceof StreamProviderHDFS) {
StreamProviderHDFS hdfsStreamProvider = (StreamProviderHDFS)streamProvider;
hdfsStreamProvider.setHadoopSecurityManager(hadoopSecurityManager);
hdfsStreamProvider.setUser(reportalStorageUser);
}
try {
// Preview file
if (hasParam(req, "preview")) {
page.add("view-preview", true);
String fileName = getParam(req, "preview");
String filePath = locationFull + "/" + fileName;
InputStream csvInputStream = streamProvider.getFileInputStream(filePath);
Scanner rowScanner = new Scanner(csvInputStream);
ArrayList<Object> lines = new ArrayList<Object>();
int lineNumber = 0;
while (rowScanner.hasNextLine() && lineNumber < 100) {
String csvLine = rowScanner.nextLine();
- String[] data = csvLine.split(",");
+ String[] data = csvLine.split("\",\"");
ArrayList<String> line = new ArrayList<String>();
for (String item: data) {
line.add(item.replace("\"", ""));
}
lines.add(line);
lineNumber++;
}
rowScanner.close();
page.add("preview", lines);
Object graphHash = project.getMetadata().get("graphHash");
if (graphHash != null) {
page.add("graphHash", graphHash);
}
}
else if (hasParam(req, "download")) {
String fileName = getParam(req, "download");
String filePath = locationFull + "/" + fileName;
InputStream csvInputStream = null;
OutputStream out = null;
try {
csvInputStream = streamProvider.getFileInputStream(filePath);
resp.setContentType("application/octet-stream");
out = resp.getOutputStream();
IOUtils.copy(csvInputStream, out);
} finally {
IOUtils.closeQuietly(out);
IOUtils.closeQuietly(csvInputStream);
}
return;
}
// List files
else {
page.add("view-files", true);
try {
String[] fileList = streamProvider.getFileList(locationFull);
String[] dataList = ReportalHelper.filterCSVFile(fileList);
Arrays.sort(dataList);
if (dataList.length > 0) {
page.add("files", dataList);
}
} catch (FileNotFoundException e) {
}
}
} finally {
streamProvider.cleanUp();
}
}
}
// List executions and their data
else {
page.add("view-executions", true);
ArrayList<ExecutableFlow> exFlows = new ArrayList<ExecutableFlow>();
int pageNumber = 0;
boolean hasNextPage = false;
if (hasParam(req, "page")) {
pageNumber = getIntParam(req, "page") - 1;
}
if (pageNumber < 0) {
pageNumber = 0;
}
try {
executorManager.getExecutableFlows(project.getId(), flow.getId(), pageNumber * itemsPerPage, itemsPerPage, exFlows);
ArrayList<ExecutableFlow> tmp = new ArrayList<ExecutableFlow>();
executorManager.getExecutableFlows(project.getId(), flow.getId(), (pageNumber + 1) * itemsPerPage, 1, tmp);
if (!tmp.isEmpty()) {
hasNextPage = true;
}
} catch (ExecutorManagerException e) {
page.add("error", "Error retrieving executable flows");
}
if (!exFlows.isEmpty()) {
ArrayList<Object> history = new ArrayList<Object>();
for (ExecutableFlow exFlow: exFlows) {
HashMap<String, Object> flowInfo = new HashMap<String, Object>();
flowInfo.put("execId", exFlow.getExecutionId());
flowInfo.put("status", exFlow.getStatus().toString());
flowInfo.put("startTime", exFlow.getStartTime());
history.add(flowInfo);
}
page.add("executions", history);
}
if (pageNumber > 0) {
page.add("pagePrev", pageNumber);
}
page.add("page", pageNumber + 1);
if (hasNextPage) {
page.add("pageNext", pageNumber + 2);
}
}
page.render();
}
private void handleRunReportal(HttpServletRequest req, HttpServletResponse resp, Session session) throws ServletException, IOException {
int id = getIntParam(req, "id");
ProjectManager projectManager = server.getProjectManager();
Page page = newPage(req, resp, session, "azkaban/viewer/reportal/reportalrunpage.vm");
preparePage(page, session);
Project project = projectManager.getProject(id);
Reportal reportal = Reportal.loadFromProject(project);
if (reportal == null) {
page.add("errorMsg", "Report not found");
page.render();
return;
}
if (!project.hasPermission(session.getUser(), Type.EXECUTE)) {
page.add("errorMsg", "You are not allowed to run this report.");
page.render();
return;
}
page.add("project", project);
page.add("title", reportal.title);
page.add("description", reportal.description);
if (reportal.variables.size() > 0) {
page.add("variableNumber", reportal.variables.size());
page.add("variables", reportal.variables);
}
page.render();
}
private void handleNewReportal(HttpServletRequest req, HttpServletResponse resp, Session session) throws ServletException, IOException {
Page page = newPage(req, resp, session, "azkaban/viewer/reportal/reportaleditpage.vm");
preparePage(page, session);
page.add("new", true);
page.add("project", false);
page.add("title", "");
page.add("description", "");
page.add("queryNumber", 1);
List<Map<String, Object>> queryList = new ArrayList<Map<String, Object>>();
page.add("queries", queryList);
Map<String, Object> query = new HashMap<String, Object>();
queryList.add(query);
query.put("title", "");
query.put("type", "");
query.put("script", "");
page.add("accessViewer", "");
page.add("accessExecutor", "");
page.add("accessOwner", "");
page.add("notifications", "");
page.render();
}
private void handleEditReportal(HttpServletRequest req, HttpServletResponse resp, Session session) throws ServletException, IOException {
int id = getIntParam(req, "id");
ProjectManager projectManager = server.getProjectManager();
Page page = newPage(req, resp, session, "azkaban/viewer/reportal/reportaleditpage.vm");
preparePage(page, session);
page.add("ReportalHelper", ReportalHelper.class);
Project project = projectManager.getProject(id);
Reportal reportal = Reportal.loadFromProject(project);
if (reportal == null) {
page.add("errorMsg", "Report not found");
page.render();
return;
}
if (!project.hasPermission(session.getUser(), Type.ADMIN)) {
page.add("errorMsg", "You are not allowed to edit this report.");
page.render();
return;
}
page.add("project", project);
page.add("title", reportal.title);
page.add("description", reportal.description);
page.add("queryNumber", reportal.queries.size());
page.add("queries", reportal.queries);
page.add("variableNumber", reportal.variables.size());
page.add("variables", reportal.variables);
page.add("schedule", reportal.schedule);
page.add("scheduleEnabled", reportal.scheduleEnabled);
page.add("scheduleInterval", reportal.scheduleInterval);
page.add("scheduleTime", reportal.scheduleTime);
page.add("notifications", reportal.notifications);
page.add("accessViewer", reportal.accessViewer);
page.add("accessExecutor", reportal.accessExecutor);
page.add("accessOwner", reportal.accessOwner);
page.render();
}
@Override
protected void handlePost(HttpServletRequest req, HttpServletResponse resp, Session session) throws ServletException, IOException {
if (hasParam(req, "ajax")) {
HashMap<String, Object> ret = new HashMap<String, Object>();
handleRunReportalWithVariables(req, ret, session);
if (ret != null) {
this.writeJSON(resp, ret);
}
}
else {
handleEditAddReportal(req, resp, session);
}
}
private void handleEditAddReportal(HttpServletRequest req, HttpServletResponse resp, Session session) throws ServletException, IOException {
ProjectManager projectManager = server.getProjectManager();
Page page = newPage(req, resp, session, "azkaban/viewer/reportal/reportaleditpage.vm");
preparePage(page, session);
page.add("ReportalHelper", ReportalHelper.class);
boolean isEdit = hasParam(req, "id");
Project project = null;
Reportal report = new Reportal();
report.title = getParam(req, "title");
report.description = getParam(req, "description");
page.add("title", report.title);
page.add("description", report.description);
report.schedule = hasParam(req, "schedule");
report.scheduleEnabled = hasParam(req, "scheduleEnabled");
report.scheduleInterval = getParam(req, "schedule-interval");
report.scheduleTime = getIntParam(req, "schedule-time");
page.add("schedule", report.schedule);
page.add("scheduleEnabled", report.scheduleEnabled);
page.add("scheduleInterval", report.scheduleInterval);
page.add("scheduleTime", report.scheduleTime);
report.accessViewer = getParam(req, "access-viewer");
report.accessExecutor = getParam(req, "access-executor");
report.accessOwner = getParam(req, "access-owner");
page.add("accessViewer", report.accessViewer);
page.add("accessExecutor", report.accessExecutor);
page.add("accessOwner", report.accessOwner);
report.notifications = getParam(req, "notifications");
page.add("notifications", report.notifications);
int queries = getIntParam(req, "queryNumber");
page.add("queryNumber", queries);
List<Query> queryList = new ArrayList<Query>(queries);
page.add("queries", queryList);
report.queries = queryList;
String typeError = null;
String typePermissionError = null;
for (int i = 0; i < queries; i++) {
Query query = new Query();
query.title = getParam(req, "query" + i + "title");
query.type = getParam(req, "query" + i + "type");
query.script = getParam(req, "query" + i + "script");
// Type check
ReportalType type = ReportalType.getTypeByName(query.type);
if (type == null && typeError == null) {
typeError = query.type;
}
if (!type.checkPermission(session.getUser())) {
typePermissionError = query.type;
}
queryList.add(query);
}
int variables = getIntParam(req, "variableNumber");
page.add("variableNumber", variables);
List<Variable> variableList = new ArrayList<Variable>(variables);
page.add("variables", variableList);
report.variables = variableList;
boolean variableErrorOccured = false;
for (int i = 0; i < variables; i++) {
Variable variable = new Variable();
variable.title = getParam(req, "variable" + i + "title");
variable.name = getParam(req, "variable" + i + "name");
if (variable.title.isEmpty() || variable.name.isEmpty()) {
variableErrorOccured = true;
}
variableList.add(variable);
}
// Make sure title isn't empty
if (report.title.isEmpty()) {
page.add("errorMsg", "Title must not be empty.");
page.render();
return;
}
// Make sure description isn't empty
if (report.description.isEmpty()) {
page.add("errorMsg", "Description must not be empty.");
page.render();
return;
}
// Empty query check
if (queries <= 0) {
page.add("errorMsg", "There needs to have at least one query.");
page.render();
return;
}
// Type error check
if (typeError != null) {
page.add("errorMsg", "Type " + typeError + " is invalid.");
page.render();
return;
}
// Type permission check
if (typePermissionError != null && report.schedule && report.scheduleEnabled) {
page.add("errorMsg", "You do not have permission to schedule Type " + typePermissionError + ".");
page.render();
return;
}
// Variable error check
if (variableErrorOccured) {
page.add("errorMsg", "Variable title and name cannot be empty.");
page.render();
return;
}
// Attempt to get a project object
if (isEdit) {
// Editing mode, load project
int projectId = getIntParam(req, "id");
project = projectManager.getProject(projectId);
report.loadImmutableFromProject(project);
}
else {
// Creation mode, create project
try {
User user = session.getUser();
project = ReportalHelper.createReportalProject(server, report.title, report.description, user);
report.reportalUser = user.getUserId();
report.ownerEmail = user.getEmail();
} catch (Exception e) {
e.printStackTrace();
page.add("errorMsg", "Error while creating report. " + e.getMessage());
page.render();
return;
}
// Project already exists
if (project == null) {
page.add("errorMsg", "A Report with the same name already exists.");
page.render();
return;
}
}
if (project == null) {
page.add("errorMsg", "Internal Error: Report not found");
page.render();
return;
}
report.project = project;
page.add("project", project);
report.updatePermissions();
try {
report.createZipAndUpload(projectManager, session.getUser(), reportalStorageUser);
} catch (Exception e) {
e.printStackTrace();
page.add("errorMsg", "Error while creating Azkaban jobs. " + e.getMessage());
page.render();
if (!isEdit) {
try {
projectManager.removeProject(project, session.getUser());
} catch (ProjectManagerException e1) {
e1.printStackTrace();
}
}
return;
}
// Prepare flow
Flow flow = project.getFlows().get(0);
project.getMetadata().put("flowName", flow.getId());
// Set reportal mailer
flow.setMailCreator(ReportalMailCreator.REPORTAL_MAIL_CREATOR);
// Create/Save schedule
ScheduleManager scheduleManager = server.getScheduleManager();
try {
report.updateSchedules(report, scheduleManager, session.getUser(), flow);
} catch (ScheduleManagerException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
page.add("errorMsg", e2.getMessage());
page.render();
return;
}
report.saveToProject(project);
try {
ReportalHelper.updateProjectNotifications(project, projectManager);
projectManager.updateProjectSetting(project);
projectManager.updateFlow(project, flow);
} catch (ProjectManagerException e) {
e.printStackTrace();
page.add("errorMsg", "Error while updating report. " + e.getMessage());
page.render();
if (!isEdit) {
try {
projectManager.removeProject(project, session.getUser());
} catch (ProjectManagerException e1) {
e1.printStackTrace();
}
}
return;
}
this.setSuccessMessageInCookie(resp, "Report Saved.");
resp.sendRedirect(req.getRequestURI() + "?edit&id=" + project.getId());
}
private void handleRunReportalWithVariables(HttpServletRequest req, HashMap<String, Object> ret, Session session) throws ServletException, IOException {
int id = getIntParam(req, "id");
ProjectManager projectManager = server.getProjectManager();
Project project = projectManager.getProject(id);
Reportal report = Reportal.loadFromProject(project);
if (!project.hasPermission(session.getUser(), Type.EXECUTE)) {
ret.put("error", "You are not allowed to run this report.");
return;
}
for (Query query: report.queries) {
String jobType = query.type;
ReportalType type = ReportalType.getTypeByName(jobType);
if (!type.checkPermission(session.getUser())) {
ret.put("error", "You are not allowed to run this report as you don't have permission to run job type " + type.toString() + ".");
return;
}
}
Flow flow = project.getFlows().get(0);
ExecutableFlow exflow = new ExecutableFlow(flow);
exflow.setSubmitUser(session.getUser().getUserId());
exflow.addAllProxyUsers(project.getProxyUsers());
ExecutionOptions options = exflow.getExecutionOptions();
int i = 0;
for (Variable variable: report.variables) {
options.getFlowParameters().put(REPORTAL_VARIABLE_PREFIX + i + ".from", variable.name);
options.getFlowParameters().put(REPORTAL_VARIABLE_PREFIX + i + ".to", getParam(req, "variable" + i));
i++;
}
options.getFlowParameters().put("reportal.execution.user", session.getUser().getUserId());
options.getFlowParameters().put("reportal.title", report.title);
try {
String message = server.getExecutorManager().submitExecutableFlow(exflow, session.getUser().getUserId()) + ".";
ret.put("message", message);
ret.put("result", "success");
ret.put("redirect", "/reportal?view&logs&id=" + project.getId() + "&execid=" + exflow.getExecutionId());
} catch (ExecutorManagerException e) {
e.printStackTrace();
ret.put("error", "Error running report " + report.title + ". " + e.getMessage());
}
}
private void preparePage(Page page, Session session) {
page.add("viewerName", viewerName);
page.add("hideNavigation", !showNav);
page.add("userid", session.getUser().getUserId());
}
private class CleanerThread extends Thread {
// Every hour, clean execution dir.
private static final long EXECUTION_DIR_CLEAN_INTERVAL_MS = 60 * 60 * 1000;
private boolean shutdown = false;
private long lastExecutionDirCleanTime = -1;
private long executionDirRetention = 1 * 24 * 60 * 60 * 1000;
public CleanerThread() {
this.setName("Reportal-Cleaner-Thread");
}
@SuppressWarnings("unused")
public void shutdown() {
shutdown = true;
this.interrupt();
}
public void run() {
while (!shutdown) {
synchronized (this) {
long currentTime = System.currentTimeMillis();
if (currentTime - EXECUTION_DIR_CLEAN_INTERVAL_MS > lastExecutionDirCleanTime) {
logger.info("Cleaning old execution dirs");
cleanOldReportalDirs();
lastExecutionDirCleanTime = currentTime;
}
}
}
}
private void cleanOldReportalDirs() {
File dir = reportalMailDirectory;
final long pastTimeThreshold = System.currentTimeMillis() - executionDirRetention;
File[] executionDirs = dir.listFiles(new FileFilter() {
@Override
public boolean accept(File path) {
if (path.isDirectory() && path.lastModified() < pastTimeThreshold) {
return true;
}
return false;
}
});
for (File exDir: executionDirs) {
try {
FileUtils.deleteDirectory(exDir);
} catch (IOException e) {
logger.error("Error cleaning execution dir " + exDir.getPath(), e);
}
}
}
}
}
| false | false | null | null |
diff --git a/opentripplanner-routing/src/main/java/org/opentripplanner/routing/edgetype/RentABikeAbstractEdge.java b/opentripplanner-routing/src/main/java/org/opentripplanner/routing/edgetype/RentABikeAbstractEdge.java
index 64743abd9..1b077a4c3 100644
--- a/opentripplanner-routing/src/main/java/org/opentripplanner/routing/edgetype/RentABikeAbstractEdge.java
+++ b/opentripplanner-routing/src/main/java/org/opentripplanner/routing/edgetype/RentABikeAbstractEdge.java
@@ -1,114 +1,114 @@
/* This program is free software: you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public License
as published by the Free Software Foundation, either version 3 of
the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
package org.opentripplanner.routing.edgetype;
import org.opentripplanner.routing.core.EdgeNarrative;
import org.opentripplanner.routing.core.State;
import org.opentripplanner.routing.core.StateEditor;
import org.opentripplanner.routing.core.TraverseMode;
import org.opentripplanner.routing.core.RoutingRequest;
import org.opentripplanner.routing.graph.AbstractEdge;
import org.opentripplanner.routing.graph.Vertex;
import org.opentripplanner.routing.vertextype.BikeRentalStationVertex;
import com.vividsolutions.jts.geom.Geometry;
/**
* Renting or dropping off a rented bike edge.
*
* @author laurent
*
*/
public abstract class RentABikeAbstractEdge extends AbstractEdge {
private static final long serialVersionUID = 1L;
public RentABikeAbstractEdge(Vertex from, Vertex to) {
super(from, to);
}
protected State traverseRent(State s0) {
RoutingRequest options = s0.getOptions();
/*
* If we already have a bike (rented or own) we won't go any faster by having a second
* one.
*/
if (!s0.getNonTransitMode(options).equals(TraverseMode.WALK))
return null;
/*
* To rent a bike, we need to have BICYCLE in allowed modes.
*/
if (!options.getModes().contains(TraverseMode.BICYCLE))
return null;
BikeRentalStationVertex dropoff = (BikeRentalStationVertex) tov;
if (options.isUseBikeRentalAvailabilityInformation() && dropoff.getBikesAvailable() == 0) {
return null;
}
EdgeNarrative en = new FixedModeEdge(this, s0.getNonTransitMode(options));
StateEditor s1 = s0.edit(this, en);
- s1.incrementWeight(options.bikeRentalPickupCost);
- s1.incrementTimeInSeconds(options.bikeRentalPickupTime);
+ s1.incrementWeight(options.isArriveBy() ? options.bikeRentalDropoffCost : options.bikeRentalPickupCost);
+ s1.incrementTimeInSeconds(options.isArriveBy() ? options.bikeRentalDropoffTime : options.bikeRentalPickupTime);
s1.setBikeRenting(true);
State s1b = s1.makeState();
return s1b;
}
protected State traverseDropoff(State s0) {
RoutingRequest options = s0.getOptions();
/*
* To dropoff a bike, we need to have rented one.
*/
if (!s0.isBikeRenting())
return null;
BikeRentalStationVertex pickup = (BikeRentalStationVertex) tov;
if (options.isUseBikeRentalAvailabilityInformation() && pickup.getSpacesAvailable() == 0) {
return null;
}
EdgeNarrative en = new FixedModeEdge(this, s0.getNonTransitMode(options));
StateEditor s1e = s0.edit(this, en);
- s1e.incrementWeight(options.bikeRentalDropoffCost);
- s1e.incrementTimeInSeconds(options.bikeRentalDropoffTime);
+ s1e.incrementWeight(options.isArriveBy() ? options.bikeRentalPickupCost : options.bikeRentalDropoffCost);
+ s1e.incrementTimeInSeconds(options.isArriveBy() ? options.bikeRentalPickupTime : options.bikeRentalDropoffTime);
s1e.setBikeRenting(false);
State s1 = s1e.makeState();
return s1;
}
@Override
public double getDistance() {
return 0;
}
@Override
public Geometry getGeometry() {
return null;
}
@Override
public TraverseMode getMode() {
return TraverseMode.WALK;
}
@Override
public String getName() {
return getToVertex().getName();
}
@Override
public boolean hasBogusName() {
return false;
}
}
| false | false | null | null |
diff --git a/core/plugins/org.eclipse.dltk.ui/src/org/eclipse/dltk/ui/search/ScriptSearchPage.java b/core/plugins/org.eclipse.dltk.ui/src/org/eclipse/dltk/ui/search/ScriptSearchPage.java
index e42edf10b..ef5579250 100644
--- a/core/plugins/org.eclipse.dltk.ui/src/org/eclipse/dltk/ui/search/ScriptSearchPage.java
+++ b/core/plugins/org.eclipse.dltk.ui/src/org/eclipse/dltk/ui/search/ScriptSearchPage.java
@@ -1,948 +1,947 @@
/*******************************************************************************
* Copyright (c) 2000, 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
-
+ * Contributors:
+ * IBM Corporation and others. - initial API and Implementation
+ * xored software, Inc. - Ported to DLTK from JDT
+ * Alon Peled <[email protected]> - Fix of bug bug 235137
*******************************************************************************/
package org.eclipse.dltk.ui.search;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.dltk.core.DLTKCore;
import org.eclipse.dltk.core.IDLTKLanguageToolkit;
import org.eclipse.dltk.core.IField;
import org.eclipse.dltk.core.IMethod;
import org.eclipse.dltk.core.IModelElement;
import org.eclipse.dltk.core.IType;
import org.eclipse.dltk.core.ModelException;
import org.eclipse.dltk.core.search.IDLTKSearchConstants;
import org.eclipse.dltk.core.search.IDLTKSearchScope;
import org.eclipse.dltk.core.search.SearchPattern;
import org.eclipse.dltk.internal.ui.actions.SelectionConverter;
import org.eclipse.dltk.internal.ui.dialogs.TextFieldNavigationHandler;
import org.eclipse.dltk.internal.ui.editor.ScriptEditor;
import org.eclipse.dltk.internal.ui.search.DLTKSearchQuery;
import org.eclipse.dltk.internal.ui.search.DLTKSearchScopeFactory;
import org.eclipse.dltk.internal.ui.search.PatternStrings;
import org.eclipse.dltk.internal.ui.search.SearchMessages;
import org.eclipse.dltk.internal.ui.search.SearchUtil;
import org.eclipse.dltk.ui.DLTKUIPlugin;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.DialogPage;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.search.ui.ISearchPage;
import org.eclipse.search.ui.ISearchPageContainer;
import org.eclipse.search.ui.NewSearchUI;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkingSet;
import org.eclipse.ui.IWorkingSetManager;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.model.IWorkbenchAdapter;
public abstract class ScriptSearchPage extends DialogPage implements
ISearchPage, IDLTKSearchConstants {
private static class SearchPatternData {
private int searchFor;
private int limitTo;
private String pattern;
private boolean isCaseSensitive;
private IModelElement modelElement;
private boolean includeInterpreterEnvironment;
private int scope;
private IWorkingSet[] workingSets;
public SearchPatternData(int searchFor, int limitTo,
boolean isCaseSensitive, String pattern, IModelElement element,
boolean includeInterpreterEnvironment) {
this(searchFor, limitTo, pattern, isCaseSensitive, element,
ISearchPageContainer.WORKSPACE_SCOPE, null,
includeInterpreterEnvironment);
}
public SearchPatternData(int searchFor, int limitTo, String pattern,
boolean isCaseSensitive, IModelElement element, int scope,
IWorkingSet[] workingSets, boolean includeInterpreterEnvironment) {
this.searchFor = searchFor;
this.limitTo = limitTo;
this.pattern = pattern;
this.isCaseSensitive = isCaseSensitive;
this.scope = scope;
this.workingSets = workingSets;
this.includeInterpreterEnvironment = includeInterpreterEnvironment;
setModelElement(element);
}
public void setModelElement(IModelElement modelElement) {
this.modelElement = modelElement;
}
public boolean isCaseSensitive() {
return isCaseSensitive;
}
public IModelElement getModelElement() {
return modelElement;
}
public int getLimitTo() {
return limitTo;
}
public String getPattern() {
return pattern;
}
public int getScope() {
return scope;
}
public int getSearchFor() {
return searchFor;
}
public IWorkingSet[] getWorkingSets() {
return workingSets;
}
public boolean includesInterpreterEnvironment() {
return includeInterpreterEnvironment;
}
public void store(IDialogSettings settings) {
settings.put("searchFor", searchFor); //$NON-NLS-1$
settings.put("scope", scope); //$NON-NLS-1$
settings.put("pattern", pattern); //$NON-NLS-1$
settings.put("limitTo", limitTo); //$NON-NLS-1$
settings
.put(
"modelElement", modelElement != null ? modelElement.getHandleIdentifier() : ""); //$NON-NLS-1$ //$NON-NLS-2$
settings.put("isCaseSensitive", isCaseSensitive); //$NON-NLS-1$
if (workingSets != null) {
String[] wsIds = new String[workingSets.length];
for (int i = 0; i < workingSets.length; i++) {
wsIds[i] = workingSets[i].getName();
}
settings.put("workingSets", wsIds); //$NON-NLS-1$
} else {
settings.put("workingSets", new String[0]); //$NON-NLS-1$
}
settings
.put(
"includeInterpreterEnvironment", includeInterpreterEnvironment); //$NON-NLS-1$
}
public static SearchPatternData create(IDialogSettings settings) {
String pattern = settings.get("pattern"); //$NON-NLS-1$
if (pattern.length() == 0) {
return null;
}
IModelElement elem = null;
String handleId = settings.get("modelElement"); //$NON-NLS-1$
if (handleId != null && handleId.length() > 0) {
IModelElement restored = DLTKCore.create(handleId);
if (restored != null && isSearchableType(restored)
&& restored.exists()) {
elem = restored;
}
}
String[] wsIds = settings.getArray("workingSets"); //$NON-NLS-1$
IWorkingSet[] workingSets = null;
if (wsIds != null && wsIds.length > 0) {
IWorkingSetManager workingSetManager = PlatformUI
.getWorkbench().getWorkingSetManager();
workingSets = new IWorkingSet[wsIds.length];
for (int i = 0; workingSets != null && i < wsIds.length; i++) {
workingSets[i] = workingSetManager.getWorkingSet(wsIds[i]);
if (workingSets[i] == null) {
workingSets = null;
}
}
}
try {
int searchFor = settings.getInt("searchFor"); //$NON-NLS-1$
int scope = settings.getInt("scope"); //$NON-NLS-1$
int limitTo = settings.getInt("limitTo"); //$NON-NLS-1$
boolean isCaseSensitive = settings
.getBoolean("isCaseSensitive"); //$NON-NLS-1$
boolean includeInterpreterEnvironment;
if (settings.get("includeInterpreterEnvironment") != null) { //$NON-NLS-1$
includeInterpreterEnvironment = settings
.getBoolean("includeInterpreterEnvironment"); //$NON-NLS-1$
} else {
includeInterpreterEnvironment = forceIncludeInterpreterEnvironment(limitTo);
}
return new SearchPatternData(searchFor, limitTo, pattern,
isCaseSensitive, elem, scope, workingSets,
includeInterpreterEnvironment);
} catch (NumberFormatException e) {
return null;
}
}
}
public static final String PARTICIPANT_EXTENSION_POINT = "org.eclipse.dltk.ui.queryParticipants"; //$NON-NLS-1$
public static final String EXTENSION_POINT_ID = "org.eclipse.dltk.ui.DLTKSearchPage"; //$NON-NLS-1$
private static final int HISTORY_SIZE = 12;
// Dialog store id constants
private final static String PAGE_NAME = "DLTKSearchPage"; //$NON-NLS-1$
private final static String STORE_CASE_SENSITIVE = "CASE_SENSITIVE"; //$NON-NLS-1$
private final static String STORE_HISTORY = "HISTORY"; //$NON-NLS-1$
private final static String STORE_HISTORY_SIZE = "HISTORY_SIZE"; //$NON-NLS-1$
private final List fPreviousSearchPatterns;
private SearchPatternData fInitialData;
private IModelElement fModelElement;
private boolean fFirstTime = true;
private IDialogSettings fDialogSettings;
private boolean fIsCaseSensitive;
private Combo fPattern;
private ISearchPageContainer fContainer;
private Button fCaseSensitive;
private Button[] fSearchFor;
private String[] fSearchForText = {
SearchMessages.SearchPage_searchFor_type,
SearchMessages.SearchPage_searchFor_method,
// SearchMessages.SearchPage_searchFor_package,
// SearchMessages.SearchPage_searchFor_constructor,
SearchMessages.SearchPage_searchFor_field };
private Button[] fLimitTo;
private String[] fLimitToText = {
SearchMessages.SearchPage_limitTo_declarations,
// SearchMessages.SearchPage_limitTo_implementors,
SearchMessages.SearchPage_limitTo_references,
SearchMessages.SearchPage_limitTo_allOccurrences
// SearchMessages.SearchPage_limitTo_readReferences,
// SearchMessages.SearchPage_limitTo_writeReferences
};
private Button fIncludeInterpreterEnvironmentCheckbox;
public ScriptSearchPage() {
fPreviousSearchPatterns = new ArrayList();
}
public boolean performAction() {
return performNewSearch();
}
private boolean performNewSearch() {
SearchPatternData data = getPatternData();
// Setup search scope
IDLTKSearchScope scope = null;
String scopeDescription = ""; //$NON-NLS-1$
boolean includeInterpreterEnvironment = data
.includesInterpreterEnvironment();
DLTKSearchScopeFactory factory = DLTKSearchScopeFactory.getInstance();
switch (getContainer().getSelectedScope()) {
case ISearchPageContainer.WORKSPACE_SCOPE:
scopeDescription = factory
.getWorkspaceScopeDescription(includeInterpreterEnvironment);
scope = factory.createWorkspaceScope(includeInterpreterEnvironment,
getLanguageToolkit());
break;
case ISearchPageContainer.SELECTION_SCOPE:
IModelElement[] modelElements = factory
.getModelElements(getContainer().getSelection());
scope = factory.createSearchScope(modelElements,
includeInterpreterEnvironment, getLanguageToolkit());
scopeDescription = factory.getSelectionScopeDescription(
modelElements, includeInterpreterEnvironment);
break;
case ISearchPageContainer.SELECTED_PROJECTS_SCOPE: {
String[] projectNames = getContainer().getSelectedProjectNames();
scope = factory.createProjectSearchScope(projectNames,
includeInterpreterEnvironment, getLanguageToolkit());
scopeDescription = factory.getProjectScopeDescription(projectNames,
includeInterpreterEnvironment);
break;
}
case ISearchPageContainer.WORKING_SET_SCOPE: {
IWorkingSet[] workingSets = getContainer().getSelectedWorkingSets();
// should not happen - just to be sure
if (workingSets == null || workingSets.length < 1)
return false;
scopeDescription = factory.getWorkingSetScopeDescription(
workingSets, includeInterpreterEnvironment);
scope = factory.createSearchScope(workingSets,
includeInterpreterEnvironment, getLanguageToolkit());
SearchUtil.updateLRUWorkingSets(workingSets);
}
}
QuerySpecification querySpec = null;
if (data.getModelElement() != null
&& getPattern().equals(fInitialData.getPattern())) {
// if (data.getLimitTo() == IDLTKSearchConstants.REFERENCES)
// SearchUtil.warnIfBinaryConstant(data.getModelElement(),
// getShell());
querySpec = new ElementQuerySpecification(data.getModelElement(),
data.getLimitTo(), scope, scopeDescription);
} else {
querySpec = new PatternQuerySpecification(data.getPattern(), data
.getSearchFor(), data.isCaseSensitive(), data.getLimitTo(),
scope, scopeDescription);
data.setModelElement(null);
}
DLTKSearchQuery textSearchJob = new DLTKSearchQuery(querySpec);
NewSearchUI.runQueryInBackground(textSearchJob);
return true;
}
private int getLimitTo() {
for (int i = 0; i < fLimitTo.length; i++) {
if (fLimitTo[i].getSelection())
return i;
}
return -1;
}
private void setLimitTo(int searchFor, int limitTo) {
- if (!(searchFor == TYPE) /* && limitTo == IMPLEMENTORS */) {
- limitTo = REFERENCES;
- }
-
- if (!(searchFor == FIELD) /*
- * && (limitTo == READ_ACCESSES || limitTo ==
- * WRITE_ACCESSES)
- */) {
- limitTo = REFERENCES;
- }
-
+ /*
+ * if (!(searchFor == TYPE) && limitTo == IMPLEMENTORS ) { limitTo =
+ * REFERENCES; }
+ *
+ * if (!(searchFor == FIELD) && (limitTo == READ_ACCESSES || limitTo ==
+ * WRITE_ACCESSES)) { limitTo = REFERENCES; }
+ */
for (int i = 0; i < fLimitTo.length; i++) {
fLimitTo[i].setSelection(limitTo == i);
}
fLimitTo[DECLARATIONS].setEnabled(true);
// fLimitTo[IMPLEMENTORS].setEnabled( searchFor == TYPE);
fLimitTo[REFERENCES].setEnabled(true);
fLimitTo[ALL_OCCURRENCES].setEnabled(true);
// fLimitTo[READ_ACCESSES].setEnabled(searchFor == FIELD);
// fLimitTo[WRITE_ACCESSES].setEnabled(searchFor == FIELD);
}
private String[] getPreviousSearchPatterns() {
// Search results are not persistent
int patternCount = fPreviousSearchPatterns.size();
String[] patterns = new String[patternCount];
for (int i = 0; i < patternCount; i++)
patterns[i] = ((SearchPatternData) fPreviousSearchPatterns.get(i))
.getPattern();
return patterns;
}
private int getSearchFor() {
for (int i = 0; i < fSearchFor.length; i++) {
if (fSearchFor[i].getSelection())
return i;
}
return -1;
}
private String getPattern() {
return fPattern.getText();
}
private SearchPatternData findInPrevious(String pattern) {
for (Iterator iter = fPreviousSearchPatterns.iterator(); iter.hasNext();) {
SearchPatternData element = (SearchPatternData) iter.next();
if (pattern.equals(element.getPattern())) {
return element;
}
}
return null;
}
/**
* Return search pattern data and update previous searches. An existing
* entry will be updated.
*/
private SearchPatternData getPatternData() {
String pattern = getPattern();
SearchPatternData match = findInPrevious(pattern);
if (match != null) {
fPreviousSearchPatterns.remove(match);
}
match = new SearchPatternData(getSearchFor(), getLimitTo(), pattern,
fCaseSensitive.getSelection(), fModelElement, getContainer()
.getSelectedScope(), getContainer()
.getSelectedWorkingSets(),
fIncludeInterpreterEnvironmentCheckbox.getSelection());
fPreviousSearchPatterns.add(0, match); // insert on top
return match;
}
/*
* Implements method from IDialogPage
*/
public void setVisible(boolean visible) {
if (visible && fPattern != null) {
if (fFirstTime) {
fFirstTime = false;
// Set item and text here to prevent page from resizing
fPattern.setItems(getPreviousSearchPatterns());
initSelections();
}
fPattern.setFocus();
}
updateOKStatus();
super.setVisible(visible);
}
public boolean isValid() {
return true;
}
// ---- Widget creation ------------------------------------------------
/**
* Creates the page's content.
*/
public void createControl(Composite parent) {
initializeDialogUnits(parent);
readConfiguration();
Composite result = new Composite(parent, SWT.NONE);
GridLayout layout = new GridLayout(2, false);
layout.horizontalSpacing = 10;
result.setLayout(layout);
Control expressionComposite = createExpression(result);
expressionComposite.setLayoutData(new GridData(GridData.FILL,
GridData.CENTER, true, false, 2, 1));
Label separator = new Label(result, SWT.NONE);
separator.setVisible(false);
GridData data = new GridData(GridData.FILL, GridData.FILL, false,
false, 2, 1);
data.heightHint = convertHeightInCharsToPixels(1) / 3;
separator.setLayoutData(data);
Control searchFor = createSearchFor(result);
searchFor.setLayoutData(new GridData(GridData.FILL, GridData.FILL,
true, false, 1, 1));
Control limitTo = createLimitTo(result);
limitTo.setLayoutData(new GridData(GridData.FILL, GridData.FILL, true,
false, 1, 1));
fIncludeInterpreterEnvironmentCheckbox = new Button(result, SWT.CHECK);
fIncludeInterpreterEnvironmentCheckbox
.setText(SearchMessages.SearchPage_searchInterpreterEnvironment_label);
fIncludeInterpreterEnvironmentCheckbox.setLayoutData(new GridData(
SWT.FILL, SWT.CENTER, false, false, 2, 1));
// createParticipants(result);
SelectionAdapter modelElementInitializer = new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
if (getSearchFor() == fInitialData.getSearchFor())
fModelElement = fInitialData.getModelElement();
else
fModelElement = null;
setLimitTo(getSearchFor(), getLimitTo());
doPatternModified();
}
};
fSearchFor[TYPE].addSelectionListener(modelElementInitializer);
fSearchFor[METHOD].addSelectionListener(modelElementInitializer);
fSearchFor[FIELD].addSelectionListener(modelElementInitializer);
- // fSearchFor[CONSTRUCTOR].addSelectionListener(modelElementInitializer);
+ //fSearchFor[CONSTRUCTOR].addSelectionListener(modelElementInitializer);
// fSearchFor[PACKAGE].addSelectionListener(modelElementInitializer);
setControl(result);
Dialog.applyDialogFont(result);
// PlatformUI.getWorkbench().getHelpSystem().setHelp(result,
// IJavaHelpContextIds.JAVA_SEARCH_PAGE);
if (DLTKCore.DEBUG) {
System.out.println("TODO: Add help support here..."); //$NON-NLS-1$
}
}
private Control createExpression(Composite parent) {
Composite result = new Composite(parent, SWT.NONE);
GridLayout layout = new GridLayout(2, false);
layout.marginWidth = 0;
layout.marginHeight = 0;
result.setLayout(layout);
// Pattern text + info
Label label = new Label(result, SWT.LEFT);
label.setText(SearchMessages.SearchPage_expression_label);
label.setLayoutData(new GridData(GridData.FILL, GridData.FILL, false,
false, 2, 1));
// Pattern combo
fPattern = new Combo(result, SWT.SINGLE | SWT.BORDER);
fPattern.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
handlePatternSelected();
updateOKStatus();
}
});
fPattern.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
doPatternModified();
updateOKStatus();
}
});
TextFieldNavigationHandler.install(fPattern);
GridData data = new GridData(GridData.FILL, GridData.FILL, true, false,
1, 1);
data.widthHint = convertWidthInCharsToPixels(50);
fPattern.setLayoutData(data);
// Ignore case checkbox
fCaseSensitive = new Button(result, SWT.CHECK);
fCaseSensitive
.setText(SearchMessages.SearchPage_expression_caseSensitive);
fCaseSensitive.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
fIsCaseSensitive = fCaseSensitive.getSelection();
}
});
fCaseSensitive.setLayoutData(new GridData(GridData.FILL, GridData.FILL,
false, false, 1, 1));
return result;
}
final void updateOKStatus() {
boolean isValid = isValidSearchPattern();
getContainer().setPerformActionEnabled(isValid);
}
private boolean isValidSearchPattern() {
if (getPattern().length() == 0) {
return false;
}
if (fModelElement != null) {
return true;
}
return SearchPattern
.createPattern(getPattern(), getSearchFor(), getLimitTo(),
SearchPattern.R_EXACT_MATCH, getLanguageToolkit()) != null;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.dialogs.DialogPage#dispose()
*/
public void dispose() {
writeConfiguration();
super.dispose();
}
private void doPatternModified() {
if (fInitialData != null
&& getPattern().equals(fInitialData.getPattern())
&& fInitialData.getModelElement() != null
&& fInitialData.getSearchFor() == getSearchFor()) {
fCaseSensitive.setEnabled(false);
fCaseSensitive.setSelection(true);
fModelElement = fInitialData.getModelElement();
} else {
fCaseSensitive.setEnabled(true);
fCaseSensitive.setSelection(fIsCaseSensitive);
fModelElement = null;
}
}
private void handlePatternSelected() {
int selectionIndex = fPattern.getSelectionIndex();
if (selectionIndex < 0
|| selectionIndex >= fPreviousSearchPatterns.size())
return;
SearchPatternData initialData = (SearchPatternData) fPreviousSearchPatterns
.get(selectionIndex);
setSearchFor(initialData.getSearchFor());
setLimitTo(initialData.getSearchFor(), initialData.getLimitTo());
fPattern.setText(initialData.getPattern());
fIsCaseSensitive = initialData.isCaseSensitive();
fModelElement = initialData.getModelElement();
fCaseSensitive.setEnabled(fModelElement == null);
fCaseSensitive.setSelection(initialData.isCaseSensitive());
if (initialData.getWorkingSets() != null)
getContainer().setSelectedWorkingSets(initialData.getWorkingSets());
else
getContainer().setSelectedScope(initialData.getScope());
fInitialData = initialData;
}
private void setSearchFor(int searchFor) {
for (int i = 0; i < fSearchFor.length; i++) {
fSearchFor[i].setSelection(searchFor == i);
}
}
private Control createSearchFor(Composite parent) {
Group result = new Group(parent, SWT.NONE);
result.setText(SearchMessages.SearchPage_searchFor_label);
result.setLayout(new GridLayout(2, true));
fSearchFor = new Button[fSearchForText.length];
for (int i = 0; i < fSearchForText.length; i++) {
Button button = new Button(result, SWT.RADIO);
button.setText(fSearchForText[i]);
button.setSelection(i == TYPE);
button.setLayoutData(new GridData());
fSearchFor[i] = button;
}
// Fill with dummy radio buttons
Label filler = new Label(result, SWT.NONE);
filler.setVisible(false);
filler.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 1,
1));
return result;
}
private Control createLimitTo(Composite parent) {
Group result = new Group(parent, SWT.NONE);
result.setText(SearchMessages.SearchPage_limitTo_label);
result.setLayout(new GridLayout(2, true));
SelectionAdapter listener = new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
updateUseInterpreterEnvironment();
}
};
fLimitTo = new Button[fLimitToText.length];
for (int i = 0; i < fLimitToText.length; i++) {
Button button = new Button(result, SWT.RADIO);
button.setText(fLimitToText[i]);
fLimitTo[i] = button;
button.setSelection(i == REFERENCES);
button.addSelectionListener(listener);
button.setLayoutData(new GridData());
}
return result;
}
private void initSelections() {
ISelection sel = getContainer().getSelection();
SearchPatternData initData = null;
if (sel instanceof IStructuredSelection) {
initData = tryStructuredSelection((IStructuredSelection) sel);
} else if (sel instanceof ITextSelection) {
IEditorPart activePart = getActiveEditor();
if (activePart instanceof ScriptEditor) {
try {
IModelElement[] elements = SelectionConverter
.codeResolve((ScriptEditor) activePart);
if (elements != null && elements.length > 0) {
initData = determineInitValuesFrom(elements[0]);
}
} catch (ModelException e) {
// ignore
}
}
if (initData == null) {
initData = trySimpleTextSelection((ITextSelection) sel);
}
}
if (initData == null) {
initData = getDefaultInitValues();
}
fInitialData = initData;
fModelElement = initData.getModelElement();
fCaseSensitive.setSelection(initData.isCaseSensitive());
fCaseSensitive.setEnabled(fModelElement == null);
setSearchFor(initData.getSearchFor());
setLimitTo(initData.getSearchFor(), initData.getLimitTo());
fPattern.setText(initData.getPattern());
boolean forceIncludeInterpreterEnvironment = forceIncludeInterpreterEnvironment(getLimitTo());
fIncludeInterpreterEnvironmentCheckbox
.setEnabled(!forceIncludeInterpreterEnvironment);
fIncludeInterpreterEnvironmentCheckbox
.setSelection(forceIncludeInterpreterEnvironment
|| initData.includesInterpreterEnvironment());
}
private void updateUseInterpreterEnvironment() {
boolean forceIncludeInterpreterEnvironment = forceIncludeInterpreterEnvironment(getLimitTo());
fIncludeInterpreterEnvironmentCheckbox
.setEnabled(!forceIncludeInterpreterEnvironment);
boolean isSelected = true;
if (!forceIncludeInterpreterEnvironment) {
isSelected = fIncludeInterpreterEnvironmentCheckbox.getSelection();
} else {
isSelected = true;
}
fIncludeInterpreterEnvironmentCheckbox.setSelection(isSelected);
}
private static boolean forceIncludeInterpreterEnvironment(int limitTo) {
return limitTo == DECLARATIONS; /* || limitTo == IMPLEMENTORS; */
}
private SearchPatternData tryStructuredSelection(
IStructuredSelection selection) {
if (selection == null || selection.size() > 1)
return null;
Object o = selection.getFirstElement();
SearchPatternData res = null;
if (o instanceof IModelElement) {
res = determineInitValuesFrom((IModelElement) o);
}
// else if (o instanceof LogicalPackage) {
// LogicalPackage lp= (LogicalPackage)o;
// return new SearchPatternData(PACKAGE, REFERENCES, fIsCaseSensitive,
// lp.getElementName(), null, false);
// }
else if (o instanceof IAdaptable) {
IModelElement element = (IModelElement) ((IAdaptable) o)
.getAdapter(IModelElement.class);
if (element != null) {
res = determineInitValuesFrom(element);
}
}
if (res == null && o instanceof IAdaptable) {
IWorkbenchAdapter adapter = (IWorkbenchAdapter) ((IAdaptable) o)
.getAdapter(IWorkbenchAdapter.class);
if (adapter != null) {
return new SearchPatternData(TYPE, REFERENCES,
fIsCaseSensitive, adapter.getLabel(o), null, false);
}
}
return res;
}
final static boolean isSearchableType(IModelElement element) {
switch (element.getElementType()) {
case IModelElement.SCRIPT_FOLDER:
case IModelElement.PACKAGE_DECLARATION:
// case IModelElement.IMPORT_DECLARATION:
case IModelElement.TYPE:
case IModelElement.FIELD:
case IModelElement.METHOD:
return true;
}
return false;
}
private SearchPatternData determineInitValuesFrom(IModelElement element) {
DLTKSearchScopeFactory factory = DLTKSearchScopeFactory.getInstance();
boolean isInsideInterpreterEnvironment = factory
.isInsideInterpreter(element);
switch (element.getElementType()) {
case IModelElement.SCRIPT_FOLDER:
// case IModelElement.PACKAGE_DECLARATION:
// return new SearchPatternData(PACKAGE, REFERENCES, true,
// element.getElementName(), element,
// isInsideInterpreterEnvironment);
// case IModelElement.IMPORT_DECLARATION: {
// IImportDeclaration declaration= (IImportDeclaration) element;
// if (declaration.isOnDemand()) {
// String name=
// Signature.getQualifier(declaration.getElementName());
// return new SearchPatternData(PACKAGE, DECLARATIONS, true, name,
// element, true);
// }
// return new SearchPatternData(TYPE, DECLARATIONS, true,
// element.getElementName(), element, true);
// }
break;
case IModelElement.TYPE:
return new SearchPatternData(TYPE, REFERENCES, true, PatternStrings
.getTypeSignature((IType) element), element,
isInsideInterpreterEnvironment);
case IModelElement.SOURCE_MODULE: {
if (DLTKCore.DEBUG) {
System.out
.println("TODO: DLTKSearchPage: Add init values for source module support."); //$NON-NLS-1$
}
// IType mainType= ((ISourceModule) element).
// if (mainType != null) {
// return new SearchPatternData(TYPE, REFERENCES, true,
// PatternStrings.getTypeSignature(mainType), mainType,
// isInsideInterpreterEnvironment);
// }
break;
}
case IModelElement.FIELD:
return new SearchPatternData(FIELD, REFERENCES, true,
PatternStrings.getFieldSignature((IField) element),
element, isInsideInterpreterEnvironment);
case IModelElement.METHOD:
IMethod method = (IMethod) element;
int searchFor = /* method.isConstructor() ? CONSTRUCTOR : */METHOD;
return new SearchPatternData(searchFor, REFERENCES, true,
PatternStrings.getMethodSignature(method), element,
isInsideInterpreterEnvironment);
}
return null;
}
public static boolean isLineDelimiterChar(char ch) {
return ch == '\n' || ch == '\r';
}
private SearchPatternData trySimpleTextSelection(ITextSelection selection) {
String selectedText = selection.getText();
if (selectedText != null && selectedText.length() > 0) {
int i = 0;
while (i < selectedText.length()
&& !isLineDelimiterChar(selectedText.charAt(i))) {
i++;
}
if (i > 0) {
return new SearchPatternData(TYPE, REFERENCES,
fIsCaseSensitive, selectedText.substring(0, i), null,
true);
}
}
return null;
}
private SearchPatternData getDefaultInitValues() {
if (!fPreviousSearchPatterns.isEmpty()) {
return (SearchPatternData) fPreviousSearchPatterns.get(0);
}
return new SearchPatternData(TYPE, REFERENCES, fIsCaseSensitive,
"", null, false); //$NON-NLS-1$
}
/*
* Implements method from ISearchPage
*/
public void setContainer(ISearchPageContainer container) {
fContainer = container;
}
/**
* Returns the search page's container.
*/
private ISearchPageContainer getContainer() {
return fContainer;
}
private IEditorPart getActiveEditor() {
IWorkbenchPage activePage = DLTKUIPlugin.getActivePage();
if (activePage != null) {
return activePage.getActiveEditor();
}
return null;
}
// --------------- Configuration handling --------------
/**
* Returns the page settings for this Script search page.
*
* @return the page settings to be used
*/
private IDialogSettings getDialogSettings() {
IDialogSettings settings = DLTKUIPlugin.getDefault()
.getDialogSettings();
fDialogSettings = settings.getSection(PAGE_NAME);
if (fDialogSettings == null)
fDialogSettings = settings.addNewSection(PAGE_NAME);
return fDialogSettings;
}
/**
* Initializes itself from the stored page settings.
*/
private void readConfiguration() {
IDialogSettings s = getDialogSettings();
fIsCaseSensitive = s.getBoolean(STORE_CASE_SENSITIVE);
try {
int historySize = s.getInt(STORE_HISTORY_SIZE);
for (int i = 0; i < historySize; i++) {
IDialogSettings histSettings = s.getSection(STORE_HISTORY + i);
if (histSettings != null) {
SearchPatternData data = SearchPatternData
.create(histSettings);
if (data != null) {
fPreviousSearchPatterns.add(data);
}
}
}
} catch (NumberFormatException e) {
// ignore
}
}
/**
* Stores it current configuration in the dialog store.
*/
private void writeConfiguration() {
IDialogSettings s = getDialogSettings();
s.put(STORE_CASE_SENSITIVE, fIsCaseSensitive);
int historySize = Math
.min(fPreviousSearchPatterns.size(), HISTORY_SIZE);
s.put(STORE_HISTORY_SIZE, historySize);
for (int i = 0; i < historySize; i++) {
IDialogSettings histSettings = s.addNewSection(STORE_HISTORY + i);
SearchPatternData data = ((SearchPatternData) fPreviousSearchPatterns
.get(i));
data.store(histSettings);
}
}
protected abstract IDLTKLanguageToolkit getLanguageToolkit();
}
| false | false | null | null |
diff --git a/n3phele/src/n3phele/service/actions/StackServiceAction.java b/n3phele/src/n3phele/service/actions/StackServiceAction.java
index b586445..8c03d2a 100644
--- a/n3phele/src/n3phele/service/actions/StackServiceAction.java
+++ b/n3phele/src/n3phele/service/actions/StackServiceAction.java
@@ -1,266 +1,266 @@
package n3phele.service.actions;
import java.io.FileNotFoundException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import org.json.JSONArray;
import org.json.JSONException;
import n3phele.service.core.NotFoundException;
import n3phele.service.core.ResourceFile;
import n3phele.service.core.ResourceFileFactory;
import n3phele.service.model.Action;
import n3phele.service.model.CloudProcess;
import n3phele.service.model.Context;
import n3phele.service.model.Relationship;
import n3phele.service.model.SignalKind;
import n3phele.service.model.Stack;
import n3phele.service.model.core.User;
import n3phele.service.rest.impl.ActionResource;
import n3phele.service.rest.impl.CloudProcessResource;
import com.googlecode.objectify.annotation.Cache;
import com.googlecode.objectify.annotation.Embed;
import com.googlecode.objectify.annotation.EntitySubclass;
import com.googlecode.objectify.annotation.Ignore;
import com.googlecode.objectify.annotation.Unindex;
@EntitySubclass(index = true)
@XmlRootElement(name = "StackServiceAction")
@XmlType(name = "StackServiceAction", propOrder = { "serviceDescription", "stacks", "relationships" })
@Unindex
@Cache
public class StackServiceAction extends ServiceAction {
// generates the id of stacks
private long stackNumber;
private String serviceDescription;
private List<String> adopted = new ArrayList<String>();
@Embed private List<Stack> stacks = new ArrayList<Stack>();
@Embed private List<Relationship> relationships = new ArrayList<Relationship>();
@Ignore private ResourceFileFactory resourceFileFactory;
public StackServiceAction()
{
super();
stackNumber = 0;
this.resourceFileFactory = new ResourceFileFactory();
}
public StackServiceAction(String description, String name, User owner, Context context) {
super(owner, name, context);
this.serviceDescription = description;
stackNumber = 0;
}
@Override
public Action create(URI owner, String name, Context context) {
super.create(owner, name, context);
this.serviceDescription = "";
registerServiceCommandsToContext();
return this;
}
public void setResourceFileFactory(ResourceFileFactory factory)
{
this.resourceFileFactory = factory;
}
public void registerServiceCommandsToContext()
{
List<String> commands = new ArrayList<String>();
try {
ResourceFile fileConfiguration = this.resourceFileFactory.create("n3phele.resource.service_commands");
String commandsString = fileConfiguration.get("charms", "");
JSONArray jsonArray = new JSONArray(commandsString);
for(int i=0; i<jsonArray.length(); i++)
{
commands.add(jsonArray.getString(i));
}
} catch (JSONException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
this.context.putValue("deploy_commands", commands);
}
public List<String> getAcceptedCommands()
{
List<String> commands = this.context.getListValue("deploy_commands");
if(commands == null) commands = new ArrayList<String>();
return commands;
}
public void addNewCommand(String newCommandUri)
{
List<String> oldCommands = this.context.getListValue("deploy_commands");
List<String> commands = new ArrayList<String>(oldCommands);
commands.add(newCommandUri);
this.context.putValue("deploy_commands", commands);
}
/*
* Automatic Generated Methods
*/
@Override
public String getDescription() {
return "StackService " + this.getName();
}
public String getServiceDescription() {
return this.serviceDescription;
}
public void setServiceDescription(String description) {
this.serviceDescription = description;
}
public List<Stack> getStacks() {
return this.stacks;
}
public void setStacks(List<Stack> stacks) {
this.stacks = stacks;
}
public boolean addStack(Stack stack) {
if(stack.getId() == -1)
stack.setId(this.getNextStackNumber());
return stacks.add(stack);
}
public List<Relationship> getRelationships() {
return this.relationships;
}
public void setRelationships(List<Relationship> relationships) {
this.relationships = relationships;
}
public boolean addRelationhip(Relationship relation) {
return relationships.add(relation);
}
public long getNextStackNumber() {
long id = stackNumber;
stackNumber++;
return id;
}
@Override
public void cancel() {
log.info("Cancelling " + stacks.size() + " stacks");
for (Stack stack : stacks) {
for (URI uri : stack.getVms()) {
try {
processLifecycle().cancel(uri);
} catch (NotFoundException e) {
log.severe("Not found: " + e.getMessage());
}
}
}
for (String vm : adopted) {
try {
processLifecycle().cancel(URI.create(vm));
} catch (NotFoundException e) {
log.severe("Not found: " + e.getMessage());
}
}
}
@Override
public void dump() {
log.info("Dumping " + stacks.size() + " stacks");
for (Stack stack : stacks) {
for (URI uri : stack.getVms()) {
try {
processLifecycle().dump(uri);
} catch (NotFoundException e) {
log.severe("Not found: " + e.getMessage());
}
}
}
for (String vm : adopted) {
try {
processLifecycle().cancel(URI.create(vm));
} catch (NotFoundException e) {
log.severe("Not found: " + e.getMessage());
}
}
}
@Override
public String toString() {
return "StackServiceAction [description=" + this.serviceDescription + ", stacks=" + this.stacks + ", relationships=" + this.relationships + ", idStack=" + this.stackNumber + ", context=" + this.context + ", name=" + this.name + ", uri=" + this.uri + ", owner=" + this.owner + ", isPublic="
+ this.isPublic + "]";
}
@Override
public void signal(SignalKind kind, String assertion) throws NotFoundException {
boolean isStacked = false;
Stack stacked = null;
for (Stack s : stacks) {
if (s.getDeployProcess() == null)
continue;
if (s.getDeployProcess().equals(assertion)) {
isStacked = true;
stacked = s;
break;
}
}
boolean isAdopted = this.adopted.contains(assertion);
log.info("Signal " + kind + ":" + assertion);
switch (kind) {
case Adoption:
URI processURI = URI.create(assertion);
try {
CloudProcess child = CloudProcessResource.dao.load(processURI);
Action action = ActionResource.dao.load(child.getAction());
log.info("Adopting child " + child.getName() + " " + child.getClass().getSimpleName());
this.adopted.add(assertion);
- if (action instanceof AssimilateAction) {
+ if (action instanceof AssimilateVMAction) {
for (Stack s : stacks) {
if (s.getId() == action.getContext().getLongValue("stackId")) {
s.addVm(child.getUri());
}
}
}
} catch (Exception e) {
log.info("Assertion is not a cloudProcess");
}
break;
case Cancel:
if (isStacked) {
stacks.remove(stacked);
} else if (isAdopted) {
adopted.remove(assertion);
}
break;
case Event:
break;
case Failed:
if (isStacked) {
stacks.remove(stacked);
} else if (isAdopted) {
adopted.remove(assertion);
}
break;
case Ok:
log.info(assertion + " ok");
break;
default:
return;
}
ActionResource.dao.update(this);
}
}
| true | true | public void signal(SignalKind kind, String assertion) throws NotFoundException {
boolean isStacked = false;
Stack stacked = null;
for (Stack s : stacks) {
if (s.getDeployProcess() == null)
continue;
if (s.getDeployProcess().equals(assertion)) {
isStacked = true;
stacked = s;
break;
}
}
boolean isAdopted = this.adopted.contains(assertion);
log.info("Signal " + kind + ":" + assertion);
switch (kind) {
case Adoption:
URI processURI = URI.create(assertion);
try {
CloudProcess child = CloudProcessResource.dao.load(processURI);
Action action = ActionResource.dao.load(child.getAction());
log.info("Adopting child " + child.getName() + " " + child.getClass().getSimpleName());
this.adopted.add(assertion);
if (action instanceof AssimilateAction) {
for (Stack s : stacks) {
if (s.getId() == action.getContext().getLongValue("stackId")) {
s.addVm(child.getUri());
}
}
}
} catch (Exception e) {
log.info("Assertion is not a cloudProcess");
}
break;
case Cancel:
if (isStacked) {
stacks.remove(stacked);
} else if (isAdopted) {
adopted.remove(assertion);
}
break;
case Event:
break;
case Failed:
if (isStacked) {
stacks.remove(stacked);
} else if (isAdopted) {
adopted.remove(assertion);
}
break;
case Ok:
log.info(assertion + " ok");
break;
default:
return;
}
ActionResource.dao.update(this);
}
| public void signal(SignalKind kind, String assertion) throws NotFoundException {
boolean isStacked = false;
Stack stacked = null;
for (Stack s : stacks) {
if (s.getDeployProcess() == null)
continue;
if (s.getDeployProcess().equals(assertion)) {
isStacked = true;
stacked = s;
break;
}
}
boolean isAdopted = this.adopted.contains(assertion);
log.info("Signal " + kind + ":" + assertion);
switch (kind) {
case Adoption:
URI processURI = URI.create(assertion);
try {
CloudProcess child = CloudProcessResource.dao.load(processURI);
Action action = ActionResource.dao.load(child.getAction());
log.info("Adopting child " + child.getName() + " " + child.getClass().getSimpleName());
this.adopted.add(assertion);
if (action instanceof AssimilateVMAction) {
for (Stack s : stacks) {
if (s.getId() == action.getContext().getLongValue("stackId")) {
s.addVm(child.getUri());
}
}
}
} catch (Exception e) {
log.info("Assertion is not a cloudProcess");
}
break;
case Cancel:
if (isStacked) {
stacks.remove(stacked);
} else if (isAdopted) {
adopted.remove(assertion);
}
break;
case Event:
break;
case Failed:
if (isStacked) {
stacks.remove(stacked);
} else if (isAdopted) {
adopted.remove(assertion);
}
break;
case Ok:
log.info(assertion + " ok");
break;
default:
return;
}
ActionResource.dao.update(this);
}
|
diff --git a/dbfit-java/mysql/src/test/java/dbfit/environment/FlowModeTest.java b/dbfit-java/mysql/src/test/java/dbfit/environment/FlowModeTest.java
index 05a6cd39..1ea4c1d2 100644
--- a/dbfit-java/mysql/src/test/java/dbfit/environment/FlowModeTest.java
+++ b/dbfit-java/mysql/src/test/java/dbfit/environment/FlowModeTest.java
@@ -1,16 +1,16 @@
package dbfit.environment;
import fitnesse.junit.FitNesseSuite;
import org.junit.Test;
import org.junit.runner.RunWith;
import static fitnesse.junit.FitNesseSuite.*;
@RunWith(FitNesseSuite.class)
-@Name("DbFit.AcceptanceTests.JavaTests.MysqlTests.FlowMode")
+@Name("DbFit.AcceptanceTests.JavaTests.MySqlTests.FlowMode")
@FitnesseDir("../..")
@OutputDir(systemProperty = "java.io.tmpdir", pathExtension = "fitnesse")
@Port(1234)
public class FlowModeTest {
@Test public void dummy(){}
-}
\ No newline at end of file
+}
diff --git a/dbfit-java/mysql/src/test/java/dbfit/environment/StandaloneFixturesTest.java b/dbfit-java/mysql/src/test/java/dbfit/environment/StandaloneFixturesTest.java
index 9b7d080d..596b5353 100644
--- a/dbfit-java/mysql/src/test/java/dbfit/environment/StandaloneFixturesTest.java
+++ b/dbfit-java/mysql/src/test/java/dbfit/environment/StandaloneFixturesTest.java
@@ -1,16 +1,16 @@
package dbfit.environment;
import fitnesse.junit.FitNesseSuite;
import org.junit.Test;
import org.junit.runner.RunWith;
import static fitnesse.junit.FitNesseSuite.*;
@RunWith(FitNesseSuite.class)
-@Name("DbFit.AcceptanceTests.JavaTests.MysqlTests.StandaloneFixtures")
+@Name("DbFit.AcceptanceTests.JavaTests.MySqlTests.StandaloneFixtures")
@FitnesseDir("../..")
@OutputDir(systemProperty = "java.io.tmpdir", pathExtension = "fitnesse")
@Port(1234)
public class StandaloneFixturesTest {
@Test public void dummy(){}
-}
\ No newline at end of file
+}
| false | false | null | null |
diff --git a/io/plugins/eu.esdihumboldt.hale.io.gml/src/eu/esdihumboldt/hale/io/gml/writer/internal/StreamGmlWriter.java b/io/plugins/eu.esdihumboldt.hale.io.gml/src/eu/esdihumboldt/hale/io/gml/writer/internal/StreamGmlWriter.java
index 10ce3e23b..ff3686779 100644
--- a/io/plugins/eu.esdihumboldt.hale.io.gml/src/eu/esdihumboldt/hale/io/gml/writer/internal/StreamGmlWriter.java
+++ b/io/plugins/eu.esdihumboldt.hale.io.gml/src/eu/esdihumboldt/hale/io/gml/writer/internal/StreamGmlWriter.java
@@ -1,872 +1,875 @@
/*
* HUMBOLDT: A Framework for Data Harmonisation and Service Integration.
* EU Integrated Project #030962 01.10.2006 - 30.09.2010
*
* For more information on the project, please refer to the this web site:
* http://www.esdi-humboldt.eu
*
* LICENSE: For information on the license under which this program is
* available, please refer to http:/www.esdi-humboldt.eu/license.html#core
* (c) the HUMBOLDT Consortium, 2007 to 2010.
*/
package eu.esdihumboldt.hale.io.gml.writer.internal;
import java.io.IOException;
import java.net.URI;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.xml.XMLConstants;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
import org.geotools.gml3.GML;
import com.vividsolutions.jts.geom.Geometry;
import de.cs3d.util.logging.ALogger;
import de.cs3d.util.logging.ALoggerFactory;
import eu.esdihumboldt.hale.common.core.io.IOProvider;
import eu.esdihumboldt.hale.common.core.io.IOProviderConfigurationException;
import eu.esdihumboldt.hale.common.core.io.ProgressIndicator;
import eu.esdihumboldt.hale.common.core.io.impl.AbstractIOProvider;
import eu.esdihumboldt.hale.common.core.io.report.IOReport;
import eu.esdihumboldt.hale.common.core.io.report.IOReporter;
import eu.esdihumboldt.hale.common.core.io.report.impl.IOMessageImpl;
import eu.esdihumboldt.hale.common.core.io.supplier.DefaultInputSupplier;
import eu.esdihumboldt.hale.common.instance.io.impl.AbstractInstanceWriter;
import eu.esdihumboldt.hale.common.instance.model.Group;
import eu.esdihumboldt.hale.common.instance.model.Instance;
import eu.esdihumboldt.hale.common.instance.model.InstanceCollection;
import eu.esdihumboldt.hale.common.instance.model.ResourceIterator;
import eu.esdihumboldt.hale.common.schema.geometry.GeometryProperty;
import eu.esdihumboldt.hale.common.schema.model.ChildDefinition;
import eu.esdihumboldt.hale.common.schema.model.DefinitionGroup;
import eu.esdihumboldt.hale.common.schema.model.DefinitionUtil;
import eu.esdihumboldt.hale.common.schema.model.PropertyDefinition;
import eu.esdihumboldt.hale.common.schema.model.Schema;
import eu.esdihumboldt.hale.common.schema.model.SchemaSpace;
import eu.esdihumboldt.hale.common.schema.model.TypeDefinition;
import eu.esdihumboldt.hale.common.schema.model.constraint.property.Cardinality;
import eu.esdihumboldt.hale.common.schema.model.constraint.property.NillableFlag;
import eu.esdihumboldt.hale.common.schema.model.constraint.type.AbstractFlag;
import eu.esdihumboldt.hale.common.schema.model.constraint.type.HasValueFlag;
import eu.esdihumboldt.hale.io.gml.internal.simpletype.SimpleTypeUtil;
import eu.esdihumboldt.hale.io.gml.writer.internal.geometry.AbstractTypeMatcher;
import eu.esdihumboldt.hale.io.gml.writer.internal.geometry.DefinitionPath;
import eu.esdihumboldt.hale.io.gml.writer.internal.geometry.Descent;
import eu.esdihumboldt.hale.io.gml.writer.internal.geometry.StreamGeometryWriter;
import eu.esdihumboldt.hale.io.xsd.constraint.XmlAttributeFlag;
import eu.esdihumboldt.hale.io.xsd.constraint.XmlElements;
import eu.esdihumboldt.hale.io.xsd.model.XmlElement;
import eu.esdihumboldt.hale.io.xsd.model.XmlIndex;
import eu.esdihumboldt.hale.io.xsd.reader.XmlSchemaReader;
/**
* Writes GML/XML using a {@link XMLStreamWriter}
*
* @author Simon Templer
* @partner 01 / Fraunhofer Institute for Computer Graphics Research
*/
public class StreamGmlWriter extends AbstractInstanceWriter {
/**
* Schema instance namespace (for specifying schema locations)
*/
public static final String SCHEMA_INSTANCE_NS = XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI; //$NON-NLS-1$
private static final ALogger log = ALoggerFactory.getLogger(StreamGmlWriter.class);
/**
* The parameter name for the XML root element name
*/
public static final String PARAM_ROOT_ELEMENT_NAME = "xml.rootElement.name";
/**
* The parameter name for the XML root element namespace
*/
public static final String PARAM_ROOT_ELEMENT_NAMESPACE = "xml.rootElement.namespace";
/**
* The XML stream writer
*/
private XMLStreamWriter writer;
/**
* The GML namespace
*/
private String gmlNs;
// /**
// * The type index
// */
// private TypeIndex types;
/**
* The geometry writer
*/
private StreamGeometryWriter geometryWriter;
/**
* Additional schemas included in the document
*/
private final List<Schema> additionalSchemas = new ArrayList<Schema>();
/**
* States if a feature collection shall be used
*/
private final boolean useFeatureCollection;
private XmlIndex targetIndex;
/**
* Create a GML writer
*
* @param useFeatureCollection if a GML feature collection shall be used to
* store the instances (if possible)
*/
public StreamGmlWriter(boolean useFeatureCollection) {
super();
this.useFeatureCollection = useFeatureCollection;
addSupportedParameter(PARAM_ROOT_ELEMENT_NAMESPACE);
addSupportedParameter(PARAM_ROOT_ELEMENT_NAME);
}
/**
* @see AbstractIOProvider#execute(ProgressIndicator, IOReporter)
*/
@Override
protected IOReport execute(ProgressIndicator progress, IOReporter reporter)
throws IOProviderConfigurationException, IOException {
try {
init();
} catch (XMLStreamException e) {
throw new IOException("Creating the XML stream writer failed", e);
}
try {
write(getInstances(), progress, reporter);
reporter.setSuccess(true);
} catch (XMLStreamException e) {
reporter.error(new IOMessageImpl(e.getLocalizedMessage(), e));
reporter.setSuccess(false);
} finally {
progress.end();
}
return reporter;
}
//FIXME
// /**
// * @see AbstractInstanceWriter#getValidationSchemas()
// */
// @Override
// public List<Schema> getValidationSchemas() {
// List<Schema> result = new ArrayList<Schema>(super.getValidationSchemas());
// result.addAll(additionalSchemas);
// return result;
// }
/**
* @see AbstractInstanceWriter#validate()
*/
@Override
public void validate() throws IOProviderConfigurationException {
if (getXMLIndex() == null) {
fail("No XML target schema");
}
}
/**
* Get the XML type index.
* @return the target type index
*/
protected XmlIndex getXMLIndex() {
if (targetIndex == null) {
targetIndex = getXMLIndex(getTargetSchema());
}
return targetIndex;
}
/**
* Get the XML index from the given schema space
* @param schemas the schema space
* @return the XML index or <code>null</code>
*/
public static XmlIndex getXMLIndex(SchemaSpace schemas) {
//XXX respect a container, types?
for (Schema schema : schemas.getSchemas()) {
if (schema instanceof XmlIndex) {
//TODO respect root element for schema selection?
return (XmlIndex) schema;
}
}
return null;
}
/**
* Create and setup the stream writer, the type index and the GML namespace
* (Initializes {@link #writer}, {@link #gmlNs} and {@link #targetIndex},
* resets {@link #geometryWriter} and {@link #additionalSchemas}).
*
* @throws XMLStreamException if creating the {@link XMLStreamWriter} fails
* @throws IOException if creating the output stream fails
*/
private void init() throws XMLStreamException, IOException {
// reset target index
targetIndex = null;
// reset geometry writer
geometryWriter = null;
// reset additional schemas
additionalSchemas.clear();
// create and set-up a writer
XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
// will set namespaces if these not set explicitly
outputFactory.setProperty("javax.xml.stream.isRepairingNamespaces", //$NON-NLS-1$
Boolean.valueOf(true));
// create XML stream writer with UTF-8 encoding
XMLStreamWriter tmpWriter = outputFactory.createXMLStreamWriter(getTarget().getOutput(), "UTF-8"); //$NON-NLS-1$
String defNamespace = null;
XmlIndex index = getXMLIndex();
// read the namespaces from the map containing namespaces
if (index.getPrefixes() != null) {
for (Entry<String, String> entry : index.getPrefixes().entrySet()) {
if (entry.getValue().isEmpty()) {
//XXX don't use a default namespace, as this results in problems with schemas w/o elementFormQualified=true
//defNamespace = entry.getKey();
}
else {
tmpWriter.setPrefix(entry.getValue(), entry.getKey());
}
}
}
GmlWriterUtil.addNamespace(tmpWriter, SCHEMA_INSTANCE_NS, "xsi"); //$NON-NLS-1$
// determine default namespace
if (defNamespace == null) {
//XXX don't use a default namespace, as this results in problems with schemas w/o elementFormQualified=true
//defNamespace = index.getNamespace();
//TODO remove prefix for target schema namespace?
}
tmpWriter.setDefaultNamespace(defNamespace);
writer = new IndentingXMLStreamWriter(tmpWriter);
// determine GML namespace from target schema
String gml = null;
if (index.getPrefixes() != null) {
for (String ns : index.getPrefixes().keySet()) {
if (ns.startsWith("http://www.opengis.net/gml")) { //$NON-NLS-1$
gml = ns;
break;
}
}
}
if (gml == null) {
// default to GML 2/3 namespace
gml = GML.NAMESPACE;
}
gmlNs = gml;
if (log.isDebugEnabled()) {
log.debug("GML namespace is " + gmlNs); //$NON-NLS-1$
}
//FIXME fill type index with root types
// types = new TypeIndex();
// for (SchemaElement element : getTargetSchema().getElements().values()) {
// types.addType(element.getType());
// }
// for (Definition def : getTargetSchema().getTypes().keySet()) {
// types.addType(DefinitionUtil.getType(def));
// }
}
/**
* @see IOProvider#isCancelable()
*/
@Override
public boolean isCancelable() {
return true;
}
/**
* @see AbstractIOProvider#getDefaultTypeName()
*/
@Override
protected String getDefaultTypeName() {
return "GML/XML";
}
/**
* Write the given instances.
* @param instances the instance collection
* @param reporter the reporter
* @param progress the progress
* @throws XMLStreamException if writing the feature collection fails
*/
public void write(InstanceCollection instances,
ProgressIndicator progress, IOReporter reporter) throws XMLStreamException {
progress.begin("Generating " + getTypeName(), instances.size());
TypeDefinition containerDefinition = null;
QName containerName = null;
if (useFeatureCollection) {
// try to find FeatureCollection element
Iterator<XmlElement> it = targetIndex.getElements().values().iterator();
Collection<XmlElement> fcElements = new HashSet<XmlElement>();
while (it.hasNext()) {
XmlElement el = it.next();
if (isFeatureCollection(el)) {
fcElements.add(el);
}
}
if (fcElements.isEmpty() && gmlNs.equals("http://www.opengis.net/gml")) { //$NON-NLS-1$
// no FeatureCollection defined and "old" namespace -> GML 2
// include WFS 1.0.0 for the FeatureCollection element
try {
URI location = StreamGmlWriter.class.getResource("/schemas/wfs/1.0.0/WFS-basic.xsd").toURI(); //$NON-NLS-1$
XmlSchemaReader schemaReader = new XmlSchemaReader();
schemaReader.setSource(new DefaultInputSupplier(location));
+ //FIXME to work with the extra schema it must be integrated with the main schema
+// schemaReader.setSharedTypes(sharedTypes);
IOReport report = schemaReader.execute(null);
if (report.isSuccess()) {
Schema wfsSchema = schemaReader.getSchema();
// look for FeatureCollection element
if (wfsSchema instanceof XmlIndex) {
for (XmlElement el : ((XmlIndex) wfsSchema).getElements().values()) {
if (isFeatureCollection(el)) {
fcElements.add(el);
}
}
}
// add as additional schema, replace location for verification
additionalSchemas.add(new SchemaDecorator(wfsSchema) {
@Override
public URI getLocation() {
return URI.create("http://schemas.opengis.net/wfs/1.0.0/WFS-basic.xsd");
}
});
// add namespace
GmlWriterUtil.addNamespace(writer, wfsSchema.getNamespace(), "wfs"); //$NON-NLS-1$
}
} catch (Exception e) {
log.warn("Using WFS schema for the FeatureCollection definition failed", e); //$NON-NLS-1$
}
}
if (fcElements.isEmpty()) {
reporter.warn(new IOMessageImpl(
"No element describing a FeatureCollection found", null)); //$NON-NLS-1$
}
else {
// select fc element TODO priorized selection (root element parameters)
XmlElement fcElement = fcElements.iterator().next();
containerDefinition = fcElement.getType();
containerName = fcElement.getName();
log.info("Found " + fcElements.size() + " possible FeatureCollection elements" + //$NON-NLS-1$ //$NON-NLS-2$
", using element " + fcElement.getName()); //$NON-NLS-1$
}
}
if (containerDefinition == null) {
// no container defined, try to use a custom root element
String namespace = getParameter(PARAM_ROOT_ELEMENT_NAMESPACE);
// determine target namespace
if (namespace == null) {
// default to target namespace
namespace = targetIndex.getNamespace();
}
String elementName = getParameter(PARAM_ROOT_ELEMENT_NAME);
// find root element
if (elementName != null) {
Iterator<XmlElement> it = targetIndex.getElements().values().iterator();
while (it.hasNext() && containerDefinition == null) {
XmlElement el = it.next();
if (el.getName().getNamespaceURI().equals(namespace) &&
el.getName().getLocalPart().equals(elementName)) {
containerDefinition = el.getType();
containerName = el.getName();
}
}
}
}
if (containerDefinition == null || containerName == null) {
throw new IllegalStateException("No root element/container found");
}
writer.writeStartDocument();
GmlWriterUtil.writeStartElement(writer, containerName);
// generate mandatory id attribute (for feature collection)
GmlWriterUtil.writeRequiredID(writer, containerDefinition, null, false);
// write schema locations
StringBuffer locations = new StringBuffer();
locations.append(targetIndex.getNamespace());
locations.append(" "); //$NON-NLS-1$
locations.append(targetIndex.getLocation().toString());
for (Schema schema : additionalSchemas) {
locations.append(" "); //$NON-NLS-1$
locations.append(schema.getNamespace());
locations.append(" "); //$NON-NLS-1$
locations.append(schema.getLocation().toString());
}
writer.writeAttribute(SCHEMA_INSTANCE_NS, "schemaLocation", locations.toString()); //$NON-NLS-1$
// boundedBy is needed for GML 2 FeatureCollections
//XXX working like this - getting the child with only a local name?
ChildDefinition<?> boundedBy = containerDefinition.getChild(new QName("boundedBy")); //$NON-NLS-1$
if (boundedBy != null && boundedBy.asProperty() != null
&& boundedBy.asProperty().getConstraint(Cardinality.class).getMinOccurs() > 0) {
writer.writeStartElement(
boundedBy.getName().getNamespaceURI(),
boundedBy.getName().getLocalPart());
writer.writeStartElement(gmlNs, "null"); //$NON-NLS-1$
writer.writeCharacters("missing"); //$NON-NLS-1$
writer.writeEndElement();
writer.writeEndElement();
}
//FIXME write the instances
ResourceIterator<Instance> itInstance = instances.iterator();
try {
Map<TypeDefinition, DefinitionPath> paths = new HashMap<TypeDefinition, DefinitionPath>();
Descent lastDescent = null;
while (itInstance.hasNext() && !progress.isCanceled()) {
Instance instance = itInstance.next();
TypeDefinition type = instance.getDefinition();
// get stored definition path for the type
DefinitionPath defPath;
if (paths.containsKey(type)) {
defPath = paths.get(type); // get the stored path, may be null
}
else {
// determine a valid definition path in the container
//TODO specify a maximum descent level? (else searching the container for matches might take _very_ long)
defPath = findMemberAttribute(
containerDefinition, containerName, type);
// store path (may be null)
paths.put(type, defPath);
}
if (defPath != null) {
// write the feature
lastDescent = Descent.descend(writer, defPath, lastDescent, false);
writeMember(instance, type);
}
else {
reporter.warn(new IOMessageImpl(MessageFormat.format(
"No compatible member attribute for type {0} found in root element {1}, one instance was skipped",
type.getDisplayName(), containerName.getLocalPart()), null));
}
progress.advance(1);
}
if (lastDescent != null) {
lastDescent.close();
}
} finally {
itInstance.close();
}
writer.writeEndElement(); // FeatureCollection
writer.writeEndDocument();
}
/**
* Find a matching attribute for the given member type in the given
* container type
*
* @param container the container type
* @param containerName the container element name
* @param memberType the member type
*
* @return the attribute definition or <code>null</code>
*/
protected DefinitionPath findMemberAttribute(
TypeDefinition container, QName containerName,
final TypeDefinition memberType) {
//XXX not working if property is no substitution of the property type - use matching instead
// for (PropertyDefinition property : GmlWriterUtil.collectProperties(container.getChildren())) {
// // direct match -
// if (property.getPropertyType().equals(memberType)) {
// long max = property.getConstraint(Cardinality.class).getMaxOccurs();
// return new DefinitionPath(
// property.getPropertyType(),
// property.getName(),
// max != Cardinality.UNBOUNDED && max <= 1);
// }
// }
AbstractTypeMatcher<TypeDefinition> matcher = new AbstractTypeMatcher<TypeDefinition>() {
@Override
protected DefinitionPath matchPath(TypeDefinition type,
TypeDefinition matchParam, DefinitionPath path) {
if (type.equals(memberType)) {
return path;
}
//XXX special case: FeatureCollection from foreign schema
Collection<? extends XmlElement> elements = matchParam.getConstraint(XmlElements.class).getElements();
Collection<? extends XmlElement> containerElements = type.getConstraint(XmlElements.class).getElements();
if (!elements.isEmpty() && !containerElements.isEmpty()) {
TypeDefinition parent = matchParam.getSuperType();
while (parent != null) {
if (parent.equals(type)) {
+ //FIXME will not work with separately loaded schemas because e.g. the choice allowing the specific type is missing
//FIXME add to path
// return new DefinitionPath(path).addSubstitution(elements.iterator().next());
}
parent = parent.getSuperType();
}
}
return null;
}
};
// candidate match
List<DefinitionPath> candidates = matcher.findCandidates(container,
containerName, true, memberType);
if (candidates != null && !candidates.isEmpty()) {
return candidates.get(0); //TODO notification? FIXME will this work? possible problem: attribute is selected even though better candidate is in other attribute
}
return null;
}
private boolean isFeatureCollection(XmlElement el) {
//TODO improve condition?
//FIXME working like this?!
return el.getName().getLocalPart().contains("FeatureCollection") && //$NON-NLS-1$
!el.getType().getConstraint(AbstractFlag.class).isEnabled() &&
hasChild(el.getType(), "featureMember"); //$NON-NLS-1$
}
private boolean hasChild(TypeDefinition type, String localName) {
for (ChildDefinition<?> child : type.getChildren()) {
if (localName.equals(child.getName().getLocalPart())) {
return true;
}
}
return false;
}
/**
* Write a given instance
*
* @param instance the instance to writer
* @param type the feature type definition
* @throws XMLStreamException if writing the feature fails
*/
protected void writeMember(Instance instance, TypeDefinition type) throws XMLStreamException {
// Name elementName = GmlWriterUtil.getElementName(type);
// writer.writeStartElement(elementName.getNamespaceURI(), elementName.getLocalPart());
writeProperties(instance, type, true);
// writer.writeEndElement(); // type element name
}
/**
* Write the given feature's properties
*
* @param group the feature
* @param definition the feature type
* @param allowElements if element properties may be written
* @throws XMLStreamException if writing the properties fails
*/
private void writeProperties(Group group, DefinitionGroup definition,
boolean allowElements) throws XMLStreamException {
// eventually generate mandatory ID that is not set
GmlWriterUtil.writeRequiredID(writer, definition, group, true);
// writing the feature is controlled by the type definition
// so retrieving values from instance must happen based on actual
// structure! (e.g. including groups)
// write the attributes, as they must be handled first
writeProperties(group, DefinitionUtil.getAllChildren(definition), true);
if (allowElements) {
// write the elements
writeProperties(group, DefinitionUtil.getAllChildren(definition), false);
}
}
/**
* Write attribute or element properties.
* @param parent the parent group
* @param children the child definitions
* @param attributes <code>true</code> if attribute properties shall be
* written, <code>false</code> if element properties shall be written
* @throws XMLStreamException if writing the attributes/elements fails
*/
private void writeProperties(Group parent,
Collection<? extends ChildDefinition<?>> children,
boolean attributes) throws XMLStreamException {
if (parent == null) {
return;
}
for (ChildDefinition<?> child : children) {
Object[] values = parent.getProperty(child.getName());
if (values == null || values.length <= 0) {
continue;
}
if (child.asProperty() != null) {
PropertyDefinition propDef = child.asProperty();
boolean isAttribute = propDef.getConstraint(XmlAttributeFlag.class).isEnabled();
if (attributes && isAttribute) {
// write attribute
writeAttribute(values[0], propDef);
if (values.length > 1) {
//TODO warning?!
}
}
else if (!attributes && !isAttribute) {
// write element
for (Object value : values) {
writeElement(value, propDef);
}
}
}
else if (child.asGroup() != null) {
// handle to child groups
for (Object value : values) {
if (value instanceof Group) {
writeProperties((Group) value,
DefinitionUtil.getAllChildren(child.asGroup()),
attributes);
}
else {
//TODO warning/error?
}
}
}
}
}
/**
* Write a property element.
* @param value the element value
* @param propDef the property definition
* @throws XMLStreamException if writing the element fails
*/
private void writeElement(Object value, PropertyDefinition propDef) throws XMLStreamException {
Group group = null;
if (value instanceof Group) {
group = (Group) value;
if (value instanceof Instance) {
// extract value from instance
value = ((Instance) value).getValue();
}
}
if (group == null) {
// just a value
if (value == null) {
// null value
if (propDef.getConstraint(Cardinality.class).getMinOccurs() > 0) {
// write empty element
GmlWriterUtil.writeEmptyElement(writer, propDef.getName());
// mark as nil
writeElementValue(null, propDef);
}
// otherwise just skip it
}
else {
GmlWriterUtil.writeStartElement(writer, propDef.getName());
if (value instanceof GeometryProperty<?> || value instanceof Geometry) {
//XXX other check, e.g. for constraints?
//FIXME currently duplicate of code some lines below!!!!
String srsName;
Geometry geom;
if (value instanceof Geometry) {
geom = (Geometry) value;
srsName = null;
}
else {
geom = ((GeometryProperty<?>) value).getGeometry();
srsName = null; //TODO
}
// write geometry
writeGeometry(geom, propDef, srsName); //FIXME getCommonSRSName());
}
else {
// simple element with value
// write value as content
writeElementValue(value, propDef);
}
writer.writeEndElement();
}
}
else {
// children and maybe a value
GmlWriterUtil.writeStartElement(writer, propDef.getName());
boolean hasValue = propDef.getPropertyType().getConstraint(
HasValueFlag.class).isEnabled();
// handle about annotated geometries
if (!hasValue && (value instanceof Geometry || value instanceof GeometryProperty<?>)) {
//XXX what about collections of geometries?
//XXX other check, e.g. for constraints?
String srsName;
Geometry geom;
if (value instanceof Geometry) {
geom = (Geometry) value;
srsName = null;
}
else {
geom = ((GeometryProperty<?>) value).getGeometry();
srsName = null; //TODO
}
// write geometry
writeGeometry(geom, propDef, srsName); //FIXME getCommonSRSName());
}
else
// write all children (no elements if there is a value)
writeProperties(group, group.getDefinition(), !hasValue);
// write value
if (hasValue) {
writeElementValue(value, propDef);
}
writer.writeEndElement();
}
}
/**
* Write an element value, either as element content or as <code>nil</code>.
* @param value the element value
* @param propDef the property definition the value is associated to
* @throws XMLStreamException if an error occurs writing the value
*/
private void writeElementValue(Object value, PropertyDefinition propDef) throws XMLStreamException {
if (value == null) {
// null value
if (!propDef.getConstraint(NillableFlag.class).isEnabled()) {
log.warn("Non-nillable element " + propDef.getName() + " is null"); //$NON-NLS-1$ //$NON-NLS-2$
}
else {
// nillable -> we may mark it as nil
writer.writeAttribute(SCHEMA_INSTANCE_NS, "nil", "true"); //$NON-NLS-1$ //$NON-NLS-2$
}
}
else {
// write value as content
writer.writeCharacters(SimpleTypeUtil.convertToXml(value,
propDef.getPropertyType()));
}
}
// /**
// * Write any attributes for simple type elements
// *
// * @param property the property of the simple type element
// * @param propDef the property definition of the simple type element
// * @throws XMLStreamException if an error occurs writing the attributes
// */
// private void writeSimpleTypeAttributes(Property property,
// PropertyDefinition propDef) throws XMLStreamException {
// if (property != null && propDef.isElement() // only elements may have properties
// && !(property instanceof AttributeProperty)) { //XXX this is a dirty hack - find a better solution
// Collection<Property> properties = FeatureInspector.getProperties(property);
// if (properties != null && !properties.isEmpty()) {
// //XXX create dummy attribute for writeProperties TODO better: FeatureInspector must support Property
// ComplexAttribute ca = new ComplexAttributeImpl(properties, GMLSchema.ABSTRACTSTYLETYPE_TYPE, null);
// writeProperties(ca, propDef.getAttributeType(), false);
// }
// }
// }
/**
* Write a geometry
*
* @param geometry the geometry
* @param property the geometry property
* @param srsName the common SRS name, may be <code>null</code>
* @throws XMLStreamException if an error occurs writing the geometry
*/
private void writeGeometry(Geometry geometry, PropertyDefinition property,
String srsName) throws XMLStreamException {
// write geometries
getGeometryWriter().write(writer, geometry, property, srsName);
}
/**
* Get the geometry writer
*
* @return the geometry writer instance to use
*/
protected StreamGeometryWriter getGeometryWriter() {
if (geometryWriter == null) {
geometryWriter = StreamGeometryWriter.getDefaultInstance(gmlNs);
}
return geometryWriter;
}
/**
* Write a property attribute
*
* @param value the attribute value, may be <code>null</code>
* @param propDef the associated property definition
* @throws XMLStreamException if writing the attribute fails
*/
private void writeAttribute(Object value,
PropertyDefinition propDef) throws XMLStreamException {
GmlWriterUtil.writeAttribute(writer, value, propDef);
}
}
| false | false | null | null |
diff --git a/testing/src/main/java/com/proofpoint/testing/Assertions.java b/testing/src/main/java/com/proofpoint/testing/Assertions.java
index 1d907a07a..cc88f0024 100644
--- a/testing/src/main/java/com/proofpoint/testing/Assertions.java
+++ b/testing/src/main/java/com/proofpoint/testing/Assertions.java
@@ -1,335 +1,335 @@
/*
* Copyright 2010 Proofpoint, 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.proofpoint.testing;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableMultiset;
import org.testng.Assert;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
public final class Assertions
{
private Assertions()
{
}
public static void assertContains(String actual, String expectedPart)
{
assertContains(actual, expectedPart, null);
}
public static void assertContainsAllOf(String actual, String... expectedParts)
{
// todo improve naive implementation
for (String expected : expectedParts) {
assertContains(actual, expected, null);
}
}
public static void assertContains(String actual, String expectedPart, String message)
{
assertNotNull(actual, "actual is null");
assertNotNull(expectedPart, "expectedPart is null");
if (actual.contains(expectedPart)) {
// ok
return;
}
fail("%sexpected:<%s> to contain <%s>", toMessageString(message), actual, expectedPart);
}
public static void assertEqualsIgnoreCase(String actual, String expected)
{
assertEqualsIgnoreCase(actual, expected, null);
}
public static void assertEqualsIgnoreCase(String actual, String expected, String message)
{
assertNotNull(actual, "actual is null");
if (actual.equalsIgnoreCase(expected)) {
// ok
return;
}
fail("%sexpected:<%s> to equal ignoring case <%s>", toMessageString(message), actual, expected);
}
public static void assertNotEquals(Object actual, Object expected)
{
assertNotEquals(actual, expected, null);
}
public static void assertNotEquals(Object actual, Object expected, String message)
{
if (actual == null) {
if (expected != null) {
// ok
return;
}
}
else {
if (!actual.equals(expected)) {
// ok
return;
}
}
fail("%sexpected:<%s> to not equal <%s>", toMessageString(message), actual, expected);
}
public static <T extends Comparable<T>> void assertGreaterThan(T actual, T expected)
{
assertGreaterThan(actual, expected, null);
}
public static <T extends Comparable<T>> void assertGreaterThan(T actual, T expected, String message)
{
assertNotNull(actual, "actual is null");
try {
if (actual.compareTo(expected) > 0) {
if (!(expected.compareTo(actual) < 0)) {
fail("%scomparison symmetry: <%s> is greater than <%s>, but <%s> is not less than <%s>",
toMessageString(message),
actual,
expected,
expected,
actual);
}
// ok
return;
}
}
catch (ClassCastException e) {
fail(e, "%sexpected:<%s> to be greater than <%s>, but %s is not comparable %s",
toMessageString(message),
actual,
expected,
actual.getClass().getName(),
expected.getClass().getName());
}
fail("%sexpected:<%s> to be greater than <%s>", toMessageString(message), actual, expected);
}
public static <T extends Comparable<T>> void assertGreaterThanOrEqual(T actual, T expected)
{
assertGreaterThanOrEqual(actual, expected, null);
}
public static <T extends Comparable<T>> void assertGreaterThanOrEqual(T actual, T expected, String message)
{
assertNotNull(actual, "actual is null");
try {
int compareValue = actual.compareTo(expected);
if (compareValue >= 0) {
int reverseCompareValue = expected.compareTo(actual);
if (!(reverseCompareValue <= 0 && (compareValue != 0 || reverseCompareValue == 0))) {
fail("%scomparison symmetry: <%s> is greater than or equal to <%s>, but <%s> is not less than or equal to<%s>",
toMessageString(message),
actual,
expected,
expected,
actual);
}
// ok
return;
}
}
catch (ClassCastException e) {
fail(e, "%sexpected:<%s> to be greater than or equal to <%s>, but %s is not comparable %s",
toMessageString(message),
actual,
expected,
actual.getClass().getName(),
expected.getClass().getName());
}
fail("%sexpected:<%s> to be greater than or equal to <%s>", toMessageString(message), actual, expected);
}
public static <T extends Comparable<T>> void assertLessThan(T actual, T expected)
{
assertLessThan(actual, expected, null);
}
public static <T extends Comparable<T>> void assertLessThan(T actual, T expected, String message)
{
assertNotNull(actual, "actual is null");
try {
if (actual.compareTo(expected) < 0) {
if (!(expected.compareTo(actual) > 0)) {
fail("%scomparison symmetry: <%s> is less than <%s>, but <%s> is not greater than <%s>",
toMessageString(message),
actual,
expected,
expected,
actual);
}
// ok
return;
}
}
catch (ClassCastException e) {
fail(e, "%sexpected:<%s> to be less than <%s>, but %s is not comparable %s",
toMessageString(message),
actual,
expected,
actual.getClass().getName(),
expected.getClass().getName());
}
fail("%sexpected:<%s> to be less than <%s>", toMessageString(message), actual, expected);
}
public static <T extends Comparable<T>> void assertLessThanOrEqual(T actual, T expected)
{
assertLessThanOrEqual(actual, expected, null);
}
public static <T extends Comparable<T>> void assertLessThanOrEqual(T actual, T expected, String message)
{
assertNotNull(actual, "actual is null");
try {
int compareValue = actual.compareTo(expected);
if (compareValue <= 0) {
int reverseCompareValue = expected.compareTo(actual);
if (!(reverseCompareValue >= 0 && (compareValue != 0 || reverseCompareValue == 0))) {
fail("%scomparison symmetry: <%s> is less than or equal to <%s>, but <%s> is not greater than or equal to <%s>",
toMessageString(message),
actual,
expected,
expected,
actual);
}
// ok
return;
}
}
catch (ClassCastException e) {
fail(e, "%sexpected:<%s> to be less than or equal to <%s>, but %s is not comparable %s",
toMessageString(message),
actual,
expected,
actual.getClass().getName(),
expected.getClass().getName());
}
fail("%sexpected:<%s> to be less than or equal to <%s>", toMessageString(message), actual, expected);
}
public static <T extends Comparable<T>> void assertBetweenInclusive(T actual, T lowerBound, T upperBound)
{
assertBetweenInclusive(actual, lowerBound, upperBound, null);
}
public static <T extends Comparable<T>> void assertBetweenInclusive(T actual, T lowerBound, T upperBound, String message)
{
assertNotNull(actual, "actual is null");
try {
if (actual.compareTo(lowerBound) >= 0 && actual.compareTo(upperBound) <= 0) {
// ok
return;
}
}
catch (ClassCastException e) {
fail(e, "%sexpected:<%s> to be between <%s> and <%s> inclusive, but %s is not comparable with %s or %s",
toMessageString(message),
actual,
lowerBound,
upperBound,
actual.getClass().getName(),
lowerBound.getClass().getName(),
upperBound.getClass().getName());
}
fail("%sexpected:<%s> to be between <%s> and <%s> inclusive", toMessageString(message), actual, lowerBound, upperBound);
}
public static <T extends Comparable<T>> void assertBetweenExclusive(T actual, T lowerBound, T upperBound)
{
assertBetweenExclusive(actual, lowerBound, upperBound, null);
}
public static <T extends Comparable<T>> void assertBetweenExclusive(T actual, T lowerBound, T upperBound, String message)
{
assertNotNull(actual, "actual is null");
try {
if (actual.compareTo(lowerBound) > 0 && actual.compareTo(upperBound) < 0) {
// ok
return;
}
}
catch (ClassCastException e) {
fail(e, "%sexpected:<%s> to be between <%s> and <%s> exclusive, but %s is not comparable with %s or %s",
toMessageString(message),
actual,
lowerBound,
upperBound,
actual.getClass().getName(),
lowerBound.getClass().getName(),
upperBound.getClass().getName());
}
fail("%sexpected:<%s> to be between <%s> and <%s> exclusive", toMessageString(message), actual, lowerBound, upperBound);
}
- public static void assertInstanceOf(Object actual, Class<?> expectedType)
+ public static <T, U extends T> void assertInstanceOf(T actual, Class<U> expectedType)
{
assertInstanceOf(actual, expectedType, null);
}
- public static void assertInstanceOf(Object actual, Class<?> expectedType, String message)
+ public static <T, U extends T> void assertInstanceOf(T actual, Class<U> expectedType, String message)
{
assertNotNull(actual, "actual is null");
assertNotNull(expectedType, "expectedType is null");
if (expectedType.isInstance(actual)) {
// ok
return;
}
fail("%sexpected:<%s> to be an instance of <%s>", toMessageString(message), actual, expectedType.getName());
}
public static void assertEqualsIgnoreOrder(Iterable<?> actual, Iterable<?> expected)
{
assertEqualsIgnoreOrder(actual, expected, null);
}
public static void assertEqualsIgnoreOrder(Iterable<?> actual, Iterable<?> expected, String message)
{
assertNotNull(actual, "actual is null");
assertNotNull(expected, "expected is null");
ImmutableMultiset<?> actualSet = ImmutableMultiset.copyOf(actual);
ImmutableMultiset<?> expectedSet = ImmutableMultiset.copyOf(expected);
if (!actualSet.equals(expectedSet)) {
Joiner joiner = Joiner.on("\n ");
fail("%sexpected: collections to be equal (ignoring order).%nActual:%n %s%nExpected:%n %s", toMessageString(message), joiner.join(actual), joiner.join(expected));
}
}
private static String toMessageString(String message)
{
return message == null ? "" : message + " ";
}
private static void fail(String format, Object... args)
{
String message = String.format(format, args);
Assert.fail(message);
}
private static void fail(Throwable e, String format, Object... args)
{
String message = String.format(format, args);
Assert.fail(message, e);
}
}
| false | false | null | null |
diff --git a/vizmap-gui-impl/src/main/java/org/cytoscape/view/vizmap/gui/internal/task/CreateNewVisualStyleTask.java b/vizmap-gui-impl/src/main/java/org/cytoscape/view/vizmap/gui/internal/task/CreateNewVisualStyleTask.java
index 487d5000a..1310999d2 100644
--- a/vizmap-gui-impl/src/main/java/org/cytoscape/view/vizmap/gui/internal/task/CreateNewVisualStyleTask.java
+++ b/vizmap-gui-impl/src/main/java/org/cytoscape/view/vizmap/gui/internal/task/CreateNewVisualStyleTask.java
@@ -1,44 +1,67 @@
package org.cytoscape.view.vizmap.gui.internal.task;
+import java.util.Iterator;
+
import org.cytoscape.view.vizmap.VisualMappingManager;
import org.cytoscape.view.vizmap.VisualStyle;
import org.cytoscape.view.vizmap.VisualStyleFactory;
import org.cytoscape.work.AbstractTask;
import org.cytoscape.work.ProvidesTitle;
import org.cytoscape.work.TaskMonitor;
import org.cytoscape.work.Tunable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import org.cytoscape.work.TunableValidator;
+import java.io.IOException;
-public class CreateNewVisualStyleTask extends AbstractTask {
+public class CreateNewVisualStyleTask extends AbstractTask implements TunableValidator {
private static final Logger logger = LoggerFactory.getLogger(CreateNewVisualStyleTask.class);
@ProvidesTitle
public String getTitle() {
return "Create New Visual Style";
}
@Tunable(description = "Name of new Visual Style:")
public String vsName;
private final VisualStyleFactory vsFactory;
private final VisualMappingManager vmm;
public CreateNewVisualStyleTask(final VisualStyleFactory vsFactory, final VisualMappingManager vmm) {
super();
this.vsFactory = vsFactory;
this.vmm = vmm;
}
public void run(TaskMonitor tm) {
if (vsName == null)
return;
// Create new style. This method call automatically fire event.
final VisualStyle newStyle = vsFactory.createVisualStyle(vsName);
vmm.addVisualStyle(newStyle);
logger.info("CreateNewVisualStyleTask created new Visual Style: " + newStyle.getTitle());
}
+
+
+ public ValidationState getValidationState(final Appendable errMsg){
+
+ Iterator<VisualStyle> it = this.vmm.getAllVisualStyles().iterator();
+ while(it.hasNext()){
+ VisualStyle exist_vs = it.next();
+ if (exist_vs.getTitle().equalsIgnoreCase(vsName)){
+ try {
+ errMsg.append("Visual style "+ vsName +" already existed!");
+ return ValidationState.INVALID;
+ }
+ catch (IOException e){
+ }
+ }
+ }
+
+ return ValidationState.OK;
+ }
}
\ No newline at end of file
| false | false | null | null |
diff --git a/gdx/src/com/badlogic/gdx/graphics/g2d/BitmapFont.java b/gdx/src/com/badlogic/gdx/graphics/g2d/BitmapFont.java
index fc82643a9..3f7645aa9 100644
--- a/gdx/src/com/badlogic/gdx/graphics/g2d/BitmapFont.java
+++ b/gdx/src/com/badlogic/gdx/graphics/g2d/BitmapFont.java
@@ -1,929 +1,929 @@
/*
* Copyright (c) 2008-2010, Matthias Mann
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following
* conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Matthias Mann nor
* the names of its contributors may be used to endorse or promote products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
* BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.badlogic.gdx.graphics.g2d;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.Texture.TextureFilter;
import com.badlogic.gdx.utils.Disposable;
import com.badlogic.gdx.utils.FloatArray;
import com.badlogic.gdx.utils.GdxRuntimeException;
import com.badlogic.gdx.utils.NumberUtils;
/** Renders bitmap fonts. The font consists of 2 files: an image file or {@link TextureRegion} containing the glyphs and a file in
* the AngleCode BMFont text format that describes where each glyph is on the image. Currently only a single image of glyphs is
* supported.<br>
* <br>
* Text is drawn using a {@link SpriteBatch}. Text can be cached in a {@link BitmapFontCache} for faster rendering of static text,
* which saves needing to compute the location of each glyph each frame.<br>
* <br>
* * The texture for a BitmapFont loaded from a file is managed. {@link #dispose()} must be called to free the texture when no
* longer needed. A BitmapFont loaded using a {@link TextureRegion} is managed if the region's texture is managed. Disposing the
* BitmapFont disposes the region's texture, which may not be desirable if the texture is still being used elsewhere.<br>
* <br>
* The code is based on Matthias Mann's TWL BitmapFont class. Thanks for sharing, Matthias! :)
* @author Nathan Sweet
* @author Matthias Mann */
public class BitmapFont implements Disposable {
static private final int LOG2_PAGE_SIZE = 9;
static private final int PAGE_SIZE = 1 << LOG2_PAGE_SIZE;
static private final int PAGES = 0x10000 / PAGE_SIZE;
static final char[] xChars = {'x', 'e', 'a', 'o', 'n', 's', 'r', 'c', 'u', 'm', 'v', 'w', 'z'};
static final char[] capChars = {'M', 'N', 'B', 'D', 'C', 'E', 'F', 'K', 'A', 'G', 'H', 'I', 'J', 'L', 'O', 'P', 'Q', 'R', 'S',
'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
TextureRegion region;
private final TextBounds textBounds = new TextBounds();
private float color = Color.WHITE.toFloatBits();
private Color tempColor = new Color(1, 1, 1, 1);
private boolean flipped;
private boolean integer = true;
final BitmapFontData data;
public static class BitmapFontData {
String imagePath;
final FileHandle fontFile;
final boolean flipped;
final float lineHeight;
float capHeight = 1;
float ascent;
float descent;
float down;
float scaleX = 1, scaleY = 1;
final Glyph[][] glyphs = new Glyph[PAGES][];
float spaceWidth;
float xHeight = 1;
public BitmapFontData (FileHandle fontFile, boolean flip) {
this.fontFile = fontFile;
this.flipped = flip;
BufferedReader reader = new BufferedReader(new InputStreamReader(fontFile.read()), 512);
try {
reader.readLine(); // info
String line = reader.readLine();
if (line == null) throw new GdxRuntimeException("Invalid font file: " + fontFile);
String[] common = line.split(" ", 4);
if (common.length < 4) throw new GdxRuntimeException("Invalid font file: " + fontFile);
if (!common[1].startsWith("lineHeight=")) throw new GdxRuntimeException("Invalid font file: " + fontFile);
lineHeight = Integer.parseInt(common[1].substring(11));
if (!common[2].startsWith("base=")) throw new GdxRuntimeException("Invalid font file: " + fontFile);
int baseLine = Integer.parseInt(common[2].substring(5));
line = reader.readLine();
if (line == null) throw new GdxRuntimeException("Invalid font file: " + fontFile);
String[] pageLine = line.split(" ", 4);
if (!pageLine[2].startsWith("file=")) throw new GdxRuntimeException("Invalid font file: " + fontFile);
String imgFilename = null;
if (pageLine[2].endsWith("\"")) {
imgFilename = pageLine[2].substring(6, pageLine[2].length() - 1);
} else {
imgFilename = pageLine[2].substring(5, pageLine[2].length());
}
imagePath = fontFile.parent().child(imgFilename).path().replaceAll("\\\\", "/");
descent = 0;
while (true) {
line = reader.readLine();
if (line == null) break;
if (line.startsWith("kernings ")) break;
if (!line.startsWith("char ")) continue;
Glyph glyph = new Glyph();
StringTokenizer tokens = new StringTokenizer(line, " =");
tokens.nextToken();
tokens.nextToken();
int ch = Integer.parseInt(tokens.nextToken());
if (ch <= Character.MAX_VALUE)
setGlyph(ch, glyph);
else
continue;
tokens.nextToken();
glyph.srcX = Integer.parseInt(tokens.nextToken());
tokens.nextToken();
glyph.srcY = Integer.parseInt(tokens.nextToken());
tokens.nextToken();
glyph.width = Integer.parseInt(tokens.nextToken());
tokens.nextToken();
glyph.height = Integer.parseInt(tokens.nextToken());
tokens.nextToken();
glyph.xoffset = Integer.parseInt(tokens.nextToken());
tokens.nextToken();
if (flip)
glyph.yoffset = Integer.parseInt(tokens.nextToken());
else
glyph.yoffset = -(glyph.height + Integer.parseInt(tokens.nextToken()));
tokens.nextToken();
glyph.xadvance = Integer.parseInt(tokens.nextToken());
descent = Math.min(baseLine + glyph.yoffset, descent);
}
while (true) {
line = reader.readLine();
if (line == null) break;
if (!line.startsWith("kerning ")) break;
StringTokenizer tokens = new StringTokenizer(line, " =");
tokens.nextToken();
tokens.nextToken();
int first = Integer.parseInt(tokens.nextToken());
tokens.nextToken();
int second = Integer.parseInt(tokens.nextToken());
if (first < 0 || first > Character.MAX_VALUE || second < 0 || second > Character.MAX_VALUE) continue;
Glyph glyph = getGlyph((char)first);
tokens.nextToken();
int amount = Integer.parseInt(tokens.nextToken());
glyph.setKerning(second, amount);
}
Glyph spaceGlyph = getGlyph(' ');
if (spaceGlyph == null) {
spaceGlyph = new Glyph();
Glyph xadvanceGlyph = getGlyph('l');
if (xadvanceGlyph == null) xadvanceGlyph = getFirstGlyph();
spaceGlyph.xadvance = xadvanceGlyph.xadvance;
setGlyph(' ', spaceGlyph);
}
spaceWidth = spaceGlyph != null ? spaceGlyph.xadvance + spaceGlyph.width : 1;
Glyph xGlyph = null;
for (int i = 0; i < xChars.length; i++) {
xGlyph = getGlyph(xChars[i]);
if (xGlyph != null) break;
}
if (xGlyph == null) xGlyph = getFirstGlyph();
xHeight = xGlyph.height;
Glyph capGlyph = null;
for (int i = 0; i < capChars.length; i++) {
capGlyph = getGlyph(capChars[i]);
if (capGlyph != null) break;
}
if (capGlyph == null) {
for (Glyph[] page : this.glyphs) {
if (page == null) continue;
for (Glyph glyph : page) {
if (glyph == null || glyph.height == 0 || glyph.width == 0) continue;
capHeight = Math.max(capHeight, glyph.height);
}
}
} else
capHeight = capGlyph.height;
ascent = baseLine - capHeight;
down = -lineHeight;
if (flip) {
ascent = -ascent;
down = -down;
}
} catch (Exception ex) {
throw new GdxRuntimeException("Error loading font file: " + fontFile, ex);
} finally {
try {
reader.close();
} catch (IOException ignored) {
}
}
}
private void setGlyph (int ch, Glyph glyph) {
Glyph[] page = glyphs[ch / PAGE_SIZE];
if (page == null) glyphs[ch / PAGE_SIZE] = page = new Glyph[PAGE_SIZE];
page[ch & PAGE_SIZE - 1] = glyph;
}
private Glyph getFirstGlyph () {
for (Glyph[] page : this.glyphs) {
if (page == null) continue;
for (Glyph glyph : page) {
if (glyph == null || glyph.height == 0 || glyph.width == 0) continue;
return glyph;
}
}
throw new GdxRuntimeException("No glyphs found!");
}
public Glyph getGlyph (char ch) {
Glyph[] page = glyphs[ch / PAGE_SIZE];
if (page != null) return page[ch & PAGE_SIZE - 1];
return null;
}
public String getImagePath () {
return imagePath;
}
public FileHandle getFontFile () {
return fontFile;
}
}
/** Creates a BitmapFont using the default 15pt Arial font included in the libgdx JAR file. This is convenient to easily display
* text without bothering with generating a bitmap font. */
public BitmapFont () {
this(Gdx.files.classpath("com/badlogic/gdx/utils/arial-15.fnt"),
Gdx.files.classpath("com/badlogic/gdx/utils/arial-15.png"), false, true);
}
/** Creates a BitmapFont using the default 15pt Arial font included in the libgdx JAR file. This is convenient to easily display
* text without bothering with generating a bitmap font.
* @param flip If true, the glyphs will be flipped for use with a perspective where 0,0 is the upper left corner. */
public BitmapFont (boolean flip) {
this(Gdx.files.classpath("com/badlogic/gdx/utils/arial-15.fnt"),
Gdx.files.classpath("com/badlogic/gdx/utils/arial-15.png"), flip, true);
}
/** Creates a BitmapFont with the glyphs relative to the specified region.
* @param region The texture region containing the glyphs. The glyphs must be relative to the lower left corner (ie, the region
* should not be flipped).
* @param flip If true, the glyphs will be flipped for use with a perspective where 0,0 is the upper left corner. */
public BitmapFont (FileHandle fontFile, TextureRegion region, boolean flip) {
this(new BitmapFontData(fontFile, flip), region, true);
}
/** Creates a BitmapFont from a BMFont file. The image file name is read from the BMFont file and the image is loaded from the
* same directory.
* @param flip If true, the glyphs will be flipped for use with a perspective where 0,0 is the upper left corner. */
public BitmapFont (FileHandle fontFile, boolean flip) {
this(new BitmapFontData(fontFile, flip), null, true);
}
/** Creates a BitmapFont from a BMFont file, using the specified image for glyphs. Any image specified in the BMFont file is
* ignored.
* @param flip If true, the glyphs will be flipped for use with a perspective where 0,0 is the upper left corner. */
public BitmapFont (FileHandle fontFile, FileHandle imageFile, boolean flip) {
this(fontFile, imageFile, flip, true);
}
/** Creates a BitmapFont from a BMFont file, using the specified image for glyphs. Any image specified in the BMFont file is
* ignored.
* @param flip If true, the glyphs will be flipped for use with a perspective where 0,0 is the upper left corner.
* @param integer If true, rendering positions will be at integer values to avoid filtering artifacts.s */
public BitmapFont (FileHandle fontFile, FileHandle imageFile, boolean flip, boolean integer) {
this(new BitmapFontData(fontFile, flip), new TextureRegion(new Texture(imageFile, false)), integer);
}
public BitmapFont (BitmapFontData data, TextureRegion region, boolean integer) {
this.region = region == null ? new TextureRegion(new Texture(Gdx.files.internal(data.imagePath), false)) : region;
this.flipped = data.flipped;
this.integer = integer;
this.data = data;
load(data);
}
private void load (BitmapFontData data) {
float invTexWidth = 1.0f / region.getTexture().getWidth();
float invTexHeight = 1.0f / region.getTexture().getHeight();
float u = region.u;
float v = region.v;
for (Glyph[] page : data.glyphs) {
if (page == null) continue;
for (Glyph glyph : page) {
if (glyph == null) continue;
glyph.u = u + glyph.srcX * invTexWidth;
glyph.u2 = u + (glyph.srcX + glyph.width) * invTexWidth;
if (data.flipped) {
glyph.v = v + glyph.srcY * invTexHeight;
glyph.v2 = v + (glyph.srcY + glyph.height) * invTexHeight;
} else {
glyph.v2 = v + glyph.srcY * invTexHeight;
glyph.v = v + (glyph.srcY + glyph.height) * invTexHeight;
}
}
}
}
/** Draws a string at the specified position.
* @param x The x position for the left most character.
* @param y The y position for the top of most capital letters in the font (the {@link #getCapHeight() cap height}).
* @return The bounds of the rendered string (the height is the distance from y to the baseline). Note the same TextBounds
* instance is used for all methods that return TextBounds. */
public TextBounds draw (SpriteBatch spriteBatch, CharSequence str, float x, float y) {
return draw(spriteBatch, str, x, y, 0, str.length());
}
/** Draws a substring at the specified position.
* @param x The x position for the left most character.
* @param y The y position for the top of most capital letters in the font (the {@link #getCapHeight() cap height}).
* @param start The first character of the string to draw.
* @param end The last character of the string to draw (exclusive).
* @return The bounds of the rendered string (the height is the distance from y to the baseline). Note the same TextBounds
* instance is used for all methods that return TextBounds. */
public TextBounds draw (SpriteBatch spriteBatch, CharSequence str, float x, float y, int start, int end) {
float batchColor = spriteBatch.color;
spriteBatch.setColor(color);
final Texture texture = region.getTexture();
y += data.ascent;
float startX = x;
Glyph lastGlyph = null;
if (data.scaleX == 1 && data.scaleY == 1) {
if (integer) {
y = (int)y;
x = (int)x;
}
while (start < end) {
lastGlyph = data.getGlyph(str.charAt(start++));
if (lastGlyph != null) {
spriteBatch.draw(texture, //
x + lastGlyph.xoffset, y + lastGlyph.yoffset, //
lastGlyph.width, lastGlyph.height, //
lastGlyph.u, lastGlyph.v, lastGlyph.u2, lastGlyph.v2);
x += lastGlyph.xadvance;
break;
}
}
while (start < end) {
char ch = str.charAt(start++);
Glyph g = data.getGlyph(ch);
if (g == null) continue;
x += lastGlyph.getKerning(ch);
if (integer) x = (int)x;
lastGlyph = g;
spriteBatch.draw(texture, //
x + lastGlyph.xoffset, y + lastGlyph.yoffset, //
lastGlyph.width, lastGlyph.height, //
lastGlyph.u, lastGlyph.v, lastGlyph.u2, lastGlyph.v2);
x += g.xadvance;
}
} else {
float scaleX = this.data.scaleX, scaleY = this.data.scaleY;
while (start < end) {
lastGlyph = data.getGlyph(str.charAt(start++));
if (lastGlyph != null) {
if (!integer) {
spriteBatch.draw(texture, //
x + lastGlyph.xoffset * scaleX, //
y + lastGlyph.yoffset * scaleY, //
lastGlyph.width * scaleX, //
lastGlyph.height * scaleY, //
lastGlyph.u, lastGlyph.v, lastGlyph.u2, lastGlyph.v2);
} else {
spriteBatch.draw(texture, //
(int)(x + lastGlyph.xoffset * scaleX), //
(int)(y + lastGlyph.yoffset * scaleY), //
(int)(lastGlyph.width * scaleX), //
(int)(lastGlyph.height * scaleY), //
lastGlyph.u, lastGlyph.v, lastGlyph.u2, lastGlyph.v2);
}
x += lastGlyph.xadvance * scaleX;
break;
}
}
while (start < end) {
char ch = str.charAt(start++);
Glyph g = data.getGlyph(ch);
if (g == null) continue;
x += lastGlyph.getKerning(ch) * scaleX;
lastGlyph = g;
if (!integer) {
spriteBatch.draw(texture, //
x + lastGlyph.xoffset * scaleX, //
y + lastGlyph.yoffset * scaleY, //
lastGlyph.width * scaleX, //
lastGlyph.height * scaleY, //
lastGlyph.u, lastGlyph.v, lastGlyph.u2, lastGlyph.v2);
} else {
spriteBatch.draw(texture, //
(int)(x + lastGlyph.xoffset * scaleX), //
(int)(y + lastGlyph.yoffset * scaleY), //
(int)(lastGlyph.width * scaleX), //
(int)(lastGlyph.height * scaleY), //
lastGlyph.u, lastGlyph.v, lastGlyph.u2, lastGlyph.v2);
}
x += g.xadvance * scaleX;
}
}
spriteBatch.setColor(batchColor);
textBounds.width = x - startX;
textBounds.height = data.capHeight;
return textBounds;
}
/** Draws a string, which may contain newlines (\n), at the specified position.
* @param x The x position for the left most character.
* @param y The y position for the top of most capital letters in the font (the {@link #getCapHeight() cap height}).
* @return The bounds of the rendered string (the height is the distance from y to the baseline of the last line). Note the
* same TextBounds instance is used for all methods that return TextBounds. */
public TextBounds drawMultiLine (SpriteBatch spriteBatch, CharSequence str, float x, float y) {
return drawMultiLine(spriteBatch, str, x, y, 0, HAlignment.LEFT);
}
/** Draws a string, which may contain newlines (\n), at the specified position and alignment. Each line is aligned horizontally
* within a rectangle of the specified width.
* @param x The x position for the left most character.
* @param y The y position for the top of most capital letters in the font (the {@link #getCapHeight() cap height}).
* @return The bounds of the rendered string (the height is the distance from y to the baseline of the last line). Note the
* same TextBounds instance is used for all methods that return TextBounds. */
public TextBounds drawMultiLine (SpriteBatch spriteBatch, CharSequence str, float x, float y, float alignmentWidth,
HAlignment alignment) {
float batchColor = spriteBatch.color;
float down = this.data.down;
int start = 0;
int numLines = 0;
int length = str.length();
float maxWidth = 0;
while (start < length) {
int lineEnd = indexOf(str, '\n', start);
float xOffset = 0;
if (alignment != HAlignment.LEFT) {
float lineWidth = getBounds(str, start, lineEnd).width;
xOffset = alignmentWidth - lineWidth;
if (alignment == HAlignment.CENTER) xOffset = xOffset / 2;
}
float lineWidth = draw(spriteBatch, str, x + xOffset, y, start, lineEnd).width;
maxWidth = Math.max(maxWidth, lineWidth);
start = lineEnd + 1;
y += down;
numLines++;
}
spriteBatch.setColor(batchColor);
textBounds.width = maxWidth;
textBounds.height = data.capHeight + (numLines - 1) * data.lineHeight;
return textBounds;
}
/** Draws a string, which may contain newlines (\n), with the specified position. Each line is automatically wrapped to keep it
* within a rectangle of the specified width.
* @param x The x position for the left most character.
* @param y The y position for the top of most capital letters in the font (the {@link #getCapHeight() cap height}).
* @return The bounds of the rendered string (the height is the distance from y to the baseline of the last line). Note the
* same TextBounds instance is used for all methods that return TextBounds. */
public TextBounds drawWrapped (SpriteBatch spriteBatch, CharSequence str, float x, float y, float wrapWidth) {
return drawWrapped(spriteBatch, str, x, y, wrapWidth, HAlignment.LEFT);
}
/** Draws a string, which may contain newlines (\n), with the specified position. Each line is automatically wrapped to keep it
* within a rectangle of the specified width, and aligned horizontally within that rectangle.
* @param x The x position for the left most character.
* @param y The y position for the top of most capital letters in the font (the {@link #getCapHeight() cap height}).
* @return The bounds of the rendered string (the height is the distance from y to the baseline of the last line). Note the
* same TextBounds instance is used for all methods that return TextBounds. */
public TextBounds drawWrapped (SpriteBatch spriteBatch, CharSequence str, float x, float y, float wrapWidth,
HAlignment alignment) {
if (wrapWidth <= 0) wrapWidth = Integer.MAX_VALUE;
float batchColor = spriteBatch.color;
float down = this.data.down;
int start = 0;
int numLines = 0;
int length = str.length();
float maxWidth = 0;
while (start < length) {
int newLine = BitmapFont.indexOf(str, '\n', start);
int lineEnd = start + computeVisibleGlyphs(str, start, newLine, wrapWidth);
- int nextStart = lineEnd;
+ int nextStart = lineEnd + 1;
if (lineEnd < newLine) {
// Find char to break on.
while (lineEnd > start) {
- if (BitmapFont.isWhitespace(str.charAt(lineEnd))) break;
+ if (BitmapFont.isWhitespace(str.charAt(lineEnd - 1))) break;
lineEnd--;
}
if (lineEnd == start)
lineEnd = nextStart; // If no characters to break, show all.
else {
nextStart = lineEnd;
// Eat whitespace at end of line.
while (lineEnd > start) {
if (!BitmapFont.isWhitespace(str.charAt(lineEnd - 1))) break;
lineEnd--;
}
}
} else
nextStart = lineEnd + 1;
if (lineEnd > start) {
float xOffset = 0;
if (alignment != HAlignment.LEFT) {
float lineWidth = getBounds(str, start, lineEnd).width;
xOffset = wrapWidth - lineWidth;
if (alignment == HAlignment.CENTER) xOffset /= 2;
}
float lineWidth = draw(spriteBatch, str, x + xOffset, y, start, lineEnd).width;
maxWidth = Math.max(maxWidth, lineWidth);
}
start = nextStart;
y += down;
numLines++;
}
spriteBatch.setColor(batchColor);
textBounds.width = maxWidth;
textBounds.height = data.capHeight + (numLines - 1) * data.lineHeight;
return textBounds;
}
/** Returns the size of the specified string. The height is the distance from the top of most capital letters in the font (the
* {@link #getCapHeight() cap height}) to the baseline. Note the same TextBounds instance is used for all methods that return
* TextBounds. */
public TextBounds getBounds (CharSequence str) {
return getBounds(str, 0, str.length());
}
/** Returns the size of the specified substring. The height is the distance from the top of most capital letters in the font
* (the {@link #getCapHeight() cap height}) to the baseline. Note the same TextBounds instance is used for all methods that
* return TextBounds.
* @param start The first character of the string.
* @param end The last character of the string (exclusive). */
public TextBounds getBounds (CharSequence str, int start, int end) {
int width = 0;
Glyph lastGlyph = null;
while (start < end) {
lastGlyph = data.getGlyph(str.charAt(start++));
if (lastGlyph != null) {
width = lastGlyph.xadvance;
break;
}
}
while (start < end) {
char ch = str.charAt(start++);
Glyph g = data.getGlyph(ch);
if (g != null) {
width += lastGlyph.getKerning(ch);
lastGlyph = g;
width += g.xadvance;
}
}
textBounds.width = width * data.scaleX;
textBounds.height = data.capHeight;
return textBounds;
}
/** Returns the size of the specified string, which may contain newlines. The height is the distance from the top of most
* capital letters in the font (the {@link #getCapHeight() cap height}) to the baseline of the last line of text. Note the same
* TextBounds instance is used for all methods that return TextBounds. */
public TextBounds getMultiLineBounds (CharSequence str) {
int start = 0;
float maxWidth = 0;
int numLines = 0;
int length = str.length();
while (start < length) {
int lineEnd = indexOf(str, '\n', start);
float lineWidth = getBounds(str, start, lineEnd).width;
maxWidth = Math.max(maxWidth, lineWidth);
start = lineEnd + 1;
numLines++;
}
textBounds.width = maxWidth;
textBounds.height = data.capHeight + (numLines - 1) * data.lineHeight;
return textBounds;
}
/** Returns the size of the specified string, which may contain newlines and is wrapped to keep it within a rectangle of the
* specified width. The height is the distance from the top of most capital letters in the font (the {@link #getCapHeight() cap
* height}) to the baseline of the last line of text. Note the same TextBounds instance is used for all methods that return
* TextBounds. */
public TextBounds getWrappedBounds (CharSequence str, float wrapWidth) {
if (wrapWidth <= 0) wrapWidth = Integer.MAX_VALUE;
float down = this.data.down;
int start = 0;
int numLines = 0;
int length = str.length();
float maxWidth = 0;
while (start < length) {
int newLine = BitmapFont.indexOf(str, '\n', start);
int lineEnd = start + computeVisibleGlyphs(str, start, newLine, wrapWidth);
- int nextStart = lineEnd;
+ int nextStart = lineEnd + 1;
if (lineEnd < newLine) {
// Find char to break on.
while (lineEnd > start) {
- if (BitmapFont.isWhitespace(str.charAt(lineEnd))) break;
+ if (BitmapFont.isWhitespace(str.charAt(lineEnd - 1))) break;
lineEnd--;
}
if (lineEnd == start)
lineEnd = nextStart; // If no characters to break, show all.
else {
nextStart = lineEnd;
// Eat whitespace at end of line.
while (lineEnd > start) {
if (!BitmapFont.isWhitespace(str.charAt(lineEnd - 1))) break;
lineEnd--;
}
}
}
if (lineEnd > start) {
float lineWidth = getBounds(str, start, lineEnd).width;
maxWidth = Math.max(maxWidth, lineWidth);
}
start = nextStart;
numLines++;
}
textBounds.width = maxWidth;
textBounds.height = data.capHeight + (numLines - 1) * data.lineHeight;
return textBounds;
}
/** Computes the glyph advances for the given character sequence and stores them in the provided {@link FloatArray}. The
* FloatArray is cleared. This will add an additional element at the end.
* @param str the character sequence
* @param glyphAdvances the glyph advances output array.
* @param glyphPositions the glyph positions output array. */
public void computeGlyphAdvancesAndPositions (CharSequence str, FloatArray glyphAdvances, FloatArray glyphPositions) {
glyphAdvances.clear();
glyphPositions.clear();
int index = 0;
int end = str.length();
int width = 0;
Glyph lastGlyph = null;
if (data.scaleX == 1) {
for (; index < end; index++) {
char ch = str.charAt(index);
Glyph g = data.getGlyph(ch);
if (g != null) {
if (lastGlyph != null) width += lastGlyph.getKerning(ch);
lastGlyph = g;
glyphAdvances.add(g.xadvance);
glyphPositions.add(width);
width += g.xadvance;
}
}
glyphAdvances.add(0);
glyphPositions.add(width);
} else {
float scaleX = this.data.scaleX;
for (; index < end; index++) {
char ch = str.charAt(index);
Glyph g = data.getGlyph(ch);
if (g != null) {
if (lastGlyph != null) width += lastGlyph.getKerning(ch) * scaleX;
lastGlyph = g;
glyphAdvances.add(g.xadvance * scaleX);
glyphPositions.add(width);
width += g.xadvance;
}
}
glyphAdvances.add(0);
glyphPositions.add(width);
}
}
/** Returns the number of glyphs from the substring that can be rendered in the specified width.
* @param start The first character of the string.
* @param end The last character of the string (exclusive). */
public int computeVisibleGlyphs (CharSequence str, int start, int end, float availableWidth) {
int index = start;
int width = 0;
Glyph lastGlyph = null;
if (data.scaleX == 1) {
for (; index < end; index++) {
char ch = str.charAt(index);
Glyph g = data.getGlyph(ch);
if (g != null) {
if (lastGlyph != null) width += lastGlyph.getKerning(ch);
if (width + g.xadvance > availableWidth) break;
width += g.xadvance;
lastGlyph = g;
}
}
} else {
float scaleX = this.data.scaleX;
for (; index < end; index++) {
char ch = str.charAt(index);
Glyph g = data.getGlyph(ch);
if (g != null) {
if (lastGlyph != null) width += lastGlyph.getKerning(ch) * scaleX;
if (width + g.xadvance * scaleX > availableWidth) break;
width += g.xadvance * scaleX;
lastGlyph = g;
}
}
}
return index - start;
}
public void setColor (float color) {
this.color = color;
}
public void setColor (Color tint) {
this.color = tint.toFloatBits();
}
public void setColor (float r, float g, float b, float a) {
int intBits = (int)(255 * a) << 24 | (int)(255 * b) << 16 | (int)(255 * g) << 8 | (int)(255 * r);
color = NumberUtils.intToFloatColor(intBits);
}
/** Returns the color of this font. Changing the returned color will have no affect, {@link #setColor(Color)} or
* {@link #setColor(float, float, float, float)} must be used. */
public Color getColor () {
int intBits = NumberUtils.floatToIntColor(color);
Color color = this.tempColor;
color.r = (intBits & 0xff) / 255f;
color.g = ((intBits >>> 8) & 0xff) / 255f;
color.b = ((intBits >>> 16) & 0xff) / 255f;
color.a = ((intBits >>> 24) & 0xff) / 255f;
return color;
}
public void setScale (float scaleX, float scaleY) {
data.spaceWidth = data.spaceWidth / this.data.scaleX * scaleX;
data.xHeight = data.xHeight / this.data.scaleY * scaleY;
data.capHeight = data.capHeight / this.data.scaleY * scaleY;
data.ascent = data.ascent / this.data.scaleY * scaleY;
data.descent = data.descent / this.data.scaleY * scaleY;
data.down = data.down / this.data.scaleY * scaleY;
data.scaleX = scaleX;
data.scaleY = scaleY;
}
/** Scales the font by the specified amount in both directions.<br>
* <br>
* Note that smoother scaling can be achieved if the texture backing the BitmapFont is using {@link TextureFilter#Linear}. The
* default is Nearest, so use a BitmapFont constructor that takes a {@link TextureRegion}. */
public void setScale (float scaleXY) {
setScale(scaleXY, scaleXY);
}
/** Sets the font's scale relative to the current scale. */
public void scale (float amount) {
setScale(data.scaleX + amount, data.scaleY + amount);
}
public float getScaleX () {
return data.scaleX;
}
public float getScaleY () {
return data.scaleY;
}
public TextureRegion getRegion () {
return region;
}
/** Returns the line height, which is the distance from one line of text to the next. */
public float getLineHeight () {
return data.lineHeight;
}
/** Returns the width of the space character. */
public float getSpaceWidth () {
return data.spaceWidth;
}
/** Returns the x-height, which is the distance from the top of most lowercase characters to the baseline. */
public float getXHeight () {
return data.xHeight;
}
/** Returns the cap height, which is the distance from the top of most uppercase characters to the baseline. Since the drawing
* position is the cap height of the first line, the cap height can be used to get the location of the baseline. */
public float getCapHeight () {
return data.capHeight;
}
/** Returns the ascent, which is the distance from the cap height to the top of the tallest glyph. */
public float getAscent () {
return data.ascent;
}
/** Returns the descent, which is the distance from the bottom of the glyph that extends the lowest to the baseline. This number
* is negative. */
public float getDescent () {
return data.descent;
}
/** Returns true if this BitmapFont has been flipped for use with a y-down coordinate system. */
public boolean isFlipped () {
return flipped;
}
/** Disposes the texture used by this BitmapFont's region. */
public void dispose () {
region.getTexture().dispose();
}
/** Makes the specified glyphs fixed width. This can be useful to make the numbers in a font fixed width. Eg, when horizontally
* centering a score or loading percentage text, it will not jump around as different numbers are shown. */
public void setFixedWidthGlyphs (CharSequence glyphs) {
int maxAdvance = 0;
for (int index = 0, end = glyphs.length(); index < end; index++) {
Glyph g = data.getGlyph(glyphs.charAt(index));
if (g != null && g.xadvance > maxAdvance) maxAdvance = g.xadvance;
}
for (int index = 0, end = glyphs.length(); index < end; index++) {
Glyph g = data.getGlyph(glyphs.charAt(index));
if (g == null) continue;
g.xoffset += (maxAdvance - g.xadvance) / 2;
g.xadvance = maxAdvance;
g.kerning = null;
}
}
/** @param character
* @return whether the given character is contained in this font. */
public boolean containsCharacter (char character) {
return data.getGlyph(character) != null;
}
/** Specifies whether to use integer positions or not. Default is to use them so filtering doesn't kick in as badly.
* @param use */
public void setUseIntegerPositions (boolean use) {
this.integer = use;
}
/** @return whether this font uses integer positions for drawing. */
public boolean usesIntegerPositions () {
return integer;
}
public BitmapFontData getData () {
return data;
}
static class Glyph {
public int srcX;
public int srcY;
int width, height;
float u, v, u2, v2;
int xoffset, yoffset;
int xadvance;
byte[][] kerning;
int getKerning (char ch) {
if (kerning != null) {
byte[] page = kerning[ch >>> LOG2_PAGE_SIZE];
if (page != null) return page[ch & PAGE_SIZE - 1];
}
return 0;
}
void setKerning (int ch, int value) {
if (kerning == null) kerning = new byte[PAGES][];
byte[] page = kerning[ch >>> LOG2_PAGE_SIZE];
if (page == null) kerning[ch >>> LOG2_PAGE_SIZE] = page = new byte[PAGE_SIZE];
page[ch & PAGE_SIZE - 1] = (byte)value;
}
}
static int indexOf (CharSequence text, char ch, int start) {
final int n = text.length();
for (; start < n; start++)
if (text.charAt(start) == ch) return start;
return n;
}
static boolean isWhitespace (char c) {
switch (c) {
case '\n':
case '\r':
case '\t':
case ' ':
return true;
default:
return false;
}
}
static public class TextBounds {
public float width;
public float height;
public TextBounds () {
}
public TextBounds (TextBounds bounds) {
set(bounds);
}
public void set (TextBounds bounds) {
width = bounds.width;
height = bounds.height;
}
}
static public enum HAlignment {
LEFT, CENTER, RIGHT
}
}
diff --git a/gdx/src/com/badlogic/gdx/graphics/g2d/BitmapFontCache.java b/gdx/src/com/badlogic/gdx/graphics/g2d/BitmapFontCache.java
index 9dd00c023..d541d873b 100644
--- a/gdx/src/com/badlogic/gdx/graphics/g2d/BitmapFontCache.java
+++ b/gdx/src/com/badlogic/gdx/graphics/g2d/BitmapFontCache.java
@@ -1,408 +1,408 @@
/*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.badlogic.gdx.graphics.g2d;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.g2d.BitmapFont.Glyph;
import com.badlogic.gdx.graphics.g2d.BitmapFont.HAlignment;
import com.badlogic.gdx.graphics.g2d.BitmapFont.TextBounds;
import com.badlogic.gdx.utils.Disposable;
import com.badlogic.gdx.utils.NumberUtils;
/** Caches glyph geometry for a BitmapFont, providing a fast way to render static text. This saves needing to compute the location
* of each glyph each frame.
* @author Nathan Sweet
* @author Matthias Mann */
public class BitmapFontCache implements Disposable {
private final BitmapFont font;
private float[] vertices = new float[0];
private int idx;
private float x, y;
private float color = Color.WHITE.toFloatBits();
private final Color tmpColor = new Color(Color.WHITE);
private final TextBounds textBounds = new TextBounds();
private boolean integer = true;
public BitmapFontCache (BitmapFont font) {
this(font, true);
}
/** Creates a new BitmapFontCache
* @param font the font to use
* @param integer whether to use integer positions and sizes. */
public BitmapFontCache (BitmapFont font, boolean integer) {
this.font = font;
this.integer = integer;
}
/** Sets the position of the text, relative to the position when the cached text was created.
* @param x The x coordinate
* @param y The y coodinate */
public void setPosition (float x, float y) {
translate(x - this.x, y - this.y);
}
/** Sets the position of the text, relative to its current position.
* @param xAmount The amount in x to move the text
* @param yAmount The amount in y to move the text */
public void translate (float xAmount, float yAmount) {
if (xAmount == 0 && yAmount == 0) return;
if (integer) {
xAmount = (int)xAmount;
yAmount = (int)yAmount;
}
x += xAmount;
y += yAmount;
float[] vertices = this.vertices;
for (int i = 0, n = idx; i < n; i += 5) {
vertices[i] += xAmount;
vertices[i + 1] += yAmount;
}
}
public void setColor (float color) {
if (color == this.color) return;
this.color = color;
float[] vertices = this.vertices;
for (int i = 2, n = idx; i < n; i += 5)
vertices[i] = color;
}
public void setColor (Color tint) {
final float color = tint.toFloatBits();
if (color == this.color) return;
this.color = color;
float[] vertices = this.vertices;
for (int i = 2, n = idx; i < n; i += 5)
vertices[i] = color;
}
public void setColor (float r, float g, float b, float a) {
int intBits = ((int)(255 * a) << 24) | ((int)(255 * b) << 16) | ((int)(255 * g) << 8) | ((int)(255 * r));
float color = NumberUtils.intToFloatColor(intBits);
if (color == this.color) return;
this.color = color;
float[] vertices = this.vertices;
for (int i = 2, n = idx; i < n; i += 5)
vertices[i] = color;
}
public void draw (SpriteBatch spriteBatch) {
spriteBatch.draw(font.getRegion().getTexture(), vertices, 0, idx);
}
public void draw (SpriteBatch spriteBatch, float alphaModulation) {
if (alphaModulation == 1) {
draw(spriteBatch);
return;
}
Color color = getColor();
float oldAlpha = color.a;
color.a *= alphaModulation;
setColor(color);
draw(spriteBatch);
color.a = oldAlpha;
setColor(color);
}
public Color getColor () {
float floatBits = color;
int intBits = NumberUtils.floatToIntColor(color);
Color color = tmpColor;
color.r = (intBits & 0xff) / 255f;
color.g = ((intBits >>> 8) & 0xff) / 255f;
color.b = ((intBits >>> 16) & 0xff) / 255f;
color.a = ((intBits >>> 24) & 0xff) / 255f;
return color;
}
private void reset (int glyphCount) {
x = 0;
y = 0;
idx = 0;
int vertexCount = glyphCount * 20;
if (vertices == null || vertices.length < vertexCount) vertices = new float[vertexCount];
}
private float addToCache (CharSequence str, float x, float y, int start, int end) {
float startX = x;
BitmapFont font = this.font;
Glyph lastGlyph = null;
if (font.data.scaleX == 1 && font.data.scaleY == 1) {
while (start < end) {
lastGlyph = font.data.getGlyph(str.charAt(start++));
if (lastGlyph != null) {
addGlyph(lastGlyph, x + lastGlyph.xoffset, y + lastGlyph.yoffset, lastGlyph.width, lastGlyph.height);
x += lastGlyph.xadvance;
break;
}
}
while (start < end) {
char ch = str.charAt(start++);
Glyph g = font.data.getGlyph(ch);
if (g != null) {
x += lastGlyph.getKerning(ch);
lastGlyph = g;
addGlyph(lastGlyph, x + g.xoffset, y + g.yoffset, g.width, g.height);
x += g.xadvance;
}
}
} else {
float scaleX = font.data.scaleX, scaleY = font.data.scaleY;
while (start < end) {
lastGlyph = font.data.getGlyph(str.charAt(start++));
if (lastGlyph != null) {
addGlyph(lastGlyph, //
x + lastGlyph.xoffset * scaleX, //
y + lastGlyph.yoffset * scaleY, //
lastGlyph.width * scaleX, //
lastGlyph.height * scaleY);
x += lastGlyph.xadvance * scaleX;
break;
}
}
while (start < end) {
char ch = str.charAt(start++);
Glyph g = font.data.getGlyph(ch);
if (g != null) {
x += lastGlyph.getKerning(ch) * scaleX;
lastGlyph = g;
addGlyph(lastGlyph, //
x + g.xoffset * scaleX, //
y + g.yoffset * scaleY, //
g.width * scaleX, //
g.height * scaleY);
x += g.xadvance * scaleX;
}
}
}
return x - startX;
}
private void addGlyph (Glyph glyph, float x, float y, float width, float height) {
float x2 = x + width;
float y2 = y + height;
final float u = glyph.u;
final float u2 = glyph.u2;
final float v = glyph.v;
final float v2 = glyph.v2;
final float[] vertices = this.vertices;
if (integer) {
x = (int)x;
y = (int)y;
x2 = (int)x2;
y2 = (int)y2;
}
vertices[idx++] = x;
vertices[idx++] = y;
vertices[idx++] = color;
vertices[idx++] = u;
vertices[idx++] = v;
vertices[idx++] = x;
vertices[idx++] = y2;
vertices[idx++] = color;
vertices[idx++] = u;
vertices[idx++] = v2;
vertices[idx++] = x2;
vertices[idx++] = y2;
vertices[idx++] = color;
vertices[idx++] = u2;
vertices[idx++] = v2;
vertices[idx++] = x2;
vertices[idx++] = y;
vertices[idx++] = color;
vertices[idx++] = u2;
vertices[idx++] = v;
}
/** Caches a string with the specified position.
* @param x The x position for the left most character.
* @param y The y position for the top of most capital letters in the font (the {@link BitmapFont#getCapHeight() cap height}).
* @return The bounds of the cached string (the height is the distance from y to the baseline). */
public TextBounds setText (CharSequence str, float x, float y) {
return setText(str, x, y, 0, str.length());
}
/** Caches a substring with the specified position.
* @param x The x position for the left most character.
* @param y The y position for the top of most capital letters in the font (the {@link BitmapFont#getCapHeight() cap height}).
* @param start The first character of the string to draw.
* @param end The last character of the string to draw (exclusive).
* @return The bounds of the cached string (the height is the distance from y to the baseline). */
public TextBounds setText (CharSequence str, float x, float y, int start, int end) {
reset(end - start);
y += font.data.ascent;
textBounds.width = addToCache(str, x, y, start, end);
textBounds.height = font.data.capHeight;
return textBounds;
}
/** Caches a string, which may contain newlines (\n), with the specified position.
* @param x The x position for the left most character.
* @param y The y position for the top of most capital letters in the font (the {@link BitmapFont#getCapHeight() cap height}).
* @return The bounds of the cached string (the height is the distance from y to the baseline of the last line). */
public TextBounds setMultiLineText (CharSequence str, float x, float y) {
return setMultiLineText(str, x, y, 0, HAlignment.LEFT);
}
/** Caches a string, which may contain newlines (\n), with the specified position and alignment. Each line is aligned
* horizontally within a rectangle of the specified width.
* @param x The x position for the left most character.
* @param y The y position for the top of most capital letters in the font (the {@link BitmapFont#getCapHeight() cap height}).
* @return The bounds of the cached string (the height is the distance from y to the baseline of the last line). */
public TextBounds setMultiLineText (CharSequence str, float x, float y, float alignmentWidth, HAlignment alignment) {
BitmapFont font = this.font;
int length = str.length();
reset(length);
y += font.data.ascent;
float down = font.data.down;
float maxWidth = 0;
float startY = y;
int start = 0;
int numLines = 0;
while (start < length) {
int lineEnd = BitmapFont.indexOf(str, '\n', start);
float xOffset = 0;
if (alignment != HAlignment.LEFT) {
float lineWidth = font.getBounds(str, start, lineEnd).width;
xOffset = alignmentWidth - lineWidth;
if (alignment == HAlignment.CENTER) xOffset /= 2;
}
float lineWidth = addToCache(str, x + xOffset, y, start, lineEnd);
maxWidth = Math.max(maxWidth, lineWidth);
start = lineEnd + 1;
y += down;
numLines++;
}
textBounds.width = maxWidth;
textBounds.height = font.data.capHeight + (numLines - 1) * font.data.lineHeight;
return textBounds;
}
/** Caches a string, which may contain newlines (\n), with the specified position. Each line is automatically wrapped to keep it
* within a rectangle of the specified width.
* @param x The x position for the left most character.
* @param y The y position for the top of most capital letters in the font (the {@link BitmapFont#getCapHeight() cap height}).
* @return The bounds of the cached string (the height is the distance from y to the baseline of the last line). */
public TextBounds setWrappedText (CharSequence str, float x, float y, float wrapWidth) {
return setWrappedText(str, x, y, wrapWidth, HAlignment.LEFT);
}
/** Caches a string, which may contain newlines (\n), with the specified position. Each line is automatically wrapped to keep it
* within a rectangle of the specified width, and aligned horizontally within that rectangle.
* @param x The x position for the left most character.
* @param y The y position for the top of most capital letters in the font (the {@link BitmapFont#getCapHeight() cap height}).
* @return The bounds of the cached string (the height is the distance from y to the baseline of the last line). */
public TextBounds setWrappedText (CharSequence str, float x, float y, float wrapWidth, HAlignment alignment) {
BitmapFont font = this.font;
int length = str.length();
reset(length);
y += font.data.ascent;
float down = font.data.down;
if (wrapWidth <= 0) wrapWidth = Integer.MAX_VALUE;
float maxWidth = 0;
int start = 0;
int numLines = 0;
while (start < length) {
int newLine = BitmapFont.indexOf(str, '\n', start);
int lineEnd = start + font.computeVisibleGlyphs(str, start, newLine, wrapWidth);
- int nextStart = lineEnd;
+ int nextStart = lineEnd + 1;
if (lineEnd < newLine) {
// Find char to break on.
while (lineEnd > start) {
- if (BitmapFont.isWhitespace(str.charAt(lineEnd))) break;
+ if (BitmapFont.isWhitespace(str.charAt(lineEnd - 1))) break;
lineEnd--;
}
if (lineEnd == start)
lineEnd = nextStart; // If no characters to break, show all.
else {
nextStart = lineEnd;
// Eat whitespace at end of line.
while (lineEnd > start) {
if (!BitmapFont.isWhitespace(str.charAt(lineEnd - 1))) break;
lineEnd--;
}
}
}
if (lineEnd > start) {
float xOffset = 0;
if (alignment != HAlignment.LEFT) {
float lineWidth = font.getBounds(str, start, lineEnd).width;
xOffset = wrapWidth - lineWidth;
if (alignment == HAlignment.CENTER) xOffset /= 2;
}
float lineWidth = addToCache(str, x + xOffset, y, start, lineEnd);
maxWidth = Math.max(maxWidth, lineWidth);
}
start = nextStart;
y += down;
numLines++;
}
textBounds.width = maxWidth;
textBounds.height = font.data.capHeight + (numLines - 1) * font.data.lineHeight;
return textBounds;
}
/** Returns the size of the cached string. The height is the distance from the top of most capital letters in the font (the
* {@link BitmapFont#getCapHeight() cap height}) to the baseline of the last line of text. */
public TextBounds getBounds () {
return textBounds;
}
/** Returns the x position of the cached string, relative to the position when the string was cached. */
public float getX () {
return x;
}
/** Returns the y position of the cached string, relative to the position when the string was cached. */
public float getY () {
return y;
}
public BitmapFont getFont () {
return font;
}
/** Disposes the underlying BitmapFont of this cache. */
public void dispose () {
font.dispose();
}
/** Specifies whether to use integer positions or not. Default is to use them so filtering doesn't kick in as badly.
* @param use */
public void setUseIntegerPositions (boolean use) {
this.integer = use;
}
/** @return whether this font uses integer positions for drawing. */
public boolean usesIntegerPositions () {
return integer;
}
}
| false | false | null | null |
diff --git a/src/main/java/org/primefaces/component/colorpicker/ColorPickerRenderer.java b/src/main/java/org/primefaces/component/colorpicker/ColorPickerRenderer.java
index 9711134dc..417355d09 100644
--- a/src/main/java/org/primefaces/component/colorpicker/ColorPickerRenderer.java
+++ b/src/main/java/org/primefaces/component/colorpicker/ColorPickerRenderer.java
@@ -1,142 +1,138 @@
/*
* Copyright 2009-2011 Prime Technology.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.primefaces.component.colorpicker;
import java.io.IOException;
import java.util.Map;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;
import org.primefaces.renderkit.CoreRenderer;
import org.primefaces.util.HTML;
public class ColorPickerRenderer extends CoreRenderer {
@Override
public void decode(FacesContext context, UIComponent component) {
ColorPicker colorPicker = (ColorPicker) component;
String paramName = colorPicker.getClientId(context) + "_input";
Map<String, String> params = context.getExternalContext().getRequestParameterMap();
if(params.containsKey(paramName)) {
String submittedValue = params.get(paramName);
colorPicker.setSubmittedValue(submittedValue);
}
}
@Override
public void encodeEnd(FacesContext context, UIComponent component) throws IOException {
ColorPicker colorPicker = (ColorPicker) component;
encodeMarkup(context, colorPicker);
encodeScript(context, colorPicker);
}
protected void encodeMarkup(FacesContext context, ColorPicker colorPicker) throws IOException {
ResponseWriter writer = context.getResponseWriter();
String clientId = colorPicker.getClientId(context);
String inputId = clientId + "_input";
String value = (String) colorPicker.getValue();
boolean isPopup = colorPicker.getMode().equals("popup");
String styleClass = colorPicker.getStyleClass();
styleClass = styleClass == null ? ColorPicker.STYLE_CLASS : ColorPicker.STYLE_CLASS + " " + styleClass;
writer.startElement("span", null);
writer.writeAttribute("id", clientId, "id");
writer.writeAttribute("class", styleClass, "styleClass");
if(colorPicker.getStyle() != null)
writer.writeAttribute("style", colorPicker.getStyle(), "style");
if(isPopup) {
encodeButton(context, clientId, value);
}
else {
encodeInline(context, clientId);
}
//Input
writer.startElement("input", null);
writer.writeAttribute("id", inputId, null);
writer.writeAttribute("name", inputId, null);
writer.writeAttribute("type", "hidden", null);
if(value != null) {
writer.writeAttribute("value", value, null);
}
writer.endElement("input");
writer.endElement("span");
}
protected void encodeButton(FacesContext context, String clientId, String value) throws IOException {
ResponseWriter writer = context.getResponseWriter();
writer.startElement("button", null);
writer.writeAttribute("id", clientId + "_button", null);
writer.writeAttribute("type", "button", null);
writer.writeAttribute("class", HTML.BUTTON_TEXT_ONLY_BUTTON_CLASS, null);
//text
writer.startElement("span", null);
writer.writeAttribute("class", HTML.BUTTON_TEXT_CLASS, null);
writer.write("<span id=\""+ clientId + "_livePreview\" style=\"overflow:hidden;width:1em;height:1em;display:block;border:solid 1px #000;text-indent:1em;white-space:nowrap;");
if(value != null) {
writer.write("background-color:#" + value);
}
writer.write("\">Live Preview</span>");
writer.endElement("span");
writer.endElement("button");
}
protected void encodeInline(FacesContext context, String clientId) throws IOException {
ResponseWriter writer = context.getResponseWriter();
writer.startElement("div", null);
writer.writeAttribute("id", clientId + "_inline", "id");
writer.endElement("div");
}
protected void encodeScript(FacesContext context, ColorPicker colorPicker) throws IOException {
ResponseWriter writer = context.getResponseWriter();
String clientId = colorPicker.getClientId(context);
String value = (String) colorPicker.getValue();
- String effect = colorPicker.getEffect();
+
startScript(writer, clientId);
writer.write("$(function() {");
writer.write("PrimeFaces.cw('ColorPicker','" + colorPicker.resolveWidgetVar() + "',{");
writer.write("id:'" + clientId + "'");
writer.write(",mode:'" + colorPicker.getMode() + "'");
- if(value != null) writer.write(",color:'" + value + "'");
- if(!effect.equals("none")) {
- writer.write(",effect:'" + effect + "'");
- writer.write(",effectSpeed:'" + colorPicker.getEffectSpeed() + "'");
- }
- if(colorPicker.getZindex() != Integer.MAX_VALUE) writer.write(",zindex:" + colorPicker.getZindex());
+ if(value != null)
+ writer.write(",color:'" + value + "'");
writer.write("},'colorpicker');});");
endScript(writer);
}
}
\ No newline at end of file
| false | false | null | null |
diff --git a/src/mygame/BladeServer.java b/src/mygame/BladeServer.java
index eb117d6..6a355e8 100644
--- a/src/mygame/BladeServer.java
+++ b/src/mygame/BladeServer.java
@@ -1,619 +1,611 @@
/*
* The Init terrain and init materials functions were both taken from the JME example code
* and modified. The rest of the code is almost entirely written from scratch.
*/
/*
* Copyright (c) 2009-2010 jMonkeyEngine
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'jMonkeyEngine' nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package mygame;
import com.jme3.animation.AnimControl;
import com.jme3.animation.Bone;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import mygame.messages.InputMessages;
import mygame.messages.CharPositionMessage;
import com.jme3.app.SimpleApplication;
import com.jme3.asset.TextureKey;
import com.jme3.bullet.BulletAppState;
import com.jme3.bullet.PhysicsSpace;
import com.jme3.bullet.PhysicsTickListener;
import com.jme3.bullet.collision.PhysicsCollisionEvent;
import com.jme3.bullet.collision.PhysicsCollisionListener;
import com.jme3.bullet.collision.PhysicsCollisionObject;
import com.jme3.bullet.collision.shapes.BoxCollisionShape;
import com.jme3.bullet.collision.shapes.CompoundCollisionShape;
import com.jme3.bullet.control.CharacterControl;
import com.jme3.bullet.control.GhostControl;
import com.jme3.bullet.control.PhysicsControl;
import com.jme3.bullet.control.RigidBodyControl;
import com.jme3.bullet.util.CollisionShapeFactory;
import com.jme3.light.DirectionalLight;
import com.jme3.material.Material;
import com.jme3.math.FastMath;
import com.jme3.math.Matrix3f;
import com.jme3.math.Vector3f;
import com.jme3.network.connection.Client;
import com.jme3.network.connection.Server;
import com.jme3.network.events.ConnectionListener;
import com.jme3.network.events.MessageListener;
import com.jme3.network.message.Message;
import com.jme3.network.serializing.Serializer;
import com.jme3.network.sync.ServerSyncService;
import com.jme3.scene.Node;
import com.jme3.scene.Spatial;
import com.jme3.system.AppSettings;
import com.jme3.system.JmeContext;
import com.jme3.terrain.geomipmap.TerrainQuad;
import com.jme3.terrain.heightmap.AbstractHeightMap;
import com.jme3.terrain.heightmap.ImageBasedHeightMap;
import com.jme3.texture.Texture;
import com.jme3.texture.Texture.WrapMode;
import com.jme3.util.SkyFactory;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.concurrent.ConcurrentHashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import jme3tools.converters.ImageToAwt;
import mygame.messages.CharCreationMessage;
import mygame.messages.CharDestructionMessage;
import mygame.messages.CharStatusMessage;
import mygame.messages.ClientReadyMessage;
import mygame.messages.HasID;
public class BladeServer extends SimpleApplication implements MessageListener,ConnectionListener{
ConcurrentHashMap<Long,Node> modelMap=new ConcurrentHashMap();
ConcurrentHashMap<Long,Vector3f> upperArmAnglesMap=new ConcurrentHashMap();
ConcurrentHashMap<Long,Vector3f> upperArmVelsMap=new ConcurrentHashMap();
ConcurrentHashMap<Long,Float> elbowWristAngleMap=new ConcurrentHashMap();
ConcurrentHashMap<Long,Float> elbowWristVelMap=new ConcurrentHashMap();
HashSet<Long> playerSet=new HashSet();
ConcurrentHashMap<Long,Client> clientMap=new ConcurrentHashMap();
ConcurrentHashMap<Client,Long> playerIDMap=new ConcurrentHashMap();
ConcurrentHashMap<Long,Vector3f> charPositionMap=new ConcurrentHashMap();
ConcurrentHashMap<Long,Vector3f> charVelocityMap=new ConcurrentHashMap();
ConcurrentHashMap<Long,Float> charAngleMap=new ConcurrentHashMap();
ConcurrentHashMap<Long,Float> charTurnVelMap=new ConcurrentHashMap();
ConcurrentHashMap<Long, Deque<Vector3f[]>> prevStates = new ConcurrentHashMap();
-
-
- ConcurrentHashMap<Long, Vector3f> prevUpperArmAnglesMap = new ConcurrentHashMap();
- ConcurrentHashMap<Long, Float> prevElbowWristAngleMap = new ConcurrentHashMap();
- ConcurrentHashMap<Long, Vector3f> prevCharPositionMap = new ConcurrentHashMap();
- ConcurrentHashMap<Long, Float> prevCharAngleMap = new ConcurrentHashMap();
+
ConcurrentHashMap<Long, Float> charLifeMap = new ConcurrentHashMap();
private final long timeBetweenSyncs=10;
private final int numPrevStates = 9;
private final int goBackNumStates = 3;
private long timeOfLastSync=0;
private long currentPlayerID=0;
private BulletAppState bulletAppState;
private TerrainQuad terrain;
Material mat_terrain;
Material wall_mat;
Material stone_mat;
Material floor_mat;
private RigidBodyControl terrain_phy;
private RigidBodyControl basic_phy;
private boolean updateNow;
float airTime = 0;
Server server;
ServerSyncService serverSyncService;
public static void main(String[] args) {
BladeServer app = new BladeServer();
AppSettings appSettings=new AppSettings(true);
appSettings.setFrameRate(60);
app.setSettings(appSettings);
//app.start();
app.start(JmeContext.Type.Headless);
}
@Override
public void simpleInitApp() {
Serializer.registerClass(CharStatusMessage.class);
Serializer.registerClass(CharCreationMessage.class);
Serializer.registerClass(CharDestructionMessage.class);
Serializer.registerClass(ClientReadyMessage.class);
InputMessages.registerInputClasses();
try {
server = new Server(BladeMain.port,BladeMain.port);
server.start();
}
catch(Exception e){
e.printStackTrace();
}
InputMessages.addInputMessageListeners(server, this);
server.addConnectionListener(this);
server.addMessageListener(this,CharCreationMessage.class,CharDestructionMessage.class,CharStatusMessage.class,ClientReadyMessage.class);
flyCam.setMoveSpeed(50);
bulletAppState = new BulletAppState();
stateManager.attach(bulletAppState);
rootNode.attachChild(SkyFactory.createSky(
assetManager, "Textures/Skysphere.jpg", true));
initMaterials();
initTerrain();
DirectionalLight sun = new DirectionalLight();
sun.setDirection(new Vector3f(-0.1f, -0.7f, -1.0f));
rootNode.addLight(sun);
DirectionalLight sun2 = new DirectionalLight();
sun2.setDirection(new Vector3f(0.1f, 0.7f, 1.0f));
rootNode.addLight(sun2);
flyCam.setEnabled(true);
this.getStateManager().getState(BulletAppState.class).getPhysicsSpace().enableDebug(this.getAssetManager());
PhysicsCollisionListener physListener = new PhysicsCollisionListener() {
public void collision(PhysicsCollisionEvent event) {
GhostControl a = event.getNodeA().getControl(GhostControl.class);
GhostControl b = event.getNodeB().getControl(GhostControl.class);
if ((a != null && b != null && a instanceof ControlID && b instanceof ControlID
&& ((ControlID)a).getID() != ((ControlID)b).getID())) {
System.out.println("Collision!");
System.out.println("A: " + a.getOverlappingCount()
+ " B: " + b.getOverlappingCount());
long playerID1 = Long.valueOf(((ControlID)a).getID());
long playerID2 = Long.valueOf(((ControlID)b).getID());
Deque player1Deque = prevStates.get(playerID1);
Deque player2Deque = prevStates.get(playerID2);
// go back some number of states
for (int i = 1; i < goBackNumStates; i++) {
player1Deque.pollLast();
player2Deque.pollLast();
}
Vector3f[] p1State = (Vector3f[])player1Deque.pollLast();
Vector3f[] p2State = (Vector3f[])player2Deque.pollLast();
// replace the removed states with the one that was grabbed
for (int i = 1; i < goBackNumStates; i++) {
player1Deque.offerLast(p1State);
player2Deque.offerLast(p2State);
}
// reposition the character as recorded in the previous state
upperArmAnglesMap.put(playerID1, p1State[0]);
upperArmAnglesMap.put(playerID2, p2State[0]);
elbowWristAngleMap.put(playerID1, p1State[1].getX());
elbowWristAngleMap.put(playerID2, p2State[1].getX());
charAngleMap.put(playerID1, p1State[1].getY());
charAngleMap.put(playerID2, p2State[1].getY());
charPositionMap.put(playerID1, p1State[2]);
charPositionMap.put(playerID2, p2State[2]);
modelMap.get(playerID1).getControl(CharacterControl.class).setPhysicsLocation(charPositionMap.get(playerID1));
modelMap.get(playerID2).getControl(CharacterControl.class).setPhysicsLocation(charPositionMap.get(playerID2));
updateCharacters(timer.getTimePerFrame());
System.out.println("A1: " + a.getOverlappingCount()
+ " B1: " + b.getOverlappingCount());
/* zeroing out velocities
// rotateStop
upperArmVelsMap.get(playerID1).z = 0;
upperArmVelsMap.get(playerID2).z = 0;
// stopMouseMovement
upperArmVelsMap.get(playerID1).x = upperArmVelsMap.get(playerID1).y = 0;
upperArmVelsMap.get(playerID2).x = upperArmVelsMap.get(playerID2).y = 0;
// stop arm
elbowWristVelMap.put(playerID1, 0f);
elbowWristVelMap.put(playerID2, 0f);
// stop char turn
charTurnVelMap.put(playerID1, 0f);
charTurnVelMap.put(playerID2, 0f);
// stop forward move
charVelocityMap.get(playerID1).z = 0;
charVelocityMap.get(playerID2).z = 0;
// stop left right move
charVelocityMap.get(playerID1).x = 0;
charVelocityMap.get(playerID2).x = 0;
*
*/
/*
upperArmVelsMap.put(playerID1, upperArmVelsMap.get(playerID1).mult(-1.0f));
upperArmVelsMap.put(playerID2, upperArmVelsMap.get(playerID2).mult(-1.0f));
elbowWristVelMap.put(playerID1, elbowWristVelMap.get(playerID1)*-1.0f);
elbowWristVelMap.put(playerID2, elbowWristVelMap.get(playerID2)*-1.0f);
charVelocityMap.put(playerID1, charVelocityMap.get(playerID1).mult(-1.0f));
charVelocityMap.put(playerID2, charVelocityMap.get(playerID2).mult(-1.0f));
charTurnVelMap.put(playerID1, charTurnVelMap.get(playerID1)*-1.0f);
charTurnVelMap.put(playerID2, charTurnVelMap.get(playerID2)*-1.0f);
*
*
*/
//updateNow = true;
}
}
};
PhysicsTickListener physTickListener = new PhysicsTickListener() {
public void prePhysicsTick(PhysicsSpace space, float f) {
updateCharacters(timer.getTimePerFrame());
//System.out.println("tpf: " + timer.getTimePerFrame() + " fps: " + timer.getFrameRate());
}
public void physicsTick(PhysicsSpace space, float f) {
updateClients();
}
};
//bulletAppState.getPhysicsSpace().setAccuracy((float)(1.0/120.0));
System.out.println("Accuracy: " + bulletAppState.getPhysicsSpace().getAccuracy());
this.getStateManager().getState(BulletAppState.class).getPhysicsSpace().addCollisionListener(physListener);
this.getStateManager().getState(BulletAppState.class).getPhysicsSpace().addTickListener(physTickListener);
updateNow = false;
}
@Override
public void simpleUpdate(float tpf){
//updateCharacters(tpf);
}
public void updateCharacters(float tpf) {
for(Iterator<Long> playerIterator=playerSet.iterator(); playerIterator.hasNext();){
long playerID = playerIterator.next();
Vector3f upperArmAngles = upperArmAnglesMap.get(playerID);
Vector3f[] prevState = new Vector3f[3];
prevState[0] = upperArmAnglesMap.get(playerID);
upperArmAnglesMap.put(playerID, CharMovement.extrapolateUpperArmAngles(upperArmAngles,
upperArmVelsMap.get(playerID), tpf));
prevState[1] = new Vector3f(elbowWristAngleMap.get(playerID), 0f, 0f);
elbowWristAngleMap.put(playerID, CharMovement.extrapolateLowerArmAngles(elbowWristAngleMap.get(playerID),
elbowWristVelMap.get(playerID), tpf));
prevState[1].setY(charAngleMap.get(playerID));
charAngleMap.put(playerID, CharMovement.extrapolateCharTurn(charAngleMap.get(playerID),
charTurnVelMap.get(playerID), tpf));
CharacterControl control=modelMap.get(playerID).getControl(CharacterControl.class);
float xDir,zDir;
zDir=FastMath.cos(charAngleMap.get(playerID));
xDir=FastMath.sin(charAngleMap.get(playerID));
Vector3f viewDirection=new Vector3f(xDir,0,zDir);
control.setViewDirection(viewDirection);
Vector3f forward,up,left;
float xVel,zVel;
xVel=charVelocityMap.get(playerID).x;
zVel=charVelocityMap.get(playerID).z;
forward=new Vector3f(viewDirection);
up=new Vector3f(0,1,0);
left=up.cross(forward);
control.setWalkDirection(left.mult(xVel).add(forward.mult(zVel)));
prevState[2] = charPositionMap.get(playerID).clone();
charPositionMap.get(playerID).set(modelMap.get(playerID).getControl(CharacterControl.class).getPhysicsLocation()); // getLocalTranslation
CharMovement.setUpperArmTransform(upperArmAnglesMap.get(playerID), modelMap.get(playerID));
CharMovement.setLowerArmTransform(elbowWristAngleMap.get(playerID), modelMap.get(playerID));
// Adjust the sword collision shape in accordance with arm movement.
// first, get rotation and position of hand
Bone hand = modelMap.get(playerID).getControl(AnimControl.class).getSkeleton().getBone("HandR");
Matrix3f rotation = hand.getModelSpaceRotation().toRotationMatrix();
Vector3f position = hand.getModelSpacePosition();
// adjust for difference in position of wrist and middle of sword
Vector3f shiftPosition = rotation.mult(new Vector3f(0f, .5f, 2.5f));
// build new collision shape
CompoundCollisionShape cShape = new CompoundCollisionShape();
Vector3f boxSize = new Vector3f(.1f, .1f, 2.25f);
cShape.addChildShape(new BoxCollisionShape(boxSize), position, rotation);
CollisionShapeFactory.shiftCompoundShapeContents(cShape, shiftPosition);
// remove GhostControl from PhysicsSpace, apply change, put in PhysicsSpace
SwordControl sword = modelMap.get(playerID).getControl(SwordControl.class);
bulletAppState.getPhysicsSpace().remove(sword);
sword.setCollisionShape(cShape);
bulletAppState.getPhysicsSpace().add(sword);
// get rid of oldest, add newest previous state
if (prevStates.get(playerID).size() >= numPrevStates) {
prevStates.get(playerID).pollFirst();
}
prevStates.get(playerID).offerLast(prevState);
}
}
public void updateClients() {
long currentTime = System.currentTimeMillis();
if ((currentTime - timeOfLastSync > timeBetweenSyncs)|| updateNow) {
timeOfLastSync = currentTime;
List<Long> playerList=new LinkedList();
playerList.addAll(playerSet);
for (Long sourcePlayerID:playerList) {
for (Long destPlayerID:playerList) {
try {
clientMap.get(destPlayerID).send(new CharStatusMessage(upperArmAnglesMap.get(sourcePlayerID),
upperArmVelsMap.get(sourcePlayerID),charPositionMap.get(sourcePlayerID),
charVelocityMap.get(sourcePlayerID),elbowWristAngleMap.get(sourcePlayerID),
elbowWristVelMap.get(sourcePlayerID),charAngleMap.get(sourcePlayerID),
charTurnVelMap.get(sourcePlayerID),sourcePlayerID,charLifeMap.get(sourcePlayerID)));
} catch (IOException ex) {
Logger.getLogger(BladeServer.class.getName()).log(Level.SEVERE, null, ex);
} catch (NullPointerException ex){
if(playerSet.contains(destPlayerID))
playerSet.remove(destPlayerID); // if the client has disconnected, remove its id
}
}
}
updateNow = false;
}
}
public void initTerrain() {
mat_terrain = new Material(assetManager, "Common/MatDefs/Terrain/Terrain.j3md");
mat_terrain.setTexture("m_Alpha", assetManager.loadTexture("Textures/alpha1.1.png"));
Texture grass = assetManager.loadTexture("Textures/grass.jpg");
grass.setWrap(WrapMode.Repeat);
mat_terrain.setTexture("m_Tex1", grass);
mat_terrain.setFloat("m_Tex1Scale", 64f);
Texture dirt = assetManager.loadTexture("Textures/TiZeta_SmlssWood1.jpg");
dirt.setWrap(WrapMode.Repeat);
mat_terrain.setTexture("m_Tex2", dirt);
mat_terrain.setFloat("m_Tex2Scale", 32f);
Texture rock = assetManager.loadTexture("Textures/TiZeta_cem1.jpg");
rock.setWrap(WrapMode.Repeat);
mat_terrain.setTexture("m_Tex3", rock);
mat_terrain.setFloat("m_Tex3Scale", 128f);
AbstractHeightMap heightmap = null;
Texture heightMapImage = assetManager.loadTexture("Textures/flatland.png");
heightmap = new ImageBasedHeightMap(
ImageToAwt.convert(heightMapImage.getImage(), false, true, 0));
heightmap.load();
terrain = new TerrainQuad("my terrain", 65, 1025, heightmap.getHeightMap());
terrain.setMaterial(mat_terrain);
terrain.setLocalTranslation(0, -100, 0);
terrain.setLocalScale(2f, 2f, 2f);
rootNode.attachChild(terrain);
terrain_phy = new RigidBodyControl(0.0f);
terrain_phy.addCollideWithGroup(PhysicsCollisionObject.COLLISION_GROUP_02);
terrain_phy.addCollideWithGroup(PhysicsCollisionObject.COLLISION_GROUP_03);
terrain.addControl(terrain_phy);
bulletAppState.getPhysicsSpace().add(terrain_phy);
}
public void initMaterials() {
wall_mat = new Material(assetManager, "Common/MatDefs/Misc/SimpleTextured.j3md");
TextureKey key = new TextureKey("Textures/road.jpg");
key.setGenerateMips(true);
Texture tex = assetManager.loadTexture(key);
wall_mat.setTexture("ColorMap", tex);
stone_mat = new Material(assetManager, "Common/MatDefs/Misc/SimpleTextured.j3md");
TextureKey key2 = new TextureKey("Textures/road.jpg");
key2.setGenerateMips(true);
Texture tex2 = assetManager.loadTexture(key2);
stone_mat.setTexture("ColorMap", tex2);
floor_mat = new Material(assetManager, "Common/MatDefs/Misc/SimpleTextured.j3md");
TextureKey key3 = new TextureKey("Textures/grass.jpg");
key3.setGenerateMips(true);
Texture tex3 = assetManager.loadTexture(key3);
tex3.setWrap(WrapMode.Repeat);
floor_mat.setTexture("ColorMap", tex3);
}
public void messageReceived(Message message) {
if (message instanceof ClientReadyMessage) {
try {
long newPlayerID = currentPlayerID++;
Client client = message.getClient();
System.out.println("Received ClientReadyMessage");
Node model = Character.createCharacter("Models/FighterRight.mesh.xml", assetManager, bulletAppState, true, newPlayerID);
rootNode.attachChild(model);
//rootNode.attachChild(geom1);
modelMap.put(newPlayerID, model);
upperArmAnglesMap.put(newPlayerID, new Vector3f());
upperArmVelsMap.put(newPlayerID, new Vector3f());
elbowWristAngleMap.put(newPlayerID, new Float(CharMovement.Constraints.lRotMin));
elbowWristVelMap.put(newPlayerID, new Float(0f));
charPositionMap.put(newPlayerID, new Vector3f());
charVelocityMap.put(newPlayerID, new Vector3f());
charAngleMap.put(newPlayerID, 0f);
charTurnVelMap.put(newPlayerID, 0f);
charLifeMap.put(newPlayerID, 1f);
- prevUpperArmAnglesMap.put(newPlayerID, new Vector3f());
- prevElbowWristAngleMap.put(newPlayerID, new Float(CharMovement.Constraints.lRotMin));
- prevCharPositionMap.put(newPlayerID, new Vector3f());
- prevCharAngleMap.put(newPlayerID, 0f);
-
+ prevStates.put(newPlayerID, new ArrayDeque<Vector3f[]>(numPrevStates));
+
client.send(new CharCreationMessage(newPlayerID, true));
for (Iterator<Long> playerIterator = playerSet.iterator(); playerIterator.hasNext();) {
long destPlayerID = playerIterator.next();
clientMap.get(destPlayerID).send(new CharCreationMessage(newPlayerID, false)); // send this new character to all other clients
client.send(new CharCreationMessage(destPlayerID, false)); // send all other client's characters to this client
System.out.println("Sent CharCreationMessage");
}
System.out.println("client connected:" + newPlayerID + "," + client);
playerSet.add(newPlayerID);
clientMap.put(newPlayerID, client);
playerIDMap.put(client, newPlayerID);
} catch (IOException ex) {
Logger.getLogger(BladeServer.class.getName()).log(Level.SEVERE, null, ex);
}
} else {
HasID hasID=(HasID)message;
long playerID=hasID.getID();
if (playerSet.contains(playerID)) {
if (message instanceof InputMessages.RotateUArmCC) {
System.out.println("rotateCC");
upperArmVelsMap.get(playerID).z = -1;
} else if (message instanceof InputMessages.RotateUArmC) {
System.out.println("rotateC");
upperArmVelsMap.get(playerID).z = 1;
} else if (message instanceof InputMessages.StopRotateTwist) {
System.out.println("rotateStop");
upperArmVelsMap.get(playerID).z = 0;
} else if (message instanceof InputMessages.MouseMovement) {
InputMessages.MouseMovement mouseMovement = (InputMessages.MouseMovement) message;
upperArmVelsMap.get(playerID).x = FastMath.cos(mouseMovement.angle);
upperArmVelsMap.get(playerID).y = FastMath.sin(mouseMovement.angle);
} else if (message instanceof InputMessages.StopMouseMovement) {
upperArmVelsMap.get(playerID).x = upperArmVelsMap.get(playerID).y = 0;
} else if (message instanceof InputMessages.LArmUp) {
System.out.println("arm up");
elbowWristVelMap.put(playerID, 1f);
} else if (message instanceof InputMessages.LArmDown) {
System.out.println("arm down");
elbowWristVelMap.put(playerID, -1f);
} else if (message instanceof InputMessages.StopLArm) {
System.out.println("arm stop");
elbowWristVelMap.put(playerID, 0f);
} else if (message instanceof InputMessages.MoveCharBackword) {
System.out.println("Move foreward");
charVelocityMap.get(playerID).z = -CharMovement.charBackwordSpeed;
} else if (message instanceof InputMessages.MoveCharForward) {
System.out.println("Move backword");
charVelocityMap.get(playerID).z = CharMovement.charForwardSpeed;
} else if (message instanceof InputMessages.MoveCharLeft) {
System.out.println("Move left");
charVelocityMap.get(playerID).x = CharMovement.charStrafeSpeed;
} else if (message instanceof InputMessages.MoveCharRight) {
System.out.println("Move right");
charVelocityMap.get(playerID).x = -CharMovement.charStrafeSpeed;
} else if (message instanceof InputMessages.TurnCharLeft) {
charTurnVelMap.put(playerID, 1f);
} else if (message instanceof InputMessages.TurnCharRight) {
charTurnVelMap.put(playerID, -1f);
} else if (message instanceof InputMessages.StopCharTurn) {
charTurnVelMap.put(playerID, 0f);
} else if (message instanceof InputMessages.StopForwardMove) {
charVelocityMap.get(playerID).z = 0;
} else if (message instanceof InputMessages.StopLeftRightMove) {
System.out.println("Stop Left Right Move");
charVelocityMap.get(playerID).x = 0;
}
} else {
System.out.println("PlayerID " + playerID + " is not in the set");
}
}
}
public void messageSent(Message message) {
// System.out.println("Sending message to "+message.getClient());
// System.out.println("Sending message "+message.getClass());
}
public void objectReceived(Object object) {
throw new UnsupportedOperationException("Not supported yet.");
}
public void objectSent(Object object) {
throw new UnsupportedOperationException("Not supported yet.");
}
public void clientConnected(Client client) {
}
public void clientDisconnected(Client client) {
System.out.println("client disconnecting is " + client);
long playerID = playerIDMap.get(client);
List<Long> players = new LinkedList();
Node model=modelMap.get(playerID);
bulletAppState.getPhysicsSpace().remove(model.getControl(SwordControl.class));
bulletAppState.getPhysicsSpace().remove(model.getControl(BodyControl.class));
bulletAppState.getPhysicsSpace().remove(model.getControl(CharacterControl.class));
rootNode.detachChild(modelMap.get(playerID));
playerIDMap.remove(client);
clientMap.remove(playerID);
players.addAll(playerSet);
playerSet.remove(playerID);
players.remove(playerID);
prevStates.remove(playerID);
for (Long destID : players) {
try {
clientMap.get(destID).send(new CharDestructionMessage(playerID));
} catch (IOException ex) {
Logger.getLogger(BladeServer.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
| false | false | null | null |
diff --git a/src/java/com/swijaya/coursera/posa/netty/EchoServer.java b/src/java/com/swijaya/coursera/posa/netty/EchoServer.java
index 7c3bb3a..0b8215a 100644
--- a/src/java/com/swijaya/coursera/posa/netty/EchoServer.java
+++ b/src/java/com/swijaya/coursera/posa/netty/EchoServer.java
@@ -1,143 +1,149 @@
package com.swijaya.coursera.posa.netty;
import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFactory;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelFutureListener;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
import org.jboss.netty.channel.group.ChannelGroup;
import org.jboss.netty.channel.group.ChannelGroupFuture;
import org.jboss.netty.channel.group.DefaultChannelGroup;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
import static org.jboss.netty.buffer.ChannelBuffers.dynamicBuffer;
import static org.jboss.netty.channel.Channels.pipeline;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.concurrent.Executors;
public class EchoServer {
public static final int PORT = 8080; // default port to bind our echo server to
// create a global channel group to hold all currently open channels so that we
// can close them all during application shutdown
static final ChannelGroup allChannels = new DefaultChannelGroup("echo-server");
public static void main(String[] args) throws Exception {
int port = PORT;
// The factory sets up a "reactor" configured with two thread pools to handle network events.
// The first argument configures a "boss" thread pool (by default containing only one boss thread)
// that accepts incoming connections, creates the channel abstractions for them, and pass them
// along to the thread pool of workers, configured in the second argument.
final ChannelFactory factory = new NioServerSocketChannelFactory(
Executors.newCachedThreadPool(),
Executors.newCachedThreadPool());
ServerBootstrap bootstrap = new ServerBootstrap(factory);
bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
@Override
public ChannelPipeline getPipeline() throws Exception {
return pipeline(
new EchoServerHandler());
}
});
// The bind() call triggers the creation of a server channel that acts as an "acceptor".
// The actual OS bind() call (and others) is done by a "boss" thread configured with the bootstrap's factory.
Channel c = bootstrap.bind(new InetSocketAddress(port));
allChannels.add(c);
// handle user Ctrl-C event to clean up after ourselves
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
ChannelGroupFuture f = allChannels.close();
f.awaitUninterruptibly();
factory.releaseExternalResources();
System.out.println("Shutdown.");
}
});
}
}
class EchoServerHandler extends SimpleChannelUpstreamHandler {
// dynamic buffer is used to store currently read bytes so far while we wait for an EOL marker
- private final ChannelBuffer buf = dynamicBuffer();
+ private ChannelBuffer buf;
@Override
public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent e) {
EchoServer.allChannels.add(e.getChannel());
}
@Override
public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) {
EchoServer.allChannels.remove(e.getChannel());
}
@Override
public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) {
SocketAddress remote = ctx.getChannel().getRemoteAddress();
System.out.println("Connected to client: " + remote.toString());
}
@Override
public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) {
SocketAddress remote = ctx.getChannel().getRemoteAddress();
System.out.println("Disconnected from client: " + remote.toString());
}
@Override
- public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
+ public void messageReceived(final ChannelHandlerContext ctx, MessageEvent e) {
Channel ch = e.getChannel();
ChannelBuffer m = (ChannelBuffer) e.getMessage();
+ if (buf == null) {
+ // create a temporary buffer to store echoed line
+ buf = dynamicBuffer();
+ }
+
// read bytes from the event's channel buffer until we run out of bytes to read,
// or we reach an EOL
boolean eolFound = false;
- for (int i = 0; i < m.capacity(); i++) {
- byte b = m.getByte(i);
+ while (m.readable()) {
+ byte b = m.readByte();
buf.writeByte(b);
if ((char) b == '\n') {
// we've read a line
eolFound = true;
break;
}
}
if (!eolFound) {
// there are still more bytes to read from the client for the current "line"
return;
}
// we have a full line in the buffer; echo it to the client and reset buffers
- ChannelFuture f = ch.write(m);
+ ChannelFuture f = ch.write(buf);
+ buf = null; // let the current echo buffer go out of scope so that we create
+ // a new buffer after every echoed line
+
f.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
- // clear the dynamic buffer we allocate for this handler so that we do not
- // run out of buffer space to write echoed lines to
- buf.clear();
+ System.out.println("Sent an echo to client: " + ctx.getChannel().getRemoteAddress().toString());
}
});
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
e.getCause().printStackTrace();
e.getChannel().close();
}
}
| false | false | null | null |
diff --git a/src/main/java/org/sukrupa/student/Student.java b/src/main/java/org/sukrupa/student/Student.java
index c44c81e3..aa2a6438 100644
--- a/src/main/java/org/sukrupa/student/Student.java
+++ b/src/main/java/org/sukrupa/student/Student.java
@@ -1,334 +1,338 @@
package org.sukrupa.student;
import com.google.common.collect.Sets;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.hibernate.annotations.Type;
import org.joda.time.LocalDate;
import org.joda.time.Years;
import org.joda.time.format.DateTimeFormat;
import org.sukrupa.platform.DoNotRemove;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
@Entity
public class Student {
public static final String DATE_OF_BIRTH_FORMAT = "dd-MM-YYYY";
private static final String PLACEHOLDER_IMAGE = "placeholderImage";
@Id
@GeneratedValue
private long id;
@Column(name = "STUDENT_ID")
private String studentId;
private String name;
private String religion;
private String caste;
private String mother;
private String father;
@Column(name = "SUB_CASTE")
private String subCaste;
@Column(name = "COMMUNITY_LOCATION")
private String communityLocation;
private String gender;
@Column(name = "STUDENT_CLASS")
private String studentClass;
@Column(name = "IMAGE_LINK")
private String imageLink;
@Type(type = "org.jadira.usertype.dateandtime.joda.PersistentLocalDate")
@Column(name = "DATE_OF_BIRTH")
private LocalDate dateOfBirth;
@ManyToMany
@JoinTable(name = "STUDENT_TALENT",
joinColumns = @JoinColumn(name = "student_id"),
inverseJoinColumns = @JoinColumn(name = "talent_id"))
private Set<Talent> talents;
@OrderBy("date desc")
@OneToMany(cascade = CascadeType.ALL)
@JoinTable(name = "STUDENT_NOTE",
joinColumns = @JoinColumn(name = "student_id"),
inverseJoinColumns = @JoinColumn(name = "note_id"))
private Set<Note> notes;
public static final Student EMPTY_STUDENT = new EmptyStudent();
@Enumerated(EnumType.ORDINAL)
private StudentStatus status = StudentStatus.NOT_SET;
@DoNotRemove
public Student() {
}
public Student(String studentId, String name, String religion, String caste, String subCaste,
String communityLocation, String gender, String studentClass, Set<Talent> talents,
String father, String mother, LocalDate dateOfBirth, Set<Note> notes, String imageLink,
StudentStatus status) {
this.studentId = studentId;
this.name = name;
this.religion = religion;
this.caste = caste;
this.subCaste = subCaste;
this.communityLocation = communityLocation;
this.gender = gender;
this.studentClass = studentClass;
this.father = father;
this.mother = mother;
this.dateOfBirth = dateOfBirth;
this.talents = talents;
this.notes = notes;
this.imageLink = imageLink;
+
+ if(status == null)
+ status = StudentStatus.NOT_SET;
+
this.status = status;
}
public Student(String studentId, String name, String dateOfBirth) {
this.studentId = studentId;
this.name = name;
this.dateOfBirth = convertDate(dateOfBirth);
}
private LocalDate convertDate(String dateOfBirth) {
return new LocalDate(DateTimeFormat.forPattern(DATE_OF_BIRTH_FORMAT).parseDateTime(dateOfBirth));
}
public String getName() {
return name;
}
public String getReligion() {
return religion;
}
public String getCaste() {
return caste;
}
public String getSubCaste() {
return subCaste;
}
public String getCommunityLocation() {
return communityLocation;
}
public String getStudentId() {
return studentId;
}
public String getGender() {
return gender;
}
public String getStudentClass() {
return studentClass;
}
public String getMother() {
return mother;
}
public String getFather() {
return father;
}
public LocalDate getDateOfBirth() {
return dateOfBirth;
}
public Set<Talent> getTalents() {
return talents;
}
public String getTalentsForDisplay() {
return StringUtils.join(talentDescriptions(), ", ");
}
public List<String> talentDescriptions() {
List<String> talentDescriptions = new ArrayList<String>();
for (Talent talent : talents) {
talentDescriptions.add(talent.getDescription());
}
return talentDescriptions;
}
public int getAge() {
return Years.yearsBetween(dateOfBirth, getCurrentDate()).getYears();
}
public String getImageLink() {
if (imageLink==null){
return PLACEHOLDER_IMAGE;
} else {
return imageLink;
}
}
protected LocalDate getCurrentDate() {
return new LocalDate();
}
public void addNote(Note note) {
notes.add(note);
}
public Set<Note> getNotes() {
return notes;
}
public StudentStatus getStatus() {
return status;
}
private static String[] excludedFields = new String[]{"id"};
public boolean equals(Object other) {
return EqualsBuilder.reflectionEquals(this, other, excludedFields);
}
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this, excludedFields);
}
public String toString() {
return ToStringBuilder.reflectionToString(this, ToStringStyle.SIMPLE_STYLE);
}
public String getDateOfBirthForDisplay() {
return DateTimeFormat.forPattern(DATE_OF_BIRTH_FORMAT).print(dateOfBirth);
}
public void updateFrom(StudentCreateOrUpdateParameters studentUpdateParameters, Set<Talent> newTalents) {
this.studentClass = studentUpdateParameters.getStudentClass();
this.gender = studentUpdateParameters.getGender();
this.name = studentUpdateParameters.getName();
this.religion = studentUpdateParameters.getReligion();
this.caste = studentUpdateParameters.getCaste();
this.subCaste = studentUpdateParameters.getSubCaste();
this.communityLocation = studentUpdateParameters.getCommunityLocation();
this.father = studentUpdateParameters.getFather();
this.mother = studentUpdateParameters.getMother();
this.talents = Sets.newHashSet(newTalents);
this.dateOfBirth = convertDate(studentUpdateParameters.getDateOfBirth());
this.status = StudentStatus.fromString(studentUpdateParameters.getStatus());
}
public void promote() {
if(this.studentClass.equals("Graduated")){
this.studentClass = this.studentClass;
}else if(this.studentClass.equals("UKG")){
this.studentClass = "1 Std";
}else if(this.studentClass.equals("LKG")) {
this.studentClass = "UKG";
}else if(this.studentClass.equals("Preschool")){
this.studentClass = "LKG";
}else if(this.studentClass.equals("10 Std")){
this.studentClass = "Graduated";
}
else{
int studentClassInt = Integer.parseInt(this.studentClass.substring(0,1));
studentClassInt++;
this.studentClass = this.studentClass.replace(this.studentClass.substring(0,1), Integer.toString(studentClassInt));
}
}
private static class EmptyStudent extends Student {
@Override
public String getName() {
return "";
}
@Override
public String getReligion() {
return "";
}
@Override
public String getCaste() {
return "";
}
@Override
public String getSubCaste() {
return "";
}
@Override
public String getCommunityLocation() {
return "";
}
@Override
public String getStudentId() {
return "";
}
@Override
public String getGender() {
return "";
}
@Override
public String getStudentClass() {
return "";
}
@Override
public String getMother() {
return "";
}
@Override
public String getFather() {
return "";
}
@Override
public LocalDate getDateOfBirth() {
return new LocalDate();
}
@Override
public Set<Talent> getTalents() {
return Collections.emptySet();
}
@Override
public String getTalentsForDisplay() {
return "";
}
@Override
public List<String> talentDescriptions() {
return Collections.emptyList();
}
@Override
public int getAge() {
return 0;
}
}
}
diff --git a/src/test/unit/java/org/sukrupa/student/StudentServiceTest.java b/src/test/unit/java/org/sukrupa/student/StudentServiceTest.java
index 0f6197b6..7d77a7ec 100644
--- a/src/test/unit/java/org/sukrupa/student/StudentServiceTest.java
+++ b/src/test/unit/java/org/sukrupa/student/StudentServiceTest.java
@@ -1,199 +1,199 @@
package org.sukrupa.student;
import com.google.common.collect.Sets;
import org.hamcrest.Matchers;
import org.joda.time.LocalDate;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.Mockito;
import java.util.ArrayList;
import java.util.List;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import static org.mockito.Matchers.argThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.mockito.MockitoAnnotations.initMocks;
import static org.sukrupa.platform.date.DateManipulation.freezeDateToMidnightOn_31_12_2010;
import static org.sukrupa.platform.date.DateManipulation.unfreezeTime;
import static org.sukrupa.platform.hamcrest.SchoolAdminMatchers.hasNote;
import static org.sukrupa.student.StudentService.NUMBER_OF_STUDENTS_TO_LIST_PER_PAGE;
public class StudentServiceTest {
private static final String MUSIC = "Music";
private static final String SPORT = "Sport";
private static final String COOKING = "Cooking";
private final Talent music = new Talent(MUSIC);
private final Talent sport = new Talent(SPORT);
private final Talent cooking = new Talent(COOKING);
private final StudentSearchParameter all = new StudentSearchParameterBuilder().build();
@Mock
private StudentRepository studentRepository;
@Mock
private TalentRepository talentRepository;
private StudentService service;
@Mock
private StudentFactory studentFactory;
@Before
public void setUp() throws Exception {
initMocks(this);
service = new StudentService(studentRepository, talentRepository, null, studentFactory);
freezeDateToMidnightOn_31_12_2010();
}
@After
public void tearDown() throws Exception {
unfreezeTime();
}
@Test
public void shouldAddANoteToStudent() {
String studentId = "42";
Note note = new Note("Fish like plankton!");
when(studentRepository.findByStudentId(studentId)).thenReturn(new StudentBuilder().build());
service.addNoteFor(studentId, note.getMessage());
verify(studentRepository).put(argThat(hasNote(note)));
}
@Test
public void shouldRetrievePageOneOfOne() {
when(studentRepository.getCountBasedOn(org.mockito.Matchers.<StudentSearchParameter>anyObject())).thenReturn(NUMBER_OF_STUDENTS_TO_LIST_PER_PAGE);
assertThat(service.getPage(all, 1, "").isNextEnabled(), is(false));
Mockito.verify(studentRepository).findBySearchParameter(all, 0, NUMBER_OF_STUDENTS_TO_LIST_PER_PAGE);
}
@Test
public void shouldRetrievePageOneOfMultiple() {
when(studentRepository.getCountBasedOn(org.mockito.Matchers.<StudentSearchParameter>anyObject())).thenReturn(NUMBER_OF_STUDENTS_TO_LIST_PER_PAGE + 1);
assertThat(service.getPage(all, 1, "").isNextEnabled(), is(true));
Mockito.verify(studentRepository).findBySearchParameter(all, 0, NUMBER_OF_STUDENTS_TO_LIST_PER_PAGE);
}
@Test
public void shouldRetrievePageTwoOfTwo() {
when(studentRepository.getCountBasedOn(org.mockito.Matchers.<StudentSearchParameter>anyObject())).thenReturn(NUMBER_OF_STUDENTS_TO_LIST_PER_PAGE + 1);
assertThat(service.getPage(all, 2, "page=2").isNextEnabled(), is(false));
Mockito.verify(studentRepository).findBySearchParameter(all, NUMBER_OF_STUDENTS_TO_LIST_PER_PAGE, NUMBER_OF_STUDENTS_TO_LIST_PER_PAGE);
}
@Test
public void shouldIncrementClassOfEachStudentByOne() {
// given
List<Student> students = new ArrayList<Student>();
Student sahil = new StudentBuilder().name("sahil").studentClass("1 Std").build();
students.add(sahil);
Student mark = new StudentBuilder().name("mark").studentClass("1 Std").build();
students.add(mark);
when(studentRepository.findAll()).thenReturn(students);
// when
service.promoteStudentsToNextClass();
// then
Student promotedSahil = new StudentBuilder().name("sahil").studentClass("2 Std").build();
Student promotedMark = new StudentBuilder().name("mark").studentClass("2 Std").build();
Mockito.verify(studentRepository).put(promotedSahil);
Mockito.verify(studentRepository).put(promotedMark);
}
@Test
public void shouldUpdateStudent() {
Student philOld = new StudentBuilder().studentId("12345")
.name("Phil").studentClass("1 Std").gender("Male").religion("Hindu").area("Bhuvaneshwari Slum")
- .caste("SC").subCaste("AD").talents(Sets.newHashSet(cooking, sport)).dateOfBirth(new LocalDate(2000, 05, 03)).build();
+ .caste("SC").subCaste("AD").talents(Sets.newHashSet(cooking, sport)).dateOfBirth(new LocalDate(2000, 05, 03)).status(StudentStatus.NOT_SET).build();
Student philNew = new StudentBuilder().studentId("12345")
.name("Philippa").studentClass("2 Std").gender("Female").religion("Catholic").area("Chamundi Nagar")
- .caste("ST").subCaste("AK").talents(Sets.newHashSet(music, sport)).dateOfBirth(new LocalDate(2000, 02, 03)).build();
+ .caste("ST").subCaste("AK").talents(Sets.newHashSet(music, sport)).dateOfBirth(new LocalDate(2000, 02, 03)).status(StudentStatus.ACTIVE).build();
when(studentRepository.findByStudentId(philOld.getStudentId())).thenReturn(philOld);
when(studentRepository.update(philNew)).thenReturn(philNew);
when(talentRepository.findTalents(Sets.newHashSet(MUSIC, SPORT))).thenReturn(Sets.newHashSet(music, sport));
StudentCreateOrUpdateParameters updateParameters = new StudentUpdateParameterBuilder().studentId(philOld.getStudentId())
.area("Chamundi Nagar")
.caste("ST")
.subCaste("AK")
.religion("Catholic")
.name("Philippa")
.gender("Female")
.studentClass("2 Std")
.dateOfBirth("03-02-2000")
- .talents(Sets.<String>newHashSet(MUSIC, SPORT)).build();
+ .talents(Sets.<String>newHashSet(MUSIC, SPORT)).status(StudentStatus.ACTIVE).build();
Student updatedStudent = service.update(updateParameters);
assertThat(updatedStudent, Matchers.is(philNew));
}
@Test
public void shouldUpdateStudentStatus() {
Student philOld = new StudentBuilder().studentId("12345")
.name("Phil").studentClass("1 Std").gender("Male").religion("Hindu").area("Bhuvaneshwari Slum")
.caste("SC").subCaste("AD").talents(Sets.newHashSet(cooking, sport)).dateOfBirth(new LocalDate(2000, 05, 03)).status(StudentStatus.NOT_SET).build();
Student philNew = new StudentBuilder().studentId("12345")
.name("Philippa").studentClass("2 Std").gender("Female").religion("Catholic").area("Chamundi Nagar")
.caste("ST").subCaste("AK").talents(Sets.newHashSet(music, sport)).dateOfBirth(new LocalDate(2000, 02, 03)).status(StudentStatus.ALUMNI).build();
when(studentRepository.findByStudentId(philOld.getStudentId())).thenReturn(philOld);
when(studentRepository.update(philNew)).thenReturn(philNew);
when(talentRepository.findTalents(Sets.newHashSet(MUSIC, SPORT))).thenReturn(Sets.newHashSet(music, sport));
StudentCreateOrUpdateParameters updateParameters = new StudentUpdateParameterBuilder().studentId(philOld.getStudentId())
.area("Chamundi Nagar")
.caste("ST")
.subCaste("AK")
.religion("Catholic")
.name("Philippa")
.gender("Female")
.studentClass("2 Std")
.dateOfBirth("03-02-2000")
.talents(Sets.<String>newHashSet(MUSIC, SPORT))
.status(StudentStatus.ALUMNI).build();
Student updatedStudent = service.update(updateParameters);
assertThat(updatedStudent, Matchers.is(philNew));
}
@Test
public void shouldFailToUpdateNonexistantStudent() {
assertThat(service.update(new StudentUpdateParameterBuilder().build()), Matchers.<Object>nullValue());
}
@Test
public void shouldCreateStudent() {
StudentCreateOrUpdateParameters studentParam =new StudentCreateOrUpdateParameters();
String studentId = "SK20091001";
String studentName = "Yael";
String studentDateOfBirth = "06-03-1982";
studentParam.setStudentId("SK20091001");
studentParam.setName("Yael");
studentParam.setDateOfBirth("06-03-1982");
Student expectedStudent = mock(Student.class);
when(studentFactory.create(studentParam.getStudentId(), studentParam.getName(), studentParam.getDateOfBirth())).thenReturn(expectedStudent);
Student student = service.create(studentParam);
verify(studentRepository).put(expectedStudent);
assertEquals(expectedStudent, student);
}
}
| false | false | null | null |
diff --git a/struts/plugins/org.jboss.tools.struts/src/org/jboss/tools/struts/validation/StrutsPreferenceInitializer.java b/struts/plugins/org.jboss.tools.struts/src/org/jboss/tools/struts/validation/StrutsPreferenceInitializer.java
index c9e5c92fa..bb05f091e 100644
--- a/struts/plugins/org.jboss.tools.struts/src/org/jboss/tools/struts/validation/StrutsPreferenceInitializer.java
+++ b/struts/plugins/org.jboss.tools.struts/src/org/jboss/tools/struts/validation/StrutsPreferenceInitializer.java
@@ -1,37 +1,37 @@
/*******************************************************************************
* Copyright (c) 2011 Red Hat, Inc.
* Distributed under license by Red Hat, Inc. All rights reserved.
* This program is made available under the terms of the
* Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Red Hat, Inc. - initial API and implementation
******************************************************************************/
package org.jboss.tools.struts.validation;
import org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer;
import org.eclipse.core.runtime.preferences.DefaultScope;
import org.eclipse.core.runtime.preferences.IEclipsePreferences;
import org.eclipse.core.runtime.preferences.IScopeContext;
import org.jboss.tools.common.preferences.SeverityPreferences;
-import org.jboss.tools.jst.web.WebModelPlugin;
+import org.jboss.tools.struts.StrutsModelPlugin;
/**
* @author Viacheslav Kabanovich
*/
public class StrutsPreferenceInitializer extends AbstractPreferenceInitializer {
/* (non-Javadoc)
* @see org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer#initializeDefaultPreferences()
*/
@Override
public void initializeDefaultPreferences() {
- IEclipsePreferences defaultPreferences = ((IScopeContext) new DefaultScope()).getNode(WebModelPlugin.PLUGIN_ID);
+ IEclipsePreferences defaultPreferences = ((IScopeContext) new DefaultScope()).getNode(StrutsModelPlugin.PLUGIN_ID);
defaultPreferences.putBoolean(SeverityPreferences.ENABLE_BLOCK_PREFERENCE_NAME, true);
for (String name : StrutsPreferences.SEVERITY_OPTION_NAMES) {
defaultPreferences.put(name, SeverityPreferences.WARNING);
}
defaultPreferences.putInt(SeverityPreferences.MAX_NUMBER_OF_MARKERS_PREFERENCE_NAME, SeverityPreferences.DEFAULT_MAX_NUMBER_OF_MARKERS_PER_FILE);
}
}
diff --git a/struts/plugins/org.jboss.tools.struts/src/org/jboss/tools/struts/validation/StrutsPreferences.java b/struts/plugins/org.jboss.tools.struts/src/org/jboss/tools/struts/validation/StrutsPreferences.java
index 1b9673260..2763355e5 100644
--- a/struts/plugins/org.jboss.tools.struts/src/org/jboss/tools/struts/validation/StrutsPreferences.java
+++ b/struts/plugins/org.jboss.tools.struts/src/org/jboss/tools/struts/validation/StrutsPreferences.java
@@ -1,90 +1,90 @@
/*******************************************************************************
* Copyright (c) 2011 Red Hat, Inc.
* Distributed under license by Red Hat, Inc. All rights reserved.
* This program is made available under the terms of the
* Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Red Hat, Inc. - initial API and implementation
******************************************************************************/
package org.jboss.tools.struts.validation;
import java.util.HashSet;
import java.util.Set;
import org.eclipse.core.resources.IProject;
import org.jboss.tools.common.preferences.SeverityPreferences;
-import org.jboss.tools.jst.web.WebModelPlugin;
+import org.jboss.tools.struts.StrutsModelPlugin;
/**
* @author Viacheslav Kabanovich
*/
public class StrutsPreferences extends SeverityPreferences {
public static final Set<String> SEVERITY_OPTION_NAMES = new HashSet<String>();
private static StrutsPreferences INSTANCE = new StrutsPreferences();
public static final String INVALID_ACTION_FORWARD = INSTANCE.createSeverityOption("invalidActionForward"); //$NON-NLS-1$
public static final String INVALID_ACTION_NAME = INSTANCE.createSeverityOption("invalidActionName"); //$NON-NLS-1$
public static final String INVALID_ACTION_REFERENCE_ATTRIBUTE = INSTANCE.createSeverityOption("invalidActionReferenceAttribute"); //$NON-NLS-1$
public static final String INVALID_ACTION_TYPE = INSTANCE.createSeverityOption("invalidActionType"); //$NON-NLS-1$
public static final String INVALID_GLOBAL_FORWARD = INSTANCE.createSeverityOption("invalidGlobalForward"); //$NON-NLS-1$
public static final String INVALID_GLOBAL_EXCEPTION = INSTANCE.createSeverityOption("invalidGlobalException"); //$NON-NLS-1$
public static final String INVALID_CONTROLLER = INSTANCE.createSeverityOption("invalidController"); //$NON-NLS-1$
public static final String INVALID_MESSAGE_RESOURCES = INSTANCE.createSeverityOption("invalidMessageResources"); //$NON-NLS-1$
public static final String INVALID_INIT_PARAM = INSTANCE.createSeverityOption("invalidInitParam"); //$NON-NLS-1$
/**
* @return the only instance of CDIPreferences
*/
public static StrutsPreferences getInstance() {
return INSTANCE;
}
private StrutsPreferences() {
}
/* (non-Javadoc)
* @see org.jboss.tools.common.preferences.SeverityPreferences#createSeverityOption(java.lang.String)
*/
@Override
protected String createSeverityOption(String shortName) {
String name = getPluginId() + ".validator.problem." + shortName; //$NON-NLS-1$
SEVERITY_OPTION_NAMES.add(name);
return name;
}
/* (non-Javadoc)
* @see org.jboss.tools.common.preferences.SeverityPreferences#getPluginId()
*/
@Override
protected String getPluginId() {
- return WebModelPlugin.PLUGIN_ID;
+ return StrutsModelPlugin.PLUGIN_ID;
}
/* (non-Javadoc)
* @see org.jboss.tools.common.preferences.SeverityPreferences#getSeverityOptionNames()
*/
@Override
protected Set<String> getSeverityOptionNames() {
return SEVERITY_OPTION_NAMES;
}
public static boolean shouldValidateCore(IProject project) {
return true;
}
public static boolean isValidationEnabled(IProject project) {
return INSTANCE.isEnabled(project);
}
public static int getMaxNumberOfProblemMarkersPerFile(IProject project) {
return INSTANCE.getMaxNumberOfProblemMarkersPerResource(project);
}
}
\ No newline at end of file
| false | false | null | null |
diff --git a/cloud/services/src/main/java/org/exoplatform/platform/cloud/services/multitenancy/PlatformTenantResourcesManager.java b/cloud/services/src/main/java/org/exoplatform/platform/cloud/services/multitenancy/PlatformTenantResourcesManager.java
index ee78333272..7ff7cd6706 100644
--- a/cloud/services/src/main/java/org/exoplatform/platform/cloud/services/multitenancy/PlatformTenantResourcesManager.java
+++ b/cloud/services/src/main/java/org/exoplatform/platform/cloud/services/multitenancy/PlatformTenantResourcesManager.java
@@ -1,664 +1,664 @@
/*
* Copyright (C) 2003-2011 eXo Platform SAS.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see<http://www.gnu.org/licenses/>.
*/
package org.exoplatform.platform.cloud.services.multitenancy;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
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.StringWriter;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
import javax.naming.NamingException;
import javax.naming.RefAddr;
import javax.naming.Reference;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.stream.XMLStreamException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.exoplatform.services.jcr.config.QueryHandlerParams;
import org.exoplatform.services.jcr.config.RepositoryConfigurationException;
import org.exoplatform.services.jcr.config.RepositoryEntry;
import org.exoplatform.services.jcr.config.ValueStorageEntry;
import org.exoplatform.services.jcr.config.WorkspaceEntry;
import org.exoplatform.services.jcr.impl.storage.value.fs.FileValueStorage;
import org.exoplatform.services.naming.InitialContextBinder;
import org.exoplatform.services.naming.InitialContextInitializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
/**
* Support for JCR Value Storage in eXo Cloud. It's cop-paste of Cloud Management's TenantResourcesManager. It wasn't
* possible to extend it due to use of private fields.
*
* @author <a href="mailto:[email protected]">Peter Nedonosko</a>
* @version $Id: PlatformTenantResourcesManager.java 00001 2011-09-05 10:06:10Z pnedonosko $
*/
public class PlatformTenantResourcesManager {
private static final String FILE_SEPARATOR = System.getProperty("file.separator");
public static final String ZIP_INDEX_DIRECTORY = "jcr" + FILE_SEPARATOR + "index" + FILE_SEPARATOR;
public static final String ZIP_VALUES_DIRECTORY = "jcr" + FILE_SEPARATOR + "values" + FILE_SEPARATOR;
public static final String ZIP_LOG_DIRECTORY = "log" + FILE_SEPARATOR;
public static final String PATH_TO_LOG_DIRECTORY = System.getProperty("tenant.logs.dir");
public static final String SYSTEM_WORKSPACE_SUFFIX = "_system";
public static final String PATH_TO_TENANT_DATA_DIR = System.getProperty("tenant.data.dir");
/**
* Tag names in bind-references.xml file
*/
private static final String BIND_REFERENCES_FILE_NAME = "bind-references.xml";
private static final String REFERENCE_TAG = "reference";
private static final String BIND_NAME_TAG = "bind-name";
private static final String CLASS_NAME_TAG = "class-name";
private static final String FACTORY_NAME_TAG = "factory-name";
private static final String FACTORY_LOCATION_TAG = "factory-location";
private static final String PROPERTY_TAG = "property";
private static final Logger LOG = LoggerFactory.getLogger(PlatformTenantResourcesManager.class);
private static final Integer DEFAULT_BUFFER_SIZE = 4096;
private final Map<String, String> indexDirectories;
private final Map<String, String> valuesDirectories;
private final String repositoryName;
/**
* serialization resources
*/
private FileOutputStream dest = null;
private ZipOutputStream out = null;
private File zipFile = null;
public PlatformTenantResourcesManager(RepositoryEntry repositoryEntry) throws RepositoryConfigurationException
{
String systemWorkspaceName = repositoryEntry.getSystemWorkspaceName();
repositoryName = repositoryEntry.getName();
// get path to index directories
List<WorkspaceEntry> workspaces = repositoryEntry.getWorkspaceEntries();
indexDirectories = new HashMap<String, String>(workspaces.size() + 1);
for (WorkspaceEntry workspaceEntry : workspaces)
{
indexDirectories.put(workspaceEntry.getName(),
workspaceEntry.getQueryHandler().getParameterValue(QueryHandlerParams.PARAM_INDEX_DIR));
if (systemWorkspaceName.equals(workspaceEntry.getName()))
{
indexDirectories.put(workspaceEntry.getName() + SYSTEM_WORKSPACE_SUFFIX, workspaceEntry.getQueryHandler()
.getParameterValue(QueryHandlerParams.PARAM_INDEX_DIR) + SYSTEM_WORKSPACE_SUFFIX);
}
}
valuesDirectories = new HashMap<String, String>(workspaces.size());
for (WorkspaceEntry workspaceEntry : workspaces)
{
for (ValueStorageEntry vsEntry : workspaceEntry.getContainer().getValueStorages()) {
- valuesDirectories.put(workspaceEntry.getName() + FILE_SEPARATOR + vsEntry.getId(), vsEntry.getParameterValue(FileValueStorage.PATH));
+ valuesDirectories.put(vsEntry.getId() + "@" + workspaceEntry.getName(), vsEntry.getParameterValue(FileValueStorage.PATH));
}
}
}
/**
* This method initializes ZipOutputStream which will contain tenant resources
*
* @throws IOException
*/
public void initSerialization() throws IOException
{
zipFile = File.createTempFile("tenant." + repositoryName, ".zip");
zipFile.deleteOnExit();
dest = new FileOutputStream(zipFile);
out = new ZipOutputStream(new BufferedOutputStream(dest));
}
/**
* Closes Streams which were created during resources compressing
*
* @return File with zipped tenant artifacts
* @throws IOException
*/
public File completeSerialization() throws IOException
{
if (out != null)
{
out.close();
}
if (dest != null)
{
dest.close();
}
return zipFile;
}
/**
* Adds file with DataSource configuration of tenant in zip archive
*
* @param initialContextInitializer
* @throws IOException
* @throws ParserConfigurationException
* @throws TransformerException
*/
public void serializeDataSource(InitialContextInitializer initialContextInitializer) throws IOException,
ParserConfigurationException, TransformerException
{
// add bind-references.xml file with DataSource configuration to zip
zipStream(getBindReferencesConfig(initialContextInitializer), BIND_REFERENCES_FILE_NAME, out);
}
/**
* Adds index of tenant in zip archive.
*
* @throws IOException
*/
public void serializeIndex() throws IOException
{
for (Entry<String, String> entry : indexDirectories.entrySet())
{
zipDir(entry.getValue(), ZIP_INDEX_DIRECTORY + entry.getKey() + FILE_SEPARATOR, out);
}
}
/**
* Add values of tenant in zip archive.
*
* @throws IOException
*/
public void serializeValues() throws IOException
{
for (Entry<String, String> entry : valuesDirectories.entrySet())
{
zipDir(entry.getValue(), ZIP_VALUES_DIRECTORY + entry.getKey() + FILE_SEPARATOR, out);
}
}
/**
* Adds log files of tenant in zip archive.
*
* @throws IOException
*/
public void serializeLogs() throws IOException
{
// save log files
zipDir(PATH_TO_LOG_DIRECTORY + FILE_SEPARATOR + repositoryName, ZIP_LOG_DIRECTORY + repositoryName
+ FILE_SEPARATOR, out);
}
/**
* Restores from specified zip archive index, values, logs and DataSource of tenant.
*
* @param pathToZip
* @param initialContextInitializer
* @throws IOException
* @throws XMLStreamException
* @throws NamingException
* @throws SAXException
* @throws ParserConfigurationException
*/
public void deserialize(InputStream io, InitialContextInitializer initialContextInitializer)
throws ParserConfigurationException, SAXException, IOException, NamingException, XMLStreamException
{
ZipInputStream zipInputStream = null;
try
{
zipInputStream = new ZipInputStream(io);
ZipEntry zipEntry = null;
while ((zipEntry = zipInputStream.getNextEntry()) != null)
{
String entryName = zipEntry.getName();
if (entryName.startsWith(ZIP_INDEX_DIRECTORY))
{
String resourceName = entryName.substring(ZIP_INDEX_DIRECTORY.length());
if (resourceName.length() > 0)
{
String workspaceName = resourceName.substring(0, resourceName.indexOf(FILE_SEPARATOR));
String newResourceName = resourceName.substring(workspaceName.length());
extractZipEntry(zipInputStream, zipEntry, indexDirectories.get(workspaceName) + newResourceName);
}
else
{
LOG.warn("Entry {} will not unzipped", entryName);
}
}
if (entryName.startsWith(ZIP_LOG_DIRECTORY))
{
extractZipEntry(zipInputStream, zipEntry,
PATH_TO_LOG_DIRECTORY + FILE_SEPARATOR + entryName.substring(ZIP_LOG_DIRECTORY.length()));
}
if (entryName.equals(BIND_REFERENCES_FILE_NAME))
{
// resume DataSource
resumeDataSource(initialContextInitializer, copyInputStream(zipInputStream));
}
if (entryName.startsWith(ZIP_VALUES_DIRECTORY))
{
String resourceName = entryName.substring(ZIP_VALUES_DIRECTORY.length());
if (resourceName.length() > 0)
{
String vsName = resourceName.substring(0, resourceName.indexOf(FILE_SEPARATOR));
String newResourceName = resourceName.substring(vsName.length());
extractZipEntry(zipInputStream, zipEntry, valuesDirectories.get(vsName) + newResourceName);
}
else
{
LOG.warn("Entry {} will not unzipped", entryName);
}
}
zipInputStream.closeEntry();
}
}
finally
{
if (zipInputStream != null)
{
zipInputStream.close();
}
}
}
/**
* Clean index and log directories for tenant
*
* @throws RepositoryConfigurationException
*/
public void cleanTenantResources()
{
// remove index directories
for (Entry<String, String> entry : indexDirectories.entrySet())
{
if (!removeDirectory(entry.getValue()))
{
LOG.warn("Index directory {} can't be completely removed on tenant {} suspend", entry.getValue(),
repositoryName);
}
}
// remove values directories
for (Entry<String, String> entry : valuesDirectories.entrySet())
{
if (!removeDirectory(entry.getValue()))
{
LOG.warn("Values directory {} can't be completely removed on tenant {} suspend", entry.getValue(),
repositoryName);
}
}
// remove all data files
// TODO: we know that all jcr resources of tenant saved in ${jcr.data.dit}/jcr/[tenantname] directory
// it may be useful to change way detecting of this folder
if (!removeDirectory(PATH_TO_TENANT_DATA_DIR + FILE_SEPARATOR + "jcr" + FILE_SEPARATOR + repositoryName))
{
LOG.warn("Data directory can't be completely removed on tenant {} suspend", repositoryName);
}
// remove log files
if (!removeDirectory(PATH_TO_LOG_DIRECTORY + FILE_SEPARATOR + repositoryName))
{
LOG.warn("Log directory can't be completely removed on tenant {} suspend", repositoryName);
}
// TODO: remove DataSource
}
private void zipDir(String directoryToZip, String parentDir, ZipOutputStream out) throws IOException
{
File zipDir = new File(directoryToZip);
if (!zipDir.exists())
{
return;
}
out.putNextEntry(new ZipEntry(parentDir));
String[] dirList = zipDir.list();
byte[] readBuffer = new byte[DEFAULT_BUFFER_SIZE];
int bytesIn = 0;
for (String element : dirList)
{
File file = new File(zipDir, element);
if (file.isDirectory())
{
zipDir(file.getPath(), parentDir + file.getName() + FILE_SEPARATOR, out);
}
else
{
FileInputStream io = null;
try
{
io = new FileInputStream(file);
out.putNextEntry(new ZipEntry(parentDir + file.getName()));
// write the content of the file to the ZipOutputStream
while ((bytesIn = io.read(readBuffer)) != -1)
{
out.write(readBuffer, 0, bytesIn);
}
}
catch (FileNotFoundException e)
{
LOG.warn("File not found when tenant resources zipped: {}", e.getMessage());
}
finally
{
if (io != null)
{
io.close();
}
}
}
}
}
private void zipStream(InputStream streamToZip, String fileName, ZipOutputStream out) throws IOException
{
try
{
byte[] readBuffer = new byte[DEFAULT_BUFFER_SIZE];
int bytesIn = 0;
ZipEntry zipEntry = new ZipEntry(fileName);
out.putNextEntry(zipEntry);
// write the content of the file to the ZipOutputStream
while ((bytesIn = streamToZip.read(readBuffer)) != -1)
{
out.write(readBuffer, 0, bytesIn);
}
}
finally
{
if (streamToZip != null)
{
streamToZip.close();
}
}
}
private void extractZipEntry(ZipInputStream zipInputStream, ZipEntry zipEntry, String extractPath)
throws IOException
{
if (zipEntry.isDirectory())
{
File subDir = new File(extractPath);
subDir.mkdirs();
}
else
{
// creare file
FileOutputStream out = null;
try
{
byte data[] = new byte[DEFAULT_BUFFER_SIZE];
int count = 0;
File file = new File(extractPath);
file.getParentFile().mkdirs();
file.createNewFile();
out = new FileOutputStream(file);
while ((count = zipInputStream.read(data, 0, DEFAULT_BUFFER_SIZE)) != -1)
{
out.write(data, 0, count);
}
}
finally
{
if (out != null)
{
out.close();
}
}
}
}
/**
* Remove directory and all its sub-resources with specified path
*
* @param pathToDir
* @return
*/
private boolean removeDirectory(String pathToDir)
{
File directory = new File(pathToDir);
if (!directory.exists())
{
return true;
}
if (!directory.isDirectory())
{
return false;
}
String[] list = directory.list();
if (list != null)
{
for (String element : list)
{
File entry = new File(directory, element);
if (entry.isDirectory())
{
if (!removeDirectory(entry.getPath()))
{
return false;
}
}
else
{
if (!entry.delete())
{
return false;
}
}
}
}
return directory.delete();
}
private InputStream getBindReferencesConfig(InitialContextInitializer initialContextInitializer)
throws ParserConfigurationException, TransformerException
{
InitialContextBinder initialContextBinder = initialContextInitializer.getInitialContextBinder();
if (initialContextBinder == null)
{
return new ByteArrayInputStream(new byte[0]);
}
Reference bindReference = initialContextBinder.getReference(repositoryName);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.newDocument();
Element referenceElem = doc.createElement(REFERENCE_TAG);
referenceElem.setAttribute(BIND_NAME_TAG, repositoryName);
referenceElem.setAttribute(CLASS_NAME_TAG, bindReference.getClassName());
referenceElem.setAttribute(FACTORY_NAME_TAG, bindReference.getFactoryClassName());
referenceElem.setAttribute(FACTORY_LOCATION_TAG, bindReference.getFactoryClassLocation());
doc.appendChild(referenceElem);
Enumeration<RefAddr> referenceProperties = bindReference.getAll();
while (referenceProperties.hasMoreElements())
{
RefAddr property = referenceProperties.nextElement();
Element propertyTag = doc.createElement(PROPERTY_TAG);
propertyTag.setAttribute(property.getType(), (String)property.getContent());
referenceElem.appendChild(propertyTag);
}
TransformerFactory transfac = TransformerFactory.newInstance();
Transformer trans = transfac.newTransformer();
//create string from xml tree
StringWriter sw = new StringWriter();
StreamResult result = new StreamResult(sw);
DOMSource source = new DOMSource(doc);
trans.transform(source, result);
return new ByteArrayInputStream(sw.toString().getBytes());
}
public void resumeDataSource(InitialContextInitializer initialContextInitializer, ByteArrayInputStream io)
throws ParserConfigurationException, SAXException, IOException, NamingException, XMLStreamException
{
LOG.info("resumeDataSource {}", io.available());
if (io.available() == 0)
{
return;
}
try
{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(io);
NodeList referenceNodes = doc.getElementsByTagName(REFERENCE_TAG);
LOG.info("referenceNodes {}", referenceNodes.getLength());
if (referenceNodes.getLength() == 0)
{
return;
}
Element referenceElem = (Element)referenceNodes.item(0);
String bindName = referenceElem.getAttribute(BIND_NAME_TAG);
String className = referenceElem.getAttribute(CLASS_NAME_TAG);
String factoryName = referenceElem.getAttribute(FACTORY_NAME_TAG);
String factoryLocation = referenceElem.getAttribute(FACTORY_LOCATION_TAG);
LOG.info("bindName {} className{} factoryName {} factoryLocation {}", new String[]{bindName, className,
factoryName, factoryLocation});
Map<String, String> refAddr = new HashMap<String, String>();
NodeList properties = referenceElem.getChildNodes();
//old style binding
if (properties.getLength() == 1)
{
Node element = properties.item(0);
if (element.getNodeName().equals("ref-addr"))
{
properties = element.getChildNodes();
}
}
for (int i = 0; i < properties.getLength(); i++)
{
Node element = properties.item(i);
if (element.getNodeName().equals(PROPERTY_TAG))
{
NamedNodeMap attributes = element.getAttributes();
if (attributes.getLength() > 0)
{
refAddr.put(attributes.item(0).getNodeName(), attributes.item(0).getNodeValue());
}
}
}
LOG.info("refAddr {}", refAddr);
InitialContextBinder initialContextBinder = initialContextInitializer.getInitialContextBinder();
initialContextBinder.bind(bindName, className, factoryName, factoryLocation, refAddr);
LOG.info("bind ok", refAddr);
}
finally
{
if (io != null)
{
io.close();
}
}
}
private ByteArrayInputStream copyInputStream(InputStream io) throws IOException
{
byte data[] = new byte[DEFAULT_BUFFER_SIZE];
int count = 0;
ByteArrayOutputStream out = new ByteArrayOutputStream();
try
{
while ((count = io.read(data, 0, DEFAULT_BUFFER_SIZE)) != -1)
{
out.write(data, 0, count);
}
return new ByteArrayInputStream(out.toByteArray());
}
finally
{
out.close();
}
}
}
| true | false | null | null |
diff --git a/test/i2p/bote/email/IdentitiesTest.java b/test/i2p/bote/email/IdentitiesTest.java
index 479399ff..1eb244a4 100644
--- a/test/i2p/bote/email/IdentitiesTest.java
+++ b/test/i2p/bote/email/IdentitiesTest.java
@@ -1,104 +1,106 @@
/**
* Copyright (C) 2009 [email protected]
*
* The GPG fingerprint for [email protected] is:
* 6DD3 EAA2 9990 29BC 4AD2 7486 1E2C 7B61 76DC DC12
*
* This file is part of I2P-Bote.
* I2P-Bote is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* I2P-Bote is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with I2P-Bote. If not, see <http://www.gnu.org/licenses/>.
*/
package i2p.bote.email;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import i2p.bote.TestUtil;
import i2p.bote.TestUtil.TestIdentity;
import i2p.bote.crypto.CryptoImplementation;
import i2p.bote.crypto.NTRUEncrypt1087_GMSS512;
import i2p.bote.fileencryption.PasswordException;
import i2p.bote.fileencryption.PasswordHolder;
import java.io.File;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.Arrays;
import java.util.Iterator;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class IdentitiesTest {
private File testDir;
private File identitiesFile;
private PasswordHolder passwordHolder;
private Identities identities;
@Before
public void setUp() throws Exception {
File tmpDir = new File(System.getProperty("java.io.tmpdir"));
testDir = new File(tmpDir, "IdentitiesTest-" + System.currentTimeMillis());
identitiesFile = new File(testDir, "identities");
assertTrue("Can't create directory: " + testDir.getAbsolutePath(), testDir.mkdir());
- passwordHolder = TestUtil.createPasswordCache(tmpDir);
+ passwordHolder = TestUtil.createPasswordCache(testDir);
identities = new Identities(identitiesFile, passwordHolder);
for (TestIdentity identity: TestUtil.createTestIdentities())
identities.add(identity.identity);
}
@After
public void tearDown() throws Exception {
assertTrue("Can't delete file: " + identitiesFile.getAbsolutePath(), identitiesFile.delete());
+ File derivParamsFile = TestUtil.createConfiguration(testDir).getKeyDerivationParametersFile();
+ assertTrue("Can't delete file: " + derivParamsFile, derivParamsFile.delete());
assertTrue("Can't delete directory: " + testDir.getAbsolutePath(), testDir.delete());
}
/** Checks that the private signing key is updated on disk if the <code>CryptoImplementation</code> requires it */
@Test
public void testUpdateKey() throws GeneralSecurityException, PasswordException, IOException {
byte[] message = "Hopfen und Malz, Gott erhalt's!".getBytes();
Iterator<EmailIdentity> iterator = identities.iterator();
while (iterator.hasNext()) {
EmailIdentity identity = iterator.next();
PublicKey publicKey = identity.getPublicSigningKey();
PrivateKey privateKey = identity.getPrivateSigningKey();
// make a copy of the old signing keys
byte[] encodedPublicKey = publicKey.getEncoded().clone();
byte[] encodedPrivateKey = privateKey.getEncoded().clone();
CryptoImplementation cryptoImpl = identity.getCryptoImpl();
cryptoImpl.sign(message, privateKey, identities);
// read identities from file and compare keys before / after
boolean publicKeyChanged;
boolean privateKeyChanged;
if (!identitiesFile.exists())
publicKeyChanged = privateKeyChanged = false;
else {
Identities newIdentities = new Identities(identitiesFile, passwordHolder);
PublicKey newPublicKey = newIdentities.get(identity).getPublicSigningKey();
PrivateKey newPrivateKey = newIdentities.get(identity).getPrivateSigningKey();
publicKeyChanged = !Arrays.equals(encodedPublicKey, newPublicKey.getEncoded());
privateKeyChanged = !Arrays.equals(encodedPrivateKey, newPrivateKey.getEncoded());
}
assertFalse(publicKeyChanged);
assertTrue(privateKeyChanged == (cryptoImpl instanceof NTRUEncrypt1087_GMSS512));
}
}
}
\ No newline at end of file
| false | false | null | null |
diff --git a/modules/cpr/src/main/java/org/atmosphere/cpr/DefaultBroadcaster.java b/modules/cpr/src/main/java/org/atmosphere/cpr/DefaultBroadcaster.java
index 19edd0995..7040cc30a 100644
--- a/modules/cpr/src/main/java/org/atmosphere/cpr/DefaultBroadcaster.java
+++ b/modules/cpr/src/main/java/org/atmosphere/cpr/DefaultBroadcaster.java
@@ -1,1711 +1,1711 @@
/*
* Copyright 2013 Jeanfrancois Arcand
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
/*
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2007-2008 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common Development
* and Distribution License("CDDL") (collectively, the "License"). You
* may not use this file except in compliance with the License. You can obtain
* a copy of the License at https://glassfish.dev.java.net/public/CDDL+GPL.html
* or glassfish/bootstrap/legal/LICENSE.txt. See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each
* file and include the License file at glassfish/bootstrap/legal/LICENSE.txt.
* Sun designates this particular file as subject to the "Classpath" exception
* as provided by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the License
* Header, with the fields enclosed by brackets [] replaced by your own
* identifying information: "Portions Copyrighted [year]
* [name of copyright owner]"
*
* Contributor(s):
*
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding "[Contributor]
* elects to include this software in this distribution under the [CDDL or GPL
* Version 2] license." If you don't indicate a single choice of license, a
* recipient has the option to distribute your version of this file under
* either the CDDL, the GPL Version 2 or to extend the choice of license to
* its licensees as provided above. However, if you add GPL Version 2 code
* and therefore, elected the GPL Version 2 license, then the option applies
* only if the new code is made subject to such option by the copyright
* holder.
*
*/
package org.atmosphere.cpr;
import org.atmosphere.cache.UUIDBroadcasterCache;
import org.atmosphere.cpr.BroadcastFilter.BroadcastAction;
import org.atmosphere.di.InjectorProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.URI;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import static org.atmosphere.cache.UUIDBroadcasterCache.CacheMessage;
import static org.atmosphere.cpr.ApplicationConfig.MAX_INACTIVE;
import static org.atmosphere.cpr.ApplicationConfig.OUT_OF_ORDER_BROADCAST;
import static org.atmosphere.cpr.BroadcasterCache.Message;
import static org.atmosphere.cpr.BroadcasterCache.STRATEGY;
import static org.atmosphere.cpr.BroadcasterLifeCyclePolicy.ATMOSPHERE_RESOURCE_POLICY.EMPTY;
import static org.atmosphere.cpr.BroadcasterLifeCyclePolicy.ATMOSPHERE_RESOURCE_POLICY.EMPTY_DESTROY;
import static org.atmosphere.cpr.BroadcasterLifeCyclePolicy.ATMOSPHERE_RESOURCE_POLICY.IDLE;
import static org.atmosphere.cpr.BroadcasterLifeCyclePolicy.ATMOSPHERE_RESOURCE_POLICY.IDLE_DESTROY;
import static org.atmosphere.cpr.BroadcasterLifeCyclePolicy.ATMOSPHERE_RESOURCE_POLICY.IDLE_RESUME;
import static org.atmosphere.cpr.BroadcasterLifeCyclePolicy.ATMOSPHERE_RESOURCE_POLICY.NEVER;
/**
* {@link Broadcaster} implementation.
* <p/>
* Broadcast messages to suspended response using the caller's Thread.
* This basic {@link Broadcaster} use an {@link java.util.concurrent.ExecutorService}
* to broadcast message, hence the broadcast operation is asynchronous. Make sure
* you block on {@link #broadcast(Object)}.get()} if you need synchronous operations.
*
* @author Jeanfrancois Arcand
*/
public class DefaultBroadcaster implements Broadcaster {
public static final String CACHED = DefaultBroadcaster.class.getName() + ".messagesCached";
public static final String ASYNC_TOKEN = DefaultBroadcaster.class.getName() + ".token";
private static final Logger logger = LoggerFactory.getLogger(DefaultBroadcaster.class);
private static final String DESTROYED = "This Broadcaster has been destroyed and cannot be used {} by invoking {}";
protected final ConcurrentLinkedQueue<AtmosphereResource> resources =
new ConcurrentLinkedQueue<AtmosphereResource>();
protected BroadcasterConfig bc;
protected final BlockingQueue<Entry> messages = new LinkedBlockingQueue<Entry>();
protected final ConcurrentLinkedQueue<BroadcasterListener> broadcasterListeners = new ConcurrentLinkedQueue<BroadcasterListener>();
protected final AtomicBoolean started = new AtomicBoolean(false);
protected final AtomicBoolean destroyed = new AtomicBoolean(false);
protected SCOPE scope = SCOPE.APPLICATION;
protected String name = DefaultBroadcaster.class.getSimpleName();
protected final ConcurrentLinkedQueue<Entry> delayedBroadcast = new ConcurrentLinkedQueue<Entry>();
protected final ConcurrentLinkedQueue<Entry> broadcastOnResume = new ConcurrentLinkedQueue<Entry>();
protected final ConcurrentLinkedQueue<BroadcasterLifeCyclePolicyListener> lifeCycleListeners = new ConcurrentLinkedQueue<BroadcasterLifeCyclePolicyListener>();
protected final ConcurrentHashMap<String,WriteQueue> writeQueues = new ConcurrentHashMap<String,WriteQueue>();
protected final WriteQueue uniqueWriteQueue = new WriteQueue();
protected Future<?>[] notifierFuture;
protected Future<?>[] asyncWriteFuture;
private POLICY policy = POLICY.FIFO;
private final AtomicLong maxSuspendResource = new AtomicLong(-1);
private final AtomicBoolean requestScoped = new AtomicBoolean(false);
private final AtomicBoolean recentActivity = new AtomicBoolean(false);
private BroadcasterLifeCyclePolicy lifeCyclePolicy = new BroadcasterLifeCyclePolicy.Builder()
.policy(NEVER).build();
private Future<?> currentLifecycleTask;
protected URI uri;
protected AtmosphereConfig config;
protected STRATEGY cacheStrategy = STRATEGY.AFTER_FILTER;
private final Object[] awaitBarrier = new Object[0];
private final AtomicBoolean outOfOrderBroadcastSupported = new AtomicBoolean(false);
protected int writeTimeoutInSecond = -1;
protected final AtmosphereResource noOpsResource;
public DefaultBroadcaster(String name, URI uri, AtmosphereConfig config) {
this.name = name;
this.uri = uri;
this.config = config;
bc = createBroadcasterConfig(config);
String s = config.getInitParameter(ApplicationConfig.BROADCASTER_CACHE_STRATEGY);
if (s != null) {
if (s.equalsIgnoreCase("afterFilter")) {
cacheStrategy = STRATEGY.AFTER_FILTER;
} else if (s.equalsIgnoreCase("beforeFilter")) {
cacheStrategy = STRATEGY.BEFORE_FILTER;
}
}
s = config.getInitParameter(OUT_OF_ORDER_BROADCAST);
if (s != null) {
outOfOrderBroadcastSupported.set(Boolean.valueOf(s));
}
s = config.getInitParameter(ApplicationConfig.WRITE_TIMEOUT);
if (s != null) {
writeTimeoutInSecond = Integer.valueOf(s);
}
noOpsResource = AtmosphereResourceFactory.getDefault().create(config, "-1");
}
public DefaultBroadcaster(String name, AtmosphereConfig config) {
this(name, URI.create("http://localhost"), config);
}
/**
* Create {@link BroadcasterConfig}
*
* @param config the {@link AtmosphereConfig}
* @return an instance of {@link BroadcasterConfig}
*/
protected BroadcasterConfig createBroadcasterConfig(AtmosphereConfig config) {
return new BroadcasterConfig(config.framework().broadcasterFilters, config, getID());
}
/**
* {@inheritDoc}
*/
public synchronized void destroy() {
if (notifyOnPreDestroy()) return;
if (destroyed.getAndSet(true)) return;
notifyDestroyListener();
try {
logger.trace("Broadcaster {} is being destroyed and cannot be re-used. Policy was {}", getID(), policy);
logger.trace("Broadcaster {} is being destroyed and cannot be re-used. Resources are {}", getID(), resources);
if (config.getBroadcasterFactory() != null) {
config.getBroadcasterFactory().remove(this, this.getID());
}
if (currentLifecycleTask != null) {
currentLifecycleTask.cancel(true);
}
started.set(false);
releaseExternalResources();
killReactiveThreads();
if (bc != null) {
bc.destroy();
}
resources.clear();
broadcastOnResume.clear();
messages.clear();
delayedBroadcast.clear();
broadcasterListeners.clear();
writeQueues.clear();
} catch (Throwable t) {
logger.error("Unexpected exception during Broadcaster destroy {}", getID(), t);
}
}
/**
* {@inheritDoc}
*/
public Collection<AtmosphereResource> getAtmosphereResources() {
return Collections.unmodifiableCollection(resources);
}
/**
* {@inheritDoc}
*/
public void setScope(SCOPE scope) {
if (destroyed.get()) {
logger.debug(DESTROYED, getID(), "setScope");
return;
}
this.scope = scope;
if (scope != SCOPE.REQUEST) {
return;
}
logger.debug("Changing broadcaster scope for {}. This broadcaster will be destroyed.", getID());
synchronized (resources) {
try {
// Next, we need to create a new broadcaster per resource.
for (AtmosphereResource resource : resources) {
Broadcaster b = config.getBroadcasterFactory()
.get(getClass(), getClass().getSimpleName() + "/" + UUID.randomUUID());
/**
* REQUEST_SCOPE means one BroadcasterCache per Broadcaster,
*/
if (DefaultBroadcaster.class.isAssignableFrom(this.getClass())) {
BroadcasterCache cache = bc.getBroadcasterCache().getClass().newInstance();
InjectorProvider.getInjector().inject(cache);
b.getBroadcasterConfig().setBroadcasterCache(cache);
}
resource.setBroadcaster(b);
b.setScope(SCOPE.REQUEST);
if (resource.getAtmosphereResourceEvent().isSuspended()) {
b.addAtmosphereResource(resource);
}
logger.debug("Resource {} not using broadcaster {}", resource, b.getID());
}
// Do not destroy because this is a new Broadcaster
if (resources.isEmpty()) {
return;
}
destroy();
} catch (Exception e) {
logger.error("Failed to set request scope for current resources", e);
}
}
}
/**
* {@inheritDoc}
*/
public SCOPE getScope() {
return scope;
}
/**
* {@inheritDoc}
*/
public synchronized void setID(String id) {
if (id == null) {
id = getClass().getSimpleName() + "/" + UUID.randomUUID();
}
if (config.getBroadcasterFactory() == null)
return; // we are shutdown or destroyed, but someone still reference
Broadcaster b = config.getBroadcasterFactory().lookup(this.getClass(), id);
if (b != null && b.getScope() == SCOPE.REQUEST) {
throw new IllegalStateException("Broadcaster ID already assigned to SCOPE.REQUEST. Cannot change the id");
} else if (b != null) {
return;
}
config.getBroadcasterFactory().remove(this, name);
this.name = id;
config.getBroadcasterFactory().add(this, name);
bc.broadcasterID(name);
}
/**
* {@inheritDoc}
*/
public String getID() {
return name;
}
/**
* {@inheritDoc}
*/
public void resumeAll() {
synchronized (resources) {
for (AtmosphereResource r : resources) {
try {
r.resume();
} catch (Throwable t) {
logger.trace("resumeAll", t);
} finally {
removeAtmosphereResource(r);
}
}
}
}
/**
* {@inheritDoc}
*/
@Override
public void releaseExternalResources() {
}
/**
* {@inheritDoc}
*/
@Override
public void setBroadcasterLifeCyclePolicy(final BroadcasterLifeCyclePolicy lifeCyclePolicy) {
this.lifeCyclePolicy = lifeCyclePolicy;
if (currentLifecycleTask != null) {
currentLifecycleTask.cancel(false);
}
if (bc != null && bc.getScheduledExecutorService() == null) {
logger.error("No Broadcaster's SchedulerExecutorService has been configured on {}. BroadcasterLifeCyclePolicy won't work.", getID());
return;
}
if (lifeCyclePolicy.getLifeCyclePolicy() == IDLE
|| lifeCyclePolicy.getLifeCyclePolicy() == IDLE_RESUME
|| lifeCyclePolicy.getLifeCyclePolicy() == IDLE_DESTROY) {
recentActivity.set(false);
int time = lifeCyclePolicy.getTimeout();
if (time == -1) {
throw new IllegalStateException("BroadcasterLifeCyclePolicy time is not set");
}
final AtomicReference<Future<?>> ref = new AtomicReference<Future<?>>();
currentLifecycleTask = bc.getScheduledExecutorService().scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
try {
// Check for activity since the last execution.
if (recentActivity.getAndSet(false)) {
return;
} else if (resources.isEmpty()) {
if (lifeCyclePolicy.getLifeCyclePolicy() == IDLE) {
notifyEmptyListener();
notifyIdleListener();
releaseExternalResources();
logger.debug("Applying BroadcasterLifeCyclePolicy IDLE policy to Broadcaster {}", getID());
} else if (lifeCyclePolicy.getLifeCyclePolicy() == IDLE_DESTROY) {
notifyEmptyListener();
notifyIdleListener();
destroy(false);
logger.debug("Applying BroadcasterLifeCyclePolicy IDLE_DESTROY policy to Broadcaster {}", getID());
}
} else if (lifeCyclePolicy.getLifeCyclePolicy() == IDLE_RESUME) {
notifyIdleListener();
destroy(true);
logger.debug("Applying BroadcasterLifeCyclePolicy IDLE_RESUME policy to Broadcaster {}", getID());
}
} catch (Throwable t) {
if (destroyed.get()) {
logger.trace("Scheduled BroadcasterLifeCyclePolicy exception", t);
} else {
logger.warn("Scheduled BroadcasterLifeCyclePolicy exception", t);
}
}
}
void destroy(boolean resume) {
if (resume) {
logger.info("All AtmosphereResource will now be resumed from Broadcaster {}", getID());
resumeAll();
}
DefaultBroadcaster.this.destroy();
/**
* The value may be null if the timeout is too low. Hopefully next execution will
* cancel the task properly.
*/
if (ref.get() != null) {
currentLifecycleTask.cancel(true);
}
}
}, time, time, lifeCyclePolicy.getTimeUnit());
ref.set(currentLifecycleTask);
}
}
/**
* {@inheritDoc}
*/
@Override
public void addBroadcasterLifeCyclePolicyListener(BroadcasterLifeCyclePolicyListener b) {
lifeCycleListeners.add(b);
}
/**
* {@inheritDoc}
*/
@Override
public void removeBroadcasterLifeCyclePolicyListener(BroadcasterLifeCyclePolicyListener b) {
lifeCycleListeners.remove(b);
}
/**
* {@inheritDoc}
*/
@Override
public boolean isDestroyed() {
return destroyed.get();
}
/**
* {@inheritDoc}
*/
@Override
public Future<Object> awaitAndBroadcast(Object t, long time, TimeUnit timeUnit) {
if (resources.isEmpty()) {
synchronized (awaitBarrier) {
try {
logger.trace("Awaiting for AtmosphereResource for {} {}", time, timeUnit);
awaitBarrier.wait(translateTimeUnit(time, timeUnit));
} catch (Throwable e) {
logger.warn("awaitAndBroadcast", e);
return null;
}
}
}
return broadcast(t);
}
/**
* {@inheritDoc}
*/
@Override
public Broadcaster addBroadcasterListener(BroadcasterListener b) {
broadcasterListeners.add(b);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public Broadcaster removeBroadcasterListener(BroadcasterListener b) {
broadcasterListeners.remove(b);
return this;
}
public static final class Entry {
public Object message;
public Object multipleAtmoResources;
public BroadcasterFuture<?> future;
public boolean writeLocally;
public Object originalMessage;
// https://github.com/Atmosphere/atmosphere/issues/864
public CacheMessage cache;
public Entry(Object message, Object multipleAtmoResources, BroadcasterFuture<?> future, Object originalMessage) {
this.message = message;
this.multipleAtmoResources = multipleAtmoResources;
this.future = future;
this.writeLocally = true;
this.originalMessage = originalMessage;
}
public Entry(Object message, Object multipleAtmoResources, BroadcasterFuture<?> future, boolean writeLocally) {
this.message = message;
this.multipleAtmoResources = multipleAtmoResources;
this.future = future;
this.writeLocally = writeLocally;
this.originalMessage = message;
}
@Override
public String toString() {
return "Entry{" +
"message=" + message +
", multipleAtmoResources=" + multipleAtmoResources +
", future=" + future +
'}';
}
}
protected Runnable getBroadcastHandler() {
return new Runnable() {
public void run() {
Entry msg = null;
try {
msg = messages.poll(5, TimeUnit.SECONDS);
if (destroyed.get()) return;
if (outOfOrderBroadcastSupported.get()) {
bc.getExecutorService().submit(this);
}
} catch (InterruptedException ex) {
logger.trace("{} got interrupted for Broadcaster {}", Thread.currentThread().getName(), getID());
logger.trace("", ex);
if (!bc.getExecutorService().isShutdown()) {
bc.getExecutorService().submit(this);
}
return;
}
try {
if (msg != null) {
logger.trace("{} is about to broadcast {}", getID(), msg);
push(msg);
}
} catch (Throwable ex) {
if (!started.get() || destroyed.get()) {
logger.trace("Failed to submit broadcast handler runnable on shutdown for Broadcaster {}", getID(), ex);
return;
} else {
logger.warn("This message {} will be lost", msg);
logger.debug("Failed to submit broadcast handler runnable to for Broadcaster {}", getID(), ex);
}
} finally {
if (!outOfOrderBroadcastSupported.get()) {
bc.getExecutorService().submit(this);
}
}
}
};
}
protected Runnable getAsyncWriteHandler(final WriteQueue writeQueue) {
return new Runnable() {
public void run() {
AsyncWriteToken token = null;
try {
token = writeQueue.queue.poll(5, TimeUnit.SECONDS);
if (token == null && !outOfOrderBroadcastSupported.get()) {
synchronized (writeQueue) {
if (writeQueue.queue.size() == 0) {
writeQueue.monitored.set(false);
writeQueues.remove(token.resource.uuid());
return;
}
}
}
if (token == null || outOfOrderBroadcastSupported.get()) {
bc.getAsyncWriteService().submit(this);
if (token == null) {
return;
}
}
} catch (InterruptedException ex) {
logger.trace("{} got interrupted for Broadcaster {}", Thread.currentThread().getName(), getID());
logger.trace("", ex);
if (!bc.getAsyncWriteService().isShutdown()) {
bc.getAsyncWriteService().submit(this);
}
return;
}
synchronized (token.resource) {
try {
try {
executeAsyncWrite(token);
} finally {
if (!outOfOrderBroadcastSupported.get()) {
// We want this thread to wait for the write operation to happens to kept the order
bc.getAsyncWriteService().submit(this);
}
}
} catch (Throwable ex) {
if (!started.get() || destroyed.get()) {
logger.trace("Failed to execute a write operation. Broadcaster is destroyed or not yet started for Broadcaster {}", getID(), ex);
return;
} else {
if (token != null) {
logger.warn("This message {} will be lost for AtmosphereResource {}, adding it to the BroadcasterCache",
token.originalMessage, token.resource != null ? token.resource.uuid() : "null");
cacheLostMessage(token.resource, token, true);
}
logger.debug("Failed to execute a write operation for Broadcaster {}", getID(), ex);
}
}
}
}
};
}
protected void start() {
if (!started.getAndSet(true)) {
bc.getBroadcasterCache().start();
setID(name);
// Only start if we know a child haven't started them.
if (notifierFuture == null && asyncWriteFuture == null) {
spawnReactor();
}
}
}
protected void spawnReactor() {
killReactiveThreads();
int threads = outOfOrderBroadcastSupported.get() ? reactiveThreadsCount() : 1;
notifierFuture = new Future<?>[threads];
if (outOfOrderBroadcastSupported.get()){
for (int i = 0; i < threads; i++) {
notifierFuture[i] = bc.getExecutorService().submit(getBroadcastHandler());
}
} else {
notifierFuture[0] = bc.getExecutorService().submit(getBroadcastHandler());
}
}
protected void killReactiveThreads() {
if (notifierFuture != null) {
for (Future<?> f : notifierFuture) {
f.cancel(false);
}
}
if (asyncWriteFuture != null) {
for (Future<?> f : asyncWriteFuture) {
f.cancel(false);
}
}
}
/**
* Return the default number of reactive threads that will be waiting for work when a broadcast operation
* is executed.
* @return the default number of reactive threads
*/
protected int reactiveThreadsCount() {
return Runtime.getRuntime().availableProcessors() * 2;
}
protected void push(Entry entry) {
if (destroyed.get()) {
return;
}
deliverPush(entry, true);
}
protected void deliverPush(Entry entry, boolean rec) {
recentActivity.set(true);
String prevMessage = entry.message.toString();
if (rec && !delayedBroadcast.isEmpty()) {
Iterator<Entry> i = delayedBroadcast.iterator();
StringBuilder b = new StringBuilder();
while (i.hasNext()) {
Entry e = i.next();
e.future.cancel(true);
try {
// Append so we do a single flush
if (e.message instanceof String
&& entry.message instanceof String) {
b.append(e.message);
} else {
deliverPush(e, false);
}
} finally {
i.remove();
}
}
if (b.length() > 0) {
entry.message = b.append(entry.message).toString();
}
}
Object finalMsg = callable(entry.message);
if (finalMsg == null) {
logger.error("Callable exception. Please catch all exception from you callable. Message {} will be lost and all AtmosphereResource " +
"associated with this Broadcaster resumed.", entry.message);
entryDone(entry.future);
synchronized (resources) {
for (AtmosphereResource r : resources) {
if (r.transport().equals(AtmosphereResource.TRANSPORT.JSONP) || r.transport().equals(AtmosphereResource.TRANSPORT.LONG_POLLING))
try {
r.resume();
} catch (Throwable t) {
logger.trace("resumeAll", t);
}
}
}
return;
}
Object prevM = entry.originalMessage;
entry.originalMessage = (entry.originalMessage != entry.message ? callable(entry.originalMessage) : finalMsg);
if (entry.originalMessage == null) {
logger.debug("Broascast message was null {}", prevM);
entryDone(entry.future);
return;
}
entry.message = finalMsg;
if (resources.isEmpty()) {
logger.debug("Broadcaster {} doesn't have any associated resource. " +
"Message will be cached in the configured BroadcasterCache {}", getID(), entry.message);
AtmosphereResource r = null;
if (entry.multipleAtmoResources != null && AtmosphereResource.class.isAssignableFrom(entry.multipleAtmoResources.getClass())) {
r = AtmosphereResource.class.cast(entry.multipleAtmoResources);
}
// Make sure we execute the filter
if (r == null) {
r = noOpsResource;
}
perRequestFilter(r, entry, true, true);
entryDone(entry.future);
return;
}
// https://github.com/Atmosphere/atmosphere/issues/864
// Cache the message before executing any operation.
// TODO: This won't work with AFTER_FILTER, but anyway the message will be processed when retrieved from the cache
BroadcasterCache broadcasterCache = bc.getBroadcasterCache();
if (UUIDBroadcasterCache.class.isAssignableFrom(broadcasterCache.getClass())) {
entry.cache = UUIDBroadcasterCache.class.cast(broadcasterCache).addCacheCandidate(getID(), null, entry.originalMessage);
}
// We cache first, and if the broadcast succeed, we will remove it.
try {
if (entry.multipleAtmoResources == null) {
for (AtmosphereResource r : resources) {
finalMsg = perRequestFilter(r, entry, true);
if (finalMsg == null) {
logger.debug("Skipping broadcast delivery resource {} ", r);
continue;
}
if (entry.writeLocally) {
queueWriteIO(r, finalMsg, entry);
}
}
} else if (entry.multipleAtmoResources instanceof AtmosphereResource) {
finalMsg = perRequestFilter((AtmosphereResource) entry.multipleAtmoResources, entry, true);
if (finalMsg == null) {
logger.debug("Skipping broadcast delivery resource {} ", entry.multipleAtmoResources);
return;
}
if (entry.writeLocally) {
queueWriteIO((AtmosphereResource) entry.multipleAtmoResources, finalMsg, entry);
}
} else if (entry.multipleAtmoResources instanceof Set) {
Set<AtmosphereResource> sub = (Set<AtmosphereResource>) entry.multipleAtmoResources;
if (sub.size() != 0) {
for (AtmosphereResource r : sub) {
finalMsg = perRequestFilter(r, entry, true);
if (finalMsg == null) {
logger.debug("Skipping broadcast delivery resource {} ", r);
continue;
}
if (entry.writeLocally) {
queueWriteIO(r, finalMsg, entry);
}
}
} else {
// See https://github.com/Atmosphere/atmosphere/issues/572
if (cacheStrategy == STRATEGY.AFTER_FILTER) {
entry.message = finalMsg;
trackBroadcastMessage(null, entry);
}
}
}
entry.message = prevMessage;
} catch (InterruptedException ex) {
logger.debug(ex.getMessage(), ex);
}
}
protected void queueWriteIO(AtmosphereResource r, Object finalMsg, Entry entry) throws InterruptedException {
// The onStateChange/onRequest may change the isResumed value, hence we need to make sure only one thread flip
// the switch to garantee the Entry will be cached in the order it was broadcasted.
// Without synchronizing we may end up with a out of order BroadcasterCache queue.
if (!bc.getBroadcasterCache().getClass().equals(BroadcasterConfig.DefaultBroadcasterCache.class.getName())) {
if (r.isResumed() || r.isCancelled()) {
// https://github.com/Atmosphere/atmosphere/issues/864
// FIX ME IN 1.1 -- For legacy, we need to leave the logic here
BroadcasterCache broadcasterCache = bc.getBroadcasterCache();
if (!UUIDBroadcasterCache.class.isAssignableFrom(broadcasterCache.getClass())) {
trackBroadcastMessage(r, entry);
}
return;
}
}
AsyncWriteToken w = new AsyncWriteToken(r, finalMsg, entry.future, entry.originalMessage, entry.cache);
if (!outOfOrderBroadcastSupported.get()) {
WriteQueue writeQueue = writeQueues.get(r.uuid());
if (writeQueue == null) {
writeQueue = new WriteQueue();
writeQueues.put(r.uuid(), writeQueue);
}
writeQueue.queue.put(w);
synchronized (writeQueue) {
if (!writeQueue.monitored.getAndSet(true)) {
bc.getAsyncWriteService().submit(getAsyncWriteHandler(writeQueue));
}
}
} else {
uniqueWriteQueue.queue.offer(w);
}
}
private final static class WriteQueue {
final BlockingQueue<AsyncWriteToken> queue = new LinkedBlockingQueue<AsyncWriteToken>();;
final AtomicBoolean monitored = new AtomicBoolean();
}
protected Object perRequestFilter(AtmosphereResource r, Entry msg, boolean cache) {
return perRequestFilter(r,msg, cache, false);
}
protected Object perRequestFilter(AtmosphereResource r, Entry msg, boolean cache, boolean force) {
// A broadcaster#broadcast(msg,Set) may contains null value.
if (r == null) {
logger.trace("Null AtmosphereResource passed inside a Set");
return msg.message;
}
Object finalMsg = msg.message;
if (AtmosphereResourceImpl.class.isAssignableFrom(r.getClass())) {
if (isAtmosphereResourceValid(r)) {
if (bc.hasPerRequestFilters()) {
BroadcastAction a = bc.filter(r, msg.message, msg.originalMessage);
if (a.action() == BroadcastAction.ACTION.ABORT) {
return null;
}
if (a.message() != msg.originalMessage) {
finalMsg = a.message();
}
}
} else {
// The resource is no longer valid.
removeAtmosphereResource(r);
config.getBroadcasterFactory().removeAllAtmosphereResource(r);
}
}
// https://github.com/Atmosphere/atmosphere/issues/864
// No exception so far, so remove the message from the cache. It will be re-added if something bad happened
BroadcasterCache broadcasterCache = bc.getBroadcasterCache();
cache = !UUIDBroadcasterCache.class.isAssignableFrom(broadcasterCache.getClass()) && cache;
boolean after = cacheStrategy == BroadcasterCache.STRATEGY.AFTER_FILTER;
if (force || (cache && after)) {
msg.message = finalMsg;
trackBroadcastMessage(r != null ? (r.uuid().equals("-1") ? null: r) : r, msg);
}
return finalMsg;
}
private Object callable(Object msg) {
if (Callable.class.isAssignableFrom(msg.getClass())) {
try {
return Callable.class.cast(msg).call();
} catch (Exception e) {
logger.warn("Callable exception", e);
return null;
}
}
return msg;
}
protected void executeAsyncWrite(final AsyncWriteToken token) {
boolean notifyListeners = true;
boolean lostCandidate = false;
final AtmosphereResourceEventImpl event = (AtmosphereResourceEventImpl) token.resource.getAtmosphereResourceEvent();
final AtmosphereResourceImpl r = AtmosphereResourceImpl.class.cast(token.resource);
try {
event.setMessage(token.msg);
// https://github.com/Atmosphere/atmosphere/issues/864
// No exception so far, so remove the message from the cache. It will be re-added if something bad happened
BroadcasterCache broadcasterCache = bc.getBroadcasterCache();
if (UUIDBroadcasterCache.class.isAssignableFrom(broadcasterCache.getClass())) {
UUIDBroadcasterCache.class.cast(broadcasterCache).clearCache(getID(), r, token.cache);
}
// Make sure we cache the message in case the AtmosphereResource has been cancelled, resumed or the client disconnected.
if (!isAtmosphereResourceValid(r)) {
removeAtmosphereResource(r);
lostCandidate = true;
return;
}
try {
r.getRequest().setAttribute(getID(), token.future);
r.getRequest().setAttribute(MAX_INACTIVE, System.currentTimeMillis());
} catch (Throwable t) {
logger.warn("Invalid AtmosphereResource state {}. The connection has been remotely" +
" closed and message {} will be added to the configured BroadcasterCache for later retrieval", r.uuid(), event.getMessage());
logger.trace("If you are using Tomcat 7.0.22 and lower, your most probably hitting http://is.gd/NqicFT");
logger.trace("", t);
// The Request/Response associated with the AtmosphereResource has already been written and commited
removeAtmosphereResource(r, false);
config.getBroadcasterFactory().removeAllAtmosphereResource(r);
event.setCancelled(true);
event.setThrowable(t);
r.setIsInScope(false);
lostCandidate = true;
return;
}
r.getRequest().setAttribute(ASYNC_TOKEN, token);
prepareInvokeOnStateChange(r, event);
} finally {
if (notifyListeners) {
r.notifyListeners();
}
entryDone(token.future);
if (lostCandidate) {
cacheLostMessage(r, token, true);
}
token.destroy();
}
}
protected boolean checkCachedAndPush(final AtmosphereResource r, final AtmosphereResourceEvent e) {
retrieveTrackedBroadcast(r, e);
if (e.getMessage() instanceof List && !((List) e.getMessage()).isEmpty()) {
logger.debug("Sending cached message {} to {}", e.getMessage(), r.uuid());
List<Object> cacheMessages = (List) e.getMessage();
BroadcasterFuture<Object> f = new BroadcasterFuture<Object>(e.getMessage(), 1, this);
if (cacheStrategy.equals(STRATEGY.BEFORE_FILTER)) {
LinkedList<Object> filteredMessage = new LinkedList<Object>();
for (Object o : cacheMessages) {
filteredMessage.addLast(perRequestFilter(r, new Entry(o, r, f, o), false));
}
e.setMessage(filteredMessage);
} else {
e.setMessage(cacheMessages);
}
r.getRequest().setAttribute(CACHED, "true");
// Must make sure execute only one thread
synchronized (r) {
try {
prepareInvokeOnStateChange(r, e);
} catch (Throwable t) {
// An exception occured
logger.error("Unable to write cached message {} for {}", e.getMessage(), r.uuid());
logger.error("", t);
for (Object o : cacheMessages) {
bc.getBroadcasterCache().addToCache(getID(), r, new Message(o));
}
return true;
}
// TODO: CAST is dangerous
for (AtmosphereResourceEventListener l : AtmosphereResourceImpl.class.cast(r).atmosphereResourceEventListener()) {
l.onBroadcast(e);
}
switch (r.transport()) {
case JSONP:
case AJAX:
case LONG_POLLING:
return true;
case SSE:
break;
default:
try {
r.getResponse().flushBuffer();
} catch (IOException ioe) {
logger.trace("", ioe);
AsynchronousProcessor.destroyResource(r);
}
break;
}
}
}
return false;
}
protected boolean retrieveTrackedBroadcast(final AtmosphereResource r, final AtmosphereResourceEvent e) {
logger.trace("Checking cached message for {}", r.uuid());
List<?> missedMsg = bc.getBroadcasterCache().retrieveFromCache(getID(), r);
if (missedMsg != null && !missedMsg.isEmpty()) {
e.setMessage(missedMsg);
return true;
}
return false;
}
protected void trackBroadcastMessage(final AtmosphereResource r, Entry entry) {
if (destroyed.get() || bc.getBroadcasterCache() == null) return;
Object msg = (cacheStrategy == STRATEGY.AFTER_FILTER) ? entry.message : entry.originalMessage;
try {
bc.getBroadcasterCache().addToCache(getID(), r, new Message(String.valueOf(entry.future.hashCode()), msg));
} catch (Throwable t) {
logger.warn("Unable to track messages {}", msg, t);
}
}
protected void invokeOnStateChange(final AtmosphereResource r, final AtmosphereResourceEvent e) {
try {
r.getAtmosphereHandler().onStateChange(e);
} catch (Throwable t) {
onException(t, r);
}
}
protected void prepareInvokeOnStateChange(final AtmosphereResource r, final AtmosphereResourceEvent e) {
if (writeTimeoutInSecond != -1) {
logger.trace("Registering Write timeout {} for {}", writeTimeoutInSecond, r.uuid());
WriteOperation w = new WriteOperation(r, e, Thread.currentThread());
bc.getScheduledExecutorService().schedule(w, writeTimeoutInSecond, TimeUnit.MILLISECONDS);
try {
w.call();
} catch (Exception ex) {
logger.warn("", ex);
}
} else {
invokeOnStateChange(r,e);
}
}
final class WriteOperation implements Callable<Object> {
private final AtmosphereResource r;
private final AtmosphereResourceEvent e;
private AtomicBoolean completed = new AtomicBoolean();
private AtomicBoolean executed = new AtomicBoolean();
private final Thread ioThread;
private WriteOperation(AtmosphereResource r, AtmosphereResourceEvent e, Thread ioThread) {
this.r = r;
this.e = e;
this.ioThread = ioThread;
}
@Override
public Object call() throws Exception {
if (!completed.getAndSet(true)) {
invokeOnStateChange(r,e);
logger.trace("Cancelling Write timeout {} for {}", writeTimeoutInSecond, r.uuid());
executed.set(true);
} else if (!executed.get()){
- logger.trace("Honoring Write timeout {} for {}", writeTimeoutInSecond, r.uuid());
- onException(new IOException("Unable to write after " + writeTimeoutInSecond), r);
- AtmosphereResourceImpl.class.cast(r).cancel();
-
// https://github.com/Atmosphere/atmosphere/issues/902
try {
ioThread.interrupt();
} catch (Throwable t) {
// Swallow, this is already enough embarrassing
logger.trace("I/O failure, unable to interrupt the thread", t);
}
+
+ logger.trace("Honoring Write timeout {} for {}", writeTimeoutInSecond, r.uuid());
+ onException(new IOException("Unable to write after " + writeTimeoutInSecond), r);
+ AtmosphereResourceImpl.class.cast(r).cancel();
}
return null;
}
}
public void onException(Throwable t, final AtmosphereResource ar) {
onException(t, ar, true);
}
public void onException(Throwable t, final AtmosphereResource ar, boolean notifyAndCache) {
final AtmosphereResourceImpl r = AtmosphereResourceImpl.class.cast(ar);
// Remove to prevent other broadcast to re-use it.
removeAtmosphereResource(r);
if (notifyAndCache) {
logger.debug("onException()", t);
final AtmosphereResourceEventImpl event = r.getAtmosphereResourceEvent();
event.setThrowable(t);
r.notifyListeners(event);
r.removeEventListeners();
}
if (notifyAndCache) {
cacheLostMessage(r, (AsyncWriteToken) r.getRequest(false).getAttribute(ASYNC_TOKEN), notifyAndCache);
}
/**
* Make sure we resume the connection on every IOException.
*/
if (bc != null && bc.getAsyncWriteService() != null) {
bc.getAsyncWriteService().execute(new Runnable() {
@Override
public void run() {
try {
r.resume();
} catch (Throwable t) {
logger.trace("Was unable to resume a corrupted AtmosphereResource {}", r);
logger.trace("Cause", t);
}
}
});
} else {
r.resume();
}
}
/**
* Cache the message because an unexpected exception occurred.
*
* @param r {@link AtmosphereResource}
*/
public void cacheLostMessage(AtmosphereResource r) {
// Quite ugly cast that need to be fixed all over the place
cacheLostMessage(r, (AsyncWriteToken)
AtmosphereResourceImpl.class.cast(r).getRequest(false).getAttribute(ASYNC_TOKEN));
}
/**
* Cache the message because an unexpected exception occurred.
*
* @param r {@link AtmosphereResource}
*/
public void cacheLostMessage(AtmosphereResource r, boolean force) {
// Quite ugly cast that need to be fixed all over the place
cacheLostMessage(r, (AsyncWriteToken)
AtmosphereResourceImpl.class.cast(r).getRequest(false).getAttribute(ASYNC_TOKEN), force);
}
/**
* Cache the message because an unexpected exception occurred.
*
* @param r {@link AtmosphereResource}
*/
public void cacheLostMessage(AtmosphereResource r, AsyncWriteToken token) {
cacheLostMessage(r, token, false);
}
/**
* Cache the message because an unexpected exception occurred.
*
* @param r {@link AtmosphereResource}
*/
public void cacheLostMessage(AtmosphereResource r, AsyncWriteToken token, boolean force) {
// https://github.com/Atmosphere/atmosphere/issues/864
// FIX ME IN 1.1 -- For legacy, we need to leave the logic here
BroadcasterCache broadcasterCache = bc.getBroadcasterCache();
if (!force && UUIDBroadcasterCache.class.isAssignableFrom(broadcasterCache.getClass())) {
return;
}
try {
if (token != null && token.originalMessage != null) {
Object m = cacheStrategy.equals(STRATEGY.BEFORE_FILTER) ? token.originalMessage : token.msg;
bc.getBroadcasterCache().addToCache(getID(), r, new Message(String.valueOf(token.future.hashCode()), m));
logger.trace("Lost message cached {}", m);
}
} catch (Throwable t2) {
logger.error("Unable to cache message {} for AtmosphereResource {}", token.originalMessage, r != null ? r.uuid() : "");
logger.error("Unable to cache message", t2);
}
}
@Override
public void setSuspendPolicy(long maxSuspendResource, POLICY policy) {
this.maxSuspendResource.set(maxSuspendResource);
this.policy = policy;
}
/**
* {@inheritDoc}
*/
@Override
public Future<Object> broadcast(Object msg) {
if (destroyed.get()) {
logger.debug(DESTROYED, getID(), "broadcast(T msg)");
return futureDone(msg);
}
start();
Object newMsg = filter(msg);
if (newMsg == null) return futureDone(msg);
int callee = resources.size() == 0 ? 1 : resources.size();
BroadcasterFuture<Object> f = new BroadcasterFuture<Object>(newMsg, callee, this);
messages.offer(new Entry(newMsg, null, f, msg));
return f;
}
protected BroadcasterFuture<Object> futureDone(Object msg) {
notifyBroadcastListener();
return (new BroadcasterFuture<Object>(msg, this)).done();
}
/**
* Invoke the {@link BroadcastFilter}
*
* @param msg
* @return
*/
protected Object filter(Object msg) {
BroadcastAction a = bc.filter(msg);
if (a.action() == BroadcastAction.ACTION.ABORT || msg == null)
return null;
else
return a.message();
}
/**
* {@inheritDoc}
*/
@Override
public Future<Object> broadcast(Object msg, AtmosphereResource r) {
if (destroyed.get()) {
logger.debug(DESTROYED, getID(), "broadcast(T msg, AtmosphereResource r");
return futureDone(msg);
}
start();
Object newMsg = filter(msg);
if (newMsg == null) return futureDone(msg);
BroadcasterFuture<Object> f = new BroadcasterFuture<Object>(newMsg, 1, this);
messages.offer(new Entry(newMsg, r, f, msg));
return f;
}
/**
* {@inheritDoc}
*/
@Override
public Future<Object> broadcastOnResume(Object msg) {
if (destroyed.get()) {
logger.debug(DESTROYED, getID(), "broadcastOnResume(T msg)");
return futureDone(msg);
}
start();
Object newMsg = filter(msg);
if (newMsg == null) return futureDone(msg);
BroadcasterFuture<Object> f = new BroadcasterFuture<Object>(newMsg, resources.size(), this);
broadcastOnResume.offer(new Entry(newMsg, null, f, msg));
return f;
}
protected void broadcastOnResume(AtmosphereResource r) {
Iterator<Entry> i = broadcastOnResume.iterator();
while (i.hasNext()) {
Entry e = i.next();
e.multipleAtmoResources = r;
push(e);
}
if (resources.isEmpty()) {
broadcastOnResume.clear();
}
}
/**
* {@inheritDoc}
*/
@Override
public Future<Object> broadcast(Object msg, Set<AtmosphereResource> subset) {
if (destroyed.get()) {
logger.debug(DESTROYED, getID(), "broadcast(T msg, Set<AtmosphereResource> subset)");
return futureDone(msg);
}
start();
Object newMsg = filter(msg);
if (newMsg == null) return futureDone(msg);
BroadcasterFuture<Object> f = new BroadcasterFuture<Object>(null, newMsg, subset.size(), this);
messages.offer(new Entry(newMsg, subset, f, msg));
return f;
}
/**
* {@inheritDoc}
*/
@Override
public Broadcaster addAtmosphereResource(AtmosphereResource r) {
try {
if (destroyed.get()) {
logger.debug(DESTROYED, getID(), "addAtmosphereResource(AtmosphereResource r");
return this;
}
start();
if (scope == SCOPE.REQUEST && requestScoped.getAndSet(true)) {
throw new IllegalStateException("Broadcaster " + this
+ " cannot be used as its scope is set to REQUEST");
}
// To avoid excessive synchronization, we allow resources.size() to get larger that maxSuspendResource
if (maxSuspendResource.get() > 0 && resources.size() >= maxSuspendResource.get()) {
// Resume the first in.
if (policy == POLICY.FIFO) {
// TODO handle null return from poll()
AtmosphereResource resource = resources.poll();
try {
logger.warn("Too many resource. Forcing resume of {} ", resource.uuid());
resource.resume();
} catch (Throwable t) {
logger.warn("failed to resume resource {} ", resource, t);
}
} else if (policy == POLICY.REJECT) {
throw new RejectedExecutionException(String.format("Maximum suspended AtmosphereResources %s", maxSuspendResource));
}
}
if (resources.contains(r)) {
logger.debug("Duplicate resource {}", r.uuid());
return this;
}
// Re-add yourself
if (resources.isEmpty()) {
config.getBroadcasterFactory().add(this, name);
}
boolean wasResumed = checkCachedAndPush(r, r.getAtmosphereResourceEvent());
if (!wasResumed && isAtmosphereResourceValid(r)) {
logger.trace("Associating AtmosphereResource {} with Broadcaster {}", r.uuid(), getID());
resources.add(r);
} else if (!wasResumed) {
logger.debug("Unable to add AtmosphereResource {}", r.uuid());
}
} finally {
// OK reset
if (resources.size() > 0) {
synchronized (awaitBarrier) {
awaitBarrier.notifyAll();
}
}
}
return this;
}
private boolean isAtmosphereResourceValid(AtmosphereResource r) {
return !AtmosphereResourceImpl.class.cast(r).isResumed()
&& !AtmosphereResourceImpl.class.cast(r).isCancelled()
&& AtmosphereResourceImpl.class.cast(r).isInScope();
}
protected void entryDone(final BroadcasterFuture<?> f) {
if (f != null) {
if (bc.getExecutorService() != null) {
bc.getExecutorService().submit(new Runnable() {
@Override
public void run() {
notifyBroadcastListener();
f.done();
}
});
} else {
notifyBroadcastListener();
f.done();
}
}
}
void notifyBroadcastListener() {
for (BroadcasterListener b : broadcasterListeners) {
try {
b.onComplete(this);
} catch (Exception ex) {
logger.warn("", ex);
}
}
}
/**
* {@inheritDoc}
*/
@Override
public Broadcaster removeAtmosphereResource(AtmosphereResource r) {
return removeAtmosphereResource(r, true);
}
protected Broadcaster removeAtmosphereResource(AtmosphereResource r, boolean executeDone) {
if (destroyed.get()) {
logger.debug(DESTROYED, getID(), "removeAtmosphereResource(AtmosphereResource r)");
return this;
}
writeQueues.remove(r.uuid());
// Here we need to make sure we aren't in the process of broadcasting and unlock the Future.
if (executeDone) {
AtmosphereResourceImpl aImpl = AtmosphereResourceImpl.class.cast(r);
BroadcasterFuture f = (BroadcasterFuture) aImpl.getRequest(false).getAttribute(getID());
if (f != null && !f.isDone() && !f.isCancelled()) {
aImpl.getRequest(false).removeAttribute(getID());
entryDone(f);
}
}
resources.remove(r);
if (resources.isEmpty()) {
notifyEmptyListener();
if (scope != SCOPE.REQUEST && lifeCyclePolicy.getLifeCyclePolicy() == EMPTY) {
releaseExternalResources();
} else if (scope == SCOPE.REQUEST || lifeCyclePolicy.getLifeCyclePolicy() == EMPTY_DESTROY) {
config.getBroadcasterFactory().remove(this, name);
destroy();
}
}
return this;
}
private void notifyIdleListener() {
for (BroadcasterLifeCyclePolicyListener b : lifeCycleListeners) {
b.onIdle();
}
}
private void notifyDestroyListener() {
for (BroadcasterLifeCyclePolicyListener b : lifeCycleListeners) {
b.onDestroy();
}
}
private void notifyEmptyListener() {
for (BroadcasterLifeCyclePolicyListener b : lifeCycleListeners) {
b.onEmpty();
}
}
/**
* Set the {@link BroadcasterConfig} instance.
*
* @param bc
*/
@Override
public void setBroadcasterConfig(BroadcasterConfig bc) {
this.bc = bc;
}
/**
* Return the current {@link BroadcasterConfig}
*
* @return the current {@link BroadcasterConfig}
*/
public BroadcasterConfig getBroadcasterConfig() {
return bc;
}
/**
* {@inheritDoc}
*/
public Future<Object> delayBroadcast(Object o) {
return delayBroadcast(o, 0, null);
}
/**
* {@inheritDoc}
*/
public Future<Object> delayBroadcast(final Object o, long delay, TimeUnit t) {
if (destroyed.get()) {
logger.debug(DESTROYED, getID(), "delayBroadcast(final T o, long delay, TimeUnit t)");
return null;
}
start();
final Object msg = filter(o);
if (msg == null) return null;
final BroadcasterFuture<Object> future = new BroadcasterFuture<Object>(msg, this);
final Entry e = new Entry(msg, null, future, o);
Future<Object> f;
if (delay > 0) {
f = bc.getScheduledExecutorService().schedule(new Callable<Object>() {
public Object call() throws Exception {
delayedBroadcast.remove(e);
if (Callable.class.isAssignableFrom(o.getClass())) {
try {
Object r = Callable.class.cast(o).call();
final Object msg = filter(r);
if (msg != null) {
Entry entry = new Entry(msg, null, future, r);
push(entry);
}
return msg;
} catch (Exception e1) {
logger.error("", e);
}
}
final Object msg = filter(o);
final Entry e = new Entry(msg, null, future, o);
push(e);
return msg;
}
}, delay, t);
e.future = new BroadcasterFuture<Object>(f, msg, this);
}
delayedBroadcast.offer(e);
return future;
}
/**
* {@inheritDoc}
*/
public Future<Object> scheduleFixedBroadcast(final Object o, long period, TimeUnit t) {
return scheduleFixedBroadcast(o, 0, period, t);
}
/**
* {@inheritDoc}
*/
public Future<Object> scheduleFixedBroadcast(final Object o, long waitFor, long period, TimeUnit t) {
if (destroyed.get()) {
logger.debug(DESTROYED, getID(), "scheduleFixedBroadcast(final Object o, long waitFor, long period, TimeUnit t)");
return null;
}
start();
if (period == 0 || t == null) {
return null;
}
final Object msg = filter(o);
if (msg == null) return null;
final BroadcasterFuture<Object> f = new BroadcasterFuture<Object>(msg, DefaultBroadcaster.this);
return (Future<Object>) bc.getScheduledExecutorService().scheduleWithFixedDelay(new Runnable() {
public void run() {
if (Callable.class.isAssignableFrom(o.getClass())) {
try {
Object r = Callable.class.cast(o).call();
final Object msg = filter(r);
if (msg != null) {
Entry entry = new Entry(msg, null, f, r);
push(entry);
}
return;
} catch (Exception e) {
logger.error("", e);
}
}
final Object msg = filter(o);
final Entry e = new Entry(msg, null, f, o);
push(e);
}
}, waitFor, period, t);
}
public String toString() {
return new StringBuilder().append("\nName: ").append(name).append("\n")
.append("\n\tScope: ").append(scope).append("\n")
.append("\n\tBroasdcasterCache ").append(bc.getBroadcasterCache()).append("\n")
.append("\n\tAtmosphereResource: ").append(resources.size()).append("\n")
.append(this.getClass().getName()).append("@").append(this.hashCode())
.toString();
}
protected final static class AsyncWriteToken {
AtmosphereResource resource;
Object msg;
BroadcasterFuture future;
Object originalMessage;
CacheMessage cache;
public AsyncWriteToken(AtmosphereResource resource, Object msg, BroadcasterFuture future, Object originalMessage) {
this.resource = resource;
this.msg = msg;
this.future = future;
this.originalMessage = originalMessage;
}
public AsyncWriteToken(AtmosphereResource resource, Object msg, BroadcasterFuture future, Object originalMessage, CacheMessage cache) {
this.resource = resource;
this.msg = msg;
this.future = future;
this.originalMessage = originalMessage;
this.cache = cache;
}
public void destroy() {
this.resource = null;
this.msg = null;
this.future = null;
this.originalMessage = null;
}
@Override
public String toString() {
return "AsyncWriteToken{" +
"resource=" + resource +
", msg=" + msg +
", future=" + future +
'}';
}
}
private long translateTimeUnit(long period, TimeUnit tu) {
if (period == -1) return period;
switch (tu) {
case SECONDS:
return TimeUnit.MILLISECONDS.convert(period, TimeUnit.SECONDS);
case MINUTES:
return TimeUnit.MILLISECONDS.convert(period, TimeUnit.MINUTES);
case HOURS:
return TimeUnit.MILLISECONDS.convert(period, TimeUnit.HOURS);
case DAYS:
return TimeUnit.MILLISECONDS.convert(period, TimeUnit.DAYS);
case MILLISECONDS:
return period;
case MICROSECONDS:
return TimeUnit.MILLISECONDS.convert(period, TimeUnit.MICROSECONDS);
case NANOSECONDS:
return TimeUnit.MILLISECONDS.convert(period, TimeUnit.NANOSECONDS);
}
return period;
}
boolean notifyOnPreDestroy() {
for (BroadcasterListener l : broadcasterListeners) {
try {
l.onPreDestroy(this);
} catch (RuntimeException ex) {
if (BroadcasterListener.BroadcastListenerException.class.isAssignableFrom(ex.getClass())) {
logger.trace("onPreDestroy", ex);
return true;
}
logger.warn("onPreDestroy", ex);
}
}
return false;
}
}
| false | false | null | null |
diff --git a/src/castro/base/CCommandMgr.java b/src/castro/base/CCommandMgr.java
index e9930c2..82f4709 100644
--- a/src/castro/base/CCommandMgr.java
+++ b/src/castro/base/CCommandMgr.java
@@ -1,47 +1,47 @@
/* cPlugin
* Copyright (C) 2013 Norbert Kawinski ([email protected])
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package castro.base;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import castro.base.plugin.CPlugin;
public abstract class CCommandMgr
{
private final CPlugin plugin;
protected abstract BaseCCommand getCommand(CommandSender sender, Command command, String[] args);
public CCommandMgr(CPlugin plugin)
{
this.plugin = plugin;
}
public boolean onCommand(CommandSender sender, Command command, String[] args)
{
BaseCCommand ccommand = getCommand(sender, command, args);
if(ccommand != null)
{
ccommand.baseInit(plugin, sender, command, args);
- return ccommand.execute();
+ return ccommand.run();
}
return false;
}
}
\ No newline at end of file
| true | false | null | null |
diff --git a/src/org/odk/collect/android/logic/FormController.java b/src/org/odk/collect/android/logic/FormController.java
index 2a31a7a..c483ced 100644
--- a/src/org/odk/collect/android/logic/FormController.java
+++ b/src/org/odk/collect/android/logic/FormController.java
@@ -1,1093 +1,1121 @@
/*
* Copyright (C) 2009 JavaRosa
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.odk.collect.android.logic;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Vector;
import org.javarosa.core.model.FormDef;
import org.javarosa.core.model.FormIndex;
import org.javarosa.core.model.GroupDef;
import org.javarosa.core.model.IDataReference;
import org.javarosa.core.model.IFormElement;
import org.javarosa.core.model.SubmissionProfile;
import org.javarosa.core.model.data.IAnswerData;
import org.javarosa.core.model.data.StringData;
import org.javarosa.core.model.instance.FormInstance;
import org.javarosa.core.model.instance.TreeElement;
import org.javarosa.core.services.transport.payload.ByteArrayPayload;
import org.javarosa.form.api.FormEntryCaption;
import org.javarosa.form.api.FormEntryController;
import org.javarosa.form.api.FormEntryPrompt;
import org.javarosa.model.xform.XFormSerializingVisitor;
import org.javarosa.model.xform.XPathReference;
import org.odk.collect.android.views.ODKView;
import android.util.Log;
/**
* This class is a wrapper for Javarosa's FormEntryController. In theory, if you wanted to replace
* javarosa as the form engine, you should only need to replace the methods in this file. Also, we
* haven't wrapped every method provided by FormEntryController, only the ones we've needed so far.
* Feel free to add more as necessary.
*
* @author carlhartung
*/
public class FormController {
private static final String t = "FormController";
private File mMediaFolder;
private File mInstancePath;
private FormEntryController mFormEntryController;
private FormIndex mIndexWaitingForData = null;
public static final boolean STEP_INTO_GROUP = true;
public static final boolean STEP_OVER_GROUP = false;
/**
* OpenRosa metadata tag names.
*/
private static final String INSTANCE_ID = "instanceID";
/**
* OpenRosa metadata of a form instance.
*
* Contains the values for the required metadata
* fields and nothing else.
*
* @author [email protected]
*
*/
public static final class InstanceMetadata {
public final String instanceId;
InstanceMetadata( String instanceId ) {
this.instanceId = instanceId;
}
};
public FormController(File mediaFolder, FormEntryController fec, File instancePath) {
mMediaFolder = mediaFolder;
mFormEntryController = fec;
mInstancePath = instancePath;
}
public File getMediaFolder() {
return mMediaFolder;
}
public File getInstancePath() {
return mInstancePath;
}
public void setInstancePath(File instancePath) {
mInstancePath = instancePath;
}
public void setIndexWaitingForData(FormIndex index) {
mIndexWaitingForData = index;
}
public FormIndex getIndexWaitingForData() {
return mIndexWaitingForData;
}
/**
* For logging purposes...
*
* @param index
* @return xpath value for this index
*/
public String getXPath(FormIndex index) {
String value;
switch ( getEvent() ) {
case FormEntryController.EVENT_BEGINNING_OF_FORM:
value = "beginningOfForm";
break;
case FormEntryController.EVENT_END_OF_FORM:
value = "endOfForm";
break;
case FormEntryController.EVENT_GROUP:
value = "group." + index.getReference().toString();
break;
case FormEntryController.EVENT_QUESTION:
value = "question." + index.getReference().toString();
break;
case FormEntryController.EVENT_PROMPT_NEW_REPEAT:
value = "promptNewRepeat." + index.getReference().toString();
break;
case FormEntryController.EVENT_REPEAT:
value = "repeat." + index.getReference().toString();
break;
case FormEntryController.EVENT_REPEAT_JUNCTURE:
value = "repeatJuncture." + index.getReference().toString();
break;
default:
value = "unexpected";
break;
}
return value;
}
public FormIndex getIndexFromXPath(String xPath) {
if ( xPath.equals("beginningOfForm") ) {
return FormIndex.createBeginningOfFormIndex();
} else if ( xPath.equals("endOfForm") ) {
return FormIndex.createEndOfFormIndex();
} else if ( xPath.equals("unexpected") ) {
Log.e(t, "Unexpected string from XPath");
throw new IllegalArgumentException("unexpected string from XPath");
} else {
FormIndex returned = null;
FormIndex saved = getFormIndex();
// the only way I know how to do this is to step through the entire form
// until the XPath of a form entry matches that of the supplied XPath
try {
jumpToIndex(FormIndex.createBeginningOfFormIndex());
int event = stepToNextEvent(true);
while ( event != FormEntryController.EVENT_END_OF_FORM ) {
String candidateXPath = getXPath(getFormIndex());
// Log.i(t, "xpath: " + candidateXPath);
if ( candidateXPath.equals(xPath) ) {
returned = getFormIndex();
break;
}
event = stepToNextEvent(true);
}
} finally {
jumpToIndex(saved);
}
return returned;
}
}
/**
* returns the event for the current FormIndex.
*
* @return
*/
public int getEvent() {
return mFormEntryController.getModel().getEvent();
}
/**
* returns the event for the given FormIndex.
*
* @param index
* @return
*/
public int getEvent(FormIndex index) {
return mFormEntryController.getModel().getEvent(index);
}
/**
* @return current FormIndex.
*/
public FormIndex getFormIndex() {
return mFormEntryController.getModel().getFormIndex();
}
/**
* Return the langauges supported by the currently loaded form.
*
* @return Array of Strings containing the languages embedded in the XForm.
*/
public String[] getLanguages() {
return mFormEntryController.getModel().getLanguages();
}
/**
* @return A String containing the title of the current form.
*/
public String getFormTitle() {
return mFormEntryController.getModel().getFormTitle();
}
/**
* @return the currently selected language.
*/
public String getLanguage() {
return mFormEntryController.getModel().getLanguage();
}
public String getBindAttribute( String attributeNamespace, String attributeName) {
return getBindAttribute( getFormIndex(), attributeNamespace, attributeName );
}
public String getBindAttribute(FormIndex idx, String attributeNamespace, String attributeName) {
return mFormEntryController.getModel().getForm().getMainInstance().resolveReference(
idx.getReference()).getBindAttributeValue(attributeNamespace, attributeName);
}
/**
* @return an array of FormEntryCaptions for the current FormIndex. This is how we get group
* information Group 1 > Group 2> etc... The element at [size-1] is the current question
* text, with group names decreasing in hierarchy until array element at [0] is the root
*/
private FormEntryCaption[] getCaptionHierarchy() {
return mFormEntryController.getModel().getCaptionHierarchy();
}
/**
* @param index
* @return an array of FormEntryCaptions for the supplied FormIndex. This is how we get group
* information Group 1 > Group 2> etc... The element at [size-1] is the current question
* text, with group names decreasing in hierarchy until array element at [0] is the root
*/
private FormEntryCaption[] getCaptionHierarchy(FormIndex index) {
return mFormEntryController.getModel().getCaptionHierarchy(index);
}
/**
* Returns a caption prompt for the given index. This is used to create a multi-question per
* screen view.
*
* @param index
* @return
*/
public FormEntryCaption getCaptionPrompt(FormIndex index) {
return mFormEntryController.getModel().getCaptionPrompt(index);
}
/**
* Return the caption for the current FormIndex. This is usually used for a repeat prompt.
*
* @return
*/
public FormEntryCaption getCaptionPrompt() {
return mFormEntryController.getModel().getCaptionPrompt();
}
/**
* This fires off the jr:preload actions and events to save values like the
* end time of a form.
*
* @return
*/
public boolean postProcessInstance() {
return mFormEntryController.getModel().getForm().postProcessInstance();
}
/**
* TODO: We need a good description of what this does, exactly, and why.
*
* @return
*/
private FormInstance getInstance() {
return mFormEntryController.getModel().getForm().getInstance();
}
/**
* A convenience method for determining if the current FormIndex is in a group that is/should be
* displayed as a multi-question view. This is useful for returning from the formhierarchy view
* to a selected index.
*
* @param index
* @return
*/
private boolean groupIsFieldList(FormIndex index) {
// if this isn't a group, return right away
IFormElement element = mFormEntryController.getModel().getForm().getChild(index);
if (!(element instanceof GroupDef)) {
return false;
}
GroupDef gd = (GroupDef) element; // exceptions?
return (ODKView.FIELD_LIST.equalsIgnoreCase(gd.getAppearanceAttr()));
}
private boolean repeatIsFieldList(FormIndex index) {
// if this isn't a group, return right away
IFormElement element = mFormEntryController.getModel().getForm().getChild(index);
if (!(element instanceof GroupDef)) {
return false;
}
GroupDef gd = (GroupDef) element; // exceptions?
return (ODKView.FIELD_LIST.equalsIgnoreCase(gd.getAppearanceAttr()));
}
/**
* Tests if the FormIndex 'index' is located inside a group that is marked as a "field-list"
*
* @param index
* @return true if index is in a "field-list". False otherwise.
*/
private boolean indexIsInFieldList(FormIndex index) {
int event = getEvent(index);
if (event == FormEntryController.EVENT_QUESTION) {
// caption[0..len-1]
// caption[len-1] == the question itself
// caption[len-2] == the first group it is contained in.
FormEntryCaption[] captions = getCaptionHierarchy(index);
if (captions.length < 2) {
// no group
return false;
}
FormEntryCaption grp = captions[captions.length - 2];
return groupIsFieldList(grp.getIndex());
} else if (event == FormEntryController.EVENT_GROUP) {
return groupIsFieldList(index);
} else if (event == FormEntryController.EVENT_REPEAT) {
return repeatIsFieldList(index);
} else {
// right now we only test Questions and Groups. Should we also handle
// repeats?
return false;
}
}
public boolean currentPromptIsQuestion() {
return (getEvent() == FormEntryController.EVENT_QUESTION
|| ((getEvent() == FormEntryController.EVENT_GROUP ||
getEvent() == FormEntryController.EVENT_REPEAT)
&& indexIsInFieldList()));
}
/**
* Tests if the current FormIndex is located inside a group that is marked as a "field-list"
*
* @return true if index is in a "field-list". False otherwise.
*/
public boolean indexIsInFieldList() {
return indexIsInFieldList(getFormIndex());
}
/**
* Attempts to save answer at the current FormIndex into the data model.
*
* @param data
* @return
*/
private int answerQuestion(IAnswerData data) {
return mFormEntryController.answerQuestion(data);
}
/**
* Attempts to save answer into the given FormIndex into the data model.
*
* @param index
* @param data
* @return
*/
public int answerQuestion(FormIndex index, IAnswerData data) {
return mFormEntryController.answerQuestion(index, data);
}
/**
* Goes through the entire form to make sure all entered answers comply with their constraints.
* Constraints are ignored on 'jump to', so answers can be outside of constraints. We don't
* allow saving to disk, though, until all answers conform to their constraints/requirements.
*
* @param markCompleted
* @return ANSWER_OK and leave index unchanged or change index to bad value and return error type.
*/
public int validateAnswers(Boolean markCompleted) {
FormIndex i = getFormIndex();
jumpToIndex(FormIndex.createBeginningOfFormIndex());
int event;
while ((event =
stepToNextEvent(FormController.STEP_INTO_GROUP)) != FormEntryController.EVENT_END_OF_FORM) {
if (event != FormEntryController.EVENT_QUESTION) {
continue;
} else {
int saveStatus = answerQuestion(getQuestionPrompt().getAnswerValue());
if (markCompleted && saveStatus != FormEntryController.ANSWER_OK) {
return saveStatus;
}
}
}
jumpToIndex(i);
return FormEntryController.ANSWER_OK;
}
/**
* saveAnswer attempts to save the current answer into the data model without doing any
* constraint checking. Only use this if you know what you're doing. For normal form filling you
* should always use answerQuestion or answerCurrentQuestion.
*
* @param index
* @param data
* @return true if saved successfully, false otherwise.
*/
public boolean saveAnswer(FormIndex index, IAnswerData data) {
return mFormEntryController.saveAnswer(index, data);
}
/**
* saveAnswer attempts to save the current answer into the data model without doing any
* constraint checking. Only use this if you know what you're doing. For normal form filling you
* should always use answerQuestion().
*
* @param index
* @param data
* @return true if saved successfully, false otherwise.
*/
public boolean saveAnswer(IAnswerData data) {
return mFormEntryController.saveAnswer(data);
}
/**
* Navigates forward in the form.
*
* @return the next event that should be handled by a view.
*/
public int stepToNextEvent(boolean stepIntoGroup) {
if ((getEvent() == FormEntryController.EVENT_GROUP ||
getEvent() == FormEntryController.EVENT_REPEAT)
&& indexIsInFieldList() && !stepIntoGroup) {
return stepOverGroup();
} else {
return mFormEntryController.stepToNextEvent();
}
}
/**
* If using a view like HierarchyView that doesn't support multi-question per screen, step over
* the group represented by the FormIndex.
*
* @return
*/
private int stepOverGroup() {
ArrayList<FormIndex> indicies = new ArrayList<FormIndex>();
GroupDef gd =
(GroupDef) mFormEntryController.getModel().getForm()
.getChild(getFormIndex());
FormIndex idxChild =
mFormEntryController.getModel().incrementIndex(
getFormIndex(), true); // descend into group
for (int i = 0; i < gd.getChildren().size(); i++) {
indicies.add(idxChild);
// don't descend
idxChild = mFormEntryController.getModel().incrementIndex(idxChild, false);
}
// jump to the end of the group
mFormEntryController.jumpToIndex(indicies.get(indicies.size() - 1));
return stepToNextEvent(STEP_OVER_GROUP);
}
/**
* used to go up one level in the formIndex. That is, if you're at 5_0, 1 (the second question
* in a repeating group), this method will return a FormInex of 5_0 (the start of the repeating
* group). If your at index 16 or 5_0, this will return null;
*
* @param index
* @return index
*/
public FormIndex stepIndexOut(FormIndex index) {
if (index.isTerminal()) {
return null;
} else {
return new FormIndex(stepIndexOut(index.getNextLevel()), index);
}
}
/**
* Move the current form index to the index of the previous question in the form.
* Step backward out of repeats and groups as needed. If the resulting question
* is itself within a field-list, move upward to the group or repeat defining that
* field-list.
*
* @return
*/
public int stepToPreviousScreenEvent() {
if (getEvent() != FormEntryController.EVENT_BEGINNING_OF_FORM) {
int event = stepToPreviousEvent();
while (event == FormEntryController.EVENT_REPEAT_JUNCTURE ||
event == FormEntryController.EVENT_PROMPT_NEW_REPEAT ||
(event == FormEntryController.EVENT_QUESTION && indexIsInFieldList()) ||
((event == FormEntryController.EVENT_GROUP
|| event == FormEntryController.EVENT_REPEAT) && !indexIsInFieldList())) {
event = stepToPreviousEvent();
}
// Work-around for broken field-list handling from 1.1.7 which breaks either
// build-generated forms or XLSForm-generated forms. If the current group
// is a GROUP with field-list and it is nested within a group or repeat with just
// this containing group, and that is also a field-list, then return the parent group.
if ( getEvent() == FormEntryController.EVENT_GROUP ) {
FormIndex currentIndex = getFormIndex();
IFormElement element = mFormEntryController.getModel().getForm().getChild(currentIndex);
if (element instanceof GroupDef) {
GroupDef gd = (GroupDef) element;
if ( ODKView.FIELD_LIST.equalsIgnoreCase(gd.getAppearanceAttr()) ) {
// OK this group is a field-list... see what the parent is...
FormEntryCaption[] fclist = this.getCaptionHierarchy(currentIndex);
if ( fclist.length > 1) {
FormEntryCaption fc = fclist[fclist.length-2];
GroupDef pd = (GroupDef) fc.getFormElement();
if ( pd.getChildren().size() == 1 &&
ODKView.FIELD_LIST.equalsIgnoreCase(pd.getAppearanceAttr()) ) {
mFormEntryController.jumpToIndex(fc.getIndex());
}
}
}
}
}
}
return getEvent();
}
/**
* Move the current form index to the index of the next question in the form.
* Stop if we should ask to create a new repeat group or if we reach the end of the form.
* If we enter a group or repeat, return that if it is a field-list definition.
* Otherwise, descend into the group or repeat searching for the first question.
*
* @return
*/
public int stepToNextScreenEvent() {
if (getEvent() != FormEntryController.EVENT_END_OF_FORM) {
int event;
group_skip: do {
event = stepToNextEvent(FormController.STEP_OVER_GROUP);
switch (event) {
case FormEntryController.EVENT_QUESTION:
case FormEntryController.EVENT_END_OF_FORM:
break group_skip;
case FormEntryController.EVENT_PROMPT_NEW_REPEAT:
break group_skip;
case FormEntryController.EVENT_GROUP:
case FormEntryController.EVENT_REPEAT:
if (indexIsInFieldList()
&& getQuestionPrompts().length != 0) {
break group_skip;
}
// otherwise it's not a field-list group, so just skip it
break;
case FormEntryController.EVENT_REPEAT_JUNCTURE:
Log.i(t, "repeat juncture: "
+ getFormIndex().getReference());
// skip repeat junctures until we implement them
break;
default:
Log.w(t,
"JavaRosa added a new EVENT type and didn't tell us... shame on them.");
break;
}
} while (event != FormEntryController.EVENT_END_OF_FORM);
}
return getEvent();
}
/**
* Move the current form index to the index of the first enclosing repeat
* or to the start of the form.
*
* @return
*/
public int stepToOuterScreenEvent() {
FormIndex index = stepIndexOut(getFormIndex());
int currentEvent = getEvent();
// Step out of any group indexes that are present.
while (index != null
&& getEvent(index) == FormEntryController.EVENT_GROUP) {
index = stepIndexOut(index);
}
if (index == null) {
jumpToIndex(FormIndex.createBeginningOfFormIndex());
} else {
if (currentEvent == FormEntryController.EVENT_REPEAT) {
// We were at a repeat, so stepping back brought us to then previous level
jumpToIndex(index);
} else {
// We were at a question, so stepping back brought us to either:
// The beginning. or The start of a repeat. So we need to step
// out again to go passed the repeat.
index = stepIndexOut(index);
if (index == null) {
jumpToIndex(FormIndex.createBeginningOfFormIndex());
} else {
jumpToIndex(index);
}
}
}
return getEvent();
}
public static class FailedConstraint {
public final FormIndex index;
public final int status;
FailedConstraint(FormIndex index, int status) {
this.index = index;
this.status = status;
}
}
/**
*
* @param answers
* @param evaluateConstraints
* @return FailedConstraint of first failed constraint or null if all questions were saved.
*/
public FailedConstraint saveAllScreenAnswers(LinkedHashMap<FormIndex,IAnswerData> answers, boolean evaluateConstraints) {
if (currentPromptIsQuestion()) {
Iterator<FormIndex> it = answers.keySet().iterator();
while (it.hasNext()) {
FormIndex index = it.next();
// Within a group, you can only save for question events
if (getEvent(index) == FormEntryController.EVENT_QUESTION) {
int saveStatus;
IAnswerData answer = answers.get(index);
if (evaluateConstraints) {
saveStatus = answerQuestion(index, answer);
if (saveStatus != FormEntryController.ANSWER_OK) {
return new FailedConstraint(index, saveStatus);
}
} else {
saveAnswer(index, answer);
}
} else {
Log.w(t,
"Attempted to save an index referencing something other than a question: "
+ index.getReference());
}
}
}
return null;
}
/**
* Navigates backward in the form.
*
* @return the event that should be handled by a view.
*/
public int stepToPreviousEvent() {
/*
* Right now this will always skip to the beginning of a group if that group is represented
* as a 'field-list'. Should a need ever arise to step backwards by only one step in a
* 'field-list', this method will have to be updated.
*/
mFormEntryController.stepToPreviousEvent();
// If after we've stepped, we're in a field-list, jump back to the beginning of the group
//
if (indexIsInFieldList()
&& getEvent() == FormEntryController.EVENT_QUESTION) {
// caption[0..len-1]
// caption[len-1] == the question itself
// caption[len-2] == the first group it is contained in.
FormEntryCaption[] captions = getCaptionHierarchy();
FormEntryCaption grp = captions[captions.length - 2];
- return mFormEntryController.jumpToIndex(grp.getIndex());
+ int event = mFormEntryController.jumpToIndex(grp.getIndex());
+ // and test if this group or at least one of its children is relevant...
+ FormIndex idx = grp.getIndex();
+ if ( !mFormEntryController.getModel().isIndexRelevant(idx) ) {
+ return stepToPreviousEvent();
+ }
+ idx = mFormEntryController.getModel().incrementIndex(idx, true);
+ while ( FormIndex.isSubElement(grp.getIndex(), idx) ) {
+ if ( mFormEntryController.getModel().isIndexRelevant(idx) ) {
+ return event;
+ }
+ idx = mFormEntryController.getModel().incrementIndex(idx, true);
+ }
+ return stepToPreviousEvent();
+ } else if ( indexIsInFieldList() && getEvent() == FormEntryController.EVENT_GROUP) {
+ FormIndex grpidx = mFormEntryController.getModel().getFormIndex();
+ int event = mFormEntryController.getModel().getEvent();
+ // and test if this group or at least one of its children is relevant...
+ if ( !mFormEntryController.getModel().isIndexRelevant(grpidx) ) {
+ return stepToPreviousEvent(); // shouldn't happen?
+ }
+ FormIndex idx = mFormEntryController.getModel().incrementIndex(grpidx, true);
+ while ( FormIndex.isSubElement(grpidx, idx) ) {
+ if ( mFormEntryController.getModel().isIndexRelevant(idx) ) {
+ return event;
+ }
+ idx = mFormEntryController.getModel().incrementIndex(idx, true);
+ }
+ return stepToPreviousEvent();
}
return getEvent();
}
/**
* Jumps to a given FormIndex.
*
* @param index
* @return EVENT for the specified Index.
*/
public int jumpToIndex(FormIndex index) {
return mFormEntryController.jumpToIndex(index);
}
/**
* Creates a new repeated instance of the group referenced by the current FormIndex.
*
* @param questionIndex
*/
public void newRepeat() {
mFormEntryController.newRepeat();
}
/**
* If the current FormIndex is within a repeated group, will find the innermost repeat, delete
* it, and jump the FormEntryController to the previous valid index. That is, if you have group1
* (2) > group2 (3) and you call deleteRepeat, it will delete the 3rd instance of group2.
*/
public void deleteRepeat() {
FormIndex fi = mFormEntryController.deleteRepeat();
mFormEntryController.jumpToIndex(fi);
}
/**
* Sets the current language.
*
* @param language
*/
public void setLanguage(String language) {
mFormEntryController.setLanguage(language);
}
/**
* Returns an array of question promps.
*
* @return
*/
public FormEntryPrompt[] getQuestionPrompts() throws RuntimeException {
ArrayList<FormIndex> indicies = new ArrayList<FormIndex>();
FormIndex currentIndex = getFormIndex();
// For questions, there is only one.
// For groups, there could be many, but we set that below
FormEntryPrompt[] questions = new FormEntryPrompt[1];
IFormElement element = mFormEntryController.getModel().getForm().getChild(currentIndex);
if (element instanceof GroupDef) {
GroupDef gd = (GroupDef) element;
// descend into group
FormIndex idxChild = mFormEntryController.getModel().incrementIndex(currentIndex, true);
if ( gd.getChildren().size() == 1 && getEvent(idxChild) == FormEntryController.EVENT_GROUP ) {
// if we have a group definition within a field-list attribute group, and this is the
// only child in the group, check to see if it is also a field-list appearance.
// If it is, then silently recurse into it to pick up its elements.
// Work-around for the inconsistent treatment of field-list groups and repeats in 1.1.7 that
// either breaks forms generated by build or breaks forms generated by XLSForm.
IFormElement nestedElement = mFormEntryController.getModel().getForm().getChild(idxChild);
if (nestedElement instanceof GroupDef) {
GroupDef nestedGd = (GroupDef) nestedElement;
if ( ODKView.FIELD_LIST.equalsIgnoreCase(nestedGd.getAppearanceAttr()) ) {
gd = nestedGd;
idxChild = mFormEntryController.getModel().incrementIndex(idxChild, true);
}
}
}
for (int i = 0; i < gd.getChildren().size(); i++) {
indicies.add(idxChild);
// don't descend
idxChild = mFormEntryController.getModel().incrementIndex(idxChild, false);
}
// we only display relevant questions
ArrayList<FormEntryPrompt> questionList = new ArrayList<FormEntryPrompt>();
for (int i = 0; i < indicies.size(); i++) {
FormIndex index = indicies.get(i);
if (getEvent(index) != FormEntryController.EVENT_QUESTION) {
String errorMsg =
"Only questions are allowed in 'field-list'. Bad node is: "
+ index.getReference().toString(false);
RuntimeException e = new RuntimeException(errorMsg);
Log.e(t, errorMsg);
throw e;
}
// we only display relevant questions
if (mFormEntryController.getModel().isIndexRelevant(index)) {
questionList.add(getQuestionPrompt(index));
}
questions = new FormEntryPrompt[questionList.size()];
questionList.toArray(questions);
}
} else {
// We have a quesion, so just get the one prompt
questions[0] = getQuestionPrompt();
}
return questions;
}
public FormEntryPrompt getQuestionPrompt(FormIndex index) {
return mFormEntryController.getModel().getQuestionPrompt(index);
}
public FormEntryPrompt getQuestionPrompt() {
return mFormEntryController.getModel().getQuestionPrompt();
}
/**
* Returns an array of FormEntryCaptions for current FormIndex.
*
* @return
*/
public FormEntryCaption[] getGroupsForCurrentIndex() {
// return an empty array if you ask for something impossible
if (!(getEvent() == FormEntryController.EVENT_QUESTION
|| getEvent() == FormEntryController.EVENT_PROMPT_NEW_REPEAT
|| getEvent() == FormEntryController.EVENT_GROUP
|| getEvent() == FormEntryController.EVENT_REPEAT)) {
return new FormEntryCaption[0];
}
// the first caption is the question, so we skip it if it's an EVENT_QUESTION
// otherwise, the first caption is a group so we start at index 0
int lastquestion = 1;
if (getEvent() == FormEntryController.EVENT_PROMPT_NEW_REPEAT
|| getEvent() == FormEntryController.EVENT_GROUP
|| getEvent() == FormEntryController.EVENT_REPEAT) {
lastquestion = 0;
}
FormEntryCaption[] v = getCaptionHierarchy();
FormEntryCaption[] groups = new FormEntryCaption[v.length - lastquestion];
for (int i = 0; i < v.length - lastquestion; i++) {
groups[i] = v[i];
}
return groups;
}
/**
* This is used to enable/disable the "Delete Repeat" menu option.
*
* @return
*/
public boolean indexContainsRepeatableGroup() {
FormEntryCaption[] groups = getCaptionHierarchy();
if (groups.length == 0) {
return false;
}
for (int i = 0; i < groups.length; i++) {
if (groups[i].repeats())
return true;
}
return false;
}
/**
* The count of the closest group that repeats or -1.
*/
public int getLastRepeatedGroupRepeatCount() {
FormEntryCaption[] groups = getCaptionHierarchy();
if (groups.length > 0) {
for (int i = groups.length - 1; i > -1; i--) {
if (groups[i].repeats()) {
return groups[i].getMultiplicity();
}
}
}
return -1;
}
/**
* The name of the closest group that repeats or null.
*/
public String getLastRepeatedGroupName() {
FormEntryCaption[] groups = getCaptionHierarchy();
// no change
if (groups.length > 0) {
for (int i = groups.length - 1; i > -1; i--) {
if (groups[i].repeats()) {
return groups[i].getLongText();
}
}
}
return null;
}
/**
* The closest group the prompt belongs to.
*
* @return FormEntryCaption
*/
private FormEntryCaption getLastGroup() {
FormEntryCaption[] groups = getCaptionHierarchy();
if (groups == null || groups.length == 0)
return null;
else
return groups[groups.length - 1];
}
/**
* The repeat count of closest group the prompt belongs to.
*/
public int getLastRepeatCount() {
if (getLastGroup() != null) {
return getLastGroup().getMultiplicity();
}
return -1;
}
/**
* The text of closest group the prompt belongs to.
*/
public String getLastGroupText() {
if (getLastGroup() != null) {
return getLastGroup().getLongText();
}
return null;
}
/**
* Find the portion of the form that is to be submitted
*
* @return
*/
private IDataReference getSubmissionDataReference() {
FormDef formDef = mFormEntryController.getModel().getForm();
// Determine the information about the submission...
SubmissionProfile p = formDef.getSubmissionProfile();
if (p == null || p.getRef() == null) {
return new XPathReference("/");
} else {
return p.getRef();
}
}
/**
* Once a submission is marked as complete, it is saved in the
* submission format, which might be a fragment of the original
* form or might be a SMS text string, etc.
*
* @return true if the submission is the entire form. If it is,
* then the submission can be re-opened for editing
* after it was marked-as-complete (provided it has
* not been encrypted).
*/
public boolean isSubmissionEntireForm() {
IDataReference sub = getSubmissionDataReference();
return ( getInstance().resolveReference(sub) == null );
}
/**
* Constructs the XML payload for a filled-in form instance. This payload
* enables a filled-in form to be re-opened and edited.
*
* @return
* @throws IOException
*/
public ByteArrayPayload getFilledInFormXml() throws IOException {
// assume no binary data inside the model.
FormInstance datamodel = getInstance();
XFormSerializingVisitor serializer = new XFormSerializingVisitor();
ByteArrayPayload payload =
(ByteArrayPayload) serializer.createSerializedPayload(datamodel);
return payload;
}
/**
* Extract the portion of the form that should be uploaded to the server.
*
* @return
* @throws IOException
*/
public ByteArrayPayload getSubmissionXml() throws IOException {
FormInstance instance = getInstance();
XFormSerializingVisitor serializer = new XFormSerializingVisitor();
ByteArrayPayload payload =
(ByteArrayPayload) serializer.createSerializedPayload(instance,
getSubmissionDataReference());
return payload;
}
/**
* Traverse the submission looking for the first matching tag in depth-first order.
*
* @param parent
* @param name
* @return
*/
private TreeElement findDepthFirst(TreeElement parent, String name) {
int len = parent.getNumChildren();
for ( int i = 0; i < len ; ++i ) {
TreeElement e = parent.getChildAt(i);
if ( name.equals(e.getName()) ) {
return e;
} else if ( e.getNumChildren() != 0 ) {
TreeElement v = findDepthFirst(e, name);
if ( v != null ) return v;
}
}
return null;
}
/**
* Get the OpenRosa required metadata of the portion of the form beng submitted
* @return
*/
public InstanceMetadata getSubmissionMetadata() {
FormDef formDef = mFormEntryController.getModel().getForm();
TreeElement rootElement = formDef.getInstance().getRoot();
TreeElement trueSubmissionElement;
// Determine the information about the submission...
SubmissionProfile p = formDef.getSubmissionProfile();
if ( p == null || p.getRef() == null ) {
trueSubmissionElement = rootElement;
} else {
IDataReference ref = p.getRef();
trueSubmissionElement = formDef.getInstance().resolveReference(ref);
// resolveReference returns null if the reference is to the root element...
if ( trueSubmissionElement == null ) {
trueSubmissionElement = rootElement;
}
}
// and find the depth-first meta block in this...
TreeElement e = findDepthFirst(trueSubmissionElement, "meta");
String instanceId = null;
if ( e != null ) {
Vector<TreeElement> v;
// instance id...
v = e.getChildrenWithName(INSTANCE_ID);
if ( v.size() == 1 ) {
StringData sa = (StringData) v.get(0).getValue();
instanceId = (String) sa.getValue();
}
}
return new InstanceMetadata(instanceId);
}
}
| true | false | null | null |
diff --git a/src/main/java/org/primefaces/component/tabview/TabViewRenderer.java b/src/main/java/org/primefaces/component/tabview/TabViewRenderer.java
index ddf2635d9..675d55858 100644
--- a/src/main/java/org/primefaces/component/tabview/TabViewRenderer.java
+++ b/src/main/java/org/primefaces/component/tabview/TabViewRenderer.java
@@ -1,198 +1,197 @@
/*
- * Copyright 2010 Prime Technology.
+ * Copyright 2009-2011 Prime Technology.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.primefaces.component.tabview;
import java.io.IOException;
import java.util.Map;
import javax.el.MethodExpression;
-import javax.faces.FacesException;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;
import javax.faces.event.PhaseId;
import org.primefaces.event.TabChangeEvent;
import org.primefaces.renderkit.CoreRenderer;
import org.primefaces.util.ComponentUtils;
public class TabViewRenderer extends CoreRenderer {
@Override
public void decode(FacesContext context, UIComponent component) {
Map<String, String> params = context.getExternalContext().getRequestParameterMap();
TabView tabView = (TabView) component;
String activeIndexValue = params.get(tabView.getClientId(context) + "_activeIndex");
if(!isValueEmpty(activeIndexValue)) {
tabView.setActiveIndex(Integer.parseInt(activeIndexValue));
}
if(tabView.isTabChangeRequest(context)) {
TabChangeEvent changeEvent = new TabChangeEvent(tabView, tabView.findTabToLoad(context));
changeEvent.setPhaseId(PhaseId.INVOKE_APPLICATION);
tabView.queueEvent(changeEvent);
}
}
@Override
public void encodeEnd(FacesContext context, UIComponent component) throws IOException {
Map<String, String> params = context.getExternalContext().getRequestParameterMap();
TabView tabView = (TabView) component;
if(tabView.isContentLoadRequest(context)) {
Tab tabToLoad = (Tab) tabView.findTabToLoad(context);
tabToLoad.encodeAll(context);
} else {
encodeMarkup(context, tabView);
encodeScript(context, tabView);
}
}
protected void encodeScript(FacesContext context, TabView tabView) throws IOException {
ResponseWriter writer = context.getResponseWriter();
String clientId = tabView.getClientId(context);
MethodExpression tabChangeListener = tabView.getTabChangeListener();
writer.startElement("script", null);
writer.writeAttribute("type", "text/javascript", null);
writer.write(tabView.resolveWidgetVar() + " = new PrimeFaces.widget.TabView('" + clientId + "', {");
writer.write("selected:" + tabView.getActiveIndex());
writer.write(",dynamic:" + tabView.isDynamic());
if(tabView.isDynamic() || tabChangeListener != null) {
writer.write(",url:'" + getActionURL(context) + "'");
writer.write(",cache:" + tabView.isCache());
}
if(tabView.isCollapsible()) writer.write(",collapsible:true");
if(tabView.getEvent() != null) writer.write(",event:'" + tabView.getEvent() + "'");
if(tabView.getOnTabChange() != null) writer.write(",onTabChange: function(event, ui) {" + tabView.getOnTabChange() + "}");
if(tabView.getOnTabShow() != null) writer.write(",onTabShow:function(event, ui) {" + tabView.getOnTabShow() + "}");
if(tabView.getEffect() != null) {
writer.write(",fx: {");
writer.write(tabView.getEffect() + ":'toggle'");
writer.write(",duration:'" + tabView.getEffectDuration() + "'");
writer.write("}");
}
if(tabChangeListener != null) {
writer.write(",ajaxTabChange:true");
if(tabView.getOnTabChangeUpdate() != null) {
writer.write(",onTabChangeUpdate:'" + ComponentUtils.findClientIds(context, tabView, tabView.getOnTabChangeUpdate()) + "'");
}
}
writer.write("});");
writer.endElement("script");
}
protected void encodeMarkup(FacesContext facesContext, TabView tabView) throws IOException {
ResponseWriter writer = facesContext.getResponseWriter();
String clientId = tabView.getClientId(facesContext);
int activeIndex = tabView.getActiveIndex();
writer.startElement("div", tabView);
writer.writeAttribute("id", clientId, null);
if(tabView.getStyle() != null) writer.writeAttribute("style", tabView.getStyle(), "style");
if(tabView.getStyleClass() != null) writer.writeAttribute("class", tabView.getStyleClass(), "styleClass");
encodeHeaders(facesContext, tabView, activeIndex);
encodeContents(facesContext, tabView, activeIndex);
encodeActiveIndexHolder(facesContext, tabView);
writer.endElement("div");
}
protected void encodeActiveIndexHolder(FacesContext facesContext, TabView tabView) throws IOException {
ResponseWriter writer = facesContext.getResponseWriter();
String paramName = tabView.getClientId(facesContext) + "_activeIndex";
writer.startElement("input", null);
writer.writeAttribute("type", "hidden", null);
writer.writeAttribute("id", paramName, null);
writer.writeAttribute("name", paramName, null);
writer.writeAttribute("value", tabView.getActiveIndex(), null);
writer.endElement("input");
}
protected void encodeHeaders(FacesContext facesContext, TabView tabView, int activeTabIndex) throws IOException {
ResponseWriter writer = facesContext.getResponseWriter();
writer.startElement("ul", null);
for (UIComponent kid : tabView.getChildren()) {
if (kid.isRendered() && kid instanceof Tab) {
Tab tab = (Tab) kid;
writer.startElement("li", null);
writer.startElement("a", null);
writer.writeAttribute("href", "#" + tab.getClientId(facesContext), null);
writer.startElement("em", null);
writer.write(tab.getTitle());
writer.endElement("em");
writer.endElement("a");
writer.endElement("li");
}
}
writer.endElement("ul");
}
protected void encodeContents(FacesContext facesContext, TabView tabView, int activeTabIndex) throws IOException {
ResponseWriter writer = facesContext.getResponseWriter();
for (int i = 0; i < tabView.getChildren().size(); i++) {
UIComponent kid = tabView.getChildren().get(i);
if (kid.isRendered() && kid instanceof Tab) {
Tab tab = (Tab) kid;
writer.startElement("div", null);
writer.writeAttribute("id", tab.getClientId(facesContext), null);
if (tabView.isDynamic()) {
if (i == activeTabIndex) {
tab.encodeAll(facesContext);
}
} else {
tab.encodeAll(facesContext);
}
writer.endElement("div");
}
}
}
@Override
public void encodeChildren(FacesContext facesContext, UIComponent component) throws IOException {
//Rendering happens on encodeEnd
}
@Override
public boolean getRendersChildren() {
return true;
}
}
\ No newline at end of file
| false | false | null | null |
diff --git a/translator/src/polyglot/ext/jedd/types/PhysDom.java b/translator/src/polyglot/ext/jedd/types/PhysDom.java
index 25e2855..de7d929 100644
--- a/translator/src/polyglot/ext/jedd/types/PhysDom.java
+++ b/translator/src/polyglot/ext/jedd/types/PhysDom.java
@@ -1,1455 +1,1464 @@
/* Jedd - A language for implementing relations using BDDs
- * Copyright (C) 2003 Ondrej Lhotak
+ * Copyright (C) 2003, 2004 Ondrej Lhotak
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
package polyglot.ext.jedd.types;
import polyglot.ast.*;
import polyglot.types.*;
import polyglot.ext.jedd.ast.*;
import polyglot.ext.jl.ast.*;
import polyglot.ext.jl.types.*;
import polyglot.util.*;
import polyglot.visit.*;
import polyglot.frontend.*;
import java.util.*;
import java.io.*;
//import polyglot.ext.jedd.cudd.*;
public class PhysDom {
final static boolean INCLUDE_COMMENTS = false;
final static boolean DEBUG = false;
final static boolean STATS = false;
private static PhysDom instance = new PhysDom();
public static PhysDom v() { return instance; }
public Map domainAssignment = new HashMap();
public Set assignEdges = new HashSet();
public Set mustEqualEdges = new HashSet();
public Collection allPhys = new HashSet();
private String satSolver = System.getProperty("user.home")+System.getProperty("file.separator")+"zchaff.2003.10.9.linux";
private String satCore = System.getProperty("user.home")+System.getProperty("file.separator")+"zcore";
public void setSatSolver( String s ) { satSolver = s; }
public void setSatCore( String s ) { satCore = s; }
static interface HasNum {
public int getNum();
}
/*
static class SetLit implements HasNum {
Path path;
private SetLit( Path path ) {
this.path = path;
}
public static SetLit v( Path path ) {
SetLit ret = new SetLit(path);
SetLit ret2 = (SetLit) setMap.get( ret );
if( ret2 == null ) {
setMap.put( ret2 = ret, ret );
}
return ret2;
}
public boolean equals( Object other ) {
if( !(other instanceof SetLit) ) return false;
SetLit o = (SetLit) other;
if( !o.path.equals(path) ) return false;
return true;
}
public int hashCode() { return path.hashCode(); }
public int getNum() {
Integer i = (Integer) litNumMap.get(this);
if( i == null ) litNumMap.put( this, i = new Integer(++nextInt) );
return i.intValue();
}
public String toString() {
return Integer.toString(getNum());
}
}
static class NegSetLit implements HasNum {
SetLit set;
private NegSetLit( SetLit set ) {
this.set = set;
}
private NegSetLit( Path path ) {
this( SetLit.v( path ) );
}
public static NegSetLit v( Path path ) {
NegSetLit ret = new NegSetLit( path );
NegSetLit ret2 = (NegSetLit) setMap.get( ret );
if( ret2 == null ) {
setMap.put( ret2 = ret, ret );
}
return ret2;
}
public static NegSetLit v( SetLit e ) {
return v(e.path);
}
public boolean equals( Object other ) {
if( !(other instanceof NegSetLit) ) return false;
NegSetLit o = (NegSetLit) other;
if( !o.set.equals(set) ) return false;
return true;
}
public int hashCode() { return set.hashCode() + 1; }
public int getNum() {
return -(set.getNum());
}
public String toString() {
return Integer.toString(getNum());
}
}
*/
public static Map setMap = new HashMap();
static class Literal implements HasNum {
DNode dnode;
Type phys;
private Literal( DNode dnode, Type phys ) {
this.dnode = dnode.rep(); this.phys = phys;
}
public static Literal v( DNode dnode, Type phys ) {
if( dnode.rep() != dnode ) throw new RuntimeException();
Literal ret = new Literal( dnode, phys );
Literal ret2 = (Literal) litMap.get( ret );
if( ret2 == null ) {
litMap.put( ret2 = ret, ret );
}
return ret2;
}
public boolean equals( Object other ) {
if( !(other instanceof Literal) ) return false;
Literal o = (Literal) other;
if( o.dnode != dnode ) return false;
if( o.phys != phys ) return false;
return true;
}
public int hashCode() { return dnode.hashCode() + phys.hashCode(); }
public int getNum() {
Integer i = (Integer) litNumMap.get(this);
if( i == null ) litNumMap.put( this, i = new Integer(++nextInt) );
return i.intValue();
}
public String toString() {
return Integer.toString(getNum());
}
}
static int nextInt = 0;
public static Map litMap = new HashMap();
public static Map litNumMap = new HashMap();
static class NegLiteral implements HasNum {
Literal lit;
private NegLiteral( Literal lit ) {
this.lit = lit;
}
private NegLiteral( DNode dnode, Type phys ) {
this( Literal.v( dnode, phys ) );
}
public static NegLiteral v( DNode dnode, Type phys ) {
NegLiteral ret = new NegLiteral( dnode.rep(), phys );
NegLiteral ret2 = (NegLiteral) litMap.get( ret );
if( ret2 == null ) {
litMap.put( ret2 = ret, ret );
}
return ret2;
}
public boolean equals( Object other ) {
if( !(other instanceof NegLiteral) ) return false;
NegLiteral o = (NegLiteral) other;
if( !o.lit.equals(lit) ) return false;
return true;
}
public int hashCode() { return lit.hashCode() + 1; }
public int getNum() {
return -(lit.getNum());
}
public String toString() {
return Integer.toString(getNum());
}
}
/*
public static class Path implements Comparable {
private final int length;
private final DNode car;
private final Path cdr;
private final DNode end;
public DNode top() { return car; }
public Type phys() { return PhysDom.phys(end); }
public int size() { return length; }
public boolean contains( DNode n ) {
if( car.equals(n) ) return true;
if( cdr == null ) return false;
return cdr.contains(n);
}
private boolean isSubPath( Path other ) {
if( length > other.length ) return false;
if( car.equals(other.car) ) {
if( cdr == null ) return true;
if( other.cdr == null ) return false;
return cdr.isSubPath(other.cdr);
} else {
if( other.cdr == null ) return false;
return isSubPath(other.cdr);
}
}
public boolean isSubSet( Path other ) {
if( other.length < length ) return false;
if( !end.equals(other.end) ) return false;
if( isSubPath(other) ) return true;
// Now it gets expensive
if( !other.contains(car) ) return false;
if( cdr == null ) return true;
return cdr.isSubSet(other);
}
public Path( DNode n ) {
car = n;
cdr = null;
length = 1;
end = n;
}
private Path( Path cdr, DNode car ) {
this.car = car;
this.cdr = cdr;
this.length = cdr.length+1;
this.end = cdr.end;
}
public Path add( DNode n ) {
return new Path( this, n );
}
public int compareTo( Object o ) {
Path other = (Path) o;
int ret = length - other.length;
if( ret != 0 ) return ret;
ret = car.domNum - other.car.domNum;
if( ret != 0 ) return ret;
if( cdr == null ) return 0;
return cdr.compareTo(other.cdr);
}
public int hashCode() { return length; }
public boolean equals( Object o ) {
if( o == null ) return false;
Path other = (Path) o;
if( length != other.length ) return false;
if( !car.equals(other.car) ) return false;
if( cdr == null ) return other.cdr == null;
return cdr.equals(other.cdr);
}
public Iterator iterator() {
return new Iterator() {
Path p = Path.this;
public boolean hasNext() { return p != null; }
public Object next() {
if( p == null ) throw new NoSuchElementException();
Object ret = p.car;
p = p.cdr;
return ret;
}
public void remove() {
throw new UnsupportedOperationException();
}
};
}
}
*/
Set cnf = new HashSet();
public static class Clause extends HashSet {
public Clause() {
}
private boolean isConflict = false;
public Clause( boolean isConflict ) {
this.isConflict = isConflict;
}
public boolean isConflict() { return isConflict; }
public void setComment( String comment ) {
this.comment = comment;
}
String comment;
public String toString() {
StringBuffer ret = new StringBuffer();
if( comment != null ) ret.append( "c "+comment+"\n" );
for( Iterator litIt = this.iterator(); litIt.hasNext(); ) {
final Object lit = (Object) litIt.next();
ret.append( lit.toString() );
ret.append( " " );
}
ret.append( "0" );
return ret.toString();
}
}
JeddNodeFactory nf;
JeddTypeSystem ts;
public void findAssignment( JeddNodeFactory nf, JeddTypeSystem ts, Collection jobs ) throws SemanticException {
this.nf = nf;
this.ts = ts;
//printDomainsDot();
//printDomainsRsf();
if(DEBUG) System.out.println( "creating literals" );
createLiterals();
if(DEBUG) System.out.println( "adding equality edges" );
addMustEqualEdges();
if(DEBUG) System.out.println( "building rep list" );
buildRepList();
if(DEBUG) System.out.println( "computing adjacency lists" );
computeAdjacencies();
if(DEBUG) System.out.println( "finding possible phys" );
findPossiblePhys();
if(DEBUG) System.out.println( "dumping dot graph" );
if(DEBUG) dumpDot();
if(DEBUG) System.out.println( "creating dnode constraints" );
createDnodeConstraints();
//if(DEBUG) System.out.println( "setting programmer-specified assignments" );
//setupSpecifiedAssignment();
//if(DEBUG) System.out.println( "adding assign edges" );
//addAssignEdges();
if(DEBUG) System.out.println( "adding direction constraints" );
addDirectionConstraints();
if(DEBUG) System.out.println( "adding conflict edges" );
addConflictEdges();
printStats();
//tryWithBDDsJustForKicks();
if(DEBUG) System.out.println( "running sat solver" );
runSat();
if(DEBUG) System.out.println( "dumping dot graph" );
if(DEBUG) dumpDot();
if(DEBUG) System.out.println( "recording sat solver results" );
recordPhys(jobs);
if(DEBUG) System.out.println( "dumping dot graph" );
if(DEBUG) dumpDot();
//printDomainsDot();
//printDomainsRsf();
}
List repList;
private void buildRepList() {
repList = new ArrayList();
for( Iterator nodeIt = DNode.nodes().iterator(); nodeIt.hasNext(); ) {
final DNode node = (DNode) nodeIt.next();
if( node.rep() != node ) continue;
repList.add(node);
}
}
Set solution;
public void runSat() throws SemanticException {
int numvars = ordMap.size()+(arrMap.size()+setMap.size()+litMap.size())/2;
if( numvars == 0 ) return;
try {
File tmpFile = File.createTempFile("domainassign",".cnf");
PrintWriter file = new PrintWriter(
new FileOutputStream( tmpFile ) );
file.println( "p cnf "+numvars+" "+cnf.size() );
for( Iterator clauseIt = cnf.iterator(); clauseIt.hasNext(); ) {
final Clause clause = (Clause) clauseIt.next();
file.println( clause.toString() );
}
file.close();
Process p = Runtime.getRuntime().exec(satSolver+" "+tmpFile.getAbsolutePath());
BufferedReader br = new BufferedReader(new InputStreamReader( p.getInputStream() ) );
String str;
String soln = null;
while ((str = br.readLine()) != null) {
if(STATS) if( str.length() < 1000 ) System.out.println( str );
boolean hasNum = false;
boolean hasBad = false;
for( int i = 0; i < str.length(); i++ ) {
if( str.charAt(i) == ' ' ) continue;
if( str.charAt(i) == '\t' ) continue;
if( str.charAt(i) == '-' ) continue;
if( str.charAt(i) >= '0' && str.charAt(i) <= '9' ) {
hasNum = true;
continue;
}
hasBad = true;
}
if( hasNum && !hasBad ) {
// this looks like the solution
if( soln != null ) throw new RuntimeException( "old solution was "+soln+"; now we got "+str );
soln = str;
}
}
boolean pos[] = new boolean[numvars+1];
boolean neg[] = new boolean[numvars+1];
if( soln == null ) {
unsatCore( tmpFile );
throw new SemanticException( "SAT solver couldn't assign physical domains." );
}
StringTokenizer st = new StringTokenizer( soln );
while( st.hasMoreTokens() ) {
String tok = st.nextToken();
int i = Integer.parseInt( tok );
if( i < 0 ) neg[-i] = true;
else pos[i] = true;
}
for( int i = 1; i <= numvars; i++ ) {
if( neg[i] && pos[i] ) throw new RuntimeException("both for "+i);
if( !neg[i] && !pos[i] ) throw new RuntimeException("neither for "+i);
}
solution = new HashSet();
for( Iterator litIt = litNumMap.keySet().iterator(); litIt.hasNext(); ) {
final Object lit = (Object) litIt.next();
Integer i = (Integer) litNumMap.get( lit );
if( pos[i.intValue()] ) solution.add( lit );
}
//tmpFile.delete();
} catch( IOException e ) {
throw new RuntimeException( e.toString() );
}
}
private void unsatCore( File tmpFile ) {
System.err.println( "Attemptimg to extract unsat core." );
try {
File coreFile = File.createTempFile( "satcore", ".cnf" );
Process p = Runtime.getRuntime().exec(satCore+" "+tmpFile.getAbsolutePath()+" resolve_trace "+coreFile.getAbsolutePath());
BufferedReader br = new BufferedReader(new InputStreamReader( p.getInputStream() ) );
String line;
while ((line = br.readLine()) != null) {
System.err.println( line );
}
try {
p.waitFor();
} catch( InterruptedException e ) {}
br = new BufferedReader(new InputStreamReader(new FileInputStream( coreFile )));
line:
while ((line = br.readLine()) != null) {
if( Character.isLetter( line.charAt(0) ) ) continue;
Integer i1 = null;
Integer i2 = null;
StringTokenizer tok = new StringTokenizer(line);
while( tok.hasMoreTokens() ) {
String token = tok.nextToken();
Integer i = Integer.decode( token );
int ival = i.intValue();
if( ival > 0 ) continue line;
if( ival == 0 ) {
if( i2 == null ) continue line;
break;
}
if( i1 == null ) i1 = i;
else if( i2 == null ) i2 = i;
else continue line;
}
// got a conflict clause
clause:
for( Iterator clIt = cnf.iterator(); clIt.hasNext(); ) {
final Clause cl = (Clause) clIt.next();
if( cl.size() != 2 ) continue;
NegLiteral nl1 = null;
NegLiteral nl2 = null;
for( Iterator litIt = cl.iterator(); litIt.hasNext(); ) {
final HasNum lit = (HasNum) litIt.next();
if(!(lit instanceof NegLiteral)) continue clause;
if( lit.getNum() != i1.intValue()
&& lit.getNum() != i2.intValue() ) continue clause;
if( nl1 == null ) nl1 = (NegLiteral) lit;
else nl2 = (NegLiteral) lit;
}
if( !cl.isConflict() ) continue line;
DNode conflictingNode1 = nl1.lit.dnode;
DNode conflictingNode2 = nl2.lit.dnode;
for( Iterator exprIt = DNode.exprs().iterator(); exprIt.hasNext(); ) {
final BDDExpr expr = (BDDExpr) exprIt.next();
DNode node1 = null;
DNode node2 = null;
BDDType t = expr.getType();
Map map = t.map();
for( Iterator attrIt = map.keySet().iterator(); attrIt.hasNext(); ) {
final Type attr = (Type) attrIt.next();
DNode orig = DNode.v(expr, attr);
if( orig.rep() == conflictingNode1 ) node1 = orig;
if( orig.rep() == conflictingNode2 ) node2 = orig;
}
if( node1 != null && node2 != null ) {
StdErrorQueue seq = new StdErrorQueue( System.err, 0, "" );
seq.displayError(
new ErrorInfo(ErrorInfo.SEMANTIC_ERROR,
"Conflict between attributes "+node1.dom
+" and "+node2.dom+
( expr.isFixPhys()
? " of replaced version of"
: " of"),
expr.position() ) );
System.err.println( "over physical domain "
+nl1.lit.phys );
continue clause;
}
}
throw new RuntimeException();
}
}
} catch( IOException e ) {
throw new RuntimeException( "Problem extracting unsat core: "+e );
}
}
/*
public void tryWithBDDsJustForKicks() {
int numvars = (setMap.size()+litMap.size())/2;
System.loadLibrary("jcudd");
SWIGTYPE_p_DdManager manager = Cudd.Cudd_Init(numvars+1,0,Cudd.CUDD_UNIQUE_SLOTS,Cudd.CUDD_CACHE_SLOTS,0);
SWIGTYPE_p_DdNode bdd = Cudd.Cudd_ReadOne(manager);
Cudd.Cudd_Ref(bdd);
for( Iterator clauseIt = cnf.iterator(); clauseIt.hasNext(); ) {
final Clause clause = (Clause) clauseIt.next();
SWIGTYPE_p_DdNode clauseBdd = Cudd.Cudd_ReadLogicZero(manager);
Cudd.Cudd_Ref(clauseBdd);
for( Iterator oIt = clause.iterator(); oIt.hasNext(); ) {
final Object o = (Object) oIt.next();
int i = Integer.parseInt( o.toString() );
SWIGTYPE_p_DdNode literal = Cudd.Cudd_bddIthVar(manager, i<0?-i:i);
if( i < 0 ) literal = Cudd.Cudd_bddNot( literal );
Cudd.Cudd_Ref( literal );
SWIGTYPE_p_DdNode oldClause = clauseBdd;
clauseBdd = Cudd.Cudd_bddOr( manager, clauseBdd, literal );
Cudd.Cudd_Ref( clauseBdd );
Cudd.Cudd_RecursiveDeref( manager, oldClause );
Cudd.Cudd_RecursiveDeref( manager, literal );
}
SWIGTYPE_p_DdNode oldBdd = bdd;
bdd = Cudd.Cudd_bddAnd( manager, bdd, clauseBdd );
Cudd.Cudd_Ref( bdd );
Cudd.Cudd_RecursiveDeref( manager, oldBdd );
Cudd.Cudd_RecursiveDeref( manager, clauseBdd );
System.out.println( "BDD size: "+Cudd.Cudd_DagSize(bdd) );
}
}
*/
private void createLiterals() {
for( Iterator exprIt = DNode.exprs().iterator(); exprIt.hasNext(); ) {
final BDDExpr expr = (BDDExpr) exprIt.next();
BDDType t = expr.getType();
Map map = t.map();
for( Iterator domainIt = map.keySet().iterator(); domainIt.hasNext(); ) {
final Type domain = (Type) domainIt.next();
Type phys = (Type) map.get(domain);
if( phys != null ) allPhys.add(phys);
}
}
allPhys = new ArrayList(allPhys);
}
public void createDnodeConstraints() {
// Each dnode must be assigned to at least one phys
for( Iterator dnodeIt = repList.iterator(); dnodeIt.hasNext(); ) {
final DNode dnode = (DNode) dnodeIt.next();
Clause clause = new Clause();
if( INCLUDE_COMMENTS ) clause.setComment(
"[PHYS>=1] At least one phys for "+dnode);
+ if( allPhys(dnode).isEmpty() ) {
+ StdErrorQueue seq = new StdErrorQueue( System.err, 0, "" );
+ seq.displayError(
+ new ErrorInfo(ErrorInfo.SEMANTIC_ERROR,
+ "No physical domain for "+dnode.dom,
+ dnode.expr.position()));
+ }
+
for( Iterator physIt = allPhys(dnode).iterator(); physIt.hasNext(); ) {
+
final Type phys = (Type) physIt.next();
clause.add( Literal.v( dnode, phys ) );
}
cnf.add( clause );
}
// Each dnode must be assigned to at most one phys
/*
for( Iterator dnodeIt = repList.iterator(); dnodeIt.hasNext(); ) {
final DNode dnode = (DNode) dnodeIt.next();
for( Iterator physIt = allPhys(dnode).iterator(); physIt.hasNext(); ) {
final Type phys = (Type) physIt.next();
for( Iterator phys2It = allPhys(dnode).iterator(); phys2It.hasNext(); ) {
final Type phys2 = (Type) phys2It.next();
if( phys == phys2 ) continue;
Clause clause = new Clause();
if( INCLUDE_COMMENTS ) clause.setComment(
"[PHYS<=1] At most one phys for "+dnode);
clause.add( NegLiteral.v( dnode, phys ) );
clause.add( NegLiteral.v( dnode, phys2 ) );
cnf.add( clause );
}
}
}
*/
}
public void addMustEqualEdges() {
for( Iterator edgeIt = mustEqualEdges.iterator(); edgeIt.hasNext(); ) {
final DNode[] edge = (DNode[]) edgeIt.next();
edge[0].merge( edge[1] );
}
}
/*
private void addMustEqualEdge( DNode node1, DNode node2 ) {
if( node1 == node2 ) return;
// (xa ==> ya) /\ (ya ==> xa) = (ya \/ ~xa) /\ (xa \/ ~ya)
for( Iterator physIt = allPhys.iterator(); physIt.hasNext(); ) {
final Type phys = (Type) physIt.next();
Clause clause = new Clause();
if( INCLUDE_COMMENTS ) clause.setComment(
"[MUSTEQUAL] Must equal edge between "+node1+" and "+node2+" for "+phys);
clause.add( Literal.v( node1, phys ) );
clause.add( NegLiteral.v( node2, phys ) );
cnf.add( clause );
clause = new Clause();
if( INCLUDE_COMMENTS ) clause.setComment( "[MUSTEQUAL] Must equal edge between "+node1+" and "+node2+" for "+phys);
clause.add( NegLiteral.v( node1, phys ) );
clause.add( Literal.v( node2, phys ) );
cnf.add( clause );
}
}
*/
public void addConflictEdges() {
for( Iterator exprIt = DNode.exprs().iterator(); exprIt.hasNext(); ) {
final BDDExpr expr = (BDDExpr) exprIt.next();
BDDType t = expr.getType();
for( Iterator domainIt = t.map().keySet().iterator(); domainIt.hasNext(); ) {
final Type domain = (Type) domainIt.next();
for( Iterator domain2It = t.map().keySet().iterator(); domain2It.hasNext(); ) {
final Type domain2 = (Type) domain2It.next();
if( domain.equals(domain2) ) continue;
addConflictEdge( DNode.v(expr,domain).rep(), DNode.v(expr,domain2).rep() );
}
}
}
}
static int conflictEdgeCount;
private void addConflictEdge( DNode node1, DNode node2 ) {
// (xa ==> ~ya) /\ (ya ==> ~xa) = (~ya \/ ~xa)
for( Iterator physIt = intersect(allPhys(node1), allPhys(node2)).iterator(); physIt.hasNext(); ) {
final Type phys = (Type) physIt.next();
Clause clause = new Clause(true);
if( INCLUDE_COMMENTS ) clause.setComment(
"[CONFLICT] Conflict edge between "+node1.toLongString()+" and "+node2.toLongString()+" for "+phys);
clause.add( NegLiteral.v( node1, phys ) );
clause.add( NegLiteral.v( node2, phys ) );
cnf.add( clause );
}
conflictEdgeCount++;
}
public static Type updatedPhys(DNode d) {
BDDExpr e = d.expr;
BDDType t = e.getType();
for( Iterator pairIt = t.domainPairs().iterator(); pairIt.hasNext(); ) {
final Type[] pair = (Type[]) pairIt.next();
if( pair[0] == d.dom ) return pair[1];
}
throw new RuntimeException();
}
public static Type phys(DNode d) {
return d.rep().phys;
}
private void computeAdjacencies() {
adjacentCache = new HashMap();
for( Iterator edgeIt = assignEdges.iterator(); edgeIt.hasNext(); ) {
final DNode[] edge = (DNode[]) edgeIt.next();
if( edge[0].rep() == edge[1].rep() ) continue;
addAdjacency(edge[0].rep(), edge[1].rep());
addAdjacency(edge[1].rep(), edge[0].rep());
}
}
private void addAdjacency(DNode src, DNode dst) {
Set dsts = (Set) adjacentCache.get(src);
if( dsts == null ) {
adjacentCache.put(src, dsts = new HashSet());
}
dsts.add(dst);
}
private Map adjacentCache;
public Collection adjacent(DNode d) {
Collection ret = (Collection) adjacentCache.get(d.rep());
if( ret == null ) return Collections.EMPTY_LIST;
return ret;
}
/*
public void addAssignEdges() throws SemanticException {
TreeSet worklist = new TreeSet();
Map pathMap = new HashMap();
// initialize all nodes that have a phys with a path of length 1
for( Iterator nodeIt = repList.iterator(); nodeIt.hasNext(); ) {
final DNode node = (DNode) nodeIt.next();
Set paths = new TreeSet();
pathMap.put( node, paths );
if( phys(node) == null ) continue;
Path path = new Path(node);
paths.add(path);
worklist.add(path);
}
int longest = 0;
// do a BFS, extending paths through the graph
while(!worklist.isEmpty()) {
Path path = (Path) worklist.first();
//if(DEBUG) System.out.println("worklist size: "+worklist.size()+", f: "+first.size()+", l: "+last.size()+", max path length: "+longest+", current: "+path.length );
worklist.remove(path);
if( path.size() > longest ){
longest = path.size();
System.out.println( "length: "+longest+", worklist: "+worklist.size() );
}
DNode node = path.top();
outer:
for( Iterator newNodeIt = adjacent(node).iterator(); newNodeIt.hasNext(); ) {
final DNode newNode = (DNode) newNodeIt.next();
if( newNode.rep() != newNode ) throw new RuntimeException();
if( phys(newNode) != null ) continue;
if( path.contains(newNode) ) continue;
Path newPath = path.add(newNode);
for( Iterator otherIt = ((Set)pathMap.get(newNode)).iterator(); otherIt.hasNext(); ) {
final Path other = (Path) otherIt.next();
if( other.isSubSet(newPath) ) continue outer;
}
worklist.add(newPath);
((Set)pathMap.get(newNode)).add(newPath);
}
}
// now encode paths as constraints
for( Iterator nodeIt = pathMap.keySet().iterator(); nodeIt.hasNext(); ) {
final DNode node = (DNode) nodeIt.next();
if( node.rep() != node ) throw new RuntimeException();
Set paths = (Set) pathMap.get(node);
{
// at least one path must be active for each node
Clause clause = new Clause();
if( INCLUDE_COMMENTS ) clause.setComment("[PATH>=1] At least one path for "+node);
for( Iterator pathIt = paths.iterator(); pathIt.hasNext(); ) {
final Path path = (Path) pathIt.next();
clause.add( SetLit.v( path ) );
}
if( clause.size() == 0 ) {
node.expr.throwSemanticException( "No physical domains reaching domain "+node.dom );
}
cnf.add( clause );
}
{
for( Iterator pathIt = paths.iterator(); pathIt.hasNext(); ) {
final Path path = (Path) pathIt.next();
// all the nodes in the path must have correct phys
Type phys = path.phys();
NegSetLit pathLit = NegSetLit.v(path);
for( Iterator nodeOnPathIt = path.iterator(); nodeOnPathIt.hasNext(); ) {
final DNode nodeOnPath = (DNode) nodeOnPathIt.next();
// a ==> b /\ c /\ d = (b \/ ~a) /\ (c \/ ~a) /\ (d \/ ~a)
Clause clause = new Clause();
if(INCLUDE_COMMENTS) clause.setComment("[NODEONPATH] Node "+nodeOnPath+" to node "+node);
clause.add( pathLit );
clause.add( Literal.v( nodeOnPath, phys ) );
cnf.add(clause);
}
}
}
}
}
*/
static int specifiedAttributes = 0;
/*
public void setupSpecifiedAssignment() {
for( Iterator exprIt = DNode.exprs().iterator(); exprIt.hasNext(); ) {
final BDDExpr expr = (BDDExpr) exprIt.next();
BDDType t = expr.getType();
Map map = t.map();
for( Iterator domainIt = map.keySet().iterator(); domainIt.hasNext(); ) {
final Type domain = (Type) domainIt.next();
Type phys = (Type) map.get(domain);
DNode dnode = DNode.v(expr,domain).rep();
if( phys != null ) {
Clause clause = new Clause();
if(INCLUDE_COMMENTS) clause.setComment("[SPECIFIED] "+dnode+" specified to be "+phys);
clause.add( Literal.v( dnode, phys ) );
if( cnf.add( clause ) ) {;
specifiedAttributes++;
}
}
}
}
}
*/
private Map bitsMap = new HashMap();
/** Make sure that the physical domain to which attribute is assigned has
* at least as many bits as the domain of the attribute. */
private void assigned( Type attribute, Type phys ) throws SemanticException {
FieldDecl domainDecl = ts.getField( (ClassType) attribute, "domain" );
Type domain = domainDecl.declType();
if( !( domain instanceof ClassType ) ) throw new SemanticException(
"Domain of attribute "+attribute+" is not of reference type.",
domainDecl.position() );
FieldDecl attrBits = ts.getField( (ClassType) domain, "bits" );
Expr init = attrBits.init();
if( init == null ) throw new SemanticException(
"Field bits of attribute "+attribute+" has no initializer.",
attrBits.position() );
if( !(init instanceof IntLit) ) throw new SemanticException(
"Initializer of field bits of attribute "+attribute+" is not "+
"an integer literal.", attrBits.position() );
IntLit initLit = (IntLit) init;
int bits = (int) initLit.value();
Integer physBits = (Integer) bitsMap.get( phys );
if( physBits == null || physBits.intValue() < bits ) {
physBits = new Integer( bits );
}
bitsMap.put( phys, physBits );
}
public void recordPhys(Collection jobs) throws SemanticException {
for( Iterator exprIt = DNode.exprs().iterator(); exprIt.hasNext(); ) {
final BDDExpr expr = (BDDExpr) exprIt.next();
BDDType t = expr.getType();
Set usedAlready = new HashSet();
for( Iterator pairIt = t.domainPairs().iterator(); pairIt.hasNext(); ) {
final Type[] pair = (Type[]) pairIt.next();
DNode dnode = DNode.v(expr, pair[0]).rep();
for( Iterator physIt = allPhys(dnode).iterator(); physIt.hasNext(); ) {
final Type phys = (Type) physIt.next();
if( solution.contains( Literal.v(dnode, phys) ) ) {
if( pair[1] != null && pair[1] != phys ) {
throw new RuntimeException( "Sat solver said "+phys+" for node "+dnode+" ("+dnode.domNum+") that already has phys "+pair[1] );
}
pair[1] = phys;
}
}
if( pair[1] == null ) {
throw new RuntimeException( "Sat solver said nothing for node "+dnode );
}
if( !usedAlready.add(pair[1]) ) {
for( Iterator pair2It = t.domainPairs().iterator(); pair2It.hasNext(); ) {
final Type[] pair2 = (Type[]) pair2It.next();
System.out.println( ""+DNode.v(expr, pair2[0])+pair2[1] );
}
throw new RuntimeException( "Sat solver tried to reuse "+pair[1]+" for "+dnode );
}
}
for( Iterator pairIt = t.domainPairs().iterator(); pairIt.hasNext(); ) {
final Type[] pair = (Type[]) pairIt.next();
assigned( pair[0], pair[1] );
}
}
for( Iterator physIt = bitsMap.keySet().iterator(); physIt.hasNext(); ) {
final ClassType phys = (ClassType) physIt.next();
ClassDecl cd = (ClassDecl) ts.instance2Decl().get(phys);
if( cd == null ) throw new SemanticException(
"No class declaration for physical domain "+phys+"." );
ClassBody cb = cd.body();
if( cb == null ) throw new SemanticException(
"No class body for physical domain "+phys+"." );
}
NodeVisitor v = new NodeVisitor() {
public Node leave(Node parent, Node old, Node n, NodeVisitor v) {
if( !( n instanceof ClassDecl ) ) return n;
ClassDecl cd = (ClassDecl) n;
Type t = cd.type();
Integer bits = (Integer) bitsMap.get(t);
if( bits == null ) return n;
Position pos = cd.position();
ClassBody cb = cd.body();
List newMembers = new ArrayList();
for( Iterator memberIt = cb.members().iterator(); memberIt.hasNext(); ) {
final ClassMember member = (ClassMember) memberIt.next();
if( member instanceof MethodDecl) {
MethodDecl md = (MethodDecl) member;
if( md.name().equals( "bits" )
&& md.formals().isEmpty() ) {
md = (MethodDecl) md.body(
nf.Block( pos,
nf.Return( pos,
nf.IntLit( pos,
IntLit.INT,
bits.intValue()))));
newMembers.add( md );
continue;
}
}
newMembers.add( member );
}
return cd.body( cb.members( newMembers ) );
}
};
v.begin();
for( Iterator jobIt = jobs.iterator(); jobIt.hasNext(); ) {
final Job job = (Job) jobIt.next();
Node ast = job.ast();
if( ast != null ) job.ast( ast.visit(v) );
}
v.finish();
}
/*
public void printDomainsRsf() {
try {
PrintWriter file = new PrintWriter(
new FileOutputStream( new File("domainassign.rsf") ) );
int snum = 0;
file.println( "n!type "+(++snum)+"!Root Collapse" );
for( Iterator exprIt = DNode.exprs().iterator(); exprIt.hasNext(); ) {
final BDDExpr expr = (BDDExpr) exprIt.next();
file.println( "n!type "+(++snum)+"!\""+expr+" line="+expr.position().file()+":"+expr.position().line()+"\" Expr" );
file.println( "a!level 1!"+snum+" "+snum+"!Foo" );
for( Iterator dIt = DNode.nodes().iterator(); dIt.hasNext(); ) {
final DNode d = (DNode) dIt.next();
if( d.expr != expr ) continue;
Type phys = (Type) expr.getType().map().get(d.dom);
String phs = phys == null ? "null":phys.toString();
file.println( "n!type "+(d.domNum+1000)+"!\""+d.toShortString()+":"+phs+"\" Dom" );
file.println( "a!level "+snum+"!"+(d.domNum+1000)+" "+(d.domNum+1000)+"!Foo" );
}
}
for( Iterator eIt = mustEqualEdges.iterator(); eIt.hasNext(); ) {
final DNode[] e = (DNode[]) eIt.next();
file.println( "a!MustEqual "+(e[0].domNum+1000)+"!"+(++snum)+" "+(e[1].domNum+1000)+"!Foo" );
}
for( Iterator eIt = assignEdges.iterator(); eIt.hasNext(); ) {
final DNode[] e = (DNode[]) eIt.next();
file.println( "a!Assign "+(e[0].domNum+1000)+"!"+(++snum)+" "+(e[1].domNum+1000)+"!Foo" );
}
file.close();
} catch( IOException e ) {
throw new RuntimeException( e.toString() );
}
}
*/
String dotNodes;
private void makeDotNodes() {
StringBuffer ret = new StringBuffer();
for( Iterator nodeIt = repList.iterator(); nodeIt.hasNext(); ) {
final DNode node = (DNode) nodeIt.next();
if( phys(node) == null ) {
ret.append( " "+node.domNum+" [shape=point];\n" );
} else {
String phys = phys(node).toString();
int i = phys.lastIndexOf(".");
if( i >= 0 ) phys = phys.substring( i+1, phys.length() );
ret.append( " "+node.domNum+" [label=\""+phys+"\"];\n" );
}
}
dotNodes = ret.toString();
}
public void dumpDot() {
try {
PrintWriter file = new PrintWriter(
new FileOutputStream( new File("domainassign.dot") ) );
int snum = 1;
file.println( "graph G {" );
file.println( " size=\"100,75\";" );
file.println( " nodesep=0.2;" );
file.println( " ranksep=1.5;" );
file.println( " mclimit=10;" );
file.println( " nslimit=10;" );
if( dotNodes == null ) makeDotNodes();
file.print( dotNodes );
for( Iterator nodeIt = repList.iterator(); nodeIt.hasNext(); ) {
final DNode node = (DNode) nodeIt.next();
for( Iterator adjIt = adjacent(node).iterator(); adjIt.hasNext(); ) {
final DNode adj = (DNode) adjIt.next();
if( adj.rep() != adj ) continue;
if( node.domNum > adj.domNum ) continue;
file.print( " "+node.domNum+" -- "+adj.domNum+" [" );
if( solution != null ) {
if( updatedPhys(node) != updatedPhys(adj) ) {
file.print( "style=dotted, " );
}
if( solution.contains( ArrowLit.v( node, adj ) ) ) {
file.print( "dir=forward, ");
}
if( solution.contains( ArrowLit.v( adj, node ) ) ) {
file.print( "dir=back, ");
}
}
file.println( "];" );
}
}
file.println( "}" );
file.close();
} catch( IOException e ) {
throw new RuntimeException( e.toString() );
}
}
/*
public void printDomainsDot() {
try {
PrintWriter file = new PrintWriter(
new FileOutputStream( new File("domainassign.dot") ) );
int snum = 1;
file.println( "digraph G {" );
file.println( " size=\"100,75\";" );
file.println( " nodesep=0.2;" );
file.println( " ranksep=1.5;" );
file.println( " mclimit=10;" );
file.println( " nslimit=10;" );
for( Iterator exprIt = DNode.exprs().iterator(); exprIt.hasNext(); ) {
final BDDExpr expr = (BDDExpr) exprIt.next();
file.println( " subgraph cluster"+ snum++ +" {" );
file.println( " label=\""+expr+":"+expr.position().file()+":"+expr.position().line()+"\";" );
BDDType t = expr.getType();
Map map = t.map();
for( Iterator dIt = DNode.nodes().iterator(); dIt.hasNext(); ) {
final DNode d = (DNode) dIt.next();
if( d.expr != expr ) continue;
Type phys = (Type) map.get(d.dom);
String phs = phys == null ? "null":phys.toString();
file.println( " "+d.domNum+" [label=\""+d.toShortString()+":"+phs+"\"];" );
}
file.println( " }" );
}
for( Iterator eIt = mustEqualEdges.iterator(); eIt.hasNext(); ) {
final DNode[] e = (DNode[]) eIt.next();
file.println( " "+e[0].domNum+" -> "+
e[1].domNum+";" );
}
for( Iterator eIt = assignEdges.iterator(); eIt.hasNext(); ) {
final DNode[] e = (DNode[]) eIt.next();
file.println( " "+e[0].domNum+" -> "+
e[1].domNum+" [dir=none];" );
}
file.println( "}" );
file.close();
} catch( IOException e ) {
throw new RuntimeException( e.toString() );
}
}
*/
public void printStats() {
int exprs=0, nodes=0, nonrep=0, nonrepnodes=0;
for( Iterator exprIt = DNode.exprs().iterator(); exprIt.hasNext(); ) {
final BDDExpr expr = (BDDExpr) exprIt.next();
exprs++;
if( !( expr.obj() instanceof FixPhys ) || expr.obj() instanceof Replace ) {
nonrep++;
}
}
int nodesAfterMerging = 0;
for( Iterator nodeIt = DNode.nodes().iterator(); nodeIt.hasNext(); ) {
final DNode node = (DNode) nodeIt.next();
nodes++;
if( !( node.expr.obj() instanceof FixPhys ) || node.expr.obj() instanceof Replace ) {
nonrepnodes++;
}
if( node.rep() == node ) nodesAfterMerging++;
}
if(STATS) System.out.println( "Must equal edges: "+mustEqualEdges.size() );
if(STATS) System.out.println( "Assignment edges: "+assignEdges.size() );
if(STATS) System.out.println( "Conflict edges: "+conflictEdgeCount/2 );
if(STATS) System.out.println( "Expressions: "+exprs );
if(STATS) System.out.println( "Non-replaces: "+nonrep );
if(STATS) System.out.println( "Attributes: "+nodes );
if(STATS) System.out.println( "Attributes after merging: "+nodesAfterMerging );
if(STATS) System.out.println( "Non-rep attributes: "+nonrepnodes );
if(STATS) System.out.println( "Specified attributes: "+specifiedAttributes );
if(STATS) System.out.println( "Physical domains: "+allPhys.size() );
}
static class Edge {
public final DNode src;
public final DNode dst;
public int hashCode() { return src.hashCode()+dst.hashCode(); }
public boolean equals( Object o ) {
Edge other = (Edge) o;
if( src == other.src && dst == other.dst ) return true;
if( src == other.dst && dst == other.src ) return true;
return false;
}
public Edge( DNode src, DNode dst ) {
this.src = src;
this.dst = dst;
}
public String toString() { return ""+src.domNum+" -- "+dst.domNum; }
}
class Bicon {
private Map delta;
private int nextDfsNum;
private LinkedList stack;
private Map back;
private List components;
public List doBicon() {
nextDfsNum = 0;
delta = new HashMap();
stack = new LinkedList();
back = new HashMap();
components = new ArrayList();
for( Iterator nodeIt = repList.iterator(); nodeIt.hasNext(); ) {
final DNode node = (DNode) nodeIt.next();
if( phys(node) != null ) continue;
if( delta.containsKey(node) ) continue;
bicon(node, null);
}
return components;
}
private void bicon( DNode v, DNode parent ) {
delta.put(v, new Integer(nextDfsNum));
back.put(v, new Integer(nextDfsNum));
nextDfsNum++;
for( Iterator wIt = adjacent(v).iterator(); wIt.hasNext(); ) {
final DNode w = (DNode) wIt.next();
if( phys(w) != null ) continue;
if( w.rep() != w ) continue;
if( w == parent ) continue;
Edge e = new Edge(v, w);
if( !delta.containsKey(w) || delta(w) < delta(v) ) {
stack.addLast(e);
}
if( !delta.containsKey(w) ) {
bicon(w, v);
if( back(w) >= delta(v) ) {
Set component = new HashSet();
Edge popped;
do {
popped = (Edge) stack.removeLast();
component.add(popped);
} while( !popped.equals(e) );
components.add(component);
} else {
back.put(v, new Integer(min(back(v), back(w))));
}
} else {
back.put(v, new Integer(min(back(v), delta(w))));
}
}
}
private int delta( DNode n ) {
Integer ret = (Integer) delta.get(n);
return ret.intValue();
}
private int back( DNode n ) {
Integer ret = (Integer) back.get(n);
return ret.intValue();
}
}
private void addDirectionConstraints() {
// No edge can go both ways
// No edge can go out of a phys node
// No more than one edge out of each node
for( Iterator nodeIt = repList.iterator(); nodeIt.hasNext(); ) {
final DNode node = (DNode) nodeIt.next();
Clause atLeastOne = new Clause();
if( INCLUDE_COMMENTS ) atLeastOne.setComment("[>=1 OUT] "+node);
for( Iterator adjIt = adjacent(node).iterator(); adjIt.hasNext(); ) {
final DNode adj = (DNode) adjIt.next();
if( adj.rep() != adj ) continue;
atLeastOne.add( ArrowLit.v( node, adj ) );
Clause cl = new Clause();
if( INCLUDE_COMMENTS )
cl.setComment("[BOTH WAYS] "+node+" <=> "+adj );
cl.add( NegArrowLit.v( node, adj ) );
if( phys(node) == null ) {
cl.add( NegArrowLit.v( adj, node ) );
}
cnf.add(cl);
for( Iterator adj2It = adjacent(node).iterator(); adj2It.hasNext(); ) {
final DNode adj2 = (DNode) adj2It.next();
if( adj2.rep() != adj2 ) continue;
if( adj2 == adj ) continue;
cl = new Clause();
if( INCLUDE_COMMENTS )
cl.setComment("[<=1 OUT] "+node);
cl.add( NegArrowLit.v( node, adj ) );
cl.add( NegArrowLit.v( node, adj2 ) );
cnf.add( cl );
}
}
if( phys(node) == null ) cnf.add(atLeastOne);
}
// Make arrows imply same phys
for( Iterator nodeIt = repList.iterator(); nodeIt.hasNext(); ) {
final DNode node = (DNode) nodeIt.next();
for( Iterator adjIt = adjacent(node).iterator(); adjIt.hasNext(); ) {
final DNode adj = (DNode) adjIt.next();
if( adj.rep() != adj ) continue;
Set nodePhys = allPhys(node);
Set adjPhys = allPhys(adj);
for( Iterator physIt = union(nodePhys, adjPhys).iterator(); physIt.hasNext(); ) {
final Type phys = (Type) physIt.next();
Clause cl = new Clause();
if( INCLUDE_COMMENTS )
cl.setComment("[ARROW=>PHYS] "+node+" => "+adj);
cl.add( NegArrowLit.v(node, adj) );
if( nodePhys.contains(phys) ) cl.add( Literal.v(node, phys) );
if( adjPhys.contains(phys) ) {
cl.add( NegLiteral.v(adj, phys) );
cnf.add(cl);
}
cl = new Clause();
if( INCLUDE_COMMENTS )
cl.setComment("[ARROW=>PHYS] "+node+" => "+adj);
cl.add( NegArrowLit.v(node, adj) );
if( adjPhys.contains(phys) ) cl.add( Literal.v(adj, phys) );
if( nodePhys.contains(phys) ) {
cl.add( NegLiteral.v(node, phys) );
cnf.add(cl);
}
}
}
}
// Handle biconnected components
List components = new Bicon().doBicon();
for( Iterator componentIt = components.iterator(); componentIt.hasNext(); ) {
final Set component = (Set) componentIt.next();
if( component.size() <= 1 ) continue;
if(DEBUG) System.out.println("Biconnected component of size "+component.size());
Set nodes = new HashSet();
for( Iterator eIt = component.iterator(); eIt.hasNext(); ) {
final Edge e = (Edge) eIt.next();
nodes.add( e.src );
nodes.add( e.dst );
Clause cl = new Clause();
if( INCLUDE_COMMENTS )
cl.setComment("[ARROW IMPL ORDER] "+e.src+" => "+e.dst);
cl.add( NegArrowLit.v( e.src, e.dst ) );
cl.add( OrderLit.v( e.src, e.dst ) );
cnf.add(cl);
cl = new Clause();
if( INCLUDE_COMMENTS )
cl.setComment("[ARROW IMPL ORDER] "+e.dst+" => "+e.src);
cl.add( NegArrowLit.v( e.dst, e.src ) );
cl.add( OrderLit.v( e.dst, e.src ) );
cnf.add(cl);
}
for( Iterator nodeIt = nodes.iterator(); nodeIt.hasNext(); ) {
final DNode node = (DNode) nodeIt.next();
for( Iterator adj1It = adjacent(node).iterator(); adj1It.hasNext(); ) {
final DNode adj1 = (DNode) adj1It.next();
if( !nodes.contains(adj1) ) continue;
for( Iterator adj2It = nodes.iterator(); adj2It.hasNext(); ) {
final DNode adj2 = (DNode) adj2It.next();
if( adj2 == adj1 ) continue;
if( adj2 == node ) continue;
Clause cl = new Clause();
if( INCLUDE_COMMENTS )
cl.setComment("[TRIANGLE] "+adj1+" => "+node+" => "+adj2);
cl.add( OrderLit.v( adj1, node ) );
cl.add( OrderLit.v( node, adj2 ) );
cl.add( OrderLit.v( adj2, adj1 ) );
cnf.add(cl);
}
}
}
}
}
static class ArrowLit implements HasNum {
DNode src;
DNode dst;
private ArrowLit( DNode src, DNode dst ) {
if( src.rep() != src ) throw new RuntimeException();
if( dst.rep() != dst ) throw new RuntimeException();
this.src = src.rep();
this.dst = dst.rep();
}
public static ArrowLit v( DNode src, DNode dst ) {
ArrowLit ret = new ArrowLit( src, dst );
ArrowLit ret2 = (ArrowLit) arrMap.get( ret );
if( ret2 == null ) {
arrMap.put( ret2 = ret, ret );
}
return ret2;
}
public boolean equals( Object other ) {
if( !(other instanceof ArrowLit) ) return false;
ArrowLit o = (ArrowLit) other;
if( o.src != src ) return false;
if( o.dst != dst ) return false;
return true;
}
public int hashCode() { return src.hashCode() + dst.hashCode(); }
public int getNum() {
Integer i = (Integer) litNumMap.get(this);
if( i == null ) litNumMap.put( this, i = new Integer(++nextInt) );
return i.intValue();
}
public String toString() {
return Integer.toString(getNum());
}
}
static class NegArrowLit implements HasNum {
ArrowLit lit;
private NegArrowLit( ArrowLit lit ) {
this.lit = lit;
}
private NegArrowLit( DNode src, DNode dst ) {
this( ArrowLit.v( src, dst ) );
}
public static NegArrowLit v( DNode src, DNode dst ) {
NegArrowLit ret = new NegArrowLit( src.rep(), dst.rep() );
NegArrowLit ret2 = (NegArrowLit) arrMap.get( ret );
if( ret2 == null ) {
arrMap.put( ret2 = ret, ret );
}
return ret2;
}
public boolean equals( Object other ) {
if( !(other instanceof NegArrowLit) ) return false;
NegArrowLit o = (NegArrowLit) other;
if( !o.lit.equals(lit) ) return false;
return true;
}
public int hashCode() { return lit.hashCode() + 1; }
public int getNum() {
return -(lit.getNum());
}
public String toString() {
return Integer.toString(getNum());
}
}
static class OrderLit implements HasNum {
DNode src;
DNode dst;
private OrderLit( DNode src, DNode dst ) {
this.src = src.rep();
this.dst = dst.rep();
}
public static OrderLit v( DNode src, DNode dst ) {
OrderLit ret = new OrderLit( src, dst );
OrderLit ret2 = (OrderLit) ordMap.get( ret );
if( ret2 == null ) {
ordMap.put( ret2 = ret, ret );
}
return ret2;
}
public boolean equals( Object other ) {
if( !(other instanceof OrderLit) ) return false;
OrderLit o = (OrderLit) other;
if( o.src != src ) return false;
if( o.dst != dst ) return false;
return true;
}
public int hashCode() { return src.hashCode() + dst.hashCode(); }
public int getNum() {
if( src.domNum > dst.domNum ) return -(OrderLit.v(dst,src).getNum());
Integer i = (Integer) litNumMap.get(this);
if( i == null ) litNumMap.put( this, i = new Integer(++nextInt) );
return i.intValue();
}
public String toString() {
return Integer.toString(getNum());
}
}
public static Map arrMap = new HashMap();
public static Map ordMap = new HashMap();
private int min( int i, int j ) {
if( j < i ) i = j;
return i;
}
private Map phys;
public void findPossiblePhys() {
phys = new HashMap();
LinkedList q = new LinkedList();
for( Iterator nodeIt = repList.iterator(); nodeIt.hasNext(); ) {
final DNode node = (DNode) nodeIt.next();
Set s = new HashSet();
phys.put( node, s );
if( phys(node) != null ) {
s.add(phys(node));
q.add(node);
}
}
while( !q.isEmpty() ) {
DNode node = (DNode) q.removeFirst();
Set nodeSet = allPhys(node);
for( Iterator adjIt = adjacent(node).iterator(); adjIt.hasNext(); ) {
final DNode adj = (DNode) adjIt.next();
if( phys(adj) != null ) continue;
Set adjSet = allPhys(adj);
if( !adjSet.addAll(nodeSet) ) continue;
q.addLast(adj);
}
}
}
private Set intersect( Set s1, Set s2 ) {
Set ret = new HashSet();
ret.addAll( s1 );
ret.retainAll( s2 );
return ret;
}
private Set union( Set s1, Set s2 ) {
Set ret = new HashSet();
ret.addAll( s1 );
ret.addAll( s2 );
return ret;
}
private Set allPhys( DNode node ) {
return (Set) phys.get(node.rep());
}
}
| false | false | null | null |
diff --git a/Framework/java/com/xaf/BuildConfiguration.java b/Framework/java/com/xaf/BuildConfiguration.java
index 491d7634..92314e94 100644
--- a/Framework/java/com/xaf/BuildConfiguration.java
+++ b/Framework/java/com/xaf/BuildConfiguration.java
@@ -1,42 +1,42 @@
package com.xaf;
public class BuildConfiguration
{
public static final String productName = "Sparx";
public static final String productId = "xaf";
public static final int releaseNumber = 1;
public static final int versionMajor = 2;
public static final int versionMinor = 8;
- public static final int buildNumber = 13;
+ public static final int buildNumber = 14;
static public final String getBuildPathPrefix()
{
return productId + "-" + releaseNumber + "_" + versionMajor + "_" + versionMinor + "-" + buildNumber;
}
static public final String getBuildFilePrefix()
{
return productId + "-" + releaseNumber + "_" + versionMajor + "_" + versionMinor;
}
static public final String getVersion()
{
return releaseNumber + "." + versionMajor + "." + versionMinor;
}
static public final String getVersionAndBuild()
{
return "Version " + getVersion() + " Build " + buildNumber;
}
static public final String getProductBuild()
{
return productName + " Version " + getVersion() + " Build " + buildNumber;
}
static public final String getVersionAndBuildShort()
{
return "v" + getVersion() + "b" + buildNumber;
}
}
\ No newline at end of file
| true | false | null | null |
diff --git a/org/xbill/DNS/Address.java b/org/xbill/DNS/Address.java
index de7e4b3..3e0a74f 100644
--- a/org/xbill/DNS/Address.java
+++ b/org/xbill/DNS/Address.java
@@ -1,153 +1,156 @@
// Copyright (c) 1999 Brian Wellington ([email protected])
// Portions Copyright (c) 1999 Network Associates, Inc.
package org.xbill.DNS;
import java.net.*;
/**
* Routines dealing with IP addresses. Includes functions similar to
* those in the java.net.InetAddress class.
*
* @author Brian Wellington
*/
public final class Address {
private
Address() {}
/**
* Convert a string containing an IP address to an array of 4 integers.
* @param s The string
* @return The address
*/
public static int []
toArray(String s) {
int numDigits;
int currentOctet;
int [] values = new int[4];
int length = s.length();
currentOctet = 0;
numDigits = 0;
for (int i = 0; i < length; i++) {
char c = s.charAt(i);
if (c >= '0' && c <= '9') {
/* Can't have more than 3 digits per octet. */
if (numDigits == 3)
return null;
+ /* Octets shouldn't start with 0, unless they are 0. */
+ if (numDigits > 0 && values[currentOctet] == 0)
+ return null;
numDigits++;
values[currentOctet] *= 10;
values[currentOctet] += (c - '0');
/* 255 is the maximum value for an octet. */
if (values[currentOctet] > 255)
return null;
} else if (c == '.') {
/* Can't have more than 3 dots. */
if (currentOctet == 3)
return null;
/* Two consecutive dots are bad. */
if (numDigits == 0)
return null;
currentOctet++;
numDigits = 0;
} else
return null;
}
/* Must have 4 octets. */
if (currentOctet != 3)
return null;
/* The fourth octet can't be empty. */
if (numDigits == 0)
return null;
return values;
}
/**
* Determines if a string contains a valid IP address.
* @param s The string
* @return Whether the string contains a valid IP address
*/
public static boolean
isDottedQuad(String s) {
int [] address = Address.toArray(s);
return (address != null);
}
/**
* Converts a byte array containing an IPv4 address into a dotted quad string.
* @param addr The byte array
* @return The string representation
*/
public static String
toDottedQuad(byte [] addr) {
return ((addr[0] & 0xFF) + "." + (addr[1] & 0xFF) + "." +
(addr[2] & 0xFF) + "." + (addr[3] & 0xFF));
}
private static Record []
lookupHostName(String name) throws UnknownHostException {
try {
Record [] records = new Lookup(name).run();
if (records == null)
throw new UnknownHostException("unknown host");
return records;
}
catch (TextParseException e) {
throw new UnknownHostException("invalid name");
}
}
/**
* Determines the IP address of a host
* @param name The hostname to look up
* @return The first matching IP address
* @exception UnknownHostException The hostname does not have any addresses
*/
public static InetAddress
getByName(String name) throws UnknownHostException {
if (isDottedQuad(name))
return InetAddress.getByName(name);
Record [] records = lookupHostName(name);
ARecord a = (ARecord) records[0];
return a.getAddress();
}
/**
* Determines all IP address of a host
* @param name The hostname to look up
* @return All matching IP addresses
* @exception UnknownHostException The hostname does not have any addresses
*/
public static InetAddress []
getAllByName(String name) throws UnknownHostException {
if (isDottedQuad(name))
return InetAddress.getAllByName(name);
Record [] records = lookupHostName(name);
InetAddress [] addrs = new InetAddress[records.length];
for (int i = 0; i < records.length; i++) {
ARecord a = (ARecord) records[i];
addrs[i] = a.getAddress();
}
return addrs;
}
/**
* Determines the hostname for an address
* @param addr The address to look up
* @return The associated host name
* @exception UnknownHostException There is no hostname for the address
*/
public static String
getHostName(InetAddress addr) throws UnknownHostException {
Name name = ReverseMap.fromAddress(addr);
Record [] records = new Lookup(name, Type.PTR).run();
if (records == null)
throw new UnknownHostException("unknown address");
PTRRecord ptr = (PTRRecord) records[0];
return ptr.getTarget().toString();
}
}
| true | true | public static int []
toArray(String s) {
int numDigits;
int currentOctet;
int [] values = new int[4];
int length = s.length();
currentOctet = 0;
numDigits = 0;
for (int i = 0; i < length; i++) {
char c = s.charAt(i);
if (c >= '0' && c <= '9') {
/* Can't have more than 3 digits per octet. */
if (numDigits == 3)
return null;
numDigits++;
values[currentOctet] *= 10;
values[currentOctet] += (c - '0');
/* 255 is the maximum value for an octet. */
if (values[currentOctet] > 255)
return null;
} else if (c == '.') {
/* Can't have more than 3 dots. */
if (currentOctet == 3)
return null;
/* Two consecutive dots are bad. */
if (numDigits == 0)
return null;
currentOctet++;
numDigits = 0;
} else
return null;
}
/* Must have 4 octets. */
if (currentOctet != 3)
return null;
/* The fourth octet can't be empty. */
if (numDigits == 0)
return null;
return values;
}
| public static int []
toArray(String s) {
int numDigits;
int currentOctet;
int [] values = new int[4];
int length = s.length();
currentOctet = 0;
numDigits = 0;
for (int i = 0; i < length; i++) {
char c = s.charAt(i);
if (c >= '0' && c <= '9') {
/* Can't have more than 3 digits per octet. */
if (numDigits == 3)
return null;
/* Octets shouldn't start with 0, unless they are 0. */
if (numDigits > 0 && values[currentOctet] == 0)
return null;
numDigits++;
values[currentOctet] *= 10;
values[currentOctet] += (c - '0');
/* 255 is the maximum value for an octet. */
if (values[currentOctet] > 255)
return null;
} else if (c == '.') {
/* Can't have more than 3 dots. */
if (currentOctet == 3)
return null;
/* Two consecutive dots are bad. */
if (numDigits == 0)
return null;
currentOctet++;
numDigits = 0;
} else
return null;
}
/* Must have 4 octets. */
if (currentOctet != 3)
return null;
/* The fourth octet can't be empty. */
if (numDigits == 0)
return null;
return values;
}
|
diff --git a/modules/src/main/java/org/archive/modules/fetcher/FetchFTP.java b/modules/src/main/java/org/archive/modules/fetcher/FetchFTP.java
index a10029f4..ee37d5cb 100644
--- a/modules/src/main/java/org/archive/modules/fetcher/FetchFTP.java
+++ b/modules/src/main/java/org/archive/modules/fetcher/FetchFTP.java
@@ -1,548 +1,548 @@
/* FetchFTP.java
*
* $Id$
*
* Created on Jun 5, 2003
*
* Copyright (C) 2003 Internet Archive.
*
* This file is part of the Heritrix web crawler (crawler.archive.org).
*
* Heritrix is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* any later version.
*
* Heritrix is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser Public License for more details.
*
* You should have received a copy of the GNU Lesser Public License
* along with Heritrix; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.archive.modules.fetcher;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.net.URLEncoder;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.httpclient.URIException;
import org.apache.commons.net.ftp.FTPCommand;
import org.archive.io.RecordingInputStream;
import org.archive.io.ReplayCharSequence;
import org.archive.modules.Processor;
import org.archive.modules.ProcessorURI;
import org.archive.modules.extractor.Hop;
import org.archive.modules.extractor.Link;
import org.archive.modules.extractor.LinkContext;
import org.archive.net.ClientFTP;
import org.archive.net.FTPException;
import org.archive.net.UURI;
import org.archive.net.UURIFactory;
import org.archive.util.Recorder;
/**
* Fetches documents and directory listings using FTP. This class will also
* try to extract FTP "links" from directory listings. For this class to
* archive a directory listing, the remote FTP server must support the NLIST
* command. Most modern FTP servers should.
*
* @author pjack
*
*/
public class FetchFTP extends Processor {
private static final long serialVersionUID = 1L;
/** Logger for this class. */
private static Logger logger = Logger.getLogger(FetchFTP.class.getName());
/** Pattern for matching directory entries. */
private static Pattern DIR =
Pattern.compile("(.+)$", Pattern.MULTILINE);
/**
* The username to send to FTP servers. By convention, the default value of
* "anonymous" is used for publicly available FTP sites.
*/
{
setUsername("anonymous");
}
public String getUsername() {
return (String) kp.get("username");
}
public void setUsername(String username) {
kp.put("username",username);
}
/**
* The password to send to FTP servers. By convention, anonymous users send
* their email address in this field.
*/
{
setPassword("password");
}
public String getPassword() {
return (String) kp.get("password");
}
public void setPassword(String pw) {
kp.put("password",pw);
}
/**
* Set to true to extract further URIs from FTP directories. Default is
* true.
*/
{
setExtractFromDirs(true);
}
/**
* Returns the <code>extract.from.dirs</code> attribute for this
* <code>FetchFTP</code> and the given curi.
*
* @param curi the curi whose attribute to return
* @return that curi's <code>extract.from.dirs</code>
*/
public boolean getExtractFromDirs() {
return (Boolean) kp.get("extractFromDirs");
}
public void setExtractFromDirs(boolean extractFromDirs) {
kp.put("extractFromDirs",extractFromDirs);
}
/**
* Set to true to extract the parent URI from all FTP URIs. Default is true.
*/
{
setExtractParent(true);
}
/**
* Returns the <code>extract.parent</code> attribute for this
* <code>FetchFTP</code> and the given curi.
*
* @param curi the curi whose attribute to return
* @return that curi's <code>extract-parent</code>
*/
public boolean getExtractParent() {
return (Boolean) kp.get("extractParent");
}
public void setExtractParent(boolean extractParent) {
kp.put("extractParent",extractParent);
}
/**
* Maximum length in bytes to fetch. Fetch is truncated at this length. A
* value of 0 means no limit.
*/
{
setMaxLengthBytes(0L); // no limit
}
public long getMaxLengthBytes() {
return (Long) kp.get("maxLengthBytes");
}
public void setMaxLengthBytes(long timeout) {
kp.put("maxLengthBytes",timeout);
}
/**
* The maximum KB/sec to use when fetching data from a server. The default
* of 0 means no maximum.
*/
{
setMaxFetchKBSec(0); // no limit
}
public int getMaxFetchKBSec() {
return (Integer) kp.get("maxFetchKBSec");
}
public void setMaxFetchKBSec(int rate) {
kp.put("maxFetchKBSec",rate);
}
/**
* If the fetch is not completed in this number of seconds, give up (and
* retry later).
*/
{
setTimeoutSeconds(20*60); // 20 minutes
}
public int getTimeoutSeconds() {
return (Integer) kp.get("timeoutSeconds");
}
public void setTimeoutSeconds(Integer timeout) {
kp.put("timeoutSeconds",timeout);
}
/**
* Constructs a new <code>FetchFTP</code>.
*/
public FetchFTP() {
}
@Override
protected boolean shouldProcess(ProcessorURI curi) {
if (!curi.getUURI().getScheme().equals("ftp")) {
return false;
}
return true;
}
/**
* Processes the given URI. If the given URI is not an FTP URI, then
* this method does nothing. Otherwise an attempt is made to connect
* to the FTP server.
*
* <p>If the connection is successful, an attempt will be made to CD to
* the path specified in the URI. If the remote CD command succeeds,
* then it is assumed that the URI represents a directory. If the
* CD command fails, then it is assumed that the URI represents
* a file.
*
* <p>For directories, the directory listing will be fetched using
* the FTP LIST command, and saved to the HttpRecorder. If the
* <code>extract.from.dirs</code> attribute is set to true, then
* the files in the fetched list will be added to the curi as
* extracted FTP links. (It was easier to do that here, rather
* than writing a separate FTPExtractor.)
*
* <p>For files, the file will be fetched using the FTP RETR
* command, and saved to the HttpRecorder.
*
* <p>All file transfers (including directory listings) occur using
* Binary mode transfer. Also, the local passive transfer mode
* is always used, to play well with firewalls.
*
* @param curi the curi to process
* @throws InterruptedException if the thread is interrupted during
* processing
*/
@Override
protected void innerProcess(ProcessorURI curi) throws InterruptedException {
curi.setFetchBeginTime(System.currentTimeMillis());
Recorder recorder = curi.getRecorder();
ClientFTP client = new ClientFTP();
try {
fetch(curi, client, recorder);
} catch (FTPException e) {
logger.log(Level.SEVERE, "FTP server reported problem.", e);
curi.setFetchStatus(e.getReplyCode());
} catch (IOException e) {
logger.log(Level.SEVERE, "IO Error during FTP fetch.", e);
curi.setFetchStatus(FetchStatusCodes.S_CONNECT_LOST);
} finally {
disconnect(client);
curi.setContentSize(recorder.getRecordedInput().getSize());
curi.setFetchCompletedTime(System.currentTimeMillis());
}
}
/**
* Fetches a document from an FTP server.
*
* @param curi the URI of the document to fetch
* @param client the FTPClient to use for the fetch
* @param recorder the recorder to preserve the document in
* @throws IOException if a network or protocol error occurs
* @throws InterruptedException if the thread is interrupted
*/
private void fetch(ProcessorURI curi, ClientFTP client, Recorder recorder)
throws IOException, InterruptedException {
// Connect to the FTP server.
UURI uuri = curi.getUURI();
int port = uuri.getPort();
if (port == -1) {
port = 21;
}
client.connectStrict(uuri.getHost(), port);
// Authenticate.
String[] auth = getAuth(curi);
client.loginStrict(auth[0], auth[1]);
// The given resource may or may not be a directory.
// To figure out which is which, execute a CD command to
// the UURI's path. If CD works, it's a directory.
boolean dir = client.changeWorkingDirectory(uuri.getPath());
if (dir) {
curi.setContentType("text/plain");
}
// TODO: A future version of this class could use the system string to
// set up custom directory parsing if the FTP server doesn't support
// the nlist command.
if (logger.isLoggable(Level.FINE)) {
String system = client.getSystemName();
logger.fine(system);
}
// Get a data socket. This will either be the result of a NLIST
// command for a directory, or a RETR command for a file.
int command = dir ? FTPCommand.NLST : FTPCommand.RETR;
String path = dir ? "." : uuri.getPath();
client.enterLocalPassiveMode();
client.setBinary();
Socket socket = client.openDataConnection(command, path);
curi.setFetchStatus(client.getReplyCode());
// Save the streams in the CURI, where downstream processors
// expect to find them.
try {
saveToRecorder(curi, socket, recorder);
} finally {
recorder.close();
close(socket);
}
curi.setFetchStatus(200);
if (dir) {
extract(curi, recorder);
}
addParent(curi);
}
/**
* Saves the given socket to the given recorder.
*
* @param curi the curi that owns the recorder
* @param socket the socket whose streams to save
* @param recorder the recorder to save them to
* @throws IOException if a network or file error occurs
* @throws InterruptedException if the thread is interrupted
*/
private void saveToRecorder(ProcessorURI curi,
Socket socket, Recorder recorder)
throws IOException, InterruptedException {
- recorder.markContentBegin();
recorder.inputWrap(socket.getInputStream());
recorder.outputWrap(socket.getOutputStream());
+ recorder.markContentBegin();
// Read the remote file/dir listing in its entirety.
long softMax = 0;
long hardMax = getMaxLengthBytes();
long timeout = (long)getTimeoutSeconds() * 1000L;
int maxRate = getMaxFetchKBSec();
RecordingInputStream input = recorder.getRecordedInput();
input.setLimits(hardMax, timeout, maxRate);
input.readFullyOrUntil(softMax);
}
/**
* Extract FTP links in a directory listing.
* The listing must already be saved to the given recorder.
*
* @param curi The curi to save extracted links to
* @param recorder The recorder containing the directory listing
*/
private void extract(ProcessorURI curi, Recorder recorder) {
if (!getExtractFromDirs()) {
return;
}
ReplayCharSequence seq = null;
try {
seq = recorder.getReplayCharSequence();
extract(curi, seq);
} catch (IOException e) {
logger.log(Level.SEVERE, "IO error during extraction.", e);
} catch (RuntimeException e) {
logger.log(Level.SEVERE, "IO error during extraction.", e);
} finally {
close(seq);
}
}
/**
* Extracts FTP links in a directory listing.
*
* @param curi The curi to save extracted links to
* @param dir The directory listing to extract links from
* @throws URIException if an extracted link is invalid
*/
private void extract(ProcessorURI curi, ReplayCharSequence dir) {
logger.log(Level.FINEST, "Extracting URIs from FTP directory.");
Matcher matcher = DIR.matcher(dir);
while (matcher.find()) {
String file = matcher.group(1);
addExtracted(curi, file);
}
}
/**
* Adds an extracted filename to the curi. A new URI will be formed
* by taking the given curi (which should represent the directory the
* file lives in) and appending the file.
*
* @param curi the curi to store the discovered link in
* @param file the filename of the discovered link
*/
private void addExtracted(ProcessorURI curi, String file) {
try {
file = URLEncoder.encode(file, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new AssertionError(e);
}
if (logger.isLoggable(Level.FINEST)) {
logger.log(Level.FINEST, "Found " + file);
}
String base = curi.toString();
if (base.endsWith("/")) {
base = base.substring(0, base.length() - 1);
}
try {
UURI n = UURIFactory.getInstance(base + "/" + file);
Link link = new Link(curi.getUURI(), n, LinkContext.NAVLINK_MISC, Hop.NAVLINK);
curi.getOutLinks().add(link);
} catch (URIException e) {
logger.log(Level.WARNING, "URI error during extraction.", e);
}
}
/**
* Extracts the parent URI from the given curi, then adds that parent
* URI as a discovered link to the curi.
*
* <p>If the <code>extract-parent</code> attribute is false, then this
* method does nothing. Also, if the path of the given curi is
* <code>/</code>, then this method does nothing.
*
* <p>Otherwise the parent is determined by eliminated the lowest part
* of the URI's path. Eg, the parent of <code>ftp://foo.com/one/two</code>
* is <code>ftp://foo.com/one</code>.
*
* @param curi the curi whose parent to add
*/
private void addParent(ProcessorURI curi) {
if (!getExtractParent()) {
return;
}
UURI uuri = curi.getUURI();
try {
if (uuri.getPath().equals("/")) {
// There's no parent to add.
return;
}
String scheme = uuri.getScheme();
String auth = uuri.getEscapedAuthority();
String path = uuri.getEscapedCurrentHierPath();
UURI parent = UURIFactory.getInstance(scheme + "://" + auth + path);
Link link = new Link(uuri, parent, LinkContext.NAVLINK_MISC,
Hop.NAVLINK);
curi.getOutLinks().add(link);
} catch (URIException e) {
logger.log(Level.WARNING, "URI error during extraction.", e);
}
}
/**
* Returns the username and password for the given URI. This method
* always returns an array of length 2. The first element in the returned
* array is the username for the URI, and the second element is the
* password.
*
* <p>If the URI itself contains the username and password (i.e., it looks
* like <code>ftp://username:password@host/path</code>) then that username
* and password are returned.
*
* <p>Otherwise the settings system is probed for the <code>username</code>
* and <code>password</code> attributes for this <code>FTPFetch</code>
* and the given <code>curi</code> context. The values of those
* attributes are then returned.
*
* @param curi the curi whose username and password to return
* @return an array containing the username and password
*/
private String[] getAuth(ProcessorURI curi) {
String[] result = new String[2];
UURI uuri = curi.getUURI();
String userinfo;
try {
userinfo = uuri.getUserinfo();
} catch (URIException e) {
assert false;
logger.finest("getUserinfo raised URIException.");
userinfo = null;
}
if (userinfo != null) {
int p = userinfo.indexOf(':');
if (p > 0) {
result[0] = userinfo.substring(0,p);
result[1] = userinfo.substring(p + 1);
return result;
}
}
result[0] = getUsername();
result[1] = getPassword();
return result;
}
/**
* Quietly closes the given socket.
*
* @param socket the socket to close
*/
private static void close(Socket socket) {
try {
socket.close();
} catch (IOException e) {
logger.log(Level.WARNING, "IO error closing socket.", e);
}
}
/**
* Quietly closes the given sequence.
* If an IOException is raised, this method logs it as a warning.
*
* @param seq the sequence to close
*/
private static void close(ReplayCharSequence seq) {
if (seq == null) {
return;
}
try {
seq.close();
} catch (IOException e) {
logger.log(Level.WARNING, "IO error closing ReplayCharSequence.",
e);
}
}
/**
* Quietly disconnects from the given FTP client.
* If an IOException is raised, this method logs it as a warning.
*
* @param client the client to disconnect
*/
private static void disconnect(ClientFTP client) {
if (client.isConnected()) try {
client.disconnect();
} catch (IOException e) {
if (logger.isLoggable(Level.WARNING)) {
logger.warning("Could not disconnect from FTP client: "
+ e.getMessage());
}
}
}
}
| false | false | null | null |
diff --git a/src/main/java/de/danielbechler/diff/accessor/CollectionItemAccessor.java b/src/main/java/de/danielbechler/diff/accessor/CollectionItemAccessor.java
index b5b49fe..3ed0c4c 100644
--- a/src/main/java/de/danielbechler/diff/accessor/CollectionItemAccessor.java
+++ b/src/main/java/de/danielbechler/diff/accessor/CollectionItemAccessor.java
@@ -1,103 +1,103 @@
/*
* Copyright 2012 Daniel Bechler
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.danielbechler.diff.accessor;
import de.danielbechler.diff.path.*;
import java.util.*;
/** @author Daniel Bechler */
public class CollectionItemAccessor extends AbstractAccessor implements TypeAwareAccessor
{
private final Object referenceItem;
public CollectionItemAccessor(final Object referenceItem)
{
this.referenceItem = referenceItem;
}
public Element getPathElement()
{
return new CollectionElement(referenceItem);
}
public void set(final Object target, final Object value)
{
final Collection<Object> targetCollection = objectAsCollection(target);
if (targetCollection == null)
{
return;
}
final Object previous = get(target);
if (previous != null)
{
targetCollection.remove(previous);
}
targetCollection.add(value);
}
public Object get(final Object target)
{
final Collection targetCollection = objectAsCollection(target);
if (targetCollection == null)
{
return null;
}
for (final Object item : targetCollection)
{
- if (item.equals(referenceItem))
+ if (item != null && item.equals(referenceItem))
{
return item;
}
}
return null;
}
public Class<?> getType()
{
return referenceItem != null ? referenceItem.getClass() : null;
}
private static Collection<Object> objectAsCollection(final Object object)
{
if (object == null)
{
return null;
}
else if (object instanceof Collection)
{
//noinspection unchecked
return (Collection<Object>) object;
}
throw new IllegalArgumentException(object.getClass().toString());
}
public void unset(final Object target)
{
final Collection targetCollection = objectAsCollection(target);
if (targetCollection != null)
{
targetCollection.remove(referenceItem);
}
}
@Override
public String toString()
{
return "collection item " + getPathElement();
}
}
diff --git a/src/test/java/de/danielbechler/diff/integration/DeepDiffingCollectionItemChangeIntegrationTest.java b/src/test/java/de/danielbechler/diff/integration/DeepDiffingCollectionItemChangeIntegrationTest.java
index 91d7e25..76db3dc 100644
--- a/src/test/java/de/danielbechler/diff/integration/DeepDiffingCollectionItemChangeIntegrationTest.java
+++ b/src/test/java/de/danielbechler/diff/integration/DeepDiffingCollectionItemChangeIntegrationTest.java
@@ -1,54 +1,60 @@
/*
* Copyright 2012 Daniel Bechler
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.danielbechler.diff.integration;
import de.danielbechler.diff.*;
import de.danielbechler.diff.mock.*;
import de.danielbechler.diff.node.*;
import de.danielbechler.diff.path.*;
import de.danielbechler.diff.visitor.*;
import org.testng.annotations.*;
import java.util.*;
import static de.danielbechler.diff.node.NodeAssertions.*;
/** @author Daniel Bechler */
public class DeepDiffingCollectionItemChangeIntegrationTest
{
@Test
public void test_returns_full_property_graph_of_added_collection_items()
{
final Map<String, ObjectWithString> base = Collections.emptyMap();
final Map<String, ObjectWithString> working = Collections.singletonMap("foo", new ObjectWithString("bar"));
final ObjectDiffer differ = ObjectDifferFactory.getInstance();
differ.getConfiguration().withChildrenOfAddedNodes();
final Node node = differ.compare(working, base);
node.visit(new NodeHierarchyVisitor());
assertThat(node).child(PropertyPath.createBuilder()
.withRoot()
.withMapKey("foo")).hasState(Node.State.ADDED);
assertThat(node).child(PropertyPath.createBuilder()
.withRoot()
.withMapKey("foo")
.withPropertyName("value")).hasState(Node.State.ADDED);
}
+
+ @Test
+ public void test_collection_with_null_item()
+ {
+ ObjectDifferFactory.getInstance().compare(Arrays.asList((String)null), Arrays.asList("foobar"));
+ }
}
| false | false | null | null |
diff --git a/src/test/java/org/basex/test/query/func/FNPatTest.java b/src/test/java/org/basex/test/query/func/FNPatTest.java
new file mode 100644
index 000000000..2364e3e0b
--- /dev/null
+++ b/src/test/java/org/basex/test/query/func/FNPatTest.java
@@ -0,0 +1,22 @@
+package org.basex.test.query.func;
+
+import org.basex.query.util.*;
+import org.basex.test.query.*;
+import org.junit.*;
+
+/**
+ * This class tests the functions of the <code>FNPat</code> class.
+ *
+ * @author BaseX Team 2005-12, BSD License
+ * @author Leo Woerteler
+ */
+public final class FNPatTest extends AdvancedQueryTest {
+ /** Tests for the {@code fn:replate} function. */
+ @Test
+ public void replace() {
+ // tests for issue GH-573:
+ query("replace('aaaa bbbbbbbb ddd ','(.{6,15}) ','$1@')", "aaaa bbbbbbbb@ddd ");
+ query("replace(' aaa AAA 123','(\\s+\\P{Ll}{3,280}?)','$1@')", " aaa AAA@ 123@");
+ error("replace('asdf','a{12,3}','')", Err.REGPAT);
+ }
+}
| true | false | null | null |
diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/EdgeDetectionTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/EdgeDetectionTest.java
index e3933e38f..54cf6dc7b 100644
--- a/tests/gdx-tests/src/com/badlogic/gdx/tests/EdgeDetectionTest.java
+++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/EdgeDetectionTest.java
@@ -1,111 +1,111 @@
package com.badlogic.gdx.tests;
import java.util.Arrays;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.FPSLogger;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Mesh;
import com.badlogic.gdx.graphics.PerspectiveCamera;
import com.badlogic.gdx.graphics.Pixmap.Format;
import com.badlogic.gdx.graphics.Texture.TextureWrap;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.graphics.g3d.loaders.obj.ObjLoader;
import com.badlogic.gdx.graphics.glutils.FrameBuffer;
import com.badlogic.gdx.graphics.glutils.ShaderProgram;
import com.badlogic.gdx.math.Matrix4;
import com.badlogic.gdx.tests.utils.GdxTest;
public class EdgeDetectionTest extends GdxTest {
@Override public boolean needsGL20 () {
return true;
}
FPSLogger logger;
ShaderProgram shader;
Mesh mesh;
FrameBuffer fbo;
PerspectiveCamera cam;
Matrix4 matrix = new Matrix4();
float angle = 0;
TextureRegion fboRegion;
SpriteBatch batch;
ShaderProgram batchShader;
float[] filter = { 0, 0.25f, 0,
0.25f, -1, 0.25f,
0, 0.25f, 0,
};
float[] offsets = new float[18];
public void create() {
ShaderProgram.pedantic = false;
shader = new ShaderProgram(Gdx.files.internal("data/default.vert").readString(),
Gdx.files.internal("data/depthtocolor.frag").readString());
if(!shader.isCompiled()) {
Gdx.app.log("EdgeDetectionTest", "couldn't compile scene shader: " + shader.getLog());
}
batchShader = new ShaderProgram(Gdx.files.internal("data/batch.vert").readString(),
Gdx.files.internal("data/convolution.frag").readString());
if(!batchShader.isCompiled()) {
Gdx.app.log("EdgeDetectionTest", "couldn't compile post-processing shader: " + batchShader.getLog());
}
mesh = ObjLoader.loadObj(Gdx.files.internal("data/scene.obj").read());
fbo = new FrameBuffer(Format.RGB565, Gdx.graphics.getWidth(), Gdx.graphics.getHeight(), true);
cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
cam.position.set(0, 0, 10);
cam.lookAt(0, 0, 0);
cam.far = 30;
batch = new SpriteBatch();
batch.setShader(batchShader);
fboRegion = new TextureRegion(fbo.getColorBufferTexture());
fboRegion.flip(false, true);
logger = new FPSLogger();
calculateOffsets();
}
private void calculateOffsets() {
int idx = 0;
for(int y = -1; y <= 1; y++) {
for(int x = -1; x <= 1; x++) {
offsets[idx++] = x / (float)Gdx.graphics.getWidth();
offsets[idx++] = y / (float)Gdx.graphics.getHeight();
}
}
System.out.println(Arrays.toString(offsets));
}
public void render() {
angle += 45 * Gdx.graphics.getDeltaTime();
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
cam.update();
matrix.setToRotation(0, 1, 0, angle);
cam.combined.mul(matrix);
fbo.begin();
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
Gdx.gl.glEnable(GL20.GL_DEPTH_TEST);
shader.begin();
shader.setUniformMatrix("u_projView", cam.combined);
shader.setUniformf("u_far", cam.far);
mesh.render(shader, GL10.GL_TRIANGLES);
shader.end();
fbo.end();
batch.begin();
batch.disableBlending();
batchShader.setUniformi("u_filterSize", filter.length);
batchShader.setUniform1fv("u_filter", filter, 0, filter.length);
batchShader.setUniform2fv("u_offsets", offsets, 0, offsets.length);
- batch.draw(fboRegion, 0, 0, Gdx.graphics.getWidth() / 2, Gdx.graphics.getHeight() / 2);
+ batch.draw(fboRegion, 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
batch.end();
logger.log();
}
}
| true | true | public void render() {
angle += 45 * Gdx.graphics.getDeltaTime();
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
cam.update();
matrix.setToRotation(0, 1, 0, angle);
cam.combined.mul(matrix);
fbo.begin();
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
Gdx.gl.glEnable(GL20.GL_DEPTH_TEST);
shader.begin();
shader.setUniformMatrix("u_projView", cam.combined);
shader.setUniformf("u_far", cam.far);
mesh.render(shader, GL10.GL_TRIANGLES);
shader.end();
fbo.end();
batch.begin();
batch.disableBlending();
batchShader.setUniformi("u_filterSize", filter.length);
batchShader.setUniform1fv("u_filter", filter, 0, filter.length);
batchShader.setUniform2fv("u_offsets", offsets, 0, offsets.length);
batch.draw(fboRegion, 0, 0, Gdx.graphics.getWidth() / 2, Gdx.graphics.getHeight() / 2);
batch.end();
logger.log();
}
| public void render() {
angle += 45 * Gdx.graphics.getDeltaTime();
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
cam.update();
matrix.setToRotation(0, 1, 0, angle);
cam.combined.mul(matrix);
fbo.begin();
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
Gdx.gl.glEnable(GL20.GL_DEPTH_TEST);
shader.begin();
shader.setUniformMatrix("u_projView", cam.combined);
shader.setUniformf("u_far", cam.far);
mesh.render(shader, GL10.GL_TRIANGLES);
shader.end();
fbo.end();
batch.begin();
batch.disableBlending();
batchShader.setUniformi("u_filterSize", filter.length);
batchShader.setUniform1fv("u_filter", filter, 0, filter.length);
batchShader.setUniform2fv("u_offsets", offsets, 0, offsets.length);
batch.draw(fboRegion, 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
batch.end();
logger.log();
}
|
diff --git a/src/net/sf/freecol/FreeCol.java b/src/net/sf/freecol/FreeCol.java
index d01653e1b..5ef074d62 100644
--- a/src/net/sf/freecol/FreeCol.java
+++ b/src/net/sf/freecol/FreeCol.java
@@ -1,904 +1,907 @@
/**
* Copyright (C) 2002-2007 The FreeCol Team
*
* This file is part of FreeCol.
*
* FreeCol is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* FreeCol is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with FreeCol. If not, see <http://www.gnu.org/licenses/>.
*/
package net.sf.freecol;
import java.awt.Dimension;
import java.awt.GraphicsEnvironment;
import java.awt.Image;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.Thread.UncaughtExceptionHandler;
import java.util.Locale;
import java.util.jar.Attributes;
import java.util.jar.Manifest;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JWindow;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.events.XMLEvent;
import net.sf.freecol.client.ClientOptions;
import net.sf.freecol.client.FreeColClient;
import net.sf.freecol.client.gui.ImageLibrary;
import net.sf.freecol.client.gui.i18n.Messages;
import net.sf.freecol.client.gui.plaf.FreeColLookAndFeel;
import net.sf.freecol.client.gui.sound.MusicLibrary;
import net.sf.freecol.client.gui.sound.SfxLibrary;
import net.sf.freecol.common.FreeColException;
import net.sf.freecol.common.Specification;
import net.sf.freecol.common.io.FreeColDataFile;
import net.sf.freecol.common.io.FreeColSavegameFile;
import net.sf.freecol.common.io.FreeColTcFile;
import net.sf.freecol.common.logging.DefaultHandler;
import net.sf.freecol.common.networking.NoRouteToServerException;
import net.sf.freecol.common.option.LanguageOption;
import net.sf.freecol.common.resources.ResourceManager;
import net.sf.freecol.common.util.XMLStream;
import net.sf.freecol.server.FreeColServer;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.cli.PosixParser;
/**
* This class is responsible for handling the command-line arguments
* and starting either the stand-alone server or the client-GUI.
*
* @see net.sf.freecol.client.FreeColClient FreeColClient
* @see net.sf.freecol.server.FreeColServer FreeColServer
*/
public final class FreeCol {
public static final String META_SERVER_ADDRESS = "meta.freecol.org";
public static final int META_SERVER_PORT = 3540;
public static final String CLIENT_THREAD = "FreeColClient:";
public static final String SERVER_THREAD = "FreeColServer:";
public static final String METASERVER_THREAD = "FreeColMetaServer:";
/**
* The space not being used in windowed mode.
*/
private static final int DEFAULT_WINDOW_SPACE = 100;
private static final Logger logger = Logger.getLogger(FreeCol.class.getName());
private static final String FREECOL_VERSION = "0.9.0-svn";
private static String FREECOL_REVISION;
private static final String MIN_JDK_VERSION = "1.5";
private static final String FILE_SEP = System.getProperty("file.separator");
private static final String DEFAULT_SPLASH_FILE = "splash.jpg";
private static final String DEFAULT_TC = "freecol";
private static boolean windowed = false,
sound = true,
javaCheck = true,
memoryCheck = true,
consoleLogging = false;
private static Dimension windowSize = new Dimension(-1, -1);
private static String dataFolder = "data" + FILE_SEP;
private static FreeColClient freeColClient;
private static boolean standAloneServer = false;
private static boolean publicServer = true;
private static boolean inDebugMode = false;
private static boolean usesExperimentalAI = false;
private static int serverPort;
private static String serverName = null;
private static final int DEFAULT_PORT = 3541;
private static File mainUserDirectory;
private static File saveDirectory;
private static File tcUserDirectory;
private static String tc = DEFAULT_TC;
private static File savegameFile = null;
private static File clientOptionsFile = null;
private static Level logLevel = Level.INFO;
private static boolean checkIntegrity = false;
private static final Options options = new Options();
private static String splashFilename = DEFAULT_SPLASH_FILE;
private static boolean displaySplash = false;
private FreeCol() {
// Hide constructor
}
/**
* The entrypoint.
*
* @param args The command-line arguments.
*/
public static void main(String[] args) {
try {
Manifest manifest = new Manifest(FreeCol.class.getResourceAsStream("/META-INF/MANIFEST.MF"));
Attributes attribs = manifest.getMainAttributes();
String revision = attribs.getValue("Revision");
FREECOL_REVISION = FREECOL_VERSION + " (Revision: " + revision + ")";
} catch (Exception e) {
System.out.println("Unable to load Manifest.");
FREECOL_REVISION = FREECOL_VERSION;
}
// parse command line arguments
handleArgs(args);
// Display splash screen:
final JWindow splash = (displaySplash) ? displaySplash(splashFilename) : null;
createAndSetDirectories();
initLogging();
Locale.setDefault(getLocale());
if (javaCheck && !checkJavaVersion()) {
removeSplash(splash);
System.err.println("Java version " + MIN_JDK_VERSION +
" or better is recommended in order to run FreeCol." +
" Use --no-java-check to skip this check.");
System.exit(1);
}
int minMemory = 128; // million bytes
if (memoryCheck && Runtime.getRuntime().maxMemory() < minMemory * 1000000) {
removeSplash(splash);
System.out.println("You need to assign more memory to the JVM. Restart FreeCol with:");
System.out.println("java -Xmx" + minMemory + "M -jar FreeCol.jar");
System.exit(1);
}
if (!initializeResourceFolders()) {
removeSplash(splash);
System.exit(1);
}
if (standAloneServer) {
logger.info("Starting stand-alone server.");
try {
final FreeColServer freeColServer;
if (savegameFile != null) {
XMLStream xs = null;
try {
// Get suggestions for "singleplayer" and "public game" settings from the file:
final FreeColSavegameFile fis = new FreeColSavegameFile(savegameFile);
xs = FreeColServer.createXMLStreamReader(fis);
final XMLStreamReader in = xs.getXMLStreamReader();
in.nextTag();
final boolean defaultSingleplayer = Boolean.valueOf(in.getAttributeValue(null, "singleplayer")).booleanValue();
final boolean defaultPublicServer;
final String publicServerStr = in.getAttributeValue(null, "publicServer");
if (publicServerStr != null) {
defaultPublicServer = Boolean.valueOf(publicServerStr).booleanValue();
} else {
defaultPublicServer = false;
}
xs.close();
freeColServer = new FreeColServer(fis, defaultPublicServer, defaultSingleplayer, serverPort, serverName);
} catch (Exception e) {
removeSplash(splash);
System.out.println("Could not load savegame.");
System.exit(1);
return;
} finally {
xs.close();
}
} else {
try {
freeColServer = new FreeColServer(publicServer, false, serverPort, serverName);
} catch (NoRouteToServerException e) {
removeSplash(splash);
System.out.println(Messages.message("server.noRouteToServer"));
System.exit(1);
return;
}
}
Runtime runtime = Runtime.getRuntime();
runtime.addShutdownHook(new Thread() {
public void run() {
freeColServer.getController().shutdown();
}
});
if (checkIntegrity) {
System.exit((freeColServer.getIntegrity())
? 0 : 1);
}
} catch (IOException e) {
removeSplash(splash);
System.err.println("Error while loading server: " + e);
System.exit(1);
}
} else {
final Rectangle bounds = GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds();
if (windowSize.width == -1 || windowSize.height == -1) {
// Allow room for frame handles, taskbar etc if using windowed mode:
windowSize.width = bounds.width - DEFAULT_WINDOW_SPACE;
windowSize.height = bounds.height - DEFAULT_WINDOW_SPACE;
}
final Dimension preloadSize;
if (windowed) {
preloadSize = windowSize;
} else {
preloadSize = new Dimension(bounds.width, bounds.height);
}
try {
UIManager.setLookAndFeel(new FreeColLookAndFeel(dataFolder, preloadSize));
} catch (UnsupportedLookAndFeelException e) {
logger.warning("Could not load the \"FreeCol Look and Feel\"");
} catch (FreeColException e) {
removeSplash(splash);
e.printStackTrace();
System.out.println("\nThe data files could not be found by FreeCol. Please make sure");
System.out.println("they are present. If FreeCol is looking in the wrong directory");
System.out.println("then run the game with a command-line parameter:");
System.out.println("");
printUsage();
System.exit(1);
}
// TODO: don't use same datafolder for both images and
// music because the images are best kept inside the .JAR
// file.
logger.info("Now starting to load images.");
ImageLibrary lib;
try {
lib = new ImageLibrary(dataFolder);
} catch (FreeColException e) {
removeSplash(splash);
e.printStackTrace();
System.out.println("\nThe data files could not be found by FreeCol. Please make sure");
System.out.println("they are present. If FreeCol is looking in the wrong directory");
System.out.println("then run the game with a command-line parameter:");
System.out.println("");
printUsage();
System.exit(1);
return;
}
MusicLibrary musicLibrary = null;
SfxLibrary sfxLibrary = null;
if (sound) {
try {
musicLibrary = new MusicLibrary(dataFolder);
} catch (FreeColException e) {
System.out.println("The music files could not be loaded by FreeCol. Disabling music.");
}
try {
sfxLibrary = new SfxLibrary(dataFolder);
} catch (FreeColException e) {
System.out.println("The sfx files could not be loaded by FreeCol. Disabling sfx.");
}
}
freeColClient = new FreeColClient(windowed, preloadSize, lib, musicLibrary, sfxLibrary);
if (savegameFile != null) {
final FreeColClient theFreeColClient = freeColClient;
final File theSavegameFile = savegameFile;
SwingUtilities.invokeLater(new Runnable() {
public void run() {
theFreeColClient.getConnectController().loadGame(theSavegameFile);
}
});
}
}
removeSplash(splash);
}
/**
* Displays a splash screen.
* @return The splash screen. It should be removed by the caller
* when no longer needed by a call to removeSplash().
*/
private static JWindow displaySplash(String filename) {
try {
Image im = Toolkit.getDefaultToolkit().getImage(filename);
JWindow f = new JWindow();
f.getContentPane().add(new JLabel(new ImageIcon(im)));
f.pack();
Point center = GraphicsEnvironment.getLocalGraphicsEnvironment().getCenterPoint();
f.setLocation(center.x - f.getWidth() / 2, center.y - f.getHeight() / 2);
f.setVisible(true);
return f;
} catch (Exception e) {
logger.log(Level.WARNING, "Exception while displaying splash screen", e);
return null;
}
}
/**
* Removes splash screen.
*/
private static void removeSplash(JWindow splash) {
if (splash != null) {
splash.setVisible(false);
splash.dispose();
}
}
/**
* Initialize loggers.
*/
private static void initLogging() {
final Logger baseLogger = Logger.getLogger("");
final Handler[] handlers = baseLogger.getHandlers();
for (int i = 0; i < handlers.length; i++) {
baseLogger.removeHandler(handlers[i]);
}
try {
baseLogger.addHandler(new DefaultHandler(consoleLogging, mainUserDirectory));
if (inDebugMode) {
logLevel = Level.FINEST;
}
Logger freecolLogger = Logger.getLogger("net.sf.freecol");
freecolLogger.setLevel(logLevel);
} catch (FreeColException e) {
e.printStackTrace();
}
Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {
public void uncaughtException(Thread thread, Throwable e) {
baseLogger.log(Level.WARNING, "Uncaught exception from thread: " + thread, e);
}
});
}
/**
* Determines the <code>Locale</code> to be used.
* @return Currently this method returns the locale set by
* the ClientOptions (read directly from "options.xml").
* This behavior will probably be changed.
*/
public static Locale getLocale() {
XMLInputFactory xif = XMLInputFactory.newInstance();
XMLStreamReader in = null;
try {
in = xif.createXMLStreamReader(new FileInputStream(getClientOptionsFile()), "UTF-8");
in.nextTag();
/**
* The following code was contributed by armcode to fix
* bug #[ 2045521 ] "Exception in Freecol.log on starting
* game". I was never able to reproduce the bug, but the
* patch did no harm either.
*/
for(int eventid = in.getEventType();eventid != XMLEvent.END_DOCUMENT; eventid = in.getEventType()) {
//TODO: Is checking for XMLEvent.ATTRIBUTE needed?
if(eventid == XMLEvent.START_ELEMENT) {
if (ClientOptions.LANGUAGE.equals(in.getAttributeValue(null, "id"))) {
return LanguageOption.getLocale(in.getAttributeValue(null, "value"));
}
}
in.nextTag();
}
//We don't have a language option in our file, it is either not there or the file is corrupt
logger.log(Level.WARNING, "Language setting not found in client options file. Using default.");
return Locale.getDefault();
} catch (Exception e) {
logger.log(Level.WARNING, "Exception while loading options.", e);
return Locale.getDefault();
} finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e) {
logger.log(Level.WARNING, "Exception while closing stream.", e);
return Locale.getDefault();
}
}
}
/**
* Returns the default server network port.
* @return The port number.
*/
public static int getDefaultPort() {
return DEFAULT_PORT;
}
/**
* Returns the file containing the client options.
* @return The file.
*/
public static File getClientOptionsFile() {
return clientOptionsFile;
}
/**
* Returns the specification object for Freecol.
*
* @return the specification to be used by all other classes.
*/
public static Specification getSpecification() {
return Specification.getSpecification();
}
/**
* Gets the <code>FreeColClient</code>.
* @return The <code>FreeColClient</code>, or <code>null</code>
* if the game is run as a standalone server.
*/
public static FreeColClient getFreeColClient() {
return freeColClient;
}
/**
* Creates a freecol dir for the current user.
*
* The directory is created within the current user's
* home directory. This directory will be called "freecol"
* and underneath that directory a "save" directory will
* be created.
*/
private static File createAndSetDirectories() {
// TODO: The location of the save directory should be determined by the installer.;
String freeColDirectoryName = "/".equals(System.getProperty("file.separator")) ?
".freecol" : "freecol";
if (mainUserDirectory == null) {
mainUserDirectory = new File(System.getProperty("user.home"), freeColDirectoryName);
}
if (mainUserDirectory.exists()) {
if (mainUserDirectory.isFile()) {
System.out.println("Could not create " + freeColDirectoryName + " under "
+ System.getProperty("user.home") + " because there "
+ "already exists a regular file with the same name.");
return null;
}
} else {
mainUserDirectory.mkdir();
}
if (saveDirectory == null) {
saveDirectory = new File(mainUserDirectory, "save");
}
if (saveDirectory.exists()) {
if (saveDirectory.isFile()) {
System.out.println("Could not create freecol/save under "
+ System.getProperty("user.home") + " because there "
+ "already exists a regular file with the same name.");
return null;
}
} else {
saveDirectory.mkdir();
}
tcUserDirectory = new File(mainUserDirectory, tc);
if (tcUserDirectory.exists()) {
if (tcUserDirectory.isFile()) {
System.out.println("Could not create freecol/" + tc + " under "
+ System.getProperty("user.home") + " because there "
+ "already exists a regular file with the same name.");
return null;
}
} else {
tcUserDirectory.mkdir();
}
clientOptionsFile = new File(tcUserDirectory, "options.xml");
return mainUserDirectory;
}
/**
* Set up the save file and directory
* @param name the name of the save file to use
*/
private static void setSavegame(String name) {
+ if(name == null){
+ System.out.println("No savegame given with --load-savegame parameter");
+ System.exit(1);
+ }
+
savegameFile = new File(name);
if (!savegameFile.exists() || !savegameFile.isFile()) {
savegameFile = new File(getSaveDirectory(), name);
if (!savegameFile.exists() || !savegameFile.isFile()) {
System.out.println("Could not find savegame file: " + name);
System.exit(1);
}
} else {
setSaveDirectory(savegameFile.getParentFile());
}
}
/**
* Returns the directory where the savegames should be put.
* @return The directory where the savegames should be put.
*/
public static File getSaveDirectory() {
return saveDirectory;
}
/**
* Set the directory where the savegames should be put.
* @param saveDirectory a <code>File</code> value for the savegame directory
*/
public static void setSaveDirectory(File saveDirectory) {
FreeCol.saveDirectory = saveDirectory;
}
/**
* Returns the data directory.
* @return The directory where the data files are located.
*/
public static File getDataDirectory() {
if (dataFolder.equals("")) {
return new File("data");
} else {
return new File(dataFolder);
}
}
/**
* Returns the mods directory.
* @return The directory where the mods are located.
*/
public static File getModsDirectory() {
return new File(getDataDirectory(), "mods");
}
/**
* Returns the directory where the autogenerated savegames
* should be put.
*
* @return The directory.
*/
public static File getAutosaveDirectory() {
return saveDirectory;
}
public static boolean initializeResourceFolders() {
FreeColDataFile baseData = new FreeColDataFile(new File(dataFolder, "base"));
ResourceManager.setBaseMapping(baseData.getResourceMapping());
final FreeColTcFile tcData = new FreeColTcFile(tc);
ResourceManager.setTcMapping(tcData.getResourceMapping());
// This needs to be initialized before ImageLibrary
InputStream si = null;
try {
si = tcData.getSpecificationInputStream();
Specification.createSpecification(si);
} catch (IOException e) {
System.err.println("Could not load specification.xml for: " + tc);
return false;
} finally {
try {
si.close();
} catch (Exception e) {}
}
return true;
}
/**
* Ensure that the Java version is good enough. JDK 1.4 or better is
* required.
*
* @return true if Java version is at least 1.5.0.
*/
private static boolean checkJavaVersion() {
// Must use string comparison because some JVM's provide
// versions like "1.4.1"
String version = System.getProperty("java.version");
boolean success = (version.compareTo(MIN_JDK_VERSION) >= 0);
return success;
}
/**
* Checks the command-line arguments and takes appropriate actions
* for each of them.
*
* @param args The command-line arguments.
*/
private static void handleArgs(String[] args) {
// create the command line parser
CommandLineParser parser = new PosixParser();
// create the Options
options.addOption(OptionBuilder.withLongOpt("freecol-data")
.withDescription(Messages.message("cli.freecol-data"))
.withArgName(Messages.message("cli.arg.directory"))
.hasArg()
.create());
options.addOption(OptionBuilder.withLongOpt("tc")
.withDescription(Messages.message("cli.tc"))
.withArgName(Messages.message("cli.arg.name"))
.hasArg()
.create());
options.addOption(OptionBuilder.withLongOpt("home-directory")
.withDescription(Messages.message("cli.home-directory"))
.withArgName(Messages.message("cli.arg.directory"))
.withType(new File("dummy"))
.hasArg()
.create());
options.addOption(OptionBuilder.withLongOpt("log-console")
.withDescription(Messages.message("cli.log-console"))
.create());
options.addOption(OptionBuilder.withLongOpt("log-level")
.withDescription(Messages.message("cli.log-level"))
.withArgName(Messages.message("cli.arg.loglevel"))
.hasArg()
.create());
options.addOption(OptionBuilder.withLongOpt("no-java-check")
.withDescription(Messages.message("cli.no-java-check"))
.create());
options.addOption(OptionBuilder.withLongOpt("windowed")
.withDescription(Messages.message("cli.windowed"))
.withArgName(Messages.message("cli.arg.dimensions"))
.hasOptionalArg()
.create());
options.addOption(OptionBuilder.withLongOpt("default-locale")
.withDescription(Messages.message("cli.default-locale"))
.withArgName(Messages.message("cli.arg.locale"))
.hasArg()
.create());
options.addOption(OptionBuilder.withLongOpt("no-memory-check")
.withDescription(Messages.message("cli.no-memory-check"))
.create());
options.addOption(OptionBuilder.withLongOpt("no-sound")
.withDescription(Messages.message("cli.no-sound"))
.create());
options.addOption(OptionBuilder.withLongOpt("usage")
.withDescription(Messages.message("cli.help"))
.create());
options.addOption(OptionBuilder.withLongOpt("help")
.withDescription(Messages.message("cli.help"))
.create());
options.addOption(OptionBuilder.withLongOpt("version")
.withDescription(Messages.message("cli.version"))
.create());
options.addOption(OptionBuilder.withLongOpt("debug")
.withDescription(Messages.message("cli.debug"))
.create());
options.addOption(OptionBuilder.withLongOpt("private")
.withDescription(Messages.message("cli.private"))
.create());
options.addOption(OptionBuilder.withLongOpt("server")
.withDescription(Messages.message("cli.server"))
.withArgName(Messages.message("cli.arg.port"))
.hasOptionalArg()
.create());
options.addOption(OptionBuilder.withLongOpt("load-savegame")
.withDescription(Messages.message("cli.load-savegame"))
.withArgName(Messages.message("cli.arg.file"))
.hasArg()
.create());
options.addOption(OptionBuilder.withLongOpt("server-name")
.withDescription(Messages.message("cli.server-name"))
.withArgName(Messages.message("cli.arg.name"))
.hasArg()
.create());
options.addOption(OptionBuilder.withLongOpt("splash")
.withDescription(Messages.message("cli.splash"))
.withArgName(Messages.message("cli.arg.file"))
.hasOptionalArg()
.create());
options.addOption(OptionBuilder.withLongOpt("check-savegame")
.withDescription(Messages.message("cli.check-savegame"))
- .withArgName(Messages.message("cli.arg.file"))
- .hasArg()
.create());
// TODO: remove option when AI is no longer experimental
options.addOption(OptionBuilder.withLongOpt("experimentalAI")
.withDescription(Messages.message("cli.experimentalAI"))
.create());
try {
// parse the command line arguments
CommandLine line = parser.parse(options, args);
if (line.hasOption("splash")) {
displaySplash = true;
final String str = line.getOptionValue("splash");
if (str != null) {
splashFilename = str;
}
}
if (line.hasOption("freecol-data")) {
dataFolder = line.getOptionValue("freecol-data");
if (!dataFolder.endsWith(FILE_SEP)) {
dataFolder += FILE_SEP;
}
}
if (line.hasOption("tc")) {
tc = line.getOptionValue("tc");
}
if (line.hasOption("home-directory")) {
mainUserDirectory = (File) line.getOptionObject("home-directory");
}
if (line.hasOption("log-console")) {
consoleLogging = true;
initLogging();
}
if (line.hasOption("log-level")) {
String logLevelString = line.getOptionValue("log-level").toUpperCase();
try {
logLevel = Level.parse(logLevelString);
initLogging();
} catch (IllegalArgumentException e) {
printUsage();
System.exit(1);
}
}
if (line.hasOption("no-java-check")) {
javaCheck = false;
}
if (line.hasOption("windowed")) {
windowed = true;
String dimensions = line.getOptionValue("windowed");
if (dimensions != null) {
String[] xy = dimensions.split("[^0-9]");
if (xy.length == 2) {
windowSize = new Dimension(Integer.parseInt(xy[0]), Integer.parseInt(xy[1]));
} else {
printUsage();
System.exit(1);
}
}
}
if (line.hasOption("default-locale")) {
// slightly ugly: strip encoding from LC_MESSAGES
String languageID = line.getOptionValue("default-locale");
int index = languageID.indexOf('.');
if (index > 0) {
languageID = languageID.substring(0, index);
}
Locale.setDefault(LanguageOption.getLocale(languageID));
}
if (line.hasOption("no-sound")) {
sound = false;
}
if (line.hasOption("no-memory-check")) {
memoryCheck = false;
}
if (line.hasOption("help") || line.hasOption("usage")) {
printUsage();
System.exit(0);
}
if (line.hasOption("version")) {
System.out.println("FreeCol " + getVersion());
System.exit(0);
}
if (line.hasOption("debug")) {
inDebugMode = true;
}
if (line.hasOption("server")) {
standAloneServer = true;
String arg = line.getOptionValue("server");
try {
serverPort = Integer.parseInt(arg);
} catch (NumberFormatException nfe) {
System.out.println(Messages.message("cli.error.port", "%string%", arg));
System.exit(1);
}
}
if (line.hasOption("private")) {
publicServer = false;
}
if (line.hasOption("check-savegame")) {
setSavegame(line.getOptionValue("load-savegame"));
checkIntegrity = true;
standAloneServer = true;
serverPort = DEFAULT_PORT;
}
if (line.hasOption("load-savegame")) {
setSavegame(line.getOptionValue("load-savegame"));
}
if (line.hasOption("server-name")) {
serverName = line.getOptionValue("server-name");
}
} catch(ParseException e) {
System.out.println("\n" + e.getMessage() + "\n");
printUsage();
System.exit(1);
}
}
private static void printUsage() {
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("java -Xmx 128M -jar freecol.jar [OPTIONS]", options);
}
/**
* Gets the current version of game.
*
* @return The current version of the game using the format "x.y.z",
* where "x" is major, "y" is minor and "z" is revision.
*/
public static String getVersion() {
return FREECOL_VERSION;
}
/**
* Gets the current revision of game.
*
* @return The current version and SVN Revision of the game.
*/
public static String getRevision() {
return FREECOL_REVISION;
}
/**
* Checks if the program is in "Debug mode".
* @return <code>true</code> if the program is in debug
* mode and <code>false</code> otherwise.
*/
public static boolean isInDebugMode() {
return inDebugMode;
}
/**
* Sets the "debug mode" to be active or not.
* @param debug Should be <code>true</code> in order
* to active debug mode and <code>false</code>
* otherwise.
*/
public static void setInDebugMode(boolean debug) {
inDebugMode = debug;
}
/**
* Checks if the program is in "Experimental AI mode".
* @return <code>true</code> if the program is in Experimental AI
* mode and <code>false</code> otherwise.
*/
public static boolean usesExperimentalAI() {
return usesExperimentalAI;
}
}
| false | false | null | null |
diff --git a/Arkiv/src/com/eprog/arkiv/ArkivActivity.java b/Arkiv/src/com/eprog/arkiv/ArkivActivity.java
index 5dcfc17..b6071f6 100644
--- a/Arkiv/src/com/eprog/arkiv/ArkivActivity.java
+++ b/Arkiv/src/com/eprog/arkiv/ArkivActivity.java
@@ -1,481 +1,488 @@
package com.eprog.arkiv;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.hardware.Camera;
import android.hardware.Camera.AutoFocusCallback;
import android.hardware.Camera.Parameters;
import android.hardware.Camera.PictureCallback;
import android.hardware.Camera.ShutterCallback;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.provider.MediaStore.Images;
import android.text.Editable;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class ArkivActivity extends Activity implements SurfaceHolder.Callback {
private static final int SELECT_PROGRAM = 0;
private static final int SELECT_FROM_ARCHIVE = 1;
private Camera camera = null;
private String folder = null;
private String category = null;
private String filename = null;
private Uri selectedImageUri;
private ImageView imageView;
private SharedPreferences settings;
SurfaceView surface = null;
private SurfaceHolder holder = null;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
settings = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
// Boolean onTop = settings.getBoolean("PREF_BUTTONS_ON_TOP", true);
// if (onTop) {
// setContentView(R.layout.main);
// } else {
// setContentView(R.layout.main2);
// }
// Create folders
createFolder(getResources().getString(R.string.folderIntyg));
createFolder(getResources().getString(R.string.folderLedighet));
createFolder(getResources().getString(R.string.folderKvitto));
createFolder(getResources().getString(R.string.folderFaktura));
createFolder(getResources().getString(R.string.folderOther));
// surface = (SurfaceView)findViewById(R.id.surface);
// holder = surface.getHolder();
// holder.addCallback(this);
// holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
// holder.setFixedSize(300, 200);
}
@Override
protected void onPause() {
Log.d("Arkiv", "onPause()");
super.onPause();
deactivateCamera();
holder.removeCallback(this);
surface = null;
// TODO Save folder, path and filename, reinitiate them in onResume()
}
@Override
protected void onResume() {
Log.d("Arkiv", "onResume()");
super.onResume();
Boolean statusbar = settings.getBoolean("PREF_STATUS_BAR", true);
if (statusbar) {
WindowManager.LayoutParams attrs = getWindow().getAttributes();
attrs.flags &= ~WindowManager.LayoutParams.FLAG_FULLSCREEN;
getWindow().setAttributes(attrs);
} else {
WindowManager.LayoutParams attrs = getWindow().getAttributes();
attrs.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
getWindow().setAttributes(attrs);
}
surface = (SurfaceView)findViewById(R.id.surface);
holder = surface.getHolder();
holder.addCallback(this);
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
holder.setFixedSize(300, 200);
// Boolean onTop = settings.getBoolean("PREF_BUTTONS_ON_TOP", true);
// if (onTop) {
// setContentView(R.layout.main);
// } else {
// setContentView(R.layout.main2);
// }
// Show help dialog on first start
if (settings.getBoolean(Settings.PREF_FIRST_START, true)) {
Editor editor = settings.edit();
editor.putBoolean(Settings.PREF_FIRST_START, false);
editor.commit();
showHelpDialog();
}
}
- private void createFolder(String path) {
+ private boolean createFolder(String path) {
File folder = new File(path);
boolean success = false;
if(!folder.exists())
{
success = folder.mkdirs();
}
+ return success;
}
public void clickHandler(View view) {
switch (view.getId()) {
case R.id.buttonIntyg:
takePicture(getResources().getString(R.string.folderIntyg), getResources().getString(R.string.buttonIntyg));
break;
case R.id.buttonLedighet:
takePicture(getResources().getString(R.string.folderLedighet), getResources().getString(R.string.buttonLedighet));
break;
case R.id.buttonKvitto:
takePicture(getResources().getString(R.string.folderKvitto), getResources().getString(R.string.buttonKvitto));
break;
case R.id.buttonFaktura:
takePicture(getResources().getString(R.string.folderFaktura), getResources().getString(R.string.buttonFaktura));
break;
case R.id.buttonOther:
takePicture(getResources().getString(R.string.folderOther), getResources().getString(R.string.buttonOther));
break;
case R.id.buttonLog:
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, getResources().getString(R.string.chooserTitle)), SELECT_FROM_ARCHIVE);
break;
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK) {
// Operation was cancelled, reactivate camera if needed
activateCamera(holder);
return;
}
Bitmap bitmap = null;
String path = "";
if (requestCode == SELECT_FROM_ARCHIVE) {
selectedImageUri = data.getData();
path = getRealPathFromURI(selectedImageUri); //from Gallery
if (path == null)
path = selectedImageUri.getPath(); //from File Manager
if (path != null)
bitmap = BitmapFactory.decodeFile(path);
}
imageView.setImageBitmap(bitmap);
}
public String getRealPathFromURI(Uri contentUri) {
String [] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = managedQuery( contentUri, proj, null, null,null);
if (cursor == null) {
return null;
}
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
private void activateCamera(SurfaceHolder holder) {
Log.d("Arkiv", "activateCamera() camera = " + camera);
if (camera != null) {
deactivateCamera();
}
try {
camera = Camera.open();
camera.setPreviewDisplay(holder);
Display display = ((WindowManager) getApplicationContext().getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
int rotation = display.getRotation();
if (rotation == 0) {
camera.setDisplayOrientation(90);
} else {
camera.setDisplayOrientation(0);
}
Parameters params = camera.getParameters();
params.setFlashMode(Camera.Parameters.FLASH_MODE_AUTO);
params.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
params.setJpegQuality(60);
camera.setParameters(params);
camera.startPreview();
} catch (IOException e) {
Log.d("Arkiv", e.getMessage());
deactivateCamera();
}
}
private void deactivateCamera() {
if (camera != null) {
camera.stopPreview();
camera.release();
camera = null;
}
}
private void takePicture(String folder, String category) {
Log.d("Arkiv", "takePicture()");
this.folder = folder;
this.category = category;
if (camera != null) {
// int sdk = android.os.Build.VERSION.SDK_INT;
// if (sdk > 10) {
// camera.takePicture(shutterCallback, rawCallback, jpegCallback); // TODO Remove this special case when AutoFocus works on X10 mini with ICS.
// } else {
camera.autoFocus(new AutoFocusCallback() {
public void onAutoFocus(boolean success, Camera camera) {
Log.d("Arkiv", "onAutoFocus()");
if (success) {
camera.takePicture(shutterCallback, rawCallback, jpegCallback);
} else {
// Inform user that the camera could not focus.
Toast toast = Toast.makeText(getApplicationContext(), R.string.noFocus, Toast.LENGTH_SHORT);
toast.show();
}
}
});
// }
}
}
ShutterCallback shutterCallback = new ShutterCallback() {
public void onShutter() {
}
};
PictureCallback rawCallback = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
}
};
PictureCallback jpegCallback = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd_HHmmss");
String formattedDate = df.format(c.getTime());
filename = category + formattedDate + ".jpg";
// Save the image to the right folder on the SD card
FileOutputStream outStream = null;
try {
outStream = new FileOutputStream(folder + "/" + filename);
outStream.write(data);
outStream.close();
} catch (FileNotFoundException e) {
Log.d("onPictureTaken", e.getMessage());
+ Toast toast = Toast.makeText(getApplicationContext(), R.string.unableToSaveImage, Toast.LENGTH_LONG);
+ toast.show();
+ return;
} catch (IOException e) {
Log.d("onPictureTaken", e.getMessage());
+ Toast toast = Toast.makeText(getApplicationContext(), R.string.unableToSaveImage, Toast.LENGTH_LONG);
+ toast.show();
+ return;
}
// Insert image into Media Store
ContentValues content = new ContentValues(1);
content.put(Images.Media.MIME_TYPE, "image/jpg");
content.put(MediaStore.Images.Media.DATA, folder + "/" + filename);
ContentResolver resolver = getContentResolver();
Uri uri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, content);
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
// Check if subcategory dialog shall be shown
Boolean subCategories = settings.getBoolean("PREF_SUB_CATEGORIES", false);
if (subCategories) {
showSubCategoryDialog();
} else {
sendMail(category, folder, filename);
camera.startPreview(); // TODO Is this needed?
}
}
};
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
Log.d("Arkiv", "surfaceChanged()");
}
public void surfaceCreated(SurfaceHolder holder) {
Log.d("Arkiv", "surfaceCreated()");
activateCamera(holder);
}
public void surfaceDestroyed(SurfaceHolder holder) {
Log.d("Arkiv", "surfaceDestroyed()");
deactivateCamera();
}
private void sendMail(String type, String folder, String filename) {
if (filename == null) {
Log.d("Arkiv", "sendMail(): filename == null");
return;
}
// Check if mail shall be sent
Boolean sendMail = settings.getBoolean("PREF_SEND_MAIL", false);
String emailAddress = settings.getString("PREF_EMAIL_ADDRESS", null);
if (!sendMail || emailAddress == null) {
return;
}
// Get sub-category
String sub = settings.getString(Settings.PREF_SELCETED_SUB_CATEGORY, "");
Uri uri = Uri.fromFile(new File(folder, filename));
Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, getResources().getString(R.string.emailBody));
if (sub != null && !sub.equals("")) {
sendIntent.putExtra(Intent.EXTRA_SUBJECT, "[" + type + "] [" + sub + "] " + filename);
} else {
sendIntent.putExtra(Intent.EXTRA_SUBJECT, "[" + type + "] " + filename);
}
sendIntent.putExtra(Intent.EXTRA_EMAIL,
new String[] { emailAddress });
sendIntent.putExtra(Intent.EXTRA_STREAM, uri);
sendIntent.setType("plain/txt");
startActivityForResult(Intent.createChooser(sendIntent, getResources().getString(R.string.chooserTitle)), SELECT_PROGRAM);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.arkiv_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menuPreferences:
startActivity(new Intent(this, Settings.class));
break;
case R.id.menuHelp:
{
showHelpDialog();
}
break;
case R.id.menuAbout:
{
AlertDialog aboutDialog = new AlertDialog.Builder(this).create();
Window w = aboutDialog.getWindow();
w.setFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND, WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
aboutDialog.setTitle(R.string.aboutTitle);
aboutDialog.setMessage(getResources().getText(R.string.aboutText));
aboutDialog.show();
}
break;
}
return true;
}
private void showHelpDialog() {
AlertDialog helpDialog = new AlertDialog.Builder(this).create();
Window w = helpDialog.getWindow();
w.setFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND, WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
helpDialog.setTitle(R.string.helpTitle);
helpDialog.setMessage(getResources().getText(R.string.helpText));
helpDialog.show();
}
private View dialoglayout = null;
private void showSubCategoryDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.subCategoryTitle);
LayoutInflater inflater = getLayoutInflater();
dialoglayout = inflater.inflate(R.layout.subcategory, (ViewGroup) getCurrentFocus());
builder.setView(dialoglayout);
AlertDialog dialog = builder.create();
Window w = dialog.getWindow();
w.setFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND, WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
TextView text = (TextView)dialoglayout.findViewById(R.id.subCategoryDescription);
text.setText(R.string.subCategoryText);
Spinner spinCategory = (Spinner) dialoglayout.findViewById(R.id.subCategorySpinner);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
int count = settings.getInt(Settings.PREF_CATEGORY1_SUB_COUNT, 0);
for (int i = 0; i < count; i++) {
adapter.add(settings.getString(Settings.PREF_CATEGORY1_SUB + i, ""));
}
spinCategory.setAdapter(adapter);
builder.setPositiveButton("OK", new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Editor editor = settings.edit();
// Get sub-category
EditText text = (EditText)dialoglayout.findViewById(R.id.editSubCategory);
Editable newCategory = text.getText();
if (newCategory.length() > 0) {
editor.putString(Settings.PREF_SELCETED_SUB_CATEGORY, newCategory.toString());
// Save new category
int count = settings.getInt(Settings.PREF_CATEGORY1_SUB_COUNT, 0);
editor.putString(Settings.PREF_CATEGORY1_SUB + count, newCategory.toString());
editor.putInt(Settings.PREF_CATEGORY1_SUB_COUNT, count + 1);
} else {
Spinner spinCategory = (Spinner) dialoglayout.findViewById(R.id.subCategorySpinner);
editor.putString(Settings.PREF_SELCETED_SUB_CATEGORY, (String) spinCategory.getSelectedItem());
}
editor.commit();
sendMail(category, folder, filename);
camera.startPreview(); // TODO Is this needed?
}
});
builder.show();
}
}
\ No newline at end of file
diff --git a/Arkiv/src/com/eprog/arkiv/SendActivity.java b/Arkiv/src/com/eprog/arkiv/SendActivity.java
index 16222ae..1cb9e9a 100644
--- a/Arkiv/src/com/eprog/arkiv/SendActivity.java
+++ b/Arkiv/src/com/eprog/arkiv/SendActivity.java
@@ -1,305 +1,291 @@
package com.eprog.arkiv;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
-import java.net.MalformedURLException;
-import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.DialogInterface;
+import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences;
-import android.content.DialogInterface.OnClickListener;
import android.content.SharedPreferences.Editor;
-import android.graphics.Bitmap;
-import android.graphics.BitmapFactory;
-import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.provider.MediaStore.Images;
import android.text.Editable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.EditText;
-import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
public class SendActivity extends Activity {
private static final int SELECT_PROGRAM = 0;
private SharedPreferences settings;
private Uri uri = null;
private String category = null;
- private String filename = null;
private String folder = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.send);
settings = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
Intent intent = getIntent();
Bundle extras = intent.getExtras();
String action = intent.getAction();
// if this is from the share menu
if (Intent.ACTION_SEND.equals(action))
{
if (extras.containsKey(Intent.EXTRA_STREAM))
{
try
{
// Get resource path from intent
uri = (Uri) extras.getParcelable(Intent.EXTRA_STREAM);
// TODO show image in the ImageView
//ImageView imageView = (ImageView)findViewById(R.id.sendImageView);
return;
} catch (Exception e)
{
Log.e(this.getClass().getName(), e.toString());
}
}
}
}
- private void setImageURI(Uri uri2) {
- // TODO Auto-generated method stub
-
- }
-
@Override
protected void onPause() {
super.onPause();
}
@Override
protected void onResume() {
super.onResume();
}
public void clickHandler(View view) {
// Check if subcategory dialog shall be shown
Boolean subCategories = settings.getBoolean("PREF_SUB_CATEGORIES", false);
switch (view.getId()) {
case R.id.buttonIntyg:
if (subCategories) {
folder = getResources().getString(R.string.folderIntyg);
category = getResources().getString(R.string.buttonIntyg);
showSubCategoryDialog();
} else {
copyAndSendMail(getResources().getString(R.string.folderIntyg), getResources().getString(R.string.buttonIntyg));
}
break;
case R.id.buttonLedighet:
if (subCategories) {
folder = getResources().getString(R.string.folderLedighet);
category = getResources().getString(R.string.buttonLedighet);
showSubCategoryDialog();
} else {
copyAndSendMail(getResources().getString(R.string.folderLedighet), getResources().getString(R.string.buttonLedighet));
}
break;
case R.id.buttonKvitto:
if (subCategories) {
folder = getResources().getString(R.string.folderKvitto);
category = getResources().getString(R.string.buttonKvitto);
showSubCategoryDialog();
} else {
copyAndSendMail(getResources().getString(R.string.folderKvitto), getResources().getString(R.string.buttonKvitto));
}
break;
case R.id.buttonFaktura:
if (subCategories) {
folder = getResources().getString(R.string.folderFaktura);
category = getResources().getString(R.string.buttonFaktura);
showSubCategoryDialog();
} else {
copyAndSendMail(getResources().getString(R.string.folderFaktura), getResources().getString(R.string.buttonFaktura));
}
break;
case R.id.buttonOther:
if (subCategories) {
folder = getResources().getString(R.string.folderOther);
category = getResources().getString(R.string.buttonOther);
showSubCategoryDialog();
} else {
copyAndSendMail(getResources().getString(R.string.folderOther), getResources().getString(R.string.buttonOther));
}
break;
}
}
private void copyAndSendMail(String folder, String type) {
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd_HHmmss");
String formattedDate = df.format(c.getTime());
String filename = type + formattedDate + ".jpg";
// Copy image to archive folder
ContentResolver cr = getContentResolver();
InputStream is = null;
try {
is = cr.openInputStream(uri);
} catch (FileNotFoundException e1) {
Log.d("Arkiv", e1.toString());
}
// Get binary bytes for encode
byte[] data = null;
try {
data = getBytesFromFile(is);
} catch (IOException e1) {
Log.d("Arkiv", e1.toString());
}
// Save the image to the right folder on the SD card
FileOutputStream outStream = null;
try {
outStream = new FileOutputStream(folder + "/" + filename);
outStream.write(data);
outStream.close();
} catch (FileNotFoundException e) {
Log.d("Arkiv", e.getMessage());
} catch (IOException e) {
Log.d("Arkiv", e.getMessage());
}
// Insert image into Media Store
ContentValues content = new ContentValues(1);
content.put(Images.Media.MIME_TYPE, "image/jpg");
content.put(MediaStore.Images.Media.DATA, folder + "/" + filename);
ContentResolver resolver = getContentResolver();
Uri uri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, content);
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
// Check if mail shall be sent
Boolean sendMail = settings.getBoolean("PREF_SEND_MAIL", false);
String emailAddress = settings.getString("PREF_EMAIL_ADDRESS", null);
if (!sendMail || emailAddress == null) {
return;
}
// Get sub-category
String sub = settings.getString(Settings.PREF_SELCETED_SUB_CATEGORY, "");
Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, getResources().getString(R.string.emailBody));
if (sub != null && !sub.equals("")) {
sendIntent.putExtra(Intent.EXTRA_SUBJECT, "[" + type + "] [" + sub + "] " + filename);
} else {
sendIntent.putExtra(Intent.EXTRA_SUBJECT, "[" + type + "] " + filename);
}
sendIntent.putExtra(Intent.EXTRA_EMAIL,
new String[] { emailAddress });
sendIntent.putExtra(Intent.EXTRA_STREAM, uri);
sendIntent.setType("plain/txt");
startActivityForResult(Intent.createChooser(sendIntent, getResources().getString(R.string.chooserTitle)), SELECT_PROGRAM);
finish();
}
private static byte[] getBytesFromFile(InputStream ios) throws IOException {
ByteArrayOutputStream ous = null;
try {
byte[] buffer = new byte[4096];
ous = new ByteArrayOutputStream();
int read = 0;
while ((read = ios.read(buffer)) != -1) {
ous.write(buffer, 0, read);
}
} finally {
try {
if (ous != null)
ous.close();
} catch (IOException e) {
// swallow, since not that important
}
try {
if (ios != null)
ios.close();
} catch (IOException e) {
// swallow, since not that important
}
}
return ous.toByteArray();
}
private View dialoglayout = null;
private void showSubCategoryDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.subCategoryTitle);
LayoutInflater inflater = getLayoutInflater();
dialoglayout = inflater.inflate(R.layout.subcategory, (ViewGroup) getCurrentFocus());
builder.setView(dialoglayout);
AlertDialog dialog = builder.create();
Window w = dialog.getWindow();
w.setFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND, WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
TextView text = (TextView)dialoglayout.findViewById(R.id.subCategoryDescription);
text.setText(R.string.subCategoryText);
Spinner spinCategory = (Spinner) dialoglayout.findViewById(R.id.subCategorySpinner);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
int count = settings.getInt(Settings.PREF_CATEGORY1_SUB_COUNT, 0);
for (int i = 0; i < count; i++) {
adapter.add(settings.getString(Settings.PREF_CATEGORY1_SUB + i, ""));
}
spinCategory.setAdapter(adapter);
builder.setPositiveButton("OK", new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Editor editor = settings.edit();
// Get sub-category
EditText text = (EditText)dialoglayout.findViewById(R.id.editSubCategory);
Editable newCategory = text.getText();
if (newCategory.length() > 0) {
editor.putString(Settings.PREF_SELCETED_SUB_CATEGORY, newCategory.toString());
// Save new category
int count = settings.getInt(Settings.PREF_CATEGORY1_SUB_COUNT, 0);
editor.putString(Settings.PREF_CATEGORY1_SUB + count, newCategory.toString());
editor.putInt(Settings.PREF_CATEGORY1_SUB_COUNT, count + 1);
} else {
Spinner spinCategory = (Spinner) dialoglayout.findViewById(R.id.subCategorySpinner);
editor.putString(Settings.PREF_SELCETED_SUB_CATEGORY, (String) spinCategory.getSelectedItem());
}
editor.commit();
copyAndSendMail(folder, category);
-// sendMail(folder, dirPath, filename);
-// camera.startPreview(); // TODO Is this needed?
}
});
builder.show();
}
}
| false | false | null | null |
diff --git a/src/DVN-ingest/src/edu/harvard/iq/dvn/ingest/statdataio/impl/plugins/sav/SAVFileReader.java b/src/DVN-ingest/src/edu/harvard/iq/dvn/ingest/statdataio/impl/plugins/sav/SAVFileReader.java
index bfdc0f660..0778cb5f0 100644
--- a/src/DVN-ingest/src/edu/harvard/iq/dvn/ingest/statdataio/impl/plugins/sav/SAVFileReader.java
+++ b/src/DVN-ingest/src/edu/harvard/iq/dvn/ingest/statdataio/impl/plugins/sav/SAVFileReader.java
@@ -1,3687 +1,3692 @@
/*
Copyright (C) 2005-2012, by the President and Fellows of Harvard College.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Dataverse Network - A web application to share, preserve and analyze research data.
Developed at the Institute for Quantitative Social Science, Harvard University.
Version 3.0.
*/
package edu.harvard.iq.dvn.ingest.statdataio.impl.plugins.sav;
import java.io.*;
import java.nio.*;
import java.nio.channels.*;
import java.security.NoSuchAlgorithmException;
import java.util.logging.*;
import java.util.*;
import java.lang.reflect.*;
import java.util.regex.*;
import org.apache.commons.lang.builder.*;
import org.apache.commons.io.*;
import org.apache.commons.io.input.*;
import org.apache.commons.lang.*;
import edu.harvard.iq.dvn.ingest.org.thedata.statdataio.*;
import edu.harvard.iq.dvn.ingest.org.thedata.statdataio.spi.*;
import edu.harvard.iq.dvn.ingest.org.thedata.statdataio.metadata.*;
import edu.harvard.iq.dvn.ingest.org.thedata.statdataio.data.*;
import edu.harvard.iq.dvn.unf.*;
import edu.harvard.iq.dvn.ingest.statdataio.impl.plugins.util.*;
import java.text.*;
import org.apache.commons.codec.binary.Hex;
/**
* A DVN-Project-implementation of <code>StatDataFileReader</code> for the
* SPSS System file (SAV) format.
*
* @author Akio Sone at UNC-Odum
*/
public class SAVFileReader extends StatDataFileReader{
// static fields ---------------------------------------------------------//
private static String[] FORMAT_NAMES = {"sav", "SAV"};
private static String[] EXTENSIONS = {"sav"};
private static String[] MIME_TYPE = {"application/x-spss-sav"};
// constants (static final) variables ---------------------------------------------------------//
// block length
// RecordType 1
private static final int LENGTH_SAV_INT_BLOCK = 4;
// note: OBS block is either double or String, not Integer
private static final int LENGTH_SAV_OBS_BLOCK = 8;
private static final int SAV_MAGIC_NUMBER_LENGTH = LENGTH_SAV_INT_BLOCK;
private static String SAV_FILE_SIGNATURE = "$FL2";
// Record Type 1 fields
private static final int LENGTH_RECORDTYPE1 = 172;
private static final int LENGTH_SPSS_PRODUCT_INFO = 60;
private static final int FILE_LAYOUT_CONSTANT = 2;
private static final int LENGTH_FILE_LAYOUT_CODE = LENGTH_SAV_INT_BLOCK;
private static final int LENGTH_NUMBER_OF_OBS_UNITS_PER_CASE = LENGTH_SAV_INT_BLOCK;
private static final int LENGTH_COMPRESSION_SWITCH = LENGTH_SAV_INT_BLOCK;
private static final int LENGTH_CASE_WEIGHT_VARIABLE_INDEX = LENGTH_SAV_INT_BLOCK;
private static final int LENGTH_NUMBER_OF_CASES = LENGTH_SAV_INT_BLOCK;
private static final int LENGTH_COMPRESSION_BIAS = LENGTH_SAV_OBS_BLOCK;
private static final int LENGTH_FILE_CREATION_INFO = 84;
private static final int length_file_creation_date = 9;
private static final int length_file_creation_time = 8;
private static final int length_file_creation_label= 64;
private static final int length_file_creation_padding = 3;
// Recorde Type 2
private static final int LENGTH_RECORDTYPE2_FIXED = 32;
private static final int LENGTH_RECORD_TYPE2_CODE = 4;
private static final int LENGTH_TYPE_CODE = 4;
private static final int LENGTH_LABEL_FOLLOWS = 4;
private static final int LENGTH_MISS_VALUE_FORMAT_CODE= 4;
private static final int LENGTH_PRINT_FORMAT_CODE = 4;;
private static final int LENGTH_WRITE_FORMAT_CODE = 4;
private static final int LENGTH_VARIABLE_NAME = 8;
private static final int LENGTH_VARIABLE_LABEL= 4;
private static final int LENGTH_MISS_VAL_OBS_CODE = LENGTH_SAV_OBS_BLOCK;
// Record Type 3/4
private static final int LENGTH_RECORDTYPE3_HEADER_CODE = 4;
private static final int LENGTH_RECORD_TYPE3_CODE = 4;
private static final int LENGTH_RT3_HOW_MANY_LABELS = 4;
private static final int LENGTH_RT3_VALUE = LENGTH_SAV_OBS_BLOCK;
private static final int LENGTH_RT3_LABEL_LENGTH =1;
private static final int LENGTH_RECORD_TYPE4_CODE = 4;
private static final int LENGTH_RT4_HOW_MANY_VARIABLES = 4;
private static final int LENGTH_RT4_VARIABLE_INDEX = 4;
// Record Type 6
private static final int LENGTH_RECORD_TYPE6_CODE = 4;
private static final int LENGTH_RT6_HOW_MANY_LINES = 4;
private static final int LENGTH_RT6_DOCUMENT_LINE = 80;
// Record Type 7
private static final int LENGTH_RECORD_TYPE7_CODE = 4;
private static final int LENGTH_RT7_SUB_TYPE_CODE = 4;
// Record Type 999
private static final int LENGTH_RECORD_TYPE999_CODE = 4;
private static final int LENGTH_RT999_FILLER = 4;
private static final List<String> RecordType7SubType4Fields= new ArrayList<String>();
private static final Set<Integer> validMissingValueCodeSet = new HashSet<Integer>();
private static final Map<Integer, Integer> missingValueCodeUnits = new HashMap<Integer, Integer>();
private static String unfVersionNumber = "5";
private static double SYSMIS_LITTLE =0xFFFFFFFFFFFFEFFFL;
private static double SYSMIS_BIG =0xFFEFFFFFFFFFFFFFL;
private static Calendar GCO = new GregorianCalendar();
static {
// initialize validMissingValueCodeSet
validMissingValueCodeSet.add(3);
validMissingValueCodeSet.add(2);
validMissingValueCodeSet.add(1);
validMissingValueCodeSet.add(0);
validMissingValueCodeSet.add(-2);
validMissingValueCodeSet.add(-3);
// initialize missingValueCodeUnits
missingValueCodeUnits.put(1, 1);
missingValueCodeUnits.put(2, 2);
missingValueCodeUnits.put(3, 3);
missingValueCodeUnits.put(-2,2);
missingValueCodeUnits.put(-3, 3);
missingValueCodeUnits.put(0, 0);
RecordType7SubType4Fields.add("SYSMIS");
RecordType7SubType4Fields.add("HIGHEST");
RecordType7SubType4Fields.add("LOWEST");
// set the origin of GCO to 1582-10-15
GCO.set(1, 1582);// year
GCO.set(2, 9); // month
GCO.set(5, 15);// day of month
GCO.set(9, 0);// AM(0) or PM(1)
GCO.set(10, 0);// hh
GCO.set(12, 0);// mm
GCO.set(13, 0);// ss
GCO.set(14, 0); // SS millisecond
GCO.set(15, 0);// z
}
private static final long SPSS_DATE_BIAS = 60*60*24*1000;
private static final long SPSS_DATE_OFFSET = SPSS_DATE_BIAS + Math.abs(GCO.getTimeInMillis());
// instance fields -------------------------------------------------------//
private static Logger dbgLog =
Logger.getLogger(SAVFileReader.class.getPackage().getName());
SDIOMetadata smd = new SAVMetadata();
SDIOData sdiodata;
DataTable savDataSection = new DataTable();
// global variables -------------------------------------------------------//
int caseQnty=0;
int varQnty=0;
private boolean isLittleEndian = false;
private boolean isDataSectionCompressed = true;
private Map<Integer, String> OBSIndexToVariableName =
new LinkedHashMap<Integer, String>();
private int OBSUnitsPerCase;
private List<Integer> variableTypelList= new ArrayList<Integer>();
private List<Integer> OBSwiseTypelList= new ArrayList<Integer>();
Map<String, String> printFormatTable = new LinkedHashMap<String, String>();
Map<String, String> printFormatNameTable = new LinkedHashMap<String, String>();
Set<Integer> obsNonVariableBlockSet = new LinkedHashSet<Integer>();
Map<String, String> valueVariableMappingTable = new LinkedHashMap<String, String>();
Map<String, Integer> extendedVariablesSizeTable = new LinkedHashMap<String, Integer>();
List<String> variableNameList = new ArrayList<String>();
Map<String, InvalidData> invalidDataTable = new LinkedHashMap<String, InvalidData>(); // this variable used in 2 methods; only one uses it to set the smd value -- ??
NumberFormat doubleNumberFormatter = new DecimalFormat();
Set<Integer> decimalVariableSet = new HashSet<Integer>();
int[] variableTypeFinal= null;
String[] variableFormatTypeList= null;
List<Integer> formatDecimalPointPositionList= new ArrayList<Integer>();
Object[][] dataTable2 = null;
// Used to store the date format string for all date types
// the format string is passed to the UNF calculator
String[][] dateFormats = null;
int caseWeightVariableOBSIndex = 0;
// date/time data formats
private SimpleDateFormat sdf_ymd = new SimpleDateFormat("yyyy-MM-dd");
private SimpleDateFormat sdf_ymdhms = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
private SimpleDateFormat sdf_dhms = new SimpleDateFormat("DDD HH:mm:ss");
private SimpleDateFormat sdf_hms = new SimpleDateFormat("HH:mm:ss");
Map<String, String> OBSTypeHexValue = new LinkedHashMap<String, String>();
/* We should be defaulting to ISO-Latin, NOT US-ASCII! -- L.A. */
private String defaultCharSet = "ISO-8859-1";
private int spssVersionNumber = 0;
/**
* The <code>String</code> that represents the numeric missing value
* for a tab-delimited data file, initially "NA"
* after R's missing value.
*/
private String MissingValueForTextDataFileNumeric = "";
/**
* Returns the value of the
* <code>MissingValueForTextDataFileNumeric</code> field.
*
* @return the value of the
* <code>MissingValueForTextDataFileNumeric</code> field.
*/
public String getMissingValueForTextDataFileNumeric() {
return MissingValueForTextDataFileNumeric;
}
/**
* Sets the new value of
* the <code>setMissingValueForTextDataFileNumeric</code> field.
*
* @param MissingValueToken the new value of the
* <code>setMissingValueForTextDataFileNumeric</code> field.
*/
public void setMissingValueForTextDataFileNumeric(String MissingValueToken) {
this.MissingValueForTextDataFileNumeric = MissingValueToken;
}
/**
* The <code>String</code> that represents the string missing value
* for a tab-delimited data file, initially "".
*/
String MissingValueForTextDataFileString = "";
/**
* Returns the value of the
* <code>MissingValueForTextDataFileString</code> field.
*
* @return the value of the
* <code>MissingValueForTextDataFileString</code> field. */
public String getMissingValueForTextDataFileString() {
return MissingValueForTextDataFileString;
}
/**
* Sets the new value of
* the <code>MissingValueForTextDataFileString</code> field.
*
* @param MissingValueToken the new value of the
* <code>MissingValueForTextDataFileString</code> field.
*/
public void setMissingValueForTextDataFileString(String MissingValueToken) {
this.MissingValueForTextDataFileString = MissingValueToken;
}
// Constructor -----------------------------------------------------------//
/**
* Constructs a <code>SAVFileReader</code> instance with a
* <code>StatDataFileReaderSpi</code> object.
*
* @param originator a <code>StatDataFileReaderSpi</code> object.
*/
public SAVFileReader(StatDataFileReaderSpi originator) {
super(originator);
//init();
}
private void init(){
sdf_ymd.setTimeZone(TimeZone.getTimeZone("GMT"));
sdf_ymdhms.setTimeZone(TimeZone.getTimeZone("GMT"));
sdf_dhms.setTimeZone(TimeZone.getTimeZone("GMT"));
sdf_hms.setTimeZone(TimeZone.getTimeZone("GMT"));
doubleNumberFormatter.setGroupingUsed(false);
doubleNumberFormatter.setMaximumFractionDigits(340);
}
// Accessor Methods ----------------------------------------------------//
// Methods ---------------------------------------------------------------//
/**
* Read the given SPSS SAV-format file via a <code>BufferedInputStream</code>
* object. This method calls an appropriate method associated with the given
* field header by reflection.
*
* @param stream a <code>BufferedInputStream</code>.
* @return an <code>SDIOData</code> object
* @throws java.io.IOException if an reading error occurs.
*/
@Override
public SDIOData read(BufferedInputStream stream, File dataFile) throws IOException{
dbgLog.fine("***** SAVFileReader: read() start *****");
if (dataFile != null) {
throw new IOException ("this plugin does not support external raw data files");
}
// the following methods are now executed, in this order:
// decodeHeader -- this method doesn't read any [meta]data and
// doesn't initialize any values; its only purpose is to
// make sure that the file is indeed an SPSS/SAV file.
//
// decodeRecordType1 -- there's always one RT1 record; it is
// always 176 byte long. it contains the very basic metadata
// about the data file. most notably, the number of observations
// and the number of OBS (8 byte values) per observation.
//
// decodeRecordType2 -- there are multiple RT2 records. there's
// one RT2 for every OBS (8 byte value); i.e. one per variable,
// or more per every String variable split into multiple OBS
// segments. this one is a 400 line method, that may benefit
// from being split into smaller methods.
//
// decodeRecordType3and4 -- these sections come in pairs, each
// pair dedicated to one set of variable labels.
// decodeRecordType6,
//
// decodeRecordType7 -- this RT contains some extended
// metadata for the data file. (including the information
// about the extended variables, i.e. variables longer than
// 255 bytes split into 255 byte fragments that are stored
// in the data file as independent variables).
//
// decodeRecordType999 -- this RT does not contain any data;
// its sole function is to indicate that the metadata portion
// of the data file is over and the data section follows.
//
// decodeRecordTypeData -- this method decodes the data section
// of the file. Inside this method, 2 distinct methods are
// called to process compressed or uncompressed data, depending
// on which method is used in this data file.
String methodCurrentlyExecuted = null;
try {
methodCurrentlyExecuted = "decodeHeader";
dbgLog.fine("***** SAVFileReader: executing method decodeHeader");
decodeHeader(stream);
methodCurrentlyExecuted = "decodeRecordType1";
dbgLog.fine("***** SAVFileReader: executing method decodeRecordType1");
decodeRecordType1(stream);
methodCurrentlyExecuted = "decodeRecordType2";
dbgLog.fine("***** SAVFileReader: executing method decodeRecordType1");
decodeRecordType2(stream);
methodCurrentlyExecuted = "decodeRecordType3and4";
dbgLog.fine("***** SAVFileReader: executing method decodeRecordType3and4");
decodeRecordType3and4(stream);
methodCurrentlyExecuted = "decodeRecordType6";
dbgLog.fine("***** SAVFileReader: executing method decodeRecordType6");
decodeRecordType6(stream);
methodCurrentlyExecuted = "decodeRecordType7";
dbgLog.fine("***** SAVFileReader: executing method decodeRecordType7");
decodeRecordType7(stream);
methodCurrentlyExecuted = "decodeRecordType999";
dbgLog.fine("***** SAVFileReader: executing method decodeRecordType999");
decodeRecordType999(stream);
methodCurrentlyExecuted = "decodeRecordTypeData";
dbgLog.fine("***** SAVFileReader: executing method decodeRecordTypeData");
decodeRecordTypeData(stream);
} catch (IllegalArgumentException e) {
//Throwable cause = e.getCause();
dbgLog.fine("***** SAVFileReader: ATTENTION: IllegalArgumentException thrown while executing "+methodCurrentlyExecuted);
e.printStackTrace();
throw new IllegalArgumentException ( "in method "+methodCurrentlyExecuted+": "+e.getMessage() );
} catch (IOException e) {
dbgLog.fine("***** SAVFileReader: ATTENTION: IOException thrown while executing "+methodCurrentlyExecuted);
e.printStackTrace();
throw new IOException ( "in method "+methodCurrentlyExecuted+": "+e.getMessage() );
}
if (sdiodata == null){
sdiodata = new SDIOData(smd, savDataSection);
}
dbgLog.fine("***** SAVFileReader: read() end *****");
return sdiodata;
}
void decodeHeader(BufferedInputStream stream) throws IOException {
dbgLog.fine("***** decodeHeader(): start *****");
if (stream ==null){
throw new IllegalArgumentException("stream == null!");
}
// the length of the magic number is 4 (1-byte character * 4)
// its value is expected to be $FL2
byte[] b = new byte[SAV_MAGIC_NUMBER_LENGTH];
try {
if (stream.markSupported()){
stream.mark(100);
}
int nbytes = stream.read(b, 0, SAV_MAGIC_NUMBER_LENGTH);
if (nbytes == 0){
throw new IOException();
}
} catch (IOException ex){
//ex.printStackTrace();
throw ex;
}
//printHexDump(b, "hex dump of the byte-array");
String hdr4sav = new String(b);
dbgLog.fine("from string=" + hdr4sav);
if (hdr4sav.equals(SAV_FILE_SIGNATURE)) {
dbgLog.fine("this file is spss-sav type");
// initialize version-specific parameter
init();
smd.getFileInformation().put("mimeType", MIME_TYPE[0]);
smd.getFileInformation().put("fileFormat", MIME_TYPE[0]);
} else {
dbgLog.fine("this file is NOT spss-sav type");
throw new IllegalArgumentException("given file is not spss-sav type");
}
smd.getFileInformation().put("charset", defaultCharSet);
dbgLog.fine("smd dump:"+smd.toString());
dbgLog.fine("***** decodeHeader(): end *****");
}
void decodeRecordType1(BufferedInputStream stream) throws IOException {
dbgLog.fine("***** decodeRecordType1(): start *****");
if (stream ==null){
throw new IllegalArgumentException("stream == null!");
}
// how to read each recordType
// 1. set-up the following objects before reading bytes
// a. the working byte array
// b. the storage object
// the length of this field: 172bytes = 60 + 4 + 12 + 4 + 8 + 84
// this field consists of 6 distinct blocks
byte[] recordType1 = new byte[LENGTH_RECORDTYPE1];
// int caseWeightVariableOBSIndex = 0;
try {
int nbytes = stream.read(recordType1, 0, LENGTH_RECORDTYPE1);
//printHexDump(recordType1, "recordType1");
if (nbytes == 0){
throw new IOException("reading recordType1: no byte was read");
}
// 1.1 60 byte-String that tells the platform/version of SPSS that
// wrote this file
int offset_start = 0;
int offset_end = LENGTH_SPSS_PRODUCT_INFO; // 60 bytes
String productInfo = new String(Arrays.copyOfRange(recordType1, offset_start,
offset_end),"US-ASCII");
dbgLog.fine("productInfo:\n"+productInfo+"\n");
// add the info to the fileInfo
smd.getFileInformation().put("productInfo", productInfo);
// try to parse out the SPSS version that created this data
// file:
String spssVersionNumberTag = null;
String regexpVersionNumber = ".*Release ([0-9]*)";
Pattern patternJsession = Pattern.compile(regexpVersionNumber);
Matcher matcher = patternJsession.matcher(productInfo);
if ( matcher.find() ) {
spssVersionNumberTag = matcher.group(1);
dbgLog.fine("SPSS Version Number: "+spssVersionNumberTag);
}
if (spssVersionNumberTag != null && !spssVersionNumberTag.equals("")) {
spssVersionNumber = Integer.valueOf(spssVersionNumberTag).intValue();
/*
* Starting with SPSS version 16, the default encoding is
* UTF-8.
*/
if (spssVersionNumber > 15) {
defaultCharSet = "UTF-8";
}
}
smd.getFileInformation().put("charset", defaultCharSet);
// 1.2) 4-byte file-layout-code (byte-order)
offset_start = offset_end;
offset_end += LENGTH_FILE_LAYOUT_CODE; // 4 byte
ByteBuffer bb_fileLayout_code = ByteBuffer.wrap(
recordType1, offset_start, LENGTH_FILE_LAYOUT_CODE);
ByteBuffer byteOderTest = bb_fileLayout_code.duplicate();
// interprete the 4 byte as int
int int2test = byteOderTest.getInt();
if (int2test == 2 || int2test == 3){
dbgLog.fine("integer == "+int2test+": the byte-oder of the writer is the same "+
"as the counterpart of Java: Big Endian");
} else {
// Because Java's byte-order is always big endian,
// this(!=2) means this sav file was written on a little-endian machine
// non-string, multi-bytes blocks must be byte-reversed
bb_fileLayout_code.order(ByteOrder.LITTLE_ENDIAN);
int2test = bb_fileLayout_code.getInt();
if (int2test == 2 || int2test == 3){
dbgLog.fine("The sav file was saved on a little endian machine");
dbgLog.fine("Reveral of the bytes is necessary to decode "+
"multi-byte, non-string blocks");
isLittleEndian = true;
} else {
throw new IOException("reading recordType1:unknown file layout code="+int2test);
}
}
dbgLog.fine("Endian of this platform:"+ByteOrder.nativeOrder().toString());
smd.getFileInformation().put("OSByteOrder", ByteOrder.nativeOrder().toString());
smd.getFileInformation().put("byteOrder", int2test);
// 1.3 4-byte Number_Of_OBS_Units_Per_Case
// (= how many RT2 records => how many varilables)
offset_start = offset_end;
offset_end += LENGTH_NUMBER_OF_OBS_UNITS_PER_CASE; // 4 byte
ByteBuffer bb_OBS_units_per_case = ByteBuffer.wrap(
recordType1, offset_start,LENGTH_NUMBER_OF_OBS_UNITS_PER_CASE);
if (isLittleEndian){
bb_OBS_units_per_case.order(ByteOrder.LITTLE_ENDIAN);
}
OBSUnitsPerCase = bb_OBS_units_per_case.getInt();
dbgLog.fine("RT1: OBSUnitsPerCase="+OBSUnitsPerCase);
smd.getFileInformation().put("OBSUnitsPerCase", OBSUnitsPerCase);
// 1.4 4-byte Compression_Switch
offset_start = offset_end;
offset_end += LENGTH_COMPRESSION_SWITCH; // 4 byte
ByteBuffer bb_compression_switch = ByteBuffer.wrap(recordType1,
offset_start, LENGTH_COMPRESSION_SWITCH);
if (isLittleEndian){
bb_compression_switch.order(ByteOrder.LITTLE_ENDIAN);
}
int compression_switch = bb_compression_switch.getInt();
if ( compression_switch == 0){
// data section is not compressed
isDataSectionCompressed = false;
dbgLog.fine("data section is not compressed");
} else {
dbgLog.fine("data section is compressed:"+compression_switch);
}
smd.getFileInformation().put("compressedData", compression_switch);
// 1.5 4-byte Case-Weight Variable Index
// warning: this variable index starts from 1, not 0
offset_start = offset_end;
offset_end += LENGTH_CASE_WEIGHT_VARIABLE_INDEX; // 4 byte
ByteBuffer bb_Case_Weight_Variable_Index = ByteBuffer.wrap(recordType1,
offset_start, LENGTH_CASE_WEIGHT_VARIABLE_INDEX);
if (isLittleEndian){
bb_Case_Weight_Variable_Index.order(ByteOrder.LITTLE_ENDIAN);
}
caseWeightVariableOBSIndex = bb_Case_Weight_Variable_Index.getInt();
smd.getFileInformation().put("caseWeightVariableOBSIndex", caseWeightVariableOBSIndex);
// 1.6 4-byte Number of Cases
offset_start = offset_end;
offset_end += LENGTH_NUMBER_OF_CASES; // 4 byte
ByteBuffer bb_Number_Of_Cases = ByteBuffer.wrap(recordType1,
offset_start, LENGTH_NUMBER_OF_CASES);
if (isLittleEndian){
bb_Number_Of_Cases.order(ByteOrder.LITTLE_ENDIAN);
}
int numberOfCases = bb_Number_Of_Cases.getInt();
if ( numberOfCases < 0){
// -1 if numberOfCases is unknown
throw new RuntimeException("number of cases is not recorded in the header");
} else {
dbgLog.fine("RT1: number of cases is recorded= "+numberOfCases);
caseQnty = numberOfCases;
smd.getFileInformation().put("caseQnty", numberOfCases);
}
// 1.7 8-byte compression-bias [not long but double]
offset_start = offset_end;
offset_end += LENGTH_COMPRESSION_BIAS; // 8 byte
ByteBuffer bb_compression_bias = ByteBuffer.wrap(
Arrays.copyOfRange(recordType1, offset_start,
offset_end));
if (isLittleEndian){
bb_compression_bias.order(ByteOrder.LITTLE_ENDIAN);
}
Double compressionBias = bb_compression_bias.getDouble();
if ( compressionBias == 100d){
// 100 is expected
dbgLog.fine("compressionBias is 100 as expected");
smd.getFileInformation().put("compressionBias", 100);
} else {
dbgLog.fine("compression bias is not 100: "+ compressionBias);
smd.getFileInformation().put("compressionBias", compressionBias);
}
// 1.8 84-byte File Creation Information (date/time: dd MM yyhh:mm:ss +
// 64-bytelabel)
offset_start = offset_end;
offset_end += LENGTH_FILE_CREATION_INFO; // 84 bytes
String fileCreationInfo = getNullStrippedString(new String(Arrays.copyOfRange(recordType1, offset_start,
offset_end),"US-ASCII"));
dbgLog.fine("fileCreationInfo:\n"+fileCreationInfo+"\n");
String fileCreationDate = fileCreationInfo.substring(0,length_file_creation_date);
int dateEnd = length_file_creation_date+length_file_creation_time;
String fileCreationTime = fileCreationInfo.substring(length_file_creation_date,
(dateEnd));
String fileCreationNote = fileCreationInfo.substring(dateEnd,length_file_creation_label);
dbgLog.fine("fileDate="+ fileCreationDate);
dbgLog.fine("fileTime="+ fileCreationTime);
dbgLog.fine("fileNote"+ fileCreationNote);
smd.getFileInformation().put("fileDate", fileCreationDate);
smd.getFileInformation().put("fileTime", fileCreationTime);
smd.getFileInformation().put("fileNote", fileCreationNote);
smd.getFileInformation().put("varFormat_schema", "SPSS");
// add the info to the fileInfo
smd.getFileInformation().put("mimeType", MIME_TYPE[0]);
smd.getFileInformation().put("fileFormat", MIME_TYPE[0]);
smd.setValueLabelMappingTable(valueVariableMappingTable);
} catch (IOException ex) {
//ex.printStackTrace();
throw ex;
}
dbgLog.fine("***** decodeRecordType1(): end *****");
}
void decodeRecordType2(BufferedInputStream stream) throws IOException {
dbgLog.fine("***** decodeRecordType2(): start *****");
if (stream ==null){
throw new IllegalArgumentException("stream == null!");
}
Map<String, String> variableLabelMap = new LinkedHashMap<String, String>();
Map<String, List<String>> missingValueTable = new LinkedHashMap<String, List<String>>();
List<Integer> printFormatList = new ArrayList<Integer>();
String caseWeightVariableName = null;
int caseWeightVariableIndex = 0;
boolean lastVariableIsExtendable = false;
boolean extendedVariableMode = false;
boolean obs255 = false;
String lastVariableName = null;
String lastExtendedVariable = null;
// this field repeats as many as the number of variables in
// this sav file
// (note that the above statement is not technically correct, this
// record repeats not just for every variable in the file, but for
// every OBS (8 byte unit); i.e., if a string is split into multiple
// OBS units, each one will have its own RT2 record -- L.A.).
// Each field constists of a fixed (32-byte) segment and
// then a few variable segments:
// if the variable has a label (3rd INT4 set to 1), then there's 4 more
// bytes specifying the length of the label, and then that many bytes
// holding the label itself (no more than 256).
// Then if there are optional missing value units (4th INT4 set to 1)
// there will be 3 more OBS units attached = 24 extra bytes.
int variableCounter = 0;
int obsSeqNumber = 0;
int j;
dbgLog.fine("RT2: Reading "+OBSUnitsPerCase+" OBS units.");
for (j=0; j<OBSUnitsPerCase; j++){
dbgLog.fine("RT2: \n\n+++++++++++ "+j+"-th RT2 unit is to be decoded +++++++++++");
// 2.0: read the fixed[=non-optional] 32-byte segment
byte[] recordType2Fixed = new byte[LENGTH_RECORDTYPE2_FIXED];
try {
int nbytes = stream.read(recordType2Fixed, 0, LENGTH_RECORDTYPE2_FIXED);
//printHexDump(recordType2Fixed, "recordType2 part 1");
if (nbytes == 0){
throw new IOException("reading recordType2: no bytes read!");
}
int offset = 0;
// 2.1: create int-view of the bytebuffer for the first 16-byte segment
int rt2_1st_4_units = 4;
ByteBuffer[] bb_record_type2_fixed_part1 = new ByteBuffer[rt2_1st_4_units];
int[] recordType2FixedPart1 = new int[rt2_1st_4_units];
for (int i= 0; i < rt2_1st_4_units;i++ ){
bb_record_type2_fixed_part1[i] =
ByteBuffer.wrap(recordType2Fixed, offset, LENGTH_SAV_INT_BLOCK);
offset +=LENGTH_SAV_INT_BLOCK;
if (isLittleEndian){
bb_record_type2_fixed_part1[i].order(ByteOrder.LITTLE_ENDIAN);
}
recordType2FixedPart1[i] = bb_record_type2_fixed_part1[i].getInt();
}
dbgLog.fine("recordType2FixedPart="+
ReflectionToStringBuilder.toString(recordType2FixedPart1, ToStringStyle.MULTI_LINE_STYLE));
// 1st ([0]) element must be 2 otherwise no longer Record Type 2
if (recordType2FixedPart1[0] != 2){
dbgLog.info(j+"-th RT header value is no longet RT2! "+recordType2FixedPart1[0]);
break;
//throw new IOException("RT2 reading error: The current position is no longer Record Type 2");
}
dbgLog.fine("variable type[must be 2]="+recordType2FixedPart1[0]);
// 2.3 variable name: 8 byte(space[x20]-padded)
// This field is located at the very end of the 32 byte
// fixed-size RT2 header (bytes 24-31).
// We are processing it now, so that
// we can make the decision on whether this variable is part
// of a compound variable:
String RawVariableName = new String(Arrays.copyOfRange(recordType2Fixed, 24, (24+LENGTH_VARIABLE_NAME)),defaultCharSet);
//offset +=LENGTH_VARIABLE_NAME;
String variableName = null;
if (RawVariableName.indexOf(' ') >= 0){
variableName = RawVariableName.substring(0, RawVariableName.indexOf(' '));
} else {
variableName = RawVariableName;
}
// 2nd ([1]) element: numeric variable = 0 :for string variable
// this block indicates its datum-length, i.e, >0 ;
// if -1, this RT2 unit is a non-1st RT2 unit for a string variable
// whose value is longer than 8 character.
boolean isNumericVariable = false;
dbgLog.fine("variable type(0: numeric; > 0: String;-1 continue )="+recordType2FixedPart1[1]);
//OBSwiseTypelList.add(recordType2FixedPart1[1]);
int HowManyRt2Units=1;
if (recordType2FixedPart1[1] == -1) {
dbgLog.fine("this RT2 is an 8 bit continuation chunk of an earlier string variable");
if ( obs255 ) {
if ( obsSeqNumber < 30 ) {
OBSwiseTypelList.add(recordType2FixedPart1[1]);
obsSeqNumber++;
} else {
OBSwiseTypelList.add(-2);
obs255 = false;
obsSeqNumber = 0;
}
} else {
OBSwiseTypelList.add(recordType2FixedPart1[1]);
}
obsNonVariableBlockSet.add(j);
continue;
} else if (recordType2FixedPart1[1] == 0){
// This is a numeric variable
extendedVariableMode = false;
// And as such, it cannot be an extension of a
// previous, long string variable.
OBSwiseTypelList.add(recordType2FixedPart1[1]);
variableCounter++;
isNumericVariable = true;
variableTypelList.add(recordType2FixedPart1[1]);
} else if (recordType2FixedPart1[1] > 0){
// This looks like a regular string variable. However,
// it may still be a part of a compound variable
// (a String > 255 bytes that was split into 255 byte
// chunks, stored as individual String variables).
if (recordType2FixedPart1[1] == 255){
obs255 = true;
}
if ( lastVariableIsExtendable ) {
String varNameBase = null;
if ( lastVariableName.length() > 5 ) {
varNameBase = lastVariableName.substring (0, 5);
} else {
varNameBase = lastVariableName;
}
if ( extendedVariableMode ) {
if ( variableNameIsAnIncrement ( varNameBase, lastExtendedVariable, variableName ) ) {
OBSwiseTypelList.add(-1);
lastExtendedVariable = variableName;
// OK, we stay in the "extended variable" mode;
// but we can't move on to the next OBS (hence the commented out
// "continue" below:
//continue;
// see the next comment below for the explanation.
//
// Should we also set "extendable" flag to false at this point
// if it's shorter than 255 bytes, i.e. the last extended chunk?
} else {
extendedVariableMode = false;
}
} else {
if ( variableNameIsAnIncrement ( varNameBase, variableName ) ) {
OBSwiseTypelList.add(-1);
extendedVariableMode = true;
dbgLog.fine("RT2: in extended variable mode; variable "+variableName);
lastExtendedVariable = variableName;
// Before we move on to the next OBS unit, we need to check
// if this current extended variable has its own label specified;
// If so, we need to determine its length, then read and skip
// that many bytes.
// Hence the commented out "continue" below:
//continue;
}
}
}
if ( !extendedVariableMode) {
// OK, this is a "real"
// string variable, and not a continuation chunk of a compound
// string.
OBSwiseTypelList.add(recordType2FixedPart1[1]);
variableCounter++;
if (recordType2FixedPart1[1] == 255){
// This variable is 255 bytes long, i.e. this is
// either the single "atomic" variable of the
// max allowed size, or it's a 255 byte segment
// of a compound variable. So we will check
// the next variable and see if it is the continuation
// of this one.
lastVariableIsExtendable = true;
} else {
lastVariableIsExtendable = false;
}
if (recordType2FixedPart1[1] % LENGTH_SAV_OBS_BLOCK == 0){
HowManyRt2Units = recordType2FixedPart1[1] / LENGTH_SAV_OBS_BLOCK;
} else {
HowManyRt2Units = recordType2FixedPart1[1] / LENGTH_SAV_OBS_BLOCK +1;
}
variableTypelList.add(recordType2FixedPart1[1]);
}
}
if ( !extendedVariableMode ) {
// Again, we only want to do the following steps for the "real"
// variables, not the chunks of split mega-variables:
dbgLog.fine("RT2: HowManyRt2Units for this variable="+HowManyRt2Units);
lastVariableName = variableName;
// caseWeightVariableOBSIndex starts from 1: 0 is used for does-not-exist cases
if (j == (caseWeightVariableOBSIndex -1)){
caseWeightVariableName = variableName;
caseWeightVariableIndex = variableCounter;
smd.setCaseWeightVariableName(caseWeightVariableName);
smd.getFileInformation().put("caseWeightVariableIndex", caseWeightVariableIndex);
}
OBSIndexToVariableName.put(j, variableName);
//dbgLog.fine("\nvariable name="+variableName+"<-");
dbgLog.fine("RT2: "+j+"-th variable name="+variableName+"<-");
dbgLog.fine("RT2: raw variable: "+RawVariableName);
variableNameList.add(variableName);
}
// 3rd ([2]) element: = 1 variable-label block follows; 0 = no label
//
dbgLog.fine("RT: variable label follows?(1:yes; 0: no)="+recordType2FixedPart1[2]);
boolean hasVariableLabel = recordType2FixedPart1[2] == 1 ? true : false;
if ((recordType2FixedPart1[2] != 0) && (recordType2FixedPart1[2] != 1)) {
throw new IOException("RT2: reading error: value is neither 0 or 1"+
recordType2FixedPart1[2]);
}
// 2.4 [optional]The length of a variable label followed: 4-byte int
// 3rd element of 2.1 indicates whether this field exists
// *** warning: The label block is padded to a multiple of the 4-byte
// NOT the raw integer value of this 4-byte block
if (hasVariableLabel){
byte[] length_variable_label= new byte[4];
int nbytes_2_4 = stream.read(length_variable_label);
if (nbytes_2_4 == 0){
throw new IOException("RT 2: error reading recordType2.4: no bytes read!");
} else {
dbgLog.fine("nbytes_2_4="+nbytes_2_4);
}
ByteBuffer bb_length_variable_label = ByteBuffer.wrap(
length_variable_label, 0, LENGTH_VARIABLE_LABEL);
if (isLittleEndian){
bb_length_variable_label.order(ByteOrder.LITTLE_ENDIAN);
}
int rawVariableLabelLength = bb_length_variable_label.getInt();
dbgLog.fine("rawVariableLabelLength="+rawVariableLabelLength);
int variableLabelLength = getSAVintAdjustedBlockLength(rawVariableLabelLength);
dbgLog.fine("RT2: variableLabelLength="+variableLabelLength);
-
// 2.5 [optional]variable label whose length is found at 2.4
+ String variableLabel = "";
+
+ if (rawVariableLabelLength > 0) {
byte[] variable_label = new byte[variableLabelLength];
int nbytes_2_5 = stream.read(variable_label);
if (nbytes_2_5 == 0){
- throw new IOException("RT 2: error reading recordType2.5: no bytes read!");
+ throw new IOException("RT 2: error reading recordType2.5: "
+ +variableLabelLength+" bytes requested, no bytes read!");
} else {
dbgLog.fine("nbytes_2_5="+nbytes_2_5);
}
+ variableLabel = new String(Arrays.copyOfRange(variable_label,
+ 0, rawVariableLabelLength),defaultCharSet);
+ dbgLog.fine("RT2: variableLabel="+variableLabel+"<-");
+
+ dbgLog.info(variableName + " => " + variableLabel);
+ } else {
+ dbgLog.fine("RT2: defaulting to empty variable label.");
+ }
+
if (!extendedVariableMode) {
// We only have any use for this label if it's a "real" variable.
// Thinking about it, it doesn't make much sense for the "fake"
// variables that are actually chunks of large strings to store
// their own labels. But in some files they do. Then failing to read
// the bytes would result in getting out of sync with the RT record
// borders. So we always read the bytes, but only use them for
// the real variable entries.
/*String variableLabel = new String(Arrays.copyOfRange(variable_label,
0, rawVariableLabelLength),"US-ASCII");*/
- String variableLabel = new String(Arrays.copyOfRange(variable_label,
- 0, rawVariableLabelLength),defaultCharSet);
- dbgLog.fine("RT2: variableLabel="+variableLabel+"<-");
- dbgLog.info(variableName + " => " + variableLabel);
- dbgLog.info(variableName + " => " + variableLabel);
- dbgLog.info(variableName + " => " + variableLabel);
-
variableLabelMap.put(variableName, variableLabel);
}
}
if (extendedVariableMode) {
// there's nothing else left for us to do in this iteration of the loop.
// Once again, this was not a real variable, but a dummy variable entry
// created for a chunk of a string variable longer than 255 bytes --
// that's how SPSS stores them.
continue;
}
// 4th ([3]) element: Missing value type code
// 0[none], 1, 2, 3 [point-type],-2[range], -3 [range type+ point]
dbgLog.fine("RT: missing value unit follows?(if 0, none)="+recordType2FixedPart1[3]);
boolean hasMissingValues =
(validMissingValueCodeSet.contains(
recordType2FixedPart1[3]) && (recordType2FixedPart1[3] !=0)) ?
true : false;
InvalidData invalidDataInfo = null;
if (recordType2FixedPart1[3] !=0){
invalidDataInfo = new InvalidData(recordType2FixedPart1[3]);
dbgLog.fine("RT: missing value type="+invalidDataInfo.getType());
}
// 2.2: print/write formats: 4-byte each = 8 bytes
byte[] printFormt = Arrays.copyOfRange(recordType2Fixed, offset, offset+
LENGTH_PRINT_FORMAT_CODE);
dbgLog.fine("printFrmt="+new String (Hex.encodeHex(printFormt)));
offset +=LENGTH_PRINT_FORMAT_CODE;
int formatCode = isLittleEndian ? printFormt[2] : printFormt[1];
int formatWidth = isLittleEndian ? printFormt[1] : printFormt[2];
int formatDecimalPointPosition = isLittleEndian ? printFormt[0] : printFormt[3];
dbgLog.fine("RT2: format code{5=F, 1=A[String]}="+formatCode);
formatDecimalPointPositionList.add(formatDecimalPointPosition);
if (!SPSSConstants.FORMAT_CODE_TABLE_SAV.containsKey(formatCode)){
throw new IOException("Unknown format code was found = "
+ formatCode);
} else{
printFormatList.add(formatCode);
}
byte[] writeFormt = Arrays.copyOfRange(recordType2Fixed, offset, offset+
LENGTH_WRITE_FORMAT_CODE);
dbgLog.fine("RT2: writeFrmt="+new String (Hex.encodeHex(writeFormt)));
if (writeFormt[3] != 0x00){
dbgLog.fine("byte-order(write format): reversal required");
}
offset +=LENGTH_WRITE_FORMAT_CODE;
if (!SPSSConstants.ORDINARY_FORMAT_CODE_SET.contains(formatCode)) {
StringBuilder sb = new StringBuilder(
SPSSConstants.FORMAT_CODE_TABLE_SAV.get(formatCode)+
formatWidth);
if (formatDecimalPointPosition > 0){
sb.append("."+ formatDecimalPointPosition);
}
dbgLog.info("formattable[i] = " + variableName + " -> " + sb.toString());
printFormatNameTable.put(variableName, sb.toString());
}
printFormatTable.put(variableName, SPSSConstants.FORMAT_CODE_TABLE_SAV.get(formatCode));
// 2.6 [optional] missing values:4-byte each if exists
// 4th element of 2.1 indicates the structure of this sub-field
// Should we perhaps check for this for the "fake" variables too?
//
if (hasMissingValues) {
dbgLog.fine("RT2: decoding missing value: type="+recordType2FixedPart1[3]);
int howManyMissingValueUnits = missingValueCodeUnits.get(recordType2FixedPart1[3]);
//int howManyMissingValueUnits = recordType2FixedPart1[3] > 0 ? recordType2FixedPart1[3] : 0;
dbgLog.fine("RT2: howManyMissingValueUnits="+howManyMissingValueUnits);
byte[] missing_value_code_units = new byte[LENGTH_SAV_OBS_BLOCK*howManyMissingValueUnits];
int nbytes_2_6 = stream.read(missing_value_code_units);
if (nbytes_2_6 == 0){
throw new IOException("RT 2: reading recordType2.6: no byte was read");
} else {
dbgLog.fine("nbytes_2_6="+nbytes_2_6);
}
//printHexDump(missing_value_code_units, "missing value");
if (isNumericVariable){
double[] missingValues = new double[howManyMissingValueUnits];
//List<String> mvp = new ArrayList<String>();
List<String> mv = new ArrayList<String>();
ByteBuffer[] bb_missig_value_code =
new ByteBuffer[howManyMissingValueUnits];
int offset_start = 0;
for (int i= 0; i < howManyMissingValueUnits;i++ ){
bb_missig_value_code[i] =
ByteBuffer.wrap(missing_value_code_units, offset_start,
LENGTH_SAV_OBS_BLOCK);
offset_start +=LENGTH_SAV_OBS_BLOCK;
if (isLittleEndian){
bb_missig_value_code[i].order(ByteOrder.LITTLE_ENDIAN);
}
ByteBuffer temp = bb_missig_value_code[i].duplicate();
missingValues[i] = bb_missig_value_code[i].getDouble();
if (Double.toHexString(missingValues[i]).equals("-0x1.ffffffffffffep1023")){
dbgLog.fine("1st value is LOWEST");
mv.add(Double.toHexString(missingValues[i]));
} else if (Double.valueOf(missingValues[i]).equals(Double.MAX_VALUE)){
dbgLog.fine("2nd value is HIGHEST");
mv.add(Double.toHexString(missingValues[i]));
} else {
mv.add(doubleNumberFormatter.format(missingValues[i]));
}
dbgLog.fine(i+"-th missing value="+Double.toHexString(missingValues[i]));
}
dbgLog.fine("variableName="+variableName);
if (recordType2FixedPart1[3] > 0) {
// point cases only
dbgLog.fine("mv(>0)="+mv);
missingValueTable.put(variableName, mv);
invalidDataInfo.setInvalidValues(mv);
} else if (recordType2FixedPart1[3]== -2) {
dbgLog.fine("mv(-2)="+mv);
// range
invalidDataInfo.setInvalidRange(mv);
} else if (recordType2FixedPart1[3]== -3){
// mixed case
dbgLog.fine("mv(-3)="+mv);
invalidDataInfo.setInvalidRange(mv.subList(0, 2));
invalidDataInfo.setInvalidValues(mv.subList(2, 3));
missingValueTable.put(variableName, mv.subList(2, 3));
}
dbgLog.fine("missing value="+
StringUtils.join(missingValueTable.get(variableName),"|"));
dbgLog.fine("invalidDataInfo(Numeric):\n"+invalidDataInfo);
invalidDataTable.put(variableName, invalidDataInfo);
} else {
// string variable case
String[] missingValues = new String[howManyMissingValueUnits];
List<String> mv = new ArrayList<String>();
int offset_start = 0;
int offset_end = LENGTH_SAV_OBS_BLOCK;
for (int i= 0; i < howManyMissingValueUnits;i++ ){
missingValues[i] =
StringUtils.stripEnd(new
String(Arrays.copyOfRange(missing_value_code_units, offset_start, offset_end),defaultCharSet), " ");
dbgLog.fine("missing value="+missingValues[i]+"<-");
offset_start = offset_end;
offset_end +=LENGTH_SAV_OBS_BLOCK;
mv.add(missingValues[i]);
}
invalidDataInfo.setInvalidValues(mv);
missingValueTable.put(variableName, mv);
invalidDataTable.put(variableName, invalidDataInfo);
dbgLog.fine("missing value(str)="+
StringUtils.join(missingValueTable.get(variableName),"|"));
dbgLog.fine("invalidDataInfo(String):\n"+invalidDataInfo);
} // string case
dbgLog.fine("invalidDataTable:\n"+invalidDataTable);
} // if msv
} catch (IOException ex){
//ex.printStackTrace();
throw ex;
} catch (Exception ex){
ex.printStackTrace();
// should we be throwing some exception here?
}
} // j-loop
if (j == OBSUnitsPerCase ) {
dbgLog.fine("RT2 metadata-related exit-chores");
smd.getFileInformation().put("varQnty", variableCounter);
varQnty = variableCounter;
dbgLog.fine("RT2: varQnty="+varQnty);
smd.setVariableName(variableNameList.toArray(new String[variableNameList.size()]));
smd.setVariableLabel(variableLabelMap);
smd.setMissingValueTable(missingValueTable);
smd.getFileInformation().put("caseWeightVariableName", caseWeightVariableName);
smd.setVariableTypeMinimal(ArrayUtils.toPrimitive(
variableTypelList.toArray(new Integer[variableTypelList.size()])));
dbgLog.info("sumstat:long case=" + Arrays.deepToString(variableTypelList.toArray()));
smd.setVariableFormat(printFormatList);
smd.setVariableFormatName(printFormatNameTable);
dbgLog.fine("RT2: OBSwiseTypelList="+OBSwiseTypelList);
// variableType is determined after the valueTable is finalized
} else {
dbgLog.info("RT2: attention! didn't reach the end of the OBS list!");
throw new IOException("RT2: didn't reach the end of the OBS list!");
}
dbgLog.fine("***** decodeRecordType2(): end *****");
}
void decodeRecordType3and4(BufferedInputStream stream) throws IOException {
dbgLog.fine("***** decodeRecordType3and4(): start *****");
Map<String, Map<String, String>> valueLabelTable =
new LinkedHashMap<String, Map<String, String>>();
int safteyCounter = 0;
while(true ){
try {
if (stream ==null){
throw new IllegalArgumentException("stream == null!");
}
// this secton may not exit so first check the 4-byte header value
//if (stream.markSupported()){
stream.mark(1000);
//}
// 3.0 check the first 4 bytes
byte[] headerCode = new byte[LENGTH_RECORD_TYPE3_CODE];
int nbytes_rt3 = stream.read(headerCode, 0, LENGTH_RECORD_TYPE3_CODE);
// to-do check against nbytes
//printHexDump(headerCode, "RT3 header test");
ByteBuffer bb_header_code = ByteBuffer.wrap(headerCode,
0, LENGTH_RECORD_TYPE3_CODE);
if (isLittleEndian){
bb_header_code.order(ByteOrder.LITTLE_ENDIAN);
}
int intRT3test = bb_header_code.getInt();
dbgLog.fine("header test value: RT3="+intRT3test);
if (intRT3test != 3){
//if (stream.markSupported()){
dbgLog.fine("iteration="+safteyCounter);
// We have encountered a record that's not type 3. This means we've
// processed all the type 3/4 record pairs. So we want to rewind
// the stream and return -- so that the appropriate record type
// reader can be called on it.
// But before we return, we need to save all the value labels
// we have found:
smd.setValueLabelTable(valueLabelTable);
stream.reset();
return;
//}
}
// 3.1 how many value-label pairs follow
byte[] number_of_labels = new byte[LENGTH_RT3_HOW_MANY_LABELS];
int nbytes_3_1 = stream.read(number_of_labels);
if (nbytes_3_1 == 0){
throw new IOException("RT 3: reading recordType3.1: no byte was read");
}
ByteBuffer bb_number_of_labels = ByteBuffer.wrap(number_of_labels,
0, LENGTH_RT3_HOW_MANY_LABELS);
if (isLittleEndian){
bb_number_of_labels.order(ByteOrder.LITTLE_ENDIAN);
}
int numberOfValueLabels = bb_number_of_labels.getInt();
dbgLog.fine("number of value-label pairs="+numberOfValueLabels);
ByteBuffer[] tempBB = new ByteBuffer[numberOfValueLabels];
String valueLabel[] = new String[numberOfValueLabels];
for (int i=0; i<numberOfValueLabels;i++){
// read 8-byte as value
byte[] value = new byte[LENGTH_RT3_VALUE];
int nbytes_3_value = stream.read(value);
if (nbytes_3_value == 0){
throw new IOException("RT 3: reading recordType3 value: no byte was read");
}
// note these 8 bytes are interpreted later
// currently no information about which variable's (=> type unknown)
ByteBuffer bb_value = ByteBuffer.wrap(value,
0, LENGTH_RT3_VALUE);
if (isLittleEndian){
bb_value.order(ByteOrder.LITTLE_ENDIAN);
}
tempBB[i] = bb_value;
dbgLog.fine("bb_value="+Hex.encodeHex(bb_value.array()));
/*
double valueD = bb_value.getDouble();
dbgLog.fine("value="+valueD);
*/
// read 1st byte as unsigned integer = label_length
// read label_length byte as label
byte[] labelLengthByte = new byte[LENGTH_RT3_LABEL_LENGTH];
int nbytes_3_label_length = stream.read(labelLengthByte);
// add check-routine here
dbgLog.fine("labelLengthByte"+Hex.encodeHex(labelLengthByte));
dbgLog.fine("label length = "+labelLengthByte[0]);
// the net-length of a value label is saved as
// unsigned byte; however, the length is less than 127
// byte should be ok
int rawLabelLength = labelLengthByte[0] & 0xFF;
dbgLog.fine("rawLabelLength="+rawLabelLength);
// -1 =>1-byte already read
int labelLength = getSAVobsAdjustedBlockLength(rawLabelLength+1)-1;
byte[] valueLabelBytes = new byte[labelLength];
int nbytes_3_value_label = stream.read(valueLabelBytes);
// ByteBuffer bb_label = ByteBuffer.wrap(valueLabel,0,labelLength);
valueLabel[i] = StringUtils.stripEnd(new
String(Arrays.copyOfRange(valueLabelBytes, 0, rawLabelLength),defaultCharSet), " ");
dbgLog.fine(i+"-th valueLabel="+valueLabel[i]+"<-");
} // iter rt3
dbgLog.fine("end of RT3 block");
dbgLog.fine("start of RT4 block");
// 4.0 check the first 4 bytes
byte[] headerCode4 = new byte[LENGTH_RECORD_TYPE4_CODE];
int nbytes_rt4 = stream.read(headerCode4, 0, LENGTH_RECORD_TYPE4_CODE);
if (nbytes_rt4 == 0){
throw new IOException("RT4: reading recordType4 value: no byte was read");
}
//printHexDump(headerCode4, "RT4 header test");
ByteBuffer bb_header_code_4 = ByteBuffer.wrap(headerCode4,
0, LENGTH_RECORD_TYPE4_CODE);
if (isLittleEndian){
bb_header_code_4.order(ByteOrder.LITTLE_ENDIAN);
}
int intRT4test = bb_header_code_4.getInt();
dbgLog.fine("header test value: RT4="+intRT4test);
if (intRT4test != 4){
throw new IOException("RT 4: reading recordType4 header: no byte was read");
}
// 4.1 read the how-many-variables bytes
byte[] howManyVariablesfollow = new byte[LENGTH_RT4_HOW_MANY_VARIABLES];
int nbytes_rt4_1 = stream.read(howManyVariablesfollow, 0, LENGTH_RT4_HOW_MANY_VARIABLES);
ByteBuffer bb_howManyVariablesfollow = ByteBuffer.wrap(howManyVariablesfollow,
0, LENGTH_RT4_HOW_MANY_VARIABLES);
if (isLittleEndian){
bb_howManyVariablesfollow.order(ByteOrder.LITTLE_ENDIAN);
}
int howManyVariablesRT4 = bb_howManyVariablesfollow.getInt();
dbgLog.fine("how many variables follow: RT4="+howManyVariablesRT4);
int length_indicies = LENGTH_RT4_VARIABLE_INDEX*howManyVariablesRT4;
byte[] variableIdicesBytes = new byte[length_indicies];
int nbytes_rt4_2 = stream.read(variableIdicesBytes, 0, length_indicies);
// !!!!! Caution: variableIndex in RT4 starts from 1 NOT ** 0 **
int[] variableIndex = new int[howManyVariablesRT4];
int offset = 0;
for (int i=0; i< howManyVariablesRT4; i++){
ByteBuffer bb_variable_index = ByteBuffer.wrap(variableIdicesBytes,
offset, LENGTH_RT4_VARIABLE_INDEX);
offset +=LENGTH_RT4_VARIABLE_INDEX;
if (isLittleEndian){
bb_variable_index.order(ByteOrder.LITTLE_ENDIAN);
}
variableIndex[i] = bb_variable_index.getInt();
dbgLog.fine(i+"-th variable index number="+variableIndex[i]);
}
dbgLog.fine("variable index set="+ArrayUtils.toString(variableIndex));
dbgLog.fine("subtract 1 from variableIndex for getting a variable info");
boolean isNumeric = OBSwiseTypelList.get(variableIndex[0]-1)==0 ? true : false;
Map<String, String> valueLabelPair = new LinkedHashMap<String, String>();
if (isNumeric){
// numeric variable
dbgLog.fine("processing of a numeric value-label table");
for (int j=0;j<numberOfValueLabels;j++){
valueLabelPair.put(doubleNumberFormatter.format(tempBB[j].getDouble()), valueLabel[j] );
}
} else {
// String variable
dbgLog.fine("processing of a string value-label table");
for (int j=0;j<numberOfValueLabels;j++){
valueLabelPair.put(
StringUtils.stripEnd(new String((tempBB[j].array()),defaultCharSet), " "),valueLabel[j] );
}
}
dbgLog.fine("valueLabePair="+valueLabelPair);
dbgLog.fine("key variable's (raw) index ="+variableIndex[0]);
valueLabelTable.put(OBSIndexToVariableName.get(variableIndex[0]-1),valueLabelPair);
dbgLog.fine("valueLabelTable="+valueLabelTable);
// create a mapping table that finds the key variable for this mapping table
String keyVariableName = OBSIndexToVariableName.get(variableIndex[0]-1);
for (int vn : variableIndex){
valueVariableMappingTable.put(OBSIndexToVariableName.get(vn - 1), keyVariableName);
}
dbgLog.fine("valueVariableMappingTable:\n"+valueVariableMappingTable);
} catch (IOException ex){
//ex.printStackTrace();
throw ex;
}
safteyCounter++;
if (safteyCounter >= 1000000){
break;
}
} //while
smd.setValueLabelTable(valueLabelTable);
dbgLog.fine("***** decodeRecordType3and4(): end *****");
}
void decodeRecordType6(BufferedInputStream stream) throws IOException {
dbgLog.fine("***** decodeRecordType6(): start *****");
try {
if (stream ==null){
throw new IllegalArgumentException("stream == null!");
}
// this secton may not exit so first check the 4-byte header value
//if (stream.markSupported()){
stream.mark(1000);
//}
// 6.0 check the first 4 bytes
byte[] headerCodeRt6 = new byte[LENGTH_RECORD_TYPE6_CODE];
int nbytes_rt6 = stream.read(headerCodeRt6, 0, LENGTH_RECORD_TYPE6_CODE);
// to-do check against nbytes
//printHexDump(headerCodeRt6, "RT6 header test");
ByteBuffer bb_header_code_rt6 = ByteBuffer.wrap(headerCodeRt6,
0, LENGTH_RECORD_TYPE6_CODE);
if (isLittleEndian){
bb_header_code_rt6.order(ByteOrder.LITTLE_ENDIAN);
}
int intRT6test = bb_header_code_rt6.getInt();
dbgLog.fine("RT6: header test value="+intRT6test);
if (intRT6test != 6){
//if (stream.markSupported()){
//out.print("iteration="+safteyCounter);
//dbgLog.fine("iteration="+safteyCounter);
dbgLog.fine("intRT6test failed="+intRT6test);
stream.reset();
return;
//}
}
// 6.1 check 4-byte integer that tells how many lines follow
byte[] length_how_many_line_bytes = new byte[LENGTH_RT6_HOW_MANY_LINES];
int nbytes_rt6_1 = stream.read(length_how_many_line_bytes, 0,
LENGTH_RT6_HOW_MANY_LINES);
// to-do check against nbytes
//printHexDump(length_how_many_line_bytes, "RT6 how_many_line_bytes");
ByteBuffer bb_how_many_lines = ByteBuffer.wrap(length_how_many_line_bytes,
0, LENGTH_RT6_HOW_MANY_LINES);
if (isLittleEndian){
bb_how_many_lines.order(ByteOrder.LITTLE_ENDIAN);
}
int howManyLinesRt6 = bb_how_many_lines.getInt();
dbgLog.fine("how Many lines follow="+howManyLinesRt6);
// 6.2 read 80-char-long lines
String[] documentRecord = new String[howManyLinesRt6];
for (int i=0;i<howManyLinesRt6; i++){
byte[] line = new byte[80];
int nbytes_rt6_line = stream.read(line);
documentRecord[i] = StringUtils.stripEnd(new
String(Arrays.copyOfRange(line,
0, LENGTH_RT6_DOCUMENT_LINE),defaultCharSet), " ");
dbgLog.fine(i+"-th line ="+documentRecord[i]+"<-");
}
dbgLog.fine("documentRecord:\n"+StringUtils.join(documentRecord, "\n"));
} catch (IOException ex){
//ex.printStackTrace();
throw ex;
}
dbgLog.fine("***** decodeRecordType6(): end *****");
}
void decodeRecordType7(BufferedInputStream stream) throws IOException {
dbgLog.fine("***** decodeRecordType7(): start *****");
int counter=0;
int[] headerSection = new int[2];
// the variables below may no longer needed;
// but they may be useful for debugging/logging purposes.
/// // RecordType 7
/// // Subtype 3
/// List<Integer> releaseMachineSpecificInfo = new ArrayList<Integer>();
/// List<String> releaseMachineSpecificInfoHex = new ArrayList<String>();
/// // Subytpe 4
/// Map<String, Double> OBSTypeValue = new LinkedHashMap<String, Double>();
/// Map<String, String> OBSTypeHexValue = new LinkedHashMap<String, String>();
//Subtype 11
/// List<Integer> measurementLevel = new ArrayList<Integer>();
/// List<Integer> columnWidth = new ArrayList<Integer>();
/// List<Integer> alignment = new ArrayList<Integer>();
Map<String, String> shortToLongVarialbeNameTable = new LinkedHashMap<String, String>();
while(true){
try {
if (stream ==null){
throw new IllegalArgumentException("RT7: stream == null!");
}
// first check the 4-byte header value
//if (stream.markSupported()){
stream.mark(1000);
//}
// 7.0 check the first 4 bytes
byte[] headerCodeRt7 = new byte[LENGTH_RECORD_TYPE7_CODE];
int nbytes_rt7 = stream.read(headerCodeRt7, 0,
LENGTH_RECORD_TYPE7_CODE);
// to-do check against nbytes
//printHexDump(headerCodeRt7, "RT7 header test");
ByteBuffer bb_header_code_rt7 = ByteBuffer.wrap(headerCodeRt7,
0, LENGTH_RECORD_TYPE7_CODE);
if (isLittleEndian){
bb_header_code_rt7.order(ByteOrder.LITTLE_ENDIAN);
}
int intRT7test = bb_header_code_rt7.getInt();
dbgLog.fine("RT7: header test value="+intRT7test);
if (intRT7test != 7){
//if (stream.markSupported()){
//out.print("iteration="+safteyCounter);
//dbgLog.fine("iteration="+safteyCounter);
dbgLog.fine("intRT7test failed="+intRT7test);
dbgLog.fine("counter="+counter);
stream.reset();
return;
//}
}
// 7.1 check 4-byte integer Sub-Type Code
byte[] length_sub_type_code = new byte[LENGTH_RT7_SUB_TYPE_CODE];
int nbytes_rt7_1 = stream.read(length_sub_type_code, 0,
LENGTH_RT7_SUB_TYPE_CODE);
// to-do check against nbytes
//printHexDump(length_how_many_line_bytes, "RT7 how_many_line_bytes");
ByteBuffer bb_sub_type_code = ByteBuffer.wrap(length_sub_type_code,
0, LENGTH_RT7_SUB_TYPE_CODE);
if (isLittleEndian){
bb_sub_type_code.order(ByteOrder.LITTLE_ENDIAN);
}
int subTypeCode = bb_sub_type_code.getInt();
dbgLog.fine("RT7: subTypeCode="+subTypeCode);
switch (subTypeCode) {
case 3:
// 3: Release andMachine-Specific Integer Information
//parseRT7SubTypefield(stream);
headerSection = parseRT7SubTypefieldHeader(stream);
if (headerSection != null){
int unitLength = headerSection[0];
int numberOfUnits = headerSection[1];
for (int i=0; i<numberOfUnits; i++){
dbgLog.finer(i+"-th fieldData");
byte[] work = new byte[unitLength];
int nb = stream.read(work);
dbgLog.finer("raw bytes in Hex:"+ new String(Hex.encodeHex(work)));
ByteBuffer bb_field = ByteBuffer.wrap(work);
if (isLittleEndian){
bb_field.order(ByteOrder.LITTLE_ENDIAN);
}
String dataInHex = new String(Hex.encodeHex(bb_field.array()));
/// releaseMachineSpecificInfoHex.add(dataInHex);
dbgLog.finer("raw bytes in Hex:"+ dataInHex);
if (unitLength==4){
int fieldData = bb_field.getInt();
dbgLog.finer("fieldData(int)="+fieldData);
dbgLog.finer("fieldData in Hex=0x"+Integer.toHexString(fieldData));
/// releaseMachineSpecificInfo.add(fieldData);
}
}
/// dbgLog.fine("releaseMachineSpecificInfo="+releaseMachineSpecificInfo);
/// dbgLog.fine("releaseMachineSpecificInfoHex="+releaseMachineSpecificInfoHex);
} else {
// throw new IOException
}
dbgLog.fine("***** end of subType 3 ***** \n");
break;
case 4:
// Release andMachine-SpecificOBS-Type Information
headerSection = parseRT7SubTypefieldHeader(stream);
if (headerSection != null){
int unitLength = headerSection[0];
int numberOfUnits = headerSection[1];
for (int i=0; i<numberOfUnits; i++){
dbgLog.finer(i+"-th fieldData:"+RecordType7SubType4Fields.get(i));
byte[] work = new byte[unitLength];
int nb = stream.read(work);
dbgLog.finer("raw bytes in Hex:"+ new String(Hex.encodeHex(work)));
ByteBuffer bb_field = ByteBuffer.wrap(work);
dbgLog.finer("byte order="+bb_field.order().toString());
if (isLittleEndian){
bb_field.order(ByteOrder.LITTLE_ENDIAN);
}
ByteBuffer bb_field_dup = bb_field.duplicate();
OBSTypeHexValue.put(RecordType7SubType4Fields.get(i),
new String(Hex.encodeHex(bb_field.array())) );
// dbgLog.finer("raw bytes in Hex:"+
// OBSTypeHexValue.get(RecordType7SubType4Fields.get(i)));
if (unitLength==8){
double fieldData = bb_field.getDouble();
/// OBSTypeValue.put(RecordType7SubType4Fields.get(i), fieldData);
dbgLog.finer("fieldData(double)="+fieldData);
OBSTypeHexValue.put(RecordType7SubType4Fields.get(i),
Double.toHexString(fieldData));
dbgLog.fine("fieldData in Hex="+Double.toHexString(fieldData));
}
}
/// dbgLog.fine("OBSTypeValue="+OBSTypeValue);
/// dbgLog.fine("OBSTypeHexValue="+OBSTypeHexValue);
} else {
// throw new IOException
}
dbgLog.fine("***** end of subType 4 ***** \n");
break;
case 5:
// Variable Sets Information
parseRT7SubTypefield(stream);
break;
case 6:
// Trends date information
parseRT7SubTypefield(stream);
break;
case 7:
// Multiple response groups
parseRT7SubTypefield(stream);
break;
case 8:
// Windows Data Entry data
parseRT7SubTypefield(stream);
break;
case 9:
//
parseRT7SubTypefield(stream);
break;
case 10:
// TextSmart data
parseRT7SubTypefield(stream);
break;
case 11:
// Msmt level, col width, & alignment
//parseRT7SubTypefield(stream);
headerSection = parseRT7SubTypefieldHeader(stream);
if (headerSection != null){
int unitLength = headerSection[0];
int numberOfUnits = headerSection[1];
for (int i=0; i<numberOfUnits; i++){
dbgLog.finer(i+"-th fieldData");
byte[] work = new byte[unitLength];
int nb = stream.read(work);
dbgLog.finer("raw bytes in Hex:"+ new String(Hex.encodeHex(work)));
ByteBuffer bb_field = ByteBuffer.wrap(work);
if (isLittleEndian){
bb_field.order(ByteOrder.LITTLE_ENDIAN);
}
dbgLog.finer("raw bytes in Hex:"+ new String(Hex.encodeHex(bb_field.array())));
if (unitLength==4){
int fieldData = bb_field.getInt();
dbgLog.finer("fieldData(int)="+fieldData);
dbgLog.finer("fieldData in Hex=0x"+Integer.toHexString(fieldData));
int remainder = i%3;
dbgLog.finer("remainder="+remainder);
if (remainder == 0){
/// measurementLevel.add(fieldData);
} else if (remainder == 1){
/// columnWidth.add(fieldData);
} else if (remainder == 2){
/// alignment.add(fieldData);
}
}
}
} else {
// throw new IOException
}
/// dbgLog.fine("measurementLevel="+measurementLevel);
/// dbgLog.fine("columnWidth="+columnWidth);
/// dbgLog.fine("alignment="+alignment);
dbgLog.fine("***** end of subType 11 ***** \n");
break;
case 12:
// Windows Data Entry GUID
parseRT7SubTypefield(stream);
break;
case 13:
// Extended variable names
// parseRT7SubTypefield(stream);
headerSection = parseRT7SubTypefieldHeader(stream);
if (headerSection != null){
int unitLength = headerSection[0];
dbgLog.fine("RT7: unitLength="+unitLength);
int numberOfUnits = headerSection[1];
dbgLog.fine("RT7: numberOfUnits="+numberOfUnits);
byte[] work = new byte[unitLength*numberOfUnits];
int nbtyes13 = stream.read(work);
String[] variableShortLongNamePairs = new String(work,"US-ASCII").split("\t");
for (int i=0; i<variableShortLongNamePairs.length; i++){
dbgLog.fine("RT7: "+i+"-th pair"+variableShortLongNamePairs[i]);
String[] pair = variableShortLongNamePairs[i].split("=");
shortToLongVarialbeNameTable.put(pair[0], pair[1]);
}
dbgLog.fine("RT7: shortToLongVarialbeNameTable"+
shortToLongVarialbeNameTable);
smd.setShortToLongVarialbeNameTable(shortToLongVarialbeNameTable);
} else {
// throw new IOException
}
break;
case 14:
// Extended strings
//parseRT7SubTypefield(stream);
headerSection = parseRT7SubTypefieldHeader(stream);
if (headerSection != null){
int unitLength = headerSection[0];
dbgLog.fine("RT7.14: unitLength="+unitLength);
int numberOfUnits = headerSection[1];
dbgLog.fine("RT7.14: numberOfUnits="+numberOfUnits);
byte[] work = new byte[unitLength*numberOfUnits];
int nbtyes13 = stream.read(work);
String[] extendedVariablesSizePairs = new String(work,defaultCharSet).split("\000\t");
for (int i=0; i<extendedVariablesSizePairs.length; i++){
dbgLog.fine("RT7.14: "+i+"-th pair"+extendedVariablesSizePairs[i]);
if ( extendedVariablesSizePairs[i].indexOf("=") > 0 ) {
String[] pair = extendedVariablesSizePairs[i].split("=");
extendedVariablesSizeTable.put(pair[0], Integer.valueOf(pair[1]));
}
}
dbgLog.fine("RT7.14: extendedVariablesSizeTable"+
extendedVariablesSizeTable);
} else {
// throw new IOException
}
break;
case 15:
// Clementine Metadata
parseRT7SubTypefield(stream);
break;
case 16:
// 64 bit N of cases
parseRT7SubTypefield(stream);
break;
case 17:
// File level attributes
parseRT7SubTypefield(stream);
break;
case 18:
// Variable attributes
parseRT7SubTypefield(stream);
break;
case 19:
// Extended multiple response groups
parseRT7SubTypefield(stream);
break;
case 20:
// Encoding, aka code page
parseRT7SubTypefield(stream);
/* TODO: This needs to be researched;
* Is this field really used, ever?
headerSection = parseRT7SubTypefieldHeader(stream);
if (headerSection != null){
int unitLength = headerSection[0];
dbgLog.fine("RT7-20: unitLength="+unitLength);
int numberOfUnits = headerSection[1];
dbgLog.fine("RT7-20: numberOfUnits="+numberOfUnits);
byte[] rt7st20bytes = new byte[unitLength*numberOfUnits];
int nbytes20 = stream.read(rt7st20bytes);
String dataCharSet = new String(rt7st20bytes,"US-ASCII");
if (dataCharSet != null && !(dataCharSet.equals(""))) {
dbgLog.fine("RT7-20: data charset: "+ dataCharSet);
defaultCharSet = dataCharSet;
}
} else {
// throw new IOException
}
*
*/
break;
case 21:
// Value labels for long strings
parseRT7SubTypefield(stream);
break;
case 22:
// Missing values for long strings
parseRT7SubTypefield(stream);
break;
default:
parseRT7SubTypefield(stream);
}
} catch (IOException ex){
//ex.printStackTrace();
throw ex;
}
counter++;
if (counter > 20){
break;
}
}
dbgLog.fine("RT7: counter="+counter);
dbgLog.fine("RT7: ***** decodeRecordType7(): end *****");
}
void decodeRecordType999(BufferedInputStream stream) throws IOException {
dbgLog.fine("***** decodeRecordType999(): start *****");
try {
if (stream ==null){
throw new IllegalArgumentException("RT999: stream == null!");
}
// first check the 4-byte header value
//if (stream.markSupported()){
stream.mark(1000);
//}
// 999.0 check the first 4 bytes
byte[] headerCodeRt999 = new byte[LENGTH_RECORD_TYPE999_CODE];
//dbgLog.fine("RT999: stream position="+stream.pos);
int nbytes_rt999 = stream.read(headerCodeRt999, 0,
LENGTH_RECORD_TYPE999_CODE);
// to-do check against nbytes
//printHexDump(headerCodeRt999, "RT999 header test");
ByteBuffer bb_header_code_rt999 = ByteBuffer.wrap(headerCodeRt999,
0, LENGTH_RECORD_TYPE999_CODE);
if (isLittleEndian){
bb_header_code_rt999.order(ByteOrder.LITTLE_ENDIAN);
}
int intRT999test = bb_header_code_rt999.getInt();
dbgLog.fine("header test value: RT999="+intRT999test);
if (intRT999test != 999){
//if (stream.markSupported()){
dbgLog.fine("intRT999test failed="+intRT999test);
stream.reset();
throw new IOException("RT999:Header value(999) was not correctly detected:"+intRT999test);
//}
}
// 999.1 check 4-byte integer Filler block
byte[] length_filler = new byte[LENGTH_RT999_FILLER];
int nbytes_rt999_1 = stream.read(length_filler, 0,
LENGTH_RT999_FILLER);
// to-do check against nbytes
//printHexDump(length_how_many_line_bytes, "RT999 how_many_line_bytes");
ByteBuffer bb_filler = ByteBuffer.wrap(length_filler,
0, LENGTH_RT999_FILLER);
if (isLittleEndian){
bb_filler.order(ByteOrder.LITTLE_ENDIAN);
}
int rt999filler = bb_filler.getInt();
dbgLog.fine("rt999filler="+rt999filler);
if (rt999filler == 0){
dbgLog.fine("the end of the dictionary section");
} else {
throw new IOException("RT999: failed to detect the end mark(0): value="+rt999filler);
}
// missing value processing concerning HIGHEST/LOWEST values
Set<Map.Entry<String,InvalidData>> msvlc = invalidDataTable.entrySet();
for (Iterator<Map.Entry<String,InvalidData>> itc = msvlc.iterator(); itc.hasNext();){
Map.Entry<String, InvalidData> et = itc.next();
String variable = et.getKey();
dbgLog.fine("variable="+variable);
InvalidData invalidDataInfo = et.getValue();
if (invalidDataInfo.getInvalidRange() != null &&
!invalidDataInfo.getInvalidRange().isEmpty()){
if (invalidDataInfo.getInvalidRange().get(0).equals(OBSTypeHexValue.get("LOWEST"))){
dbgLog.fine("1st value is LOWEST");
invalidDataInfo.getInvalidRange().set(0, "LOWEST");
} else if (invalidDataInfo.getInvalidRange().get(1).equals(OBSTypeHexValue.get("HIGHEST"))){
dbgLog.fine("2nd value is HIGHEST");
invalidDataInfo.getInvalidRange().set(1,"HIGHEST");
}
}
}
dbgLog.fine("invalidDataTable:\n"+invalidDataTable);
smd.setInvalidDataTable(invalidDataTable);
} catch (IOException ex){
//ex.printStackTrace();
//exit(1);
throw ex;
}
dbgLog.fine("***** decodeRecordType999(): end *****");
}
void decodeRecordTypeData(BufferedInputStream stream) throws IOException {
dbgLog.fine("***** decodeRecordTypeData(): start *****");
String fileUnfValue = null;
String[] unfValues = null;
if (stream ==null){
throw new IllegalArgumentException("stream == null!");
}
if (isDataSectionCompressed){
decodeRecordTypeDataCompressed(stream);
} else {
decodeRecordTypeDataUnCompressed(stream);
}
unfValues = new String[varQnty];
dbgLog.fine("variableTypeFinal:"+Arrays.toString(variableTypeFinal));
for (int j=0;j<varQnty; j++){
//int variableTypeNumer = variableTypelList.get(j) > 0 ? 1 : 0;
int variableTypeNumer = variableTypeFinal[j];
try {
dbgLog.finer("j = "+j);
dbgLog.finer("dataTable2[j] = " + Arrays.deepToString(dataTable2[j]));
dbgLog.finer("dateFormats[j] = " + Arrays.deepToString(dateFormats[j]));
unfValues[j] = getUNF(dataTable2[j], dateFormats[j], variableTypeNumer,
unfVersionNumber, j);
dbgLog.fine(j+"th unf value"+unfValues[j]);
} catch (NumberFormatException ex) {
ex.printStackTrace();
} catch (UnfException ex) {
ex.printStackTrace();
} catch (IOException ex) {
//ex.printStackTrace();
throw ex;
} catch (NoSuchAlgorithmException ex) {
ex.printStackTrace();
}
}
dbgLog.fine("unf set:\n"+Arrays.deepToString(unfValues));
try {
fileUnfValue = UNF5Util.calculateUNF(unfValues);
} catch (NumberFormatException ex) {
ex.printStackTrace();
} catch (IOException ex) {
//ex.printStackTrace();
throw ex;
}
dbgLog.fine("file-unf="+fileUnfValue);
savDataSection.setUnf(unfValues);
savDataSection.setFileUnf(fileUnfValue);
smd.setVariableUNF(unfValues);
smd.getFileInformation().put("fileUNF", fileUnfValue);
dbgLog.fine("unf values:\n"+unfValues);
savDataSection.setData(dataTable2);
dbgLog.fine("dataTable2:\n"+Arrays.deepToString(dataTable2));
dbgLog.fine("***** decodeRecordTypeData(): end *****");
}
PrintWriter createOutputWriter (BufferedInputStream stream) throws IOException {
PrintWriter pwout = null;
FileOutputStream fileOutTab = null;
try {
// create a File object to save the tab-delimited data file
File tabDelimitedDataFile = File.createTempFile("tempTabfile.", ".tab");
String tabDelimitedDataFileName = tabDelimitedDataFile.getAbsolutePath();
// save the temp file name in the metadata object
smd.getFileInformation().put("tabDelimitedDataFileLocation", tabDelimitedDataFileName);
fileOutTab = new FileOutputStream(tabDelimitedDataFile);
pwout = new PrintWriter(new OutputStreamWriter(fileOutTab, "utf8"), true);
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (UnsupportedEncodingException ex) {
ex.printStackTrace();
} catch (IOException ex){
//ex.printStackTrace();
throw ex;
}
return pwout;
}
void decodeRecordTypeDataCompressed(BufferedInputStream stream) throws IOException {
dbgLog.fine("***** decodeRecordTypeDataCompressed(): start *****");
if (stream == null) {
throw new IllegalArgumentException("decodeRecordTypeDataCompressed: stream == null!");
}
Map<String, String> formatCategoryTable = new LinkedHashMap<String, String>();
PrintWriter pwout = createOutputWriter(stream);
boolean hasStringVarContinuousBlock =
obsNonVariableBlockSet.size() > 0 ? true : false;
dbgLog.fine("hasStringVarContinuousBlock=" + hasStringVarContinuousBlock);
int ii = 0;
int OBS = LENGTH_SAV_OBS_BLOCK;
int nOBS = OBSUnitsPerCase;
dbgLog.fine("OBSUnitsPerCase=" + OBSUnitsPerCase);
int caseIndex = 0;
dbgLog.fine("printFormatTable:\n" + printFormatTable);
dbgLog.fine("printFormatNameTable:\n" + printFormatNameTable);
variableFormatTypeList = new String[varQnty];
dbgLog.fine("varQnty: " + varQnty);
for (int i = 0; i < varQnty; i++) {
variableFormatTypeList[i] = SPSSConstants.FORMAT_CATEGORY_TABLE.get(
printFormatTable.get(variableNameList.get(i)));
dbgLog.fine("i=" + i + "th variableFormatTypeList=" + variableFormatTypeList[i]);
formatCategoryTable.put(variableNameList.get(i), variableFormatTypeList[i]);
}
dbgLog.fine("variableFormatType:\n" + Arrays.deepToString(variableFormatTypeList));
dbgLog.fine("formatCategoryTable:\n" + formatCategoryTable);
// contents (variable) checker concering decimals
variableTypeFinal = new int[varQnty];
Arrays.fill(variableTypeFinal, 0);
List<String> casewiseRecordForUNF = new ArrayList<String>();
String[] caseWiseDateFormatForUNF = null;
List<String> casewiseRecordForTabFile = new ArrayList<String>();
// missing values are written to the tab-delimited file by
// using the default or user-specified missing-value strings;
// however, to calculate UNF/summary statistics,
// classes for these calculations require their specific
// missing values that differ from the above missing-value
// strings; therefore, after row data for the tab-delimited
// file are written, missing values in a row are changed to
// UNF/summary-statistics-OK ones.
// data-storage object for sumStat
dataTable2 = new Object[varQnty][caseQnty];
// storage of date formats to pass to UNF
dateFormats = new String[varQnty][caseQnty];
try {
// this compression is applied only to non-float data, i.e. integer;
// 8-byte float datum is kept in tact
boolean hasReachedEOF = false;
OBSERVATION:
while (true) {
dbgLog.fine("SAV Reader: compressed: ii=" + ii + "-th iteration");
byte[] octate = new byte[LENGTH_SAV_OBS_BLOCK];
int nbytes = stream.read(octate);
// processCompressedOBSblock ()
// (this means process a block of 8 compressed OBS
// values -- should result in 64 bytes of data total)
for (int i = 0; i < LENGTH_SAV_OBS_BLOCK; i++) {
dbgLog.finer("i=" + i + "-th iteration");
int octate_i = octate[i];
//dbgLog.fine("octate="+octate_i);
if (octate_i < 0) {
octate_i += 256;
}
int byteCode = octate_i;//octate_i & 0xF;
//out.println("byeCode="+byteCode);
- // processCompressedOBS()
+ // processCompressedOBS
switch (byteCode) {
case 252:
// end of the file
dbgLog.fine("SAV Reader: compressed: end of file mark [FC] was found");
hasReachedEOF = true;
break;
case 253:
// FD: uncompressed data follows after this octate
// long string datum or float datum
// read the following octate
byte[] uncompressedByte = new byte[LENGTH_SAV_OBS_BLOCK];
int ucbytes = stream.read(uncompressedByte);
int typeIndex = (ii * OBS + i) % nOBS;
if ((OBSwiseTypelList.get(typeIndex) > 0) ||
(OBSwiseTypelList.get(typeIndex) == -1)) {
// code= >0 |-1: string or its conitiguous block
// decode as a string object
String strdatum = new String(
Arrays.copyOfRange(uncompressedByte,
0, LENGTH_SAV_OBS_BLOCK), defaultCharSet);
//out.println("str_datum="+strdatum+"<-");
// add this non-missing-value string datum
casewiseRecordForTabFile.add(strdatum);
//out.println("casewiseRecordForTabFile(String)="+casewiseRecordForTabFile);
} else if (OBSwiseTypelList.get(typeIndex) == -2) {
String strdatum = new String(
Arrays.copyOfRange(uncompressedByte,
0, LENGTH_SAV_OBS_BLOCK - 1), defaultCharSet);
casewiseRecordForTabFile.add(strdatum);
//out.println("casewiseRecordForTabFile(String)="+casewiseRecordForTabFile);
} else if (OBSwiseTypelList.get(typeIndex) == 0) {
// code= 0: numeric
ByteBuffer bb_double = ByteBuffer.wrap(
uncompressedByte, 0, LENGTH_SAV_OBS_BLOCK);
if (isLittleEndian) {
bb_double.order(ByteOrder.LITTLE_ENDIAN);
}
Double ddatum = bb_double.getDouble();
// out.println("ddatum="+ddatum);
// add this non-missing-value numeric datum
casewiseRecordForTabFile.add(doubleNumberFormatter.format(ddatum));
dbgLog.fine("SAV Reader: compressed: added value to dataLine: " + ddatum);
} else {
dbgLog.fine("SAV Reader: out-of-range exception");
throw new IOException("out-of-range value was found");
}
/*
// EOF-check after reading this octate
if (stream.available() == 0){
hasReachedEOF = true;
dbgLog.fine(
"SAV Reader: *** After reading an uncompressed octate," +
" reached the end of the file at "+ii
+"th iteration and i="+i+"th octate position [0-start] *****");
}
*/
break;
case 254:
// FE: used as the missing value for string variables
// an empty case in a string variable also takes this value
// string variable does not accept space-only data
// cf: uncompressed case
// 20 20 20 20 20 20 20 20
// add the string missing value
// out.println("254: String missing data");
casewiseRecordForTabFile.add(" "); // add "." here?
// Note that technically this byte flag (254/xFE) means
// that *eight* white space characters should be
// written to the output stream. This caused me
// a great amount of confusion, because it appeared
// to me that there was a mismatch between the number
// of bytes advertised in the variable metadata and
// the number of bytes actually found in the data
// section of a compressed SAV file; this is because
// these 8 bytes "come out of nowhere"; they are not
// written in the data section, but this flag specifies
// that they should be added to the output.
// Also, as I pointed out above, we are only writing
// out one whitespace character, not 8 as instructed.
// This appears to be legit; these blocks of 8 spaces
// seem to be only used for padding, and all such
// multiple padding spaces are stripped anyway during
// the post-processing.
break;
case 255:
// FF: system missing value for numeric variables
// cf: uncompressed case (sysmis)
// FF FF FF FF FF FF eF FF(little endian)
// add the numeric missing value
dbgLog.fine("SAV Reader: compressed: Missing Value, numeric");
casewiseRecordForTabFile.add(MissingValueForTextDataFileNumeric);
break;
case 0:
// 00: do nothing
dbgLog.fine("SAV Reader: compressed: doing nothing (zero); ");
break;
default:
//out.println("byte code(default)="+ byteCode);
if ((byteCode > 0) && (byteCode < 252)) {
// datum is compressed
//Integer unCompressed = Integer.valueOf(byteCode -100);
// add this uncompressed numeric datum
Double unCompressed = Double.valueOf(byteCode - 100);
dbgLog.fine("SAV Reader: compressed: default case: " + unCompressed);
casewiseRecordForTabFile.add(doubleNumberFormatter.format(unCompressed));
// out.println("uncompressed="+unCompressed);
// out.println("dataline="+casewiseRecordForTabFile);
}
}// end of switch
// out.println("end of switch");
// The-end-of-a-case(row)-processing
// this line that follows, and the code around it
// is really confusing:
int varCounter = (ii * OBS + i + 1) % nOBS;
// while both OBS and LENGTH_SAV_OBS_BLOCK = 8
// (OBS was initialized as OBS=LENGTH_SAV_OBS_BLOCK),
// the 2 values mean different things:
// LENGTH_SAV_OBS_BLOCK is the number of bytes in one OBS;
// and OBS is the number of OBS blocks that we process
// at a time. I.e., we process 8 chunks of 8 bytes at a time.
// This is how data is organized inside an SAV file:
// 8 bytes of compression flags, followd by 8x8 or fewer
// (depending on the flags) bytes of compressed data.
// I should rename this OBS variable something more
// meaningful.
//
// Also, the "varCounter" variable name is entirely
// misleading -- it counts not variables, but OBS blocks.
dbgLog.fine("SAV Reader: compressed: OBS counter=" + varCounter + "(ii=" + ii + ")");
if ((ii * OBS + i + 1) % nOBS == 0) {
//out.println("casewiseRecordForTabFile(before)="+casewiseRecordForTabFile);
// out.println("all variables in a case are parsed == nOBS");
// out.println("hasStringVarContinuousBlock="+hasStringVarContinuousBlock);
// check whether a string-variable's continuous block exits
// if so, they must be joined
if (hasStringVarContinuousBlock) {
// string-variable's continuous-block-concatenating-processing
//out.println("concatenating process starts");
//out.println("casewiseRecordForTabFile(before)="+casewiseRecordForTabFile);
//out.println("casewiseRecordForTabFile(before:size)="+casewiseRecordForTabFile.size());
StringBuilder sb = new StringBuilder("");
int firstPosition = 0;
Set<Integer> removeJset = new HashSet<Integer>();
for (int j = 0; j < nOBS; j++) {
dbgLog.fine("RTD: j=" + j + "-th type =" + OBSwiseTypelList.get(j));
if ((OBSwiseTypelList.get(j) == -1) ||
(OBSwiseTypelList.get(j) == -2)) {
// Continued String variable found at j-th
// position. look back the j-1
firstPosition = j - 1;
int lastJ = j;
String concatenated = null;
removeJset.add(j);
sb.append(casewiseRecordForTabFile.get(j - 1));
sb.append(casewiseRecordForTabFile.get(j));
for (int jc = 1; ; jc++) {
if ((j + jc == nOBS)
|| ((OBSwiseTypelList.get(j + jc) != -1)
&& (OBSwiseTypelList.get(j + jc) != -2))) {
// j is the end unit of this string variable
concatenated = sb.toString();
sb.setLength(0);
lastJ = j + jc;
break;
} else {
sb.append(casewiseRecordForTabFile.get(j + jc));
removeJset.add(j + jc);
}
}
casewiseRecordForTabFile.set(j - 1, concatenated);
//out.println(j-1+"th concatenated="+concatenated);
j = lastJ - 1;
} // end-of-if: continuous-OBS only
} // end of loop-j
//out.println("removeJset="+removeJset);
// a new list that stores a new case with concatanated string data
List<String> newDataLine = new ArrayList<String>();
for (int jl = 0; jl < casewiseRecordForTabFile.size(); jl++) {
//out.println("jl="+jl+"-th datum =["+casewiseRecordForTabFile.get(jl)+"]");
if (!removeJset.contains(jl)) {
// if (casewiseRecordForTabFile.get(jl).equals(MissingValueForTextDataFileString)){
// out.println("NA-S jl= "+jl+"=["+casewiseRecordForTabFile.get(jl)+"]");
// } else if (casewiseRecordForTabFile.get(jl).equals(MissingValueForTextDataFileNumeric)){
// out.println("NA-N jl= "+jl+"=["+casewiseRecordForTabFile.get(jl)+"]");
// } else if (casewiseRecordForTabFile.get(jl)==null){
// out.println("null case jl="+jl+"=["+casewiseRecordForTabFile.get(jl)+"]");
// } else if (casewiseRecordForTabFile.get(jl).equals("NaN")){
// out.println("NaN jl= "+jl+"=["+casewiseRecordForTabFile.get(jl)+"]");
// } else if (casewiseRecordForTabFile.get(jl).equals("")){
// out.println("blank jl= "+jl+"=["+casewiseRecordForTabFile.get(jl)+"]");
// } else if (casewiseRecordForTabFile.get(jl).equals(" ")){
// out.println("space jl= "+jl+"=["+casewiseRecordForTabFile.get(jl)+"]");
// }
newDataLine.add(casewiseRecordForTabFile.get(jl));
} else {
// out.println("Excluded: jl="+jl+"-th datum=["+casewiseRecordForTabFile.get(jl)+"]");
}
} // end of loop-jl
//out.println("new casewiseRecordForTabFile="+newDataLine);
//out.println("new casewiseRecordForTabFile(size)="+newDataLine.size());
casewiseRecordForTabFile = newDataLine;
} // end-if: stringContinuousVar-exist case
for (int el = 0; el < casewiseRecordForTabFile.size(); el++) {
casewiseRecordForUNF.add(casewiseRecordForTabFile.get(el));
}
caseWiseDateFormatForUNF = new String[casewiseRecordForTabFile.size()];
// caseIndex starts from 1 not 0
caseIndex = (ii * OBS + i + 1) / nOBS;
for (int k = 0; k < casewiseRecordForTabFile.size(); k++) {
dbgLog.fine("k=" + k + "-th variableTypelList=" + variableTypelList.get(k));
if (variableTypelList.get(k) > 0) {
// String variable case: set to -1
variableTypeFinal[k] = -1;
// Strip the String variables off the
// whitespace padding:
// [ snipped ]
// I've removed the block of code above where
// String values were substring()-ed to the
// length specified in the variable metadata;
// Doing that was not enough, since a string
// can still be space-padded inside its
// advertised capacity. (note that extended
// variables can have many kylobytes of such
// padding in them!) Plus it was completely
// redundant, since we are stripping all the
// trailing white spaces with
// StringUtils.stripEnd() below:
String paddRemoved = StringUtils.stripEnd(casewiseRecordForTabFile.get(k).toString(), null);
// TODO: clean this up. For now, just make sure that strings contain at least one blank space.
if (paddRemoved.equals("")) {
paddRemoved = " ";
}
casewiseRecordForUNF.set(k, paddRemoved);
casewiseRecordForTabFile.set(k, "\"" + paddRemoved.replaceAll("\"", Matcher.quoteReplacement("\\\"")) + "\"");
// end of String var case
} else {
// numeric var case
if (casewiseRecordForTabFile.get(k).equals(MissingValueForTextDataFileNumeric)) {
casewiseRecordForUNF.set(k, null);
}
} // end of variable-type check
if (casewiseRecordForTabFile.get(k) != null && !casewiseRecordForTabFile.get(k).equals(MissingValueForTextDataFileNumeric)) {
String variableFormatType = variableFormatTypeList[k];
dbgLog.finer("k=" + k + "th printFormatTable format=" + printFormatTable.get(variableNameList.get(k)));
int formatDecimalPointPosition = formatDecimalPointPositionList.get(k);
if (variableFormatType.equals("date")) {
dbgLog.finer("date case");
long dateDatum = Long.parseLong(casewiseRecordForTabFile.get(k).toString()) * 1000L - SPSS_DATE_OFFSET;
String newDatum = sdf_ymd.format(new Date(dateDatum));
dbgLog.finer("k=" + k + ":" + newDatum);
caseWiseDateFormatForUNF[k] = sdf_ymd.toPattern();
/* saving date format */
dbgLog.finer("setting caseWiseDateFormatForUNF[k] = " + sdf_ymd.toPattern());
casewiseRecordForTabFile.set(k, newDatum);
casewiseRecordForUNF.set(k, newDatum);
//formatCategoryTable.put(variableNameList.get(k), "date");
} else if (variableFormatType.equals("time")) {
dbgLog.finer("time case:DTIME or DATETIME or TIME");
//formatCategoryTable.put(variableNameList.get(k), "time");
if (printFormatTable.get(variableNameList.get(k)).equals("DTIME")) {
if (casewiseRecordForTabFile.get(k).toString().indexOf(".") < 0) {
long dateDatum = Long.parseLong(casewiseRecordForTabFile.get(k).toString()) * 1000L - SPSS_DATE_BIAS;
String newDatum = sdf_dhms.format(new Date(dateDatum));
dbgLog.finer("k=" + k + ":" + newDatum);
casewiseRecordForTabFile.set(k, newDatum);
casewiseRecordForUNF.set(k, newDatum);
} else {
// decimal point included
String[] timeData = casewiseRecordForTabFile.get(k).toString().split("\\.");
dbgLog.finer(StringUtils.join(timeData, "|"));
long dateDatum = Long.parseLong(timeData[0]) * 1000L - SPSS_DATE_BIAS;
StringBuilder sb_time = new StringBuilder(
sdf_dhms.format(new Date(dateDatum)));
dbgLog.finer(sb_time.toString());
if (formatDecimalPointPosition > 0) {
sb_time.append("." + timeData[1].substring(0, formatDecimalPointPosition));
}
dbgLog.finer("k=" + k + ":" + sb_time.toString());
casewiseRecordForTabFile.set(k, sb_time.toString());
casewiseRecordForUNF.set(k, sb_time.toString());
}
} else if (printFormatTable.get(variableNameList.get(k)).equals("DATETIME")) {
if (casewiseRecordForTabFile.get(k).toString().indexOf(".") < 0) {
long dateDatum = Long.parseLong(casewiseRecordForTabFile.get(k).toString()) * 1000L - SPSS_DATE_OFFSET;
String newDatum = sdf_ymdhms.format(new Date(dateDatum));
dbgLog.finer("k=" + k + ":" + newDatum);
caseWiseDateFormatForUNF[k] = sdf_ymdhms.toPattern();
casewiseRecordForTabFile.set(k, newDatum);
casewiseRecordForUNF.set(k, newDatum);
} else {
// decimal point included
String[] timeData = casewiseRecordForTabFile.get(k).toString().split("\\.");
//dbgLog.finer(StringUtils.join(timeData, "|"));
long dateDatum = Long.parseLong(timeData[0]) * 1000L - SPSS_DATE_OFFSET;
StringBuilder sb_time = new StringBuilder(
sdf_ymdhms.format(new Date(dateDatum)));
//dbgLog.finer(sb_time.toString());
if (formatDecimalPointPosition > 0) {
sb_time.append("." + timeData[1].substring(0, formatDecimalPointPosition));
}
caseWiseDateFormatForUNF[k] = sdf_ymdhms.toPattern() + (formatDecimalPointPosition > 0 ? ".S" : "");
dbgLog.finer("k=" + k + ":" + sb_time.toString());
casewiseRecordForTabFile.set(k, sb_time.toString());
casewiseRecordForUNF.set(k, sb_time.toString());
}
} else if (printFormatTable.get(variableNameList.get(k)).equals("TIME")) {
if (casewiseRecordForTabFile.get(k).toString().indexOf(".") < 0) {
long dateDatum = Long.parseLong(casewiseRecordForTabFile.get(k).toString()) * 1000L;
String newDatum = sdf_hms.format(new Date(dateDatum));
caseWiseDateFormatForUNF[k] = sdf_hms.toPattern();
dbgLog.finer("k=" + k + ":" + newDatum);
casewiseRecordForTabFile.set(k, newDatum);
casewiseRecordForUNF.set(k, newDatum);
} else {
// decimal point included
String[] timeData = casewiseRecordForTabFile.get(k).toString().split("\\.");
//dbgLog.finer(StringUtils.join(timeData, "|"));
long dateDatum = Long.parseLong(timeData[0]) * 1000L;
StringBuilder sb_time = new StringBuilder(
sdf_hms.format(new Date(dateDatum)));
//dbgLog.finer(sb_time.toString());
if (formatDecimalPointPosition > 0) {
sb_time.append("." + timeData[1].substring(0, formatDecimalPointPosition));
}
caseWiseDateFormatForUNF[k] = this.sdf_hms.toPattern() + (formatDecimalPointPosition > 0 ? ".S" : "");
dbgLog.finer("k=" + k + ":" + sb_time.toString());
casewiseRecordForTabFile.set(k, sb_time.toString());
casewiseRecordForUNF.set(k, sb_time.toString());
}
}
} else if (variableFormatType.equals("other")) {
dbgLog.finer("other non-date/time case:=" + i);
if (printFormatTable.get(variableNameList.get(k)).equals("WKDAY")) {
// day of week
dbgLog.finer("data k=" + k + ":" + casewiseRecordForTabFile.get(k));
dbgLog.finer("data k=" + k + ":" + SPSSConstants.WEEKDAY_LIST.get(Integer.valueOf(casewiseRecordForTabFile.get(k).toString()) - 1));
String newDatum = SPSSConstants.WEEKDAY_LIST.get(Integer.valueOf(casewiseRecordForTabFile.get(k).toString()) - 1);
casewiseRecordForTabFile.set(k, newDatum);
casewiseRecordForUNF.set(k, newDatum);
dbgLog.finer("wkday:k=" + k + ":" + casewiseRecordForTabFile.get(k));
} else if (printFormatTable.get(variableNameList.get(k)).equals("MONTH")) {
// month
dbgLog.finer("data k=" + k + ":" + casewiseRecordForTabFile.get(k));
dbgLog.finer("data k=" + k + ":" + SPSSConstants.MONTH_LIST.get(Integer.valueOf(casewiseRecordForTabFile.get(k).toString()) - 1));
String newDatum = SPSSConstants.MONTH_LIST.get(Integer.valueOf(casewiseRecordForTabFile.get(k).toString()) - 1);
casewiseRecordForTabFile.set(k, newDatum);
casewiseRecordForUNF.set(k, newDatum);
dbgLog.finer("month:k=" + k + ":" + casewiseRecordForTabFile.get(k));
}
}
} // end: date-time-datum check
} // end: loop-k(2nd: variable-wise-check)
// write to tab file
if (casewiseRecordForTabFile.size() > 0) {
pwout.println(StringUtils.join(casewiseRecordForTabFile, "\t"));
}
if (casewiseRecordForTabFile.size() > 0) {
for (int ij = 0; ij < varQnty; ij++) {
dataTable2[ij][caseIndex - 1] = casewiseRecordForUNF.get(ij);
if (variableFormatTypeList[ij].equals("date") || variableFormatTypeList[ij].equals("time")) {
this.dateFormats[ij][caseIndex - 1] = caseWiseDateFormatForUNF[ij];
}
}
}
// numeric contents-check
for (int l = 0; l < casewiseRecordForTabFile.size(); l++) {
if (variableFormatTypeList[l].equals("date") ||
variableFormatTypeList[l].equals("time") ||
printFormatTable.get(variableNameList.get(l)).equals("WKDAY") ||
printFormatTable.get(variableNameList.get(l)).equals("MONTH")) {
variableTypeFinal[l] = -1;
}
if (variableTypeFinal[l] == 0) {
if (casewiseRecordForTabFile.get(l).toString().indexOf(".") >= 0) {
// TODO - check for large numbers
// l-th variable is not integer
variableTypeFinal[l] = 1;
decimalVariableSet.add(l);
}
}
}
// reset the case-wise working objects
casewiseRecordForUNF.clear();
casewiseRecordForTabFile.clear();
if ( caseQnty > 0 ) {
if ( caseIndex == caseQnty ) {
hasReachedEOF = true;
}
}
if (hasReachedEOF){
break;
}
} // if(The-end-of-a-case(row)-processing)
} // loop-i (OBS unit)
if ((hasReachedEOF) || (stream.available() == 0)) {
// reached the end of this file
// do exit-processing
dbgLog.fine("***** reached the end of the file at " + ii + "th iteration *****");
break OBSERVATION;
}
ii++;
} // while loop
pwout.close();
} catch (IOException ex) {
throw ex;
}
smd.setDecimalVariables(decimalVariableSet);
smd.getFileInformation().put("caseQnty", caseQnty);
smd.setVariableFormatCategory(formatCategoryTable);
// contents check
//out.println("variableType="+ArrayUtils.toString(variableTypeFinal));
dbgLog.fine("decimalVariableSet=" + decimalVariableSet);
//out.println("variableTypelList=\n"+ variableTypelList.toString());
// out.println("dataTable2:\n"+Arrays.deepToString(dataTable2));
dbgLog.fine("***** decodeRecordTypeDataCompressed(): end *****");
}
void decodeRecordTypeDataUnCompressed(BufferedInputStream stream) throws IOException {
dbgLog.fine("***** decodeRecordTypeDataUnCompressed(): start *****");
if (stream ==null){
throw new IllegalArgumentException("decodeRecordTypeDataUnCompressed: stream == null!");
}
Map<String, String> formatCategoryTable = new LinkedHashMap<String, String>();
//
// set-up tab file
PrintWriter pwout = createOutputWriter ( stream );
boolean hasStringVarContinuousBlock =
obsNonVariableBlockSet.size() > 0 ? true : false;
dbgLog.fine("hasStringVarContinuousBlock="+hasStringVarContinuousBlock);
int ii = 0;
int OBS = LENGTH_SAV_OBS_BLOCK;
int nOBS = OBSUnitsPerCase;
dbgLog.fine("OBSUnitsPerCase="+OBSUnitsPerCase);
int caseIndex = 0;
dbgLog.fine("printFormatTable:\n"+printFormatTable);
dbgLog.fine("printFormatNameTable:\n"+printFormatNameTable);
variableFormatTypeList = new String[varQnty];
for (int i = 0; i < varQnty; i++){
variableFormatTypeList[i]=SPSSConstants.FORMAT_CATEGORY_TABLE.get(
printFormatTable.get(variableNameList.get(i)));
dbgLog.fine("i="+i+"th variableFormatTypeList="+variableFormatTypeList[i]);
formatCategoryTable.put(variableNameList.get(i), variableFormatTypeList[i]);
}
dbgLog.fine("variableFormatType:\n"+Arrays.deepToString(variableFormatTypeList));
dbgLog.fine("formatCategoryTable:\n"+formatCategoryTable);
// contents (variable) checker concering decimals
variableTypeFinal = new int[varQnty];
Arrays.fill(variableTypeFinal, 0);
int numberOfDecimalVariables = 0;
List<String> casewiseRecordForTabFile = new ArrayList<String>();
String[] caseWiseDateFormatForUNF = null;
List<String> casewiseRecordForUNF = new ArrayList<String>();
// missing values are written to the tab-delimited file by
// using the default or user-specified missing-value strings;
// however, to calculate UNF/summary statistics,
// classes for these calculations require their specific
// missing values that differ from the above missing-value
// strings; therefore, after row data for the tab-delimited
// file are written, missing values in a row are changed to
// UNF/summary-statistics-OK ones.
// data-storage object for sumStat
dataTable2 = new Object[varQnty][caseQnty];
// storage of date formats to pass to UNF
dateFormats = new String[varQnty][caseQnty];
try {
for (int i = 0; ; i++){ // case-wise loop
byte[] buffer = new byte[OBS*nOBS];
int nbytesuc = stream.read(buffer);
StringBuilder sb_stringStorage = new StringBuilder("");
for (int k=0; k < nOBS; k++){
int offset= OBS*k;
// uncompressed case
// numeric missing value == sysmis
// FF FF FF FF FF FF eF FF(little endian)
// string missing value
// 20 20 20 20 20 20 20 20
// cf: compressed case
// numeric type:sysmis == 0xFF
// string type: missing value == 0xFE
//
boolean isNumeric = OBSwiseTypelList.get(k)==0 ? true : false;
if (isNumeric){
dbgLog.finer(k+"-th variable is numeric");
// interprete as double
ByteBuffer bb_double = ByteBuffer.wrap(
buffer, offset , LENGTH_SAV_OBS_BLOCK);
if (isLittleEndian){
bb_double.order(ByteOrder.LITTLE_ENDIAN);
}
//char[] hexpattern =
String dphex = new String(Hex.encodeHex(
Arrays.copyOfRange(bb_double.array(),
offset, offset+LENGTH_SAV_OBS_BLOCK)));
dbgLog.finer("dphex="+ dphex);
if ((dphex.equals("ffffffffffffefff"))||
(dphex.equals("ffefffffffffffff"))){
//casewiseRecordForTabFile.add(systemMissingValue);
// add the numeric missing value
dbgLog.fine("SAV Reader: adding: Missing Value (numeric)");
casewiseRecordForTabFile.add(MissingValueForTextDataFileNumeric);
} else {
Double ddatum = bb_double.getDouble();
dbgLog.fine("SAV Reader: adding: ddatum="+ddatum);
// add this non-missing-value numeric datum
casewiseRecordForTabFile.add(doubleNumberFormatter.format(ddatum)) ;
}
} else {
dbgLog.finer(k+"-th variable is string");
// string case
// strip space-padding
// do not trim: string might have spaces within it
// the missing value (hex) for a string variable is:
// "20 20 20 20 20 20 20 20"
String strdatum = new String(
Arrays.copyOfRange(buffer,
offset, (offset+LENGTH_SAV_OBS_BLOCK)),defaultCharSet);
dbgLog.finer("str_datum="+strdatum);
// add this non-missing-value string datum
casewiseRecordForTabFile.add(strdatum);
} // if isNumeric
} // k-loop
// String-variable's continuous block exits:
if (hasStringVarContinuousBlock){
// continuous blocks: string case
// concatenating process
//dbgLog.fine("concatenating process starts");
//dbgLog.fine("casewiseRecordForTabFile(before)="+casewiseRecordForTabFile);
//dbgLog.fine("casewiseRecordForTabFile(before:size)="+casewiseRecordForTabFile.size());
StringBuilder sb = new StringBuilder("");
int firstPosition = 0;
Set<Integer> removeJset = new HashSet<Integer>();
for (int j=0; j< nOBS; j++){
dbgLog.finer("j="+j+"-th type ="+OBSwiseTypelList.get(j));
if (OBSwiseTypelList.get(j) == -1){
// String continued fount at j-th
// look back the j-1
firstPosition = j-1;
int lastJ = j;
String concatanated = null;
removeJset.add(j);
sb.append(casewiseRecordForTabFile.get(j-1));
sb.append(casewiseRecordForTabFile.get(j));
for (int jc =1; ; jc++ ){
if (OBSwiseTypelList.get(j+jc) != -1){
// j is the end unit of this string variable
concatanated = sb.toString();
sb.setLength(0);
lastJ = j+jc;
break;
} else {
sb.append(casewiseRecordForTabFile.get(j+jc));
removeJset.add(j+jc);
}
}
casewiseRecordForTabFile.set(j-1, concatanated);
//out.println(j-1+"th concatanated="+concatanated);
j = lastJ -1;
} // end-of-if: continuous-OBS only
} // end of loop-j
List<String> newDataLine = new ArrayList<String>();
for (int jl=0; jl<casewiseRecordForTabFile.size();jl++){
//out.println("jl="+jl+"-th datum =["+casewiseRecordForTabFile.get(jl)+"]");
if (!removeJset.contains(jl) ){
newDataLine.add(casewiseRecordForTabFile.get(jl));
}
}
dbgLog.fine("new casewiseRecordForTabFile="+newDataLine);
dbgLog.fine("new casewiseRecordForTabFile(size)="+newDataLine.size());
casewiseRecordForTabFile = newDataLine;
} // end-if: stringContinuousVar-exist case
for (int el = 0; el < casewiseRecordForTabFile.size(); el++){
casewiseRecordForUNF.add(casewiseRecordForTabFile.get(el));
}
caseWiseDateFormatForUNF = new String[casewiseRecordForTabFile.size()];
caseIndex++;
dbgLog.finer("caseIndex="+caseIndex);
for (int k = 0; k < casewiseRecordForTabFile.size(); k++){
if (variableTypelList.get(k) > 0) {
// String variable case: set to -1
variableTypeFinal[k] = -1;
// See my comments for this padding removal logic
// in the "compressed" method -- L.A.
String paddRemoved = StringUtils.stripEnd(casewiseRecordForTabFile.get(k).toString(), null);
// TODO: clean this up. For now, just make sure that strings contain at least one blank space.
if (paddRemoved.equals("")) {
paddRemoved = " ";
}
casewiseRecordForUNF.set(k, paddRemoved);
casewiseRecordForTabFile.set(k, "\"" + paddRemoved.replaceAll("\"", Matcher.quoteReplacement("\\\"")) + "\"");
// end of String var case
} else {
// numeric var case
if (casewiseRecordForTabFile.get(k).equals(MissingValueForTextDataFileNumeric)) {
casewiseRecordForUNF.set(k, null);
}
} // end of variable-type check
if (casewiseRecordForTabFile.get(k)!=null && !casewiseRecordForTabFile.get(k).equals(MissingValueForTextDataFileNumeric)){
// to do date conversion
String variableFormatType = variableFormatTypeList[k];
dbgLog.finer("k="+k+"th variable format="+variableFormatType);
int formatDecimalPointPosition = formatDecimalPointPositionList.get(k);
if (variableFormatType.equals("date")){
dbgLog.finer("date case");
long dateDatum = Long.parseLong(casewiseRecordForTabFile.get(k).toString())*1000L- SPSS_DATE_OFFSET;
String newDatum = sdf_ymd.format(new Date(dateDatum));
dbgLog.finer("k="+k+":"+newDatum);
caseWiseDateFormatForUNF[k] = sdf_ymd.toPattern();
casewiseRecordForTabFile.set(k, newDatum);
casewiseRecordForUNF.set(k, newDatum);
//formatCategoryTable.put(variableNameList.get(k), "date");
} else if (variableFormatType.equals("time")) {
dbgLog.finer("time case:DTIME or DATETIME or TIME");
//formatCategoryTable.put(variableNameList.get(k), "time");
if (printFormatTable.get(variableNameList.get(k)).equals("DTIME")){
if (casewiseRecordForTabFile.get(k).toString().indexOf(".") < 0){
long dateDatum = Long.parseLong(casewiseRecordForTabFile.get(k).toString())*1000L - SPSS_DATE_BIAS;
String newDatum = sdf_dhms.format(new Date(dateDatum));
// Note: DTIME is not a complete date, so we don't save a date format with it
dbgLog.finer("k="+k+":"+newDatum);
casewiseRecordForTabFile.set(k, newDatum);
casewiseRecordForUNF.set(k, newDatum);
} else {
// decimal point included
String[] timeData = casewiseRecordForTabFile.get(k).toString().split("\\.");
dbgLog.finer(StringUtils.join(timeData, "|"));
long dateDatum = Long.parseLong(timeData[0])*1000L - SPSS_DATE_BIAS;
StringBuilder sb_time = new StringBuilder(
sdf_dhms.format(new Date(dateDatum)));
if (formatDecimalPointPosition > 0){
sb_time.append("."+timeData[1].substring(0,formatDecimalPointPosition));
}
dbgLog.finer("k="+k+":"+sb_time.toString());
casewiseRecordForTabFile.set(k, sb_time.toString());
casewiseRecordForUNF.set(k, sb_time.toString());
}
} else if (printFormatTable.get(variableNameList.get(k)).equals("DATETIME")){
if (casewiseRecordForTabFile.get(k).toString().indexOf(".") < 0){
long dateDatum = Long.parseLong(casewiseRecordForTabFile.get(k).toString())*1000L - SPSS_DATE_OFFSET;
String newDatum = sdf_ymdhms.format(new Date(dateDatum));
caseWiseDateFormatForUNF[k] = sdf_ymdhms.toPattern();
dbgLog.finer("k="+k+":"+newDatum);
casewiseRecordForTabFile.set(k, newDatum);
casewiseRecordForUNF.set(k, newDatum);
} else {
// decimal point included
String[] timeData = casewiseRecordForTabFile.get(k).toString().split("\\.");
//dbgLog.finer(StringUtils.join(timeData, "|"));
long dateDatum = Long.parseLong(timeData[0])*1000L- SPSS_DATE_OFFSET;
StringBuilder sb_time = new StringBuilder(
sdf_ymdhms.format(new Date(dateDatum)));
//dbgLog.finer(sb_time.toString());
if (formatDecimalPointPosition > 0){
sb_time.append("."+timeData[1].substring(0,formatDecimalPointPosition));
}
caseWiseDateFormatForUNF[k] = sdf_ymdhms.toPattern() + (formatDecimalPointPosition > 0 ? ".S" : "");
dbgLog.finer("k="+k+":"+sb_time.toString());
casewiseRecordForTabFile.set(k, sb_time.toString());
casewiseRecordForUNF.set(k, sb_time.toString());
}
} else if (printFormatTable.get(variableNameList.get(k)).equals("TIME")){
if (casewiseRecordForTabFile.get(k).toString().indexOf(".") < 0){
long dateDatum = Long.parseLong(casewiseRecordForTabFile.get(k).toString())*1000L;
String newDatum = sdf_hms.format(new Date(dateDatum));
caseWiseDateFormatForUNF[k] = sdf_hms.toPattern();
dbgLog.finer("k="+k+":"+newDatum);
casewiseRecordForTabFile.set(k, newDatum);
casewiseRecordForUNF.set(k, newDatum);
} else {
// decimal point included
String[] timeData = casewiseRecordForTabFile.get(k).toString().split("\\.");
//dbgLog.finer(StringUtils.join(timeData, "|"));
long dateDatum = Long.parseLong(timeData[0])*1000L;
StringBuilder sb_time = new StringBuilder(
sdf_hms.format(new Date(dateDatum)));
//dbgLog.finer(sb_time.toString());
if (formatDecimalPointPosition > 0){
sb_time.append("."+timeData[1].substring(0,formatDecimalPointPosition));
}
caseWiseDateFormatForUNF[k] = this.sdf_hms.toPattern() + (formatDecimalPointPosition > 0 ? ".S" : "");
dbgLog.finer("k="+k+":"+sb_time.toString());
casewiseRecordForTabFile.set(k, sb_time.toString());
casewiseRecordForUNF.set(k, sb_time.toString());
}
}
} else if (variableFormatType.equals("other")){
dbgLog.finer("other non-date/time case");
if (printFormatTable.get(variableNameList.get(k)).equals("WKDAY")){
// day of week
dbgLog.finer("data k="+k+":"+casewiseRecordForTabFile.get(k));
dbgLog.finer("data k="+k+":"+SPSSConstants.WEEKDAY_LIST.get(Integer.valueOf(casewiseRecordForTabFile.get(k).toString())-1));
String newDatum = SPSSConstants.WEEKDAY_LIST.get(Integer.valueOf(casewiseRecordForTabFile.get(k).toString())-1);
casewiseRecordForTabFile.set(k, newDatum);
casewiseRecordForUNF.set(k, newDatum);
dbgLog.finer("wkday:k="+k+":"+casewiseRecordForTabFile.get(k));
} else if (printFormatTable.get(variableNameList.get(k)).equals("MONTH")){
// month
dbgLog.finer("data k="+k+":"+casewiseRecordForTabFile.get(k));
dbgLog.finer("data k="+k+":"+SPSSConstants.MONTH_LIST.get(Integer.valueOf(casewiseRecordForTabFile.get(k).toString())-1));
String newDatum = SPSSConstants.MONTH_LIST.get(Integer.valueOf(casewiseRecordForTabFile.get(k).toString())-1);
casewiseRecordForTabFile.set(k, newDatum);
casewiseRecordForUNF.set(k, newDatum);
dbgLog.finer("month:k="+k+":"+casewiseRecordForTabFile.get(k));
}
}
// end of date/time block
} // end: date-time-datum check
} // end: loop-k(2nd: variablte-wise-check)
// write to tab file
if (casewiseRecordForTabFile.size() > 0) {
pwout.println(StringUtils.join(casewiseRecordForTabFile, "\t"));
}
if (casewiseRecordForTabFile.size() > 0) {
for (int ij = 0; ij < varQnty; ij++) {
dataTable2[ij][caseIndex - 1] = casewiseRecordForUNF.get(ij);
if (variableFormatTypeList[ij].equals("date") || variableFormatTypeList[ij].equals("time")) {
this.dateFormats[ij][caseIndex - 1] = caseWiseDateFormatForUNF[ij];
}
}
}
// numeric contents-check
for (int l = 0; l < casewiseRecordForTabFile.size(); l++){
if ( variableFormatTypeList[l].equals("date") ||
variableFormatTypeList[l].equals("time") ||
printFormatTable.get(variableNameList.get(l)).equals("WKDAY") ||
printFormatTable.get(variableNameList.get(l)).equals("MONTH") ) {
variableTypeFinal[l] = -1;
}
if (variableTypeFinal[l] == 0){
if (casewiseRecordForTabFile.get(l).toString().indexOf(".") >= 0){
// l-th variable is not integer
variableTypeFinal[l] = 1;
decimalVariableSet.add(l);
}
}
}
// reset the case-wise working objects
casewiseRecordForTabFile.clear();
casewiseRecordForUNF.clear();
if (stream.available() == 0){
// reached the end of this file
// do exit-processing
dbgLog.fine("***** reached the end of the file at "+ii
+"th iteration *****");
break;
} // if eof processing
} //i-loop: case(row) iteration
// close the writer
pwout.close();
} catch (IOException ex) {
throw ex;
}
smd.getFileInformation().put("caseQnty", caseQnty);
smd.setDecimalVariables(decimalVariableSet);
smd.setVariableFormatCategory(formatCategoryTable);
// contents check
dbgLog.fine("variableType="+ArrayUtils.toString(variableTypeFinal));
dbgLog.fine("numberOfDecimalVariables="+numberOfDecimalVariables);
dbgLog.fine("decimalVariableSet="+decimalVariableSet);
dbgLog.fine("***** decodeRecordTypeDataUnCompressed(): end *****");
}
// Utility Methods -----------------------------------------------------//
private boolean variableNameIsAnIncrement (String varNameBase, String variableName){
if ( varNameBase == null ) {
return false;
}
if ( varNameBase.concat("0").equals(variableName) ) {
return true;
}
return false;
}
private boolean variableNameIsAnIncrement (String varNameBase, String lastExtendedVariable, String currentVariable) {
if ( varNameBase == null ||
lastExtendedVariable == null ||
currentVariable == null ) {
return false;
}
if ( varNameBase.length() >= lastExtendedVariable.length() ) {
return false;
}
if ( varNameBase.length() >= currentVariable.length() ) {
return false;
}
if ( !(varNameBase.equals(currentVariable.substring(0,varNameBase.length()))) ) {
return false;
}
String lastSuffix = lastExtendedVariable.substring(varNameBase.length());
String currentSuffix = currentVariable.substring(varNameBase.length());
if ( currentSuffix.length() > 2 ) {
return false;
}
//if ( !currentSuffix.matches("^[0-9A-Z]*$") ) {
// return false;
//}
return suffixIsAnIncrement (lastSuffix, currentSuffix);
}
private boolean suffixIsAnIncrement ( String lastSuffix, String currentSuffix ) {
// Extended variable suffixes are base-36 number strings in the
// [0-9A-Z] alphabet. I.e. the incremental suffixes go from
// 0 to 9 to A to Z to 10 to 1Z ... etc.
int lastSuffixValue = intBase36 ( lastSuffix );
int currentSuffixValue = intBase36 ( currentSuffix );
if ( currentSuffixValue - lastSuffixValue > 0 ) {
return true;
}
return false;
}
private int intBase36 ( String stringBase36 ) {
// integer value of a base-36 string in [0-9A-Z] alphabet;
// i.e. "0" = 0, "9" = 9, "A" = 10,
// "Z" = 35, "10" = 36, "1Z" = 71 ...
byte[] stringBytes = stringBase36.getBytes();
int ret = 0;
for ( int i = 0; i < stringBytes.length; i++ ) {
int value = 0;
if (stringBytes[i] >= 48 && stringBytes[i] <= 57 ) {
// [0-9]
value = (int)stringBytes[i] - 48;
} else if (stringBytes[i] >= 65 && stringBytes[i] <= 90 ) {
// [A-Z]
value = (int)stringBytes[i] - 55;
}
ret = (ret * 36) + value;
}
return ret;
}
private int getSAVintAdjustedBlockLength(int rawLength){
int adjustedLength = rawLength;
if ((rawLength%LENGTH_SAV_INT_BLOCK ) != 0){
adjustedLength =
LENGTH_SAV_INT_BLOCK*(rawLength/LENGTH_SAV_INT_BLOCK +1) ;
}
return adjustedLength;
}
private int getSAVobsAdjustedBlockLength(int rawLength){
int adjustedLength = rawLength;
if ((rawLength%LENGTH_SAV_OBS_BLOCK ) != 0){
adjustedLength =
LENGTH_SAV_OBS_BLOCK*(rawLength/LENGTH_SAV_OBS_BLOCK +1) ;
}
return adjustedLength;
}
private int[] parseRT7SubTypefieldHeader(BufferedInputStream stream) throws IOException {
int length_unit_length = 4;
int length_number_of_units = 4;
int storage_size = length_unit_length + length_number_of_units;
int[] headerSection = new int[2];
byte[] byteStorage = new byte[storage_size];
try {
int nbytes = stream.read(byteStorage);
// to-do check against nbytes
//printHexDump(byteStorage, "RT7:storage");
ByteBuffer bb_data_type = ByteBuffer.wrap(byteStorage,
0, length_unit_length);
if (isLittleEndian){
bb_data_type.order(ByteOrder.LITTLE_ENDIAN);
}
int unitLength = bb_data_type.getInt();
dbgLog.fine("parseRT7 SubTypefield: unitLength="+unitLength);
ByteBuffer bb_number_of_units = ByteBuffer.wrap(byteStorage,
length_unit_length, length_number_of_units);
if (isLittleEndian){
bb_number_of_units.order(ByteOrder.LITTLE_ENDIAN);
}
int numberOfUnits = bb_number_of_units.getInt();
dbgLog.fine("parseRT7 SubTypefield: numberOfUnits="+numberOfUnits);
headerSection[0] = unitLength;
headerSection[1] = numberOfUnits;
return headerSection;
} catch (IOException ex) {
throw ex;
}
}
private void parseRT7SubTypefield(BufferedInputStream stream) throws IOException {
int length_unit_length = 4;
int length_number_of_units = 4;
int storage_size = length_unit_length + length_number_of_units;
int[] headerSection = new int[2];
byte[] byteStorage = new byte[storage_size];
try{
int nbytes = stream.read(byteStorage);
// to-do check against nbytes
//printHexDump(byteStorage, "RT7:storage");
ByteBuffer bb_data_type = ByteBuffer.wrap(byteStorage,
0, length_unit_length);
if (isLittleEndian){
bb_data_type.order(ByteOrder.LITTLE_ENDIAN);
}
int unitLength = bb_data_type.getInt();
dbgLog.fine("parseRT7 SubTypefield: unitLength="+unitLength);
ByteBuffer bb_number_of_units = ByteBuffer.wrap(byteStorage,
length_unit_length, length_number_of_units);
if (isLittleEndian){
bb_number_of_units.order(ByteOrder.LITTLE_ENDIAN);
}
int numberOfUnits = bb_number_of_units.getInt();
dbgLog.fine("parseRT7 SubTypefield: numberOfUnits="+numberOfUnits);
headerSection[0] = unitLength;
headerSection[1] = numberOfUnits;
for (int i=0; i<numberOfUnits; i++){
byte[] work = new byte[unitLength];
int nb = stream.read(work);
dbgLog.finer("raw bytes in Hex:"+ new String(Hex.encodeHex(work)));
ByteBuffer bb_field = ByteBuffer.wrap(work);
if (isLittleEndian){
bb_field.order(ByteOrder.LITTLE_ENDIAN);
}
dbgLog.fine("RT7ST: raw bytes in Hex:"+ new String(Hex.encodeHex(bb_field.array())));
if (unitLength==4){
int fieldData = bb_field.getInt();
dbgLog.fine("RT7ST: "+i+"-th fieldData="+fieldData);
dbgLog.fine("RT7ST: fieldData in Hex="+Integer.toHexString(fieldData));
} else if (unitLength==8){
double fieldData = bb_field.getDouble();
dbgLog.finer("RT7ST: "+i+"-th fieldData="+fieldData);
dbgLog.finer("RT7ST: fieldData in Hex="+Double.toHexString(fieldData));
}
dbgLog.finer("");
}
} catch (IOException ex) {
//ex.printStackTrace();
throw ex;
}
}
private List<byte[]> getRT7SubTypefieldData(BufferedInputStream stream) throws IOException {
int length_unit_length = 4;
int length_number_of_units = 4;
int storage_size = length_unit_length + length_number_of_units;
List<byte[]> dataList = new ArrayList<byte[]>();
int[] headerSection = new int[2];
byte[] byteStorage = new byte[storage_size];
try{
int nbytes = stream.read(byteStorage);
// to-do check against nbytes
//printHexDump(byteStorage, "RT7:storage");
ByteBuffer bb_data_type = ByteBuffer.wrap(byteStorage,
0, length_unit_length);
if (isLittleEndian){
bb_data_type.order(ByteOrder.LITTLE_ENDIAN);
}
int unitLength = bb_data_type.getInt();
dbgLog.fine("parseRT7SubTypefield: unitLength="+unitLength);
ByteBuffer bb_number_of_units = ByteBuffer.wrap(byteStorage,
length_unit_length, length_number_of_units);
if (isLittleEndian){
bb_number_of_units.order(ByteOrder.LITTLE_ENDIAN);
}
int numberOfUnits = bb_number_of_units.getInt();
dbgLog.fine("parseRT7SubTypefield: numberOfUnits="+numberOfUnits);
headerSection[0] = unitLength;
headerSection[1] = numberOfUnits;
for (int i=0; i<numberOfUnits; i++){
byte[] work = new byte[unitLength];
int nb = stream.read(work);
dbgLog.finer(new String(Hex.encodeHex(work)));
dataList.add(work);
}
} catch (IOException ex) {
//ex.printStackTrace();
throw ex;
}
return dataList;
}
void print2Darray(Object[][] datatable, String title){
dbgLog.fine(title);
for (int i=0; i< datatable.length; i++){
dbgLog.fine(StringUtils.join(datatable[i], "|"));
}
}
private String getUNF(Object[] varData, String[] dateFormats, int variableType,
String unfVersionNumber, int variablePosition)
throws NumberFormatException, UnfException,
IOException, NoSuchAlgorithmException{
String unfValue = null;
dbgLog.fine("variableType="+variableType);
dbgLog.finer("unfVersionNumber="+unfVersionNumber);
dbgLog.fine("variablePosition="+variablePosition);
dbgLog.fine("variableName="+variableNameList.get(variablePosition));
dbgLog.fine("varData:\n"+Arrays.deepToString(varData));
switch(variableType){
case 0:
// Integer case
// note: due to DecimalFormat class is used to
// remove an unnecessary decimal point and 0-padding
// numeric (double) data are now String objects
dbgLog.fine("Integer case");
// Convert array of Strings to array of Longs
Long[] ldata = new Long[varData.length];
for (int i = 0; i < varData.length; i++) {
if (varData[i] != null) {
ldata[i] = new Long((String) varData[i]);
}
}
unfValue = UNF5Util.calculateUNF(ldata);
dbgLog.finer("integer:unfValue=" + unfValue);
dbgLog.info("sumstat:long case=" + Arrays.deepToString(
ArrayUtils.toObject(StatHelper.calculateSummaryStatistics(ldata))));
dbgLog.info("sumstat:long case=" + Arrays.deepToString(
ArrayUtils.toObject(StatHelper.calculateSummaryStatistics(ldata))));
smd.getSummaryStatisticsTable().put(variablePosition,
ArrayUtils.toObject(StatHelper.calculateSummaryStatistics(ldata)));
Map<String, Integer> catStat = StatHelper.calculateCategoryStatistics(ldata);
smd.getCategoryStatisticsTable().put(variableNameList.get(variablePosition), catStat);
break;
case 1:
// double case
// note: due to DecimalFormat class is used to
// remove an unnecessary decimal point and 0-padding
// numeric (double) data are now String objects
dbgLog.finer("double case");
// Convert array of Strings to array of Doubles
Double[] ddata = new Double[varData.length];
for (int i=0;i<varData.length;i++) {
if (varData[i]!=null) {
ddata[i] = new Double((String)varData[i]);
}
}
unfValue = UNF5Util.calculateUNF(ddata);
dbgLog.finer("double:unfValue="+unfValue);
smd.getSummaryStatisticsTable().put(variablePosition,
ArrayUtils.toObject(StatHelper.calculateSummaryStatisticsContDistSample(ddata)));
dbgLog.info("sumstat:long case=" + Arrays.deepToString(
ArrayUtils.toObject(StatHelper.calculateSummaryStatisticsContDistSample(ddata))));
break;
case -1:
// String case
dbgLog.finer("string case");
String[] strdata = Arrays.asList(varData).toArray(
new String[varData.length]);
dbgLog.finer("string array passed to calculateUNF: "+Arrays.deepToString(strdata));
unfValue = UNF5Util.calculateUNF(strdata, dateFormats);
dbgLog.finer("string:unfValue="+unfValue);
smd.getSummaryStatisticsTable().put(variablePosition,
StatHelper.calculateSummaryStatistics(strdata));
Map<String, Integer> StrCatStat = StatHelper.calculateCategoryStatistics(strdata);
//out.println("catStat="+StrCatStat);
smd.getCategoryStatisticsTable().put(variableNameList.get(variablePosition), StrCatStat);
break;
default:
dbgLog.fine("unknown variable type found");
String errorMessage =
"unknow variable Type found at varData section";
throw new IllegalArgumentException(errorMessage);
} // switch
dbgLog.fine("unfvalue(last)="+unfValue);
dbgLog.info("[SAV] UNF = " + unfValue);
return unfValue;
}
}
| false | false | null | null |
diff --git a/src/closestpair/ClosestPairFinder.java b/src/closestpair/ClosestPairFinder.java
index acd607f..2a12e0e 100644
--- a/src/closestpair/ClosestPairFinder.java
+++ b/src/closestpair/ClosestPairFinder.java
@@ -1,41 +1,47 @@
package closestpair;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class ClosestPairFinder {
private static double minimum;
/** @param args */
public static void main(String[] args) {
List<Point> list = parse(args[0]);
Finder finder = new Finder(list);
minimum = finder.solve();
+ System.out.println(minimum);
}
private static List<Point> parse(String file) {
Scanner scanner = null;
try {
scanner = new Scanner(new File(file));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
+
+ if (file.endsWith(".tsp")) {
+ while (!scanner.nextLine().equals("NODE_COORD_SECTION")) {}
+ }
+
List<Point> list = new ArrayList<Point>();
while (scanner.hasNextLine()) {
String line = scanner.nextLine().trim();
- if (!line.equals("")) {
+ if (!line.equals("") && !line.equals("EOF")) {
String pointData[] = line.split("\\s+");
list.add(new Point(pointData[0], Double.valueOf(pointData[1]), Double.valueOf(pointData[2])));
}
}
return list;
}
public static double lastMinimum() {
return minimum;
}
}
| false | false | null | null |
diff --git a/src/com/itmill/toolkit/terminal/gwt/client/ui/layout/ChildComponentContainer.java b/src/com/itmill/toolkit/terminal/gwt/client/ui/layout/ChildComponentContainer.java
index 1527cf38d..a6700531d 100644
--- a/src/com/itmill/toolkit/terminal/gwt/client/ui/layout/ChildComponentContainer.java
+++ b/src/com/itmill/toolkit/terminal/gwt/client/ui/layout/ChildComponentContainer.java
@@ -1,707 +1,734 @@
package com.itmill.toolkit.terminal.gwt.client.ui.layout;
import java.util.Iterator;
import java.util.NoSuchElementException;
import com.google.gwt.dom.client.DivElement;
import com.google.gwt.dom.client.Document;
import com.google.gwt.user.client.ui.Panel;
import com.google.gwt.user.client.ui.Widget;
import com.itmill.toolkit.terminal.gwt.client.ApplicationConnection;
import com.itmill.toolkit.terminal.gwt.client.BrowserInfo;
import com.itmill.toolkit.terminal.gwt.client.ICaption;
import com.itmill.toolkit.terminal.gwt.client.Paintable;
import com.itmill.toolkit.terminal.gwt.client.UIDL;
import com.itmill.toolkit.terminal.gwt.client.Util;
import com.itmill.toolkit.terminal.gwt.client.RenderInformation.FloatSize;
import com.itmill.toolkit.terminal.gwt.client.RenderInformation.Size;
import com.itmill.toolkit.terminal.gwt.client.ui.AlignmentInfo;
public class ChildComponentContainer extends Panel {
/**
* Size of the container DIV excluding any margins and also excluding the
* expansion amount (containerExpansion)
*/
private Size contSize = new Size(0, 0);
/**
* Size of the widget inside the container DIV
*/
private Size widgetSize = new Size(0, 0);
/**
* Size of the caption
*/
private int captionRequiredWidth = 0;
private int captionWidth = 0;
private int captionHeight = 0;
/**
* Padding added to the container when it is larger than the component.
*/
private Size containerExpansion = new Size(0, 0);
private float expandRatio;
private int containerMarginLeft = 0;
private int containerMarginTop = 0;
AlignmentInfo alignment = new AlignmentInfo(AlignmentInfo.ALIGNMENT_LEFT,
AlignmentInfo.ALIGNMENT_TOP);
private int alignmentLeftOffsetForWidget = 0;
private int alignmentLeftOffsetForCaption = 0;
/**
* Top offset for implementing alignment. Top offset is set to the container
* DIV as it otherwise would have to be set to either the Caption or the
* Widget depending on whether there is a caption and where the caption is
* located.
*/
private int alignmentTopOffset = 0;
// private Margins alignmentOffset = new Margins(0, 0, 0, 0);
private ICaption caption = null;
private DivElement containerDIV;
private DivElement widgetDIV;
private Widget widget;
private FloatSize relativeSize = null;
public ChildComponentContainer(Widget widget, int orientation) {
super();
containerDIV = Document.get().createDivElement();
setElement(containerDIV);
containerDIV.getStyle().setProperty("height", "0");
// DOM.setStyleAttribute(containerDIV, "width", "0px");
containerDIV.getStyle().setProperty("overflow", "hidden");
widgetDIV = Document.get().createDivElement();
setFloat(widgetDIV, "left");
if (BrowserInfo.get().isIE()) {
/*
* IE requires position: relative on overflow:hidden elements if
* they should hide position:relative elements. Without this e.g. a
* 1000x1000 Panel inside an 500x500 OrderedLayout will not be
* clipped but fully shown.
*/
containerDIV.getStyle().setProperty("position", "relative");
widgetDIV.getStyle().setProperty("position", "relative");
}
containerDIV.appendChild(widgetDIV);
setOrientation(orientation);
setWidget(widget);
}
public void setWidget(Widget w) {
// Validate
if (w == widget) {
return;
}
// Detach new child.
if (w != null) {
w.removeFromParent();
}
// Remove old child.
if (widget != null) {
remove(widget);
}
// Logical attach.
widget = w;
if (w != null) {
// Physical attach.
widgetDIV.appendChild(widget.getElement());
adopt(w);
}
}
private static void setFloat(DivElement div, String floatString) {
if (BrowserInfo.get().isIE()) {
div.getStyle().setProperty("styleFloat", floatString);
// IE requires display:inline for margin-left to work together
// with float:left
if (floatString.equals("left")) {
div.getStyle().setProperty("display", "inline");
} else {
div.getStyle().setProperty("display", "block");
}
} else {
div.getStyle().setProperty("cssFloat", floatString);
}
}
public void setOrientation(int orientation) {
if (orientation == CellBasedLayout.ORIENTATION_HORIZONTAL) {
setFloat(containerDIV, "left");
} else {
setFloat(containerDIV, "");
}
setHeight("0px");
// setWidth("0px");
contSize.setHeight(0);
contSize.setWidth(0);
containerMarginLeft = 0;
containerMarginTop = 0;
getElement().getStyle().setProperty("paddingLeft", "0");
getElement().getStyle().setProperty("paddingTop", "0");
containerExpansion.setHeight(0);
containerExpansion.setWidth(0);
// Clear old alignments
clearAlignments();
}
public void renderChild(UIDL childUIDL, ApplicationConnection client,
int fixedWidth) {
/*
* Must remove width specification from container before rendering to
* allow components to grow in horizontal direction.
*
* For fixed width layouts we specify the width directly so that height
* is automatically calculated correctly (e.g. for Labels).
*/
if (fixedWidth > 0) {
containerDIV.getStyle().setProperty("width", fixedWidth + "px");
} else {
setUnlimitedContainerWidth();
}
((Paintable) widget).updateFromUIDL(childUIDL, client);
}
public void setUnlimitedContainerWidth() {
containerDIV.getStyle().setProperty("width", "1000000px");
}
public void updateWidgetSize() {
/*
* Widget wrapper includes margin which the widget offsetWidth/Height
* does not include
*/
- int w = widgetDIV.getOffsetWidth();
- int h = widgetDIV.getOffsetHeight();
+ int w = getRequiredWidth(widgetDIV);
+ int h = getRequiredHeight(widgetDIV);
+
widgetSize.setWidth(w);
widgetSize.setHeight(h);
// ApplicationConnection.getConsole().log(
// Util.getSimpleName(widget) + " size is " + w + "," + h);
}
+ public static native int getRequiredWidth(
+ com.google.gwt.dom.client.Element element)
+ /*-{
+ var width;
+ if (element.getBoundingClientRect != null) {
+ var rect = element.getBoundingClientRect();
+ width = Math.ceil(rect.right - rect.left);
+ } else {
+ width = elem.offsetWidth;
+ }
+ return width;
+ }-*/;
+
+ public static native int getRequiredHeight(
+ com.google.gwt.dom.client.Element element)
+ /*-{
+ var height;
+ if (element.getBoundingClientRect != null) {
+ var rect = element.getBoundingClientRect();
+ height = Math.ceil(rect.bottom - rect.top);
+ } else {
+ height = elem.offsetHeight;
+ }
+ return height;
+ }-*/;
+
public void setMarginLeft(int marginLeft) {
containerMarginLeft = marginLeft;
getElement().getStyle().setPropertyPx("paddingLeft", marginLeft);
}
public void setMarginTop(int marginTop) {
containerMarginTop = marginTop;
getElement().getStyle().setPropertyPx("paddingTop",
marginTop + alignmentTopOffset);
updateContainerDOMSize();
}
public void updateAlignments(int parentWidth, int parentHeight) {
if (parentHeight == -1) {
parentHeight = contSize.getHeight();
}
if (parentWidth == -1) {
parentWidth = contSize.getWidth();
}
alignmentTopOffset = calculateVerticalAlignmentTopOffset(parentHeight);
calculateHorizontalAlignment(parentWidth);
applyAlignments();
}
private void applyAlignments() {
// Update top margin to take alignment into account
setMarginTop(containerMarginTop);
if (caption != null) {
caption.getElement().getStyle().setPropertyPx("marginLeft",
alignmentLeftOffsetForCaption);
}
widgetDIV.getStyle().setPropertyPx("marginLeft",
alignmentLeftOffsetForWidget);
}
public int getCaptionRequiredWidth() {
if (caption == null) {
return 0;
}
return captionRequiredWidth;
}
public int getCaptionWidth() {
if (caption == null) {
return 0;
}
return captionWidth;
}
public int getCaptionHeight() {
if (caption == null) {
return 0;
}
return captionHeight;
}
public int getCaptionWidthAfterComponent() {
if (caption == null || !caption.shouldBePlacedAfterComponent()) {
return 0;
}
return getCaptionWidth();
}
public int getCaptionHeightAboveComponent() {
if (caption == null || caption.shouldBePlacedAfterComponent()) {
return 0;
}
return getCaptionHeight();
}
private int calculateVerticalAlignmentTopOffset(int emptySpace) {
if (alignment.isTop()) {
return 0;
}
if (caption != null) {
if (caption.shouldBePlacedAfterComponent()) {
/*
* Take into account the rare case that the caption on the right
* side of the component AND is higher than the component
*/
emptySpace -= Math.max(widgetSize.getHeight(), caption
.getHeight());
} else {
emptySpace -= widgetSize.getHeight();
emptySpace -= getCaptionHeight();
}
} else {
/*
* There is no caption and thus we do not need to take anything but
* the widget into account
*/
emptySpace -= widgetSize.getHeight();
}
int top = 0;
if (alignment.isVerticalCenter()) {
top = emptySpace / 2;
} else if (alignment.isBottom()) {
top = emptySpace;
}
if (top < 0) {
top = 0;
}
return top;
}
private void calculateHorizontalAlignment(int emptySpace) {
alignmentLeftOffsetForCaption = 0;
alignmentLeftOffsetForWidget = 0;
if (alignment.isLeft()) {
return;
}
int captionSpace = emptySpace;
int widgetSpace = emptySpace;
if (caption != null) {
// There is a caption
if (caption.shouldBePlacedAfterComponent()) {
/*
* The caption is after component. In this case the caption
* needs no alignment.
*/
captionSpace = 0;
widgetSpace -= widgetSize.getWidth();
widgetSpace -= getCaptionWidth();
} else {
/*
* The caption is above the component. Caption and widget needs
* separate alignment offsets.
*/
widgetSpace -= widgetSize.getWidth();
captionSpace -= getCaptionWidth();
}
} else {
/*
* There is no caption and thus we do not need to take anything but
* the widget into account
*/
captionSpace = 0;
widgetSpace -= widgetSize.getWidth();
}
if (alignment.isHorizontalCenter()) {
alignmentLeftOffsetForCaption = captionSpace / 2;
alignmentLeftOffsetForWidget = widgetSpace / 2;
} else if (alignment.isRight()) {
alignmentLeftOffsetForCaption = captionSpace;
alignmentLeftOffsetForWidget = widgetSpace;
}
if (alignmentLeftOffsetForCaption < 0) {
alignmentLeftOffsetForCaption = 0;
}
if (alignmentLeftOffsetForWidget < 0) {
alignmentLeftOffsetForWidget = 0;
}
}
public void setAlignment(AlignmentInfo alignmentInfo) {
alignment = alignmentInfo;
}
public Size getWidgetSize() {
return widgetSize;
}
public void updateCaption(UIDL uidl, ApplicationConnection client) {
if (ICaption.isNeeded(uidl)) {
// We need a caption
ICaption newCaption = caption;
if (newCaption == null) {
newCaption = new ICaption((Paintable) widget, client);
// Set initial height to avoid Safari flicker
newCaption.setHeight("18px");
// newCaption.setHeight(newCaption.getHeight()); // This might
// be better... ??
}
boolean positionChanged = newCaption.updateCaption(uidl);
if (newCaption != caption || positionChanged) {
setCaption(newCaption);
}
} else {
// Caption is not needed
if (caption != null) {
remove(caption);
}
}
updateCaptionSize();
}
public void updateCaptionSize() {
captionWidth = 0;
captionHeight = 0;
if (caption != null) {
captionWidth = caption.getRenderedWidth();
captionHeight = caption.getHeight();
captionRequiredWidth = caption.getRequiredWidth();
/*
* ApplicationConnection.getConsole().log(
* "Caption rendered width: " + captionWidth +
* ", caption required width: " + captionRequiredWidth +
* ", caption height: " + captionHeight);
*/
}
}
private void setCaption(ICaption newCaption) {
// Validate
// if (newCaption == caption) {
// return;
// }
// Detach new child.
if (newCaption != null) {
newCaption.removeFromParent();
}
// Remove old child.
if (caption != null && newCaption != caption) {
remove(caption);
}
// Logical attach.
caption = newCaption;
if (caption != null) {
// Physical attach.
if (caption.shouldBePlacedAfterComponent()) {
Util.setFloat(caption.getElement(), "left");
containerDIV.appendChild(caption.getElement());
} else {
Util.setFloat(caption.getElement(), "");
containerDIV.insertBefore(caption.getElement(), widgetDIV);
}
adopt(caption);
}
}
@Override
public boolean remove(Widget child) {
// Validate
if (child != caption && child != widget) {
return false;
}
// Orphan
orphan(child);
// Physical && Logical Detach
if (child == caption) {
containerDIV.removeChild(child.getElement());
caption = null;
} else {
widgetDIV.removeChild(child.getElement());
widget = null;
}
return true;
}
public Iterator<Widget> iterator() {
return new ChildComponentContainerIterator<Widget>();
}
public class ChildComponentContainerIterator<T> implements Iterator<Widget> {
private int id = 0;
public boolean hasNext() {
return (id < size());
}
public Widget next() {
Widget w = get(id);
id++;
return w;
}
private Widget get(int i) {
if (i == 0) {
if (widget != null) {
return widget;
} else if (caption != null) {
return caption;
} else {
throw new NoSuchElementException();
}
} else if (i == 1) {
if (widget != null && caption != null) {
return caption;
} else {
throw new NoSuchElementException();
}
} else {
throw new NoSuchElementException();
}
}
public void remove() {
int toRemove = id - 1;
if (toRemove == 0) {
if (widget != null) {
ChildComponentContainer.this.remove(widget);
} else if (caption != null) {
ChildComponentContainer.this.remove(caption);
} else {
throw new IllegalStateException();
}
} else if (toRemove == 1) {
if (widget != null && caption != null) {
ChildComponentContainer.this.remove(caption);
} else {
throw new IllegalStateException();
}
} else {
throw new IllegalStateException();
}
id--;
}
}
public int size() {
if (widget != null) {
if (caption != null) {
return 2;
} else {
return 1;
}
} else {
if (caption != null) {
return 1;
} else {
return 0;
}
}
}
public Widget getWidget() {
return widget;
}
/**
* Return true if the size of the widget has been specified in the selected
* orientation.
*
* @return
*/
public boolean widgetHasSizeSpecified(int orientation) {
String size;
if (orientation == CellBasedLayout.ORIENTATION_HORIZONTAL) {
size = widget.getElement().getStyle().getProperty("width");
} else {
size = widget.getElement().getStyle().getProperty("height");
}
return (size != null && !size.equals(""));
}
public boolean isComponentRelativeSized(int orientation) {
if (relativeSize == null) {
return false;
}
if (orientation == CellBasedLayout.ORIENTATION_HORIZONTAL) {
return relativeSize.getWidth() >= 0;
} else {
return relativeSize.getHeight() >= 0;
}
}
public void setRelativeSize(FloatSize relativeSize) {
this.relativeSize = relativeSize;
}
public Size getContSize() {
return contSize;
}
public void clearAlignments() {
alignmentLeftOffsetForCaption = 0;
alignmentLeftOffsetForWidget = 0;
alignmentTopOffset = 0;
applyAlignments();
}
public void setExpandRatio(int expandRatio) {
this.expandRatio = (expandRatio / 1000.0f);
}
public int expand(int orientation, int spaceForExpansion) {
int expansionAmount = (int) ((double) spaceForExpansion * expandRatio);
if (orientation == CellBasedLayout.ORIENTATION_HORIZONTAL) {
// HORIZONTAL
containerExpansion.setWidth(expansionAmount);
} else {
// VERTICAL
containerExpansion.setHeight(expansionAmount);
}
return expansionAmount;
}
public void expandExtra(int orientation, int extra) {
if (orientation == CellBasedLayout.ORIENTATION_HORIZONTAL) {
// HORIZONTAL
containerExpansion.setWidth(containerExpansion.getWidth() + extra);
} else {
// VERTICAL
containerExpansion
.setHeight(containerExpansion.getHeight() + extra);
}
}
public void setContainerSize(int widgetAndCaptionWidth,
int widgetAndCaptionHeight) {
int containerWidth = widgetAndCaptionWidth;
containerWidth += containerExpansion.getWidth();
int containerHeight = widgetAndCaptionHeight;
containerHeight += containerExpansion.getHeight();
// ApplicationConnection.getConsole().log(
// "Setting container size for " + Util.getSimpleName(widget)
// + " to " + containerWidth + "," + containerHeight);
if (containerWidth < 0) {
ApplicationConnection.getConsole().log(
"containerWidth should never be negative: "
+ containerWidth);
containerWidth = 0;
}
if (containerHeight < 0) {
ApplicationConnection.getConsole().log(
"containerHeight should never be negative: "
+ containerHeight);
containerHeight = 0;
}
contSize.setWidth(containerWidth);
contSize.setHeight(containerHeight);
updateContainerDOMSize();
}
public void updateContainerDOMSize() {
int width = contSize.getWidth();
int height = contSize.getHeight() - alignmentTopOffset;
if (width < 0) {
width = 0;
}
if (height < 0) {
height = 0;
}
setWidth(width + "px");
setHeight(height + "px");
// Also update caption max width
if (caption != null) {
if (caption.shouldBePlacedAfterComponent()) {
caption.setMaxWidth(captionWidth);
} else {
caption.setMaxWidth(width);
}
captionWidth = caption.getRenderedWidth();
// Remove initial height
caption.setHeight("");
}
}
}
| false | false | null | null |
diff --git a/easyb/src/java/org/disco/easyb/SpecificationRunner.java b/easyb/src/java/org/disco/easyb/SpecificationRunner.java
index c67d64b..603419f 100644
--- a/easyb/src/java/org/disco/easyb/SpecificationRunner.java
+++ b/easyb/src/java/org/disco/easyb/SpecificationRunner.java
@@ -1,267 +1,267 @@
package org.disco.easyb;
import groovy.lang.GroovyShell;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.disco.easyb.core.listener.DefaultListener;
import org.disco.easyb.core.listener.SpecificationListener;
import org.disco.easyb.core.report.Report;
import org.disco.easyb.core.report.ReportWriter;
import org.disco.easyb.core.report.EasybXmlReportWriter;
import org.disco.easyb.core.report.TxtStoryReportWriter;
import org.disco.easyb.core.report.TerseReportWriter;
import org.disco.easyb.core.util.ReportFormat;
import org.disco.easyb.core.util.ReportType;
import org.disco.easyb.core.util.SpecificationStepType;
import org.disco.easyb.core.SpecificationStep;
/**
* usage is:
* <p/>
* java SpecificationRunner my/path/to/spec/MyStory.groovy -txtstory ./reports/story-report.txt
* <p/>
* You don't need to pass in the file name for the report either-- if no
* path is present, then the runner will create a report in the current directory
* with a default filename following this convention: easyb-<type>-report.<format>
* <p/>
* Multiple specifications can be passed in on the command line
* <p/>
* java SpecificationRunner my/path/to/spec/MyStory.groovy my/path/to/spec/AnotherStory.groovy
*/
public class SpecificationRunner {
List<Report> reports;
public SpecificationRunner() {
this(null);
}
public SpecificationRunner(List<Report> reports) {
this.reports = addDefaultReports(reports);
}
/**
* TODO: refactor me please
*
* @param specs collection of files that contain the specifications
* @return BehaviorListener has status about failures and successes
* @throws Exception if unable to write report file
*/
public void runSpecification(Collection<File> specs) throws Exception {
SpecificationListener listener = new DefaultListener();
for (File file : specs) {
long startTime = System.currentTimeMillis();
System.out.println("Running " + file.getCanonicalPath());
Specification specification = new Specification(file);
SpecificationStep currentStep;
if (specification.isStory()) {
currentStep = listener.startStep(SpecificationStepType.STORY, specification.getPhrase());
} else {
currentStep = listener.startStep(SpecificationStepType.BEHAVIOR, specification.getPhrase());
warnOnBehaviorNaming(file);
}
new GroovyShell(SpecificationBinding.getBinding(listener)).evaluate(file);
listener.stopStep();
long endTime = System.currentTimeMillis();
- System.out.println("Specs run: " + currentStep.getChildStepSpecificationCount() + ", Failures: " + currentStep.getChildStepSpecificationFailureCount() + ", Time Elapsed: " + (endTime - startTime)/1000f + " sec");
+ System.out.println((currentStep.getChildStepSpecificationFailureCount() == 0 ? "" : "FAILURE ") + "Specs run: " + currentStep.getChildStepSpecificationCount() + ", Failures: " + currentStep.getChildStepSpecificationFailureCount() + ", Time Elapsed: " + (endTime - startTime)/1000f + " sec");
}
System.out.println("Total specs: " + listener.getSpecificationCount() + ", Failed specs: " + listener.getFailedSpecificationCount() + ", Success specs: " + listener.getSuccessfulSpecificationCount());
String easybxmlreportlocation = null;
for (Report report : reports) {
if (report.getFormat().concat(report.getType()).equals(Report.XML_EASYB)) {
easybxmlreportlocation = report.getLocation();
ReportWriter reportWriter = new EasybXmlReportWriter(report, listener);
reportWriter.writeReport();
}
}
if (easybxmlreportlocation == null) {
System.out.println("xmleasyb report is required");
System.exit(-1);
}
for (Report report : reports) {
if (report.getFormat().concat(report.getType()).equals(Report.XML_EASYB)) {
//do nothing, report was already run above.
} else if (report.getFormat().concat(report.getType()).equals(Report.TXT_STORY)) {
new TxtStoryReportWriter(report, easybxmlreportlocation).writeReport();
}
// else if (report.getFormat().concat(report.getType()).equals(Report.t)){
// new TerseReportWriter(report, listener).writeReport();
// }
}
if (listener.getFailedSpecificationCount() > 0) {
System.out.println("specification failures detected!");
System.exit(-6);
}
}
private void warnOnBehaviorNaming(File file) {
if (!file.getName().contains("Behavior.groovy")) {
System.out.println("You should consider ending your specification file (" +
file.getName() + ") with either Story or Behavior. " +
"See easyb documentation for more details. ");
}
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Options options = getOptionsForMain();
try {
CommandLine commandLine = getCommandLineForMain(args, options);
validateArguments(commandLine);
SpecificationRunner runner = new SpecificationRunner(getConfiguredReports(commandLine));
runner.runSpecification(getFileCollection(commandLine.getArgs()));
} catch (IllegalArgumentException iae) {
System.out.println(iae.getMessage());
handleHelpForMain(options);
} catch (ParseException pe) {
System.out.println(pe.getMessage());
handleHelpForMain(options);
} catch (Exception e) {
System.err.println("There was an error running the script");
e.printStackTrace(System.err);
System.exit(-6);
}
}
private static void validateArguments(CommandLine commandLine) throws IllegalArgumentException {
if (commandLine.getArgs().length == 0) {
throw new IllegalArgumentException("Required Arguments not passed in.");
}
}
private static List<Report> getConfiguredReports(CommandLine line) {
List<Report> configuredReports = new ArrayList<Report>();
if (line.hasOption(Report.XML_BEHAVIOR)) {
Report report = new Report();
report.setFormat(ReportFormat.XML.format());
if (line.getOptionValue(Report.XML_BEHAVIOR) == null) {
report.setLocation("easyb-behavior-report.xml");
} else {
report.setLocation(line.getOptionValue(Report.XML_BEHAVIOR));
}
report.setType(ReportType.BEHAVIOR.type());
configuredReports.add(report);
}
if (line.hasOption(Report.TXT_STORY)) {
Report report = new Report();
report.setFormat(ReportFormat.TXT.format());
if (line.getOptionValue(Report.TXT_STORY) == null) {
report.setLocation("easyb-story-report.txt");
} else {
report.setLocation(line.getOptionValue(Report.TXT_STORY));
}
report.setType(ReportType.STORY.type());
configuredReports.add(report);
}
if (line.hasOption(Report.XML_EASYB)) {
Report report = new Report();
report.setFormat(ReportFormat.XML.format());
if (line.getOptionValue(Report.XML_EASYB) == null) {
report.setLocation("easyb-report.xml");
} else {
report.setLocation(line.getOptionValue(Report.XML_EASYB));
}
report.setType(ReportType.EASYB.type());
configuredReports.add(report);
}
return configuredReports;
}
/**
* @param paths locations of the specifications to be loaded
* @return collection of files where the only element is the file of the spec to be run
*/
private static Collection<File> getFileCollection(String[] paths) {
Collection<File> coll = new ArrayList<File>();
for (String path : paths) {
coll.add(new File(path));
}
return coll;
}
/**
* @param options options that are available to this specification runner
*/
private static void handleHelpForMain(Options options) {
new HelpFormatter().printHelp("SpecificationRunner my/path/to/MyStory.groovy", options);
}
/**
* @param args command line arguments passed into main
* @param options options that are available to this specification runner
* @return representation of command line arguments passed in that match the available options
* @throws ParseException if there are any problems encountered while parsing the command line tokens
*/
private static CommandLine getCommandLineForMain(String[] args, Options options) throws ParseException {
CommandLineParser commandLineParser = new GnuParser();
return commandLineParser.parse(options, args);
}
/**
* @return representation of a collection of Option objects, which describe the possible options for a command-line.
*/
private static Options getOptionsForMain() {
Options options = new Options();
//noinspection AccessStaticViaInstance
Option xmleasybreport = OptionBuilder.withArgName("file").hasArg()
.withDescription("create an easyb report in xml format").create(Report.XML_EASYB);
options.addOption(xmleasybreport);
//noinspection AccessStaticViaInstance
// Option xmlbehaviorreport = OptionBuilder.withArgName("file").hasArg()
// .withDescription("create a behavior report in xml format").create(Report.XML_BEHAVIOR);
// options.addOption(xmlbehaviorreport);
//noinspection AccessStaticViaInstance
Option storyreport = OptionBuilder.withArgName("file").hasArg()
.withDescription("create a story report").create(Report.TXT_STORY);
options.addOption(storyreport);
return options;
}
private List<Report> addDefaultReports(List<Report> userConfiguredReports) {
List<Report> configuredReports = new ArrayList<Report>();
if (userConfiguredReports != null) {
configuredReports.addAll(userConfiguredReports);
}
return configuredReports;
}
}
| true | true | public void runSpecification(Collection<File> specs) throws Exception {
SpecificationListener listener = new DefaultListener();
for (File file : specs) {
long startTime = System.currentTimeMillis();
System.out.println("Running " + file.getCanonicalPath());
Specification specification = new Specification(file);
SpecificationStep currentStep;
if (specification.isStory()) {
currentStep = listener.startStep(SpecificationStepType.STORY, specification.getPhrase());
} else {
currentStep = listener.startStep(SpecificationStepType.BEHAVIOR, specification.getPhrase());
warnOnBehaviorNaming(file);
}
new GroovyShell(SpecificationBinding.getBinding(listener)).evaluate(file);
listener.stopStep();
long endTime = System.currentTimeMillis();
System.out.println("Specs run: " + currentStep.getChildStepSpecificationCount() + ", Failures: " + currentStep.getChildStepSpecificationFailureCount() + ", Time Elapsed: " + (endTime - startTime)/1000f + " sec");
}
System.out.println("Total specs: " + listener.getSpecificationCount() + ", Failed specs: " + listener.getFailedSpecificationCount() + ", Success specs: " + listener.getSuccessfulSpecificationCount());
String easybxmlreportlocation = null;
for (Report report : reports) {
if (report.getFormat().concat(report.getType()).equals(Report.XML_EASYB)) {
easybxmlreportlocation = report.getLocation();
ReportWriter reportWriter = new EasybXmlReportWriter(report, listener);
reportWriter.writeReport();
}
}
if (easybxmlreportlocation == null) {
System.out.println("xmleasyb report is required");
System.exit(-1);
}
for (Report report : reports) {
if (report.getFormat().concat(report.getType()).equals(Report.XML_EASYB)) {
//do nothing, report was already run above.
} else if (report.getFormat().concat(report.getType()).equals(Report.TXT_STORY)) {
new TxtStoryReportWriter(report, easybxmlreportlocation).writeReport();
}
// else if (report.getFormat().concat(report.getType()).equals(Report.t)){
// new TerseReportWriter(report, listener).writeReport();
// }
}
if (listener.getFailedSpecificationCount() > 0) {
System.out.println("specification failures detected!");
System.exit(-6);
}
}
| public void runSpecification(Collection<File> specs) throws Exception {
SpecificationListener listener = new DefaultListener();
for (File file : specs) {
long startTime = System.currentTimeMillis();
System.out.println("Running " + file.getCanonicalPath());
Specification specification = new Specification(file);
SpecificationStep currentStep;
if (specification.isStory()) {
currentStep = listener.startStep(SpecificationStepType.STORY, specification.getPhrase());
} else {
currentStep = listener.startStep(SpecificationStepType.BEHAVIOR, specification.getPhrase());
warnOnBehaviorNaming(file);
}
new GroovyShell(SpecificationBinding.getBinding(listener)).evaluate(file);
listener.stopStep();
long endTime = System.currentTimeMillis();
System.out.println((currentStep.getChildStepSpecificationFailureCount() == 0 ? "" : "FAILURE ") + "Specs run: " + currentStep.getChildStepSpecificationCount() + ", Failures: " + currentStep.getChildStepSpecificationFailureCount() + ", Time Elapsed: " + (endTime - startTime)/1000f + " sec");
}
System.out.println("Total specs: " + listener.getSpecificationCount() + ", Failed specs: " + listener.getFailedSpecificationCount() + ", Success specs: " + listener.getSuccessfulSpecificationCount());
String easybxmlreportlocation = null;
for (Report report : reports) {
if (report.getFormat().concat(report.getType()).equals(Report.XML_EASYB)) {
easybxmlreportlocation = report.getLocation();
ReportWriter reportWriter = new EasybXmlReportWriter(report, listener);
reportWriter.writeReport();
}
}
if (easybxmlreportlocation == null) {
System.out.println("xmleasyb report is required");
System.exit(-1);
}
for (Report report : reports) {
if (report.getFormat().concat(report.getType()).equals(Report.XML_EASYB)) {
//do nothing, report was already run above.
} else if (report.getFormat().concat(report.getType()).equals(Report.TXT_STORY)) {
new TxtStoryReportWriter(report, easybxmlreportlocation).writeReport();
}
// else if (report.getFormat().concat(report.getType()).equals(Report.t)){
// new TerseReportWriter(report, listener).writeReport();
// }
}
if (listener.getFailedSpecificationCount() > 0) {
System.out.println("specification failures detected!");
System.exit(-6);
}
}
|
diff --git a/src/edu/wpi/first/wpilibj/templates/RobotTemplate.java b/src/edu/wpi/first/wpilibj/templates/RobotTemplate.java
index dc54f06..a2a59c4 100755
--- a/src/edu/wpi/first/wpilibj/templates/RobotTemplate.java
+++ b/src/edu/wpi/first/wpilibj/templates/RobotTemplate.java
@@ -1,171 +1,173 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package edu.wpi.first.wpilibj.templates;
import edu.wpi.first.wpilibj.Compressor;
import edu.wpi.first.wpilibj.DriverStationLCD;
import edu.wpi.first.wpilibj.IterativeRobot;
import edu.wpi.first.wpilibj.Jaguar;
import edu.wpi.first.wpilibj.Joystick;
import edu.wpi.first.wpilibj.Relay;
import edu.wpi.first.wpilibj.RobotDrive;
import edu.wpi.first.wpilibj.Solenoid;
/**
* The VM is configured to automatically run this class, and to call the
* functions corresponding to each mode, as described in the IterativeRobot
* documentation. If you change the name of this class or the package after
* creating this project, you must also update the manifest file in the resource
* directory.
*/
public class RobotTemplate extends IterativeRobot {
/*public Solenoid pistonUp;
public Solenoid pistonDown;*/
Solenoid solA, solB;
RobotDrive drivetrain;
Relay spikeA;
Joystick leftStick;
Joystick rightStick;
//public String controlScheme = "twostick";
int leftStickX, leftStickY;
Compressor compressorA;
Jaguar leftJag;
Jaguar rightJag;
DriverStationLCD userMessages;
String controlScheme = "twostick";
/**
* This function is run when the robot is first started up and should be
* used for any initialization code.
*/
public void robotInit() {
//Instantialize objects for RobotTemplate
rightStick = new Joystick(1);
leftStick = new Joystick(2);
userMessages = DriverStationLCD.getInstance();
//2-Wheel tank drive
spikeA = new Relay(1);
compressorA = new Compressor(1,2);
drivetrain = new RobotDrive(1,2);
solA = new Solenoid(1);
solB = new Solenoid(2);
//leftJag = new Jaguar(1);
//rightJag = new Jaguar(2);
/*pistonUp = new Solenoid(1);
pistonDown = new Solenoid(2);
sol3 = new Solenoid(3);
sol4 = new Solenoid(4);
sol5 = new Solenoid(5);*/
//4-Wheel tank drive
//Motors must be set in the following order:
//LeftFront=1; LeftRear=2; RightFront=3; RightRear=4;
//drivetrain = new RobotDrive(1,2,3,4);
//drivetrain.tankDrive(leftStick, rightStick);
compressorA.start();
/*pistonDown.set(true);
pistonUp.set(true);*/
}
/**
* This function is called periodically during autonomous
*/
public void autonomousPeriodic() {
drivetrain.drive(1, 0);
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
- ex.printStackTrace();
+ StringWriter errors = new StringWriter();
+ ex.printStackTrace(new PrintWriter(errors));
+ printMsg(errors.toString());
}
drivetrain.drive(0, 0);
}
public void telopInit() {
//drivetrain.setSafetyEnabled(true);
//drivetrain.tankDrive(leftStick.getY(), rightStick.getY());
}
/**
* This function is called periodically during operator control
*/
public void teleopPeriodic() {
//getWatchdog().setEnabled(true);
drivetrain.tankDrive(rightStick.getY(), leftStick.getY());
/*
* if (compressorA.getPressureSwitchValue() == true) {
compressorA.stop();
printMsg("Compressor stopped. PressureSwitchValue \"True\".");
}
*/
//Pneumatics test code
if (leftStick.getTrigger()) {
solA.set(true);
solB.set(false);
printMsg("Solenoid opened.");
}
else {
solA.set(false);
solB.set(true);
printMsg("Solenoid stopped.");
}
if (rightStick.getTrigger()) {
compressorA.start();
printMsg("Compressor started.");
}
else {
compressorA.stop();
printMsg("Compressor stopped.");
}
//Switch between "onestick" and "twostick" control schemes
if (leftStick.getRawButton(6)) {
controlScheme = "twostick";
}
if (leftStick.getRawButton(7)) {
controlScheme = "onestick";
}
if (controlScheme.equals("twostick")) {
drivetrain.tankDrive(rightStick, leftStick);
printMsg("Tankdrive activated.");
}
else if (controlScheme.equals("onestick")) {
drivetrain.arcadeDrive(leftStick);
printMsg("Arcade drive activated.");
}
//Rotate in-place left and right, respectively
if (leftStick.getRawButton(8)) {
drivetrain.setLeftRightMotorOutputs(-1.0, 1.0);
printMsg("Rotating counterclockwise in place.");
}
if (leftStick.getRawButton(9)) {
drivetrain.setLeftRightMotorOutputs(1.0, -1.0);
printMsg("Rotating clockwise in place.");
}
//userMessages.println(DriverStationLCD.Line.kMain6, 1, "This is a test" );
userMessages.updateLCD();
}
/*public void disabledInit() {
compressorA.stop();
}*/
public void printMsg(String message) {
userMessages.println(DriverStationLCD.Line.kMain6, 1, message );
}
}
| true | false | null | null |
diff --git a/gerrit-gwtui/src/main/java/com/google/gerrit/client/Dispatcher.java b/gerrit-gwtui/src/main/java/com/google/gerrit/client/Dispatcher.java
index c8b1e482f..87a09cfa0 100644
--- a/gerrit-gwtui/src/main/java/com/google/gerrit/client/Dispatcher.java
+++ b/gerrit-gwtui/src/main/java/com/google/gerrit/client/Dispatcher.java
@@ -1,834 +1,834 @@
// Copyright (C) 2008 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.client;
import static com.google.gerrit.common.PageLinks.ADMIN_CREATE_GROUP;
import static com.google.gerrit.common.PageLinks.ADMIN_CREATE_PROJECT;
import static com.google.gerrit.common.PageLinks.ADMIN_GROUPS;
import static com.google.gerrit.common.PageLinks.ADMIN_PLUGINS;
import static com.google.gerrit.common.PageLinks.ADMIN_PROJECTS;
import static com.google.gerrit.common.PageLinks.DASHBOARDS;
import static com.google.gerrit.common.PageLinks.MINE;
import static com.google.gerrit.common.PageLinks.PROJECTS;
import static com.google.gerrit.common.PageLinks.REGISTER;
import static com.google.gerrit.common.PageLinks.SETTINGS;
import static com.google.gerrit.common.PageLinks.SETTINGS_AGREEMENTS;
import static com.google.gerrit.common.PageLinks.SETTINGS_CONTACT;
import static com.google.gerrit.common.PageLinks.SETTINGS_HTTP_PASSWORD;
import static com.google.gerrit.common.PageLinks.SETTINGS_MYGROUPS;
import static com.google.gerrit.common.PageLinks.SETTINGS_NEW_AGREEMENT;
import static com.google.gerrit.common.PageLinks.SETTINGS_PREFERENCES;
import static com.google.gerrit.common.PageLinks.SETTINGS_PROJECTS;
import static com.google.gerrit.common.PageLinks.SETTINGS_SSHKEYS;
import static com.google.gerrit.common.PageLinks.SETTINGS_WEBIDENT;
import static com.google.gerrit.common.PageLinks.op;
import com.google.gerrit.client.account.MyAgreementsScreen;
import com.google.gerrit.client.account.MyContactInformationScreen;
import com.google.gerrit.client.account.MyGroupsScreen;
import com.google.gerrit.client.account.MyIdentitiesScreen;
import com.google.gerrit.client.account.MyPasswordScreen;
import com.google.gerrit.client.account.MyPreferencesScreen;
import com.google.gerrit.client.account.MyProfileScreen;
import com.google.gerrit.client.account.MySshKeysScreen;
import com.google.gerrit.client.account.MyWatchedProjectsScreen;
import com.google.gerrit.client.account.NewAgreementScreen;
import com.google.gerrit.client.account.RegisterScreen;
import com.google.gerrit.client.account.ValidateEmailScreen;
import com.google.gerrit.client.admin.AccountGroupInfoScreen;
import com.google.gerrit.client.admin.AccountGroupMembersScreen;
import com.google.gerrit.client.admin.AccountGroupScreen;
import com.google.gerrit.client.admin.CreateGroupScreen;
import com.google.gerrit.client.admin.CreateProjectScreen;
import com.google.gerrit.client.admin.GroupListScreen;
import com.google.gerrit.client.admin.PluginListScreen;
import com.google.gerrit.client.admin.ProjectAccessScreen;
import com.google.gerrit.client.admin.ProjectBranchesScreen;
import com.google.gerrit.client.admin.ProjectDashboardsScreen;
import com.google.gerrit.client.admin.ProjectInfoScreen;
import com.google.gerrit.client.admin.ProjectListScreen;
import com.google.gerrit.client.admin.ProjectScreen;
import com.google.gerrit.client.changes.AccountDashboardScreen;
import com.google.gerrit.client.changes.ChangeScreen;
import com.google.gerrit.client.changes.CustomDashboardScreen;
import com.google.gerrit.client.changes.PatchTable;
import com.google.gerrit.client.changes.ProjectDashboardScreen;
import com.google.gerrit.client.changes.PublishCommentScreen;
import com.google.gerrit.client.changes.QueryScreen;
import com.google.gerrit.client.dashboards.DashboardInfo;
import com.google.gerrit.client.dashboards.DashboardList;
import com.google.gerrit.client.groups.GroupApi;
import com.google.gerrit.client.groups.GroupInfo;
import com.google.gerrit.client.patches.PatchScreen;
import com.google.gerrit.client.rpc.GerritCallback;
import com.google.gerrit.client.rpc.RestApi;
import com.google.gerrit.client.ui.Screen;
import com.google.gerrit.common.PageLinks;
import com.google.gerrit.common.data.PatchSetDetail;
import com.google.gerrit.reviewdb.client.Account;
import com.google.gerrit.reviewdb.client.AccountGroup;
import com.google.gerrit.reviewdb.client.Change;
import com.google.gerrit.reviewdb.client.Patch;
import com.google.gerrit.reviewdb.client.PatchSet;
import com.google.gerrit.reviewdb.client.Project;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.RunAsyncCallback;
import com.google.gwt.http.client.URL;
import com.google.gwt.user.client.Window;
import com.google.gwtorm.client.KeyUtil;
public class Dispatcher {
public static String toPatchSideBySide(final Patch.Key id) {
return toPatch("", null, id);
}
public static String toPatchSideBySide(PatchSet.Id diffBase, Patch.Key id) {
return toPatch("", diffBase, id);
}
public static String toPatchUnified(final Patch.Key id) {
return toPatch("unified", null, id);
}
public static String toPatchUnified(PatchSet.Id diffBase, Patch.Key id) {
return toPatch("unified", diffBase, id);
}
private static String toPatch(String type, PatchSet.Id diffBase, Patch.Key id) {
PatchSet.Id ps = id.getParentKey();
Change.Id c = ps.getParentKey();
StringBuilder p = new StringBuilder();
p.append("/c/").append(c).append("/");
if (diffBase != null) {
p.append(diffBase.get()).append("..");
}
p.append(ps.get()).append("/").append(KeyUtil.encode(id.get()));
if (type != null && !type.isEmpty()) {
p.append(",").append(type);
}
return p.toString();
}
public static String toPatch(final PatchScreen.Type type, final Patch.Key id) {
if (type == PatchScreen.Type.SIDE_BY_SIDE) {
return toPatchSideBySide(id);
} else {
return toPatchUnified(id);
}
}
public static String toPublish(PatchSet.Id ps) {
Change.Id c = ps.getParentKey();
return "/c/" + c + "/" + ps.get() + ",publish";
}
public static String toGroup(final AccountGroup.Id id) {
return "/admin/groups/" + id.toString();
}
public static String toGroup(AccountGroup.Id id, String panel) {
return "/admin/groups/" + id.toString() + "," + panel;
}
public static String toGroup(AccountGroup.UUID uuid) {
return PageLinks.toGroup(uuid);
}
public static String toGroup(AccountGroup.UUID uuid, String panel) {
return toGroup(uuid) + "," + panel;
}
public static String toProject(Project.NameKey n) {
return toProjectAdmin(n, ProjectScreen.getSavedPanel());
}
public static String toProjectAdmin(Project.NameKey n, String panel) {
if (panel == null || ProjectScreen.INFO.equals(panel)) {
return "/admin/projects/" + n.toString();
}
return "/admin/projects/" + n.toString() + "," + panel;
}
static final String RELOAD_UI = "/reload-ui/";
private static boolean wasStartedByReloadUI;
void display(String token) {
assert token != null;
try {
try {
if (matchPrefix(RELOAD_UI, token)) {
wasStartedByReloadUI = true;
token = skip(token);
}
select(token);
} finally {
wasStartedByReloadUI = false;
}
} catch (RuntimeException err) {
GWT.log("Error parsing history token: " + token, err);
Gerrit.display(token, new NotFoundScreen());
}
}
private static void select(final String token) {
if (matchPrefix("/q/", token)) {
query(token);
} else if (matchPrefix("/c/", token)) {
change(token);
} else if (matchExact(MINE, token)) {
Gerrit.display(token, mine(token));
} else if (matchPrefix("/dashboard/", token)) {
dashboard(token);
} else if (matchPrefix(PROJECTS, token)) {
projects(token);
} else if (matchExact(SETTINGS, token) //
|| matchPrefix("/settings/", token) //
|| matchExact("register", token) //
|| matchExact(REGISTER, token) //
|| matchPrefix("/register/", token) //
|| matchPrefix("/VE/", token) || matchPrefix("VE,", token) //
|| matchPrefix("/SignInFailure,", token)) {
settings(token);
} else if (matchPrefix("/admin/", token)) {
admin(token);
} else if (/* LEGACY URL */matchPrefix("all,", token)) {
redirectFromLegacyToken(token, legacyAll(token));
} else if (/* LEGACY URL */matchPrefix("mine,", token)
|| matchExact("mine", token)) {
redirectFromLegacyToken(token, legacyMine(token));
} else if (/* LEGACY URL */matchPrefix("project,", token)) {
redirectFromLegacyToken(token, legacyProject(token));
} else if (/* LEGACY URL */matchPrefix("change,", token)) {
redirectFromLegacyToken(token, legacyChange(token));
} else if (/* LEGACY URL */matchPrefix("patch,", token)) {
redirectFromLegacyToken(token, legacyPatch(token));
} else if (/* LEGACY URL */matchPrefix("admin,", token)) {
redirectFromLegacyToken(token, legacyAdmin(token));
} else if (/* LEGACY URL */matchPrefix("settings,", token)
|| matchPrefix("register,", token)
|| matchPrefix("q,", token)) {
redirectFromLegacyToken(token, legacySettings(token));
} else {
Gerrit.display(token, new NotFoundScreen());
}
}
private static void redirectFromLegacyToken(String oldToken, String newToken) {
if (newToken != null) {
Window.Location.replace(Window.Location.getPath() + "#" + newToken);
} else {
Gerrit.display(oldToken, new NotFoundScreen());
}
}
private static String legacyMine(final String token) {
if (matchExact("mine", token)) {
return MINE;
}
if (matchExact("mine,starred", token)) {
return PageLinks.toChangeQuery("is:starred");
}
if (matchExact("mine,drafts", token)) {
return PageLinks.toChangeQuery("is:draft");
}
if (matchExact("mine,comments", token)) {
return PageLinks.toChangeQuery("has:draft");
}
if (matchPrefix("mine,watched,", token)) {
return PageLinks.toChangeQuery("is:watched status:open", skip(token));
}
return null;
}
private static String legacyAll(final String token) {
if (matchPrefix("all,abandoned,", token)) {
return PageLinks.toChangeQuery("status:abandoned", skip(token));
}
if (matchPrefix("all,merged,", token)) {
return PageLinks.toChangeQuery("status:merged", skip(token));
}
if (matchPrefix("all,open,", token)) {
return PageLinks.toChangeQuery("status:open", skip(token));
}
return null;
}
private static String legacyProject(final String token) {
if (matchPrefix("project,open,", token)) {
final String s = skip(token);
final int c = s.indexOf(',');
Project.NameKey proj = Project.NameKey.parse(s.substring(0, c));
return PageLinks.toChangeQuery( //
"status:open " + op("project", proj.get()), //
s.substring(c + 1));
}
if (matchPrefix("project,merged,", token)) {
final String s = skip(token);
final int c = s.indexOf(',');
Project.NameKey proj = Project.NameKey.parse(s.substring(0, c));
return PageLinks.toChangeQuery( //
"status:merged " + op("project", proj.get()), //
s.substring(c + 1));
}
if (matchPrefix("project,abandoned,", token)) {
final String s = skip(token);
final int c = s.indexOf(',');
Project.NameKey proj = Project.NameKey.parse(s.substring(0, c));
return PageLinks.toChangeQuery( //
"status:abandoned " + op("project", proj.get()), //
s.substring(c + 1));
}
return null;
}
private static String legacyChange(final String token) {
final String s = skip(token);
final String t[] = s.split(",", 2);
if (t.length > 1 && matchPrefix("patchset=", t[1])) {
return PageLinks.toChange(PatchSet.Id.parse(t[0] + "," + skip(t[1])));
}
return PageLinks.toChange(Change.Id.parse(t[0]));
}
private static String legacyPatch(String token) {
if (/* LEGACY URL */matchPrefix("patch,sidebyside,", token)) {
return toPatchSideBySide(Patch.Key.parse(skip(token)));
}
if (/* LEGACY URL */matchPrefix("patch,unified,", token)) {
return toPatchUnified(Patch.Key.parse(skip(token)));
}
return null;
}
private static String legacyAdmin(String token) {
if (matchPrefix("admin,group,", token)) {
return "/admin/groups/" + skip(token);
}
if (matchPrefix("admin,project,", token)) {
String rest = skip(token);
int c = rest.indexOf(',');
String panel;
Project.NameKey k;
if (0 < c) {
panel = rest.substring(c + 1);
k = Project.NameKey.parse(rest.substring(0, c));
} else {
panel = ProjectScreen.INFO;
k = Project.NameKey.parse(rest);
}
return toProjectAdmin(k, panel);
}
return null;
}
private static String legacySettings(String token) {
int c = token.indexOf(',');
if (0 < c) {
return "/" + token.substring(0, c) + "/" + token.substring(c + 1);
}
return null;
}
private static void query(final String token) {
final String s = skip(token);
final int c = s.indexOf(',');
Gerrit.display(token, new QueryScreen(s.substring(0, c), s.substring(c + 1)));
}
private static Screen mine(final String token) {
if (Gerrit.isSignedIn()) {
return new AccountDashboardScreen(Gerrit.getUserAccount().getId());
} else {
Screen r = new AccountDashboardScreen(null);
r.setRequiresSignIn(true);
return r;
}
}
private static void dashboard(final String token) {
String rest = skip(token);
if (rest.matches("[0-9]+")) {
Gerrit.display(token, new AccountDashboardScreen(Account.Id.parse(rest)));
return;
}
if (rest.startsWith("?")) {
Gerrit.display(token, new CustomDashboardScreen(rest.substring(1)));
return;
}
Gerrit.display(token, new NotFoundScreen());
}
private static void projects(final String token) {
String rest = skip(token);
int c = rest.indexOf(DASHBOARDS);
if (0 <= c) {
final String project = URL.decodePathSegment(rest.substring(0, c));
rest = rest.substring(c);
if (matchPrefix(DASHBOARDS, rest)) {
final String dashboardId = skip(rest);
GerritCallback<DashboardInfo> cb = new GerritCallback<DashboardInfo>() {
@Override
public void onSuccess(DashboardInfo result) {
if (matchPrefix("/dashboard/", result.url())) {
String params = skip(result.url()).substring(1);
ProjectDashboardScreen dash = new ProjectDashboardScreen(
new Project.NameKey(project), params);
Gerrit.display(token, dash);
}
}
@Override
public void onFailure(Throwable caught) {
if ("default".equals(dashboardId) && RestApi.isNotFound(caught)) {
Gerrit.display(PageLinks.toChangeQuery(
PageLinks.projectQuery(new Project.NameKey(project))));
} else {
super.onFailure(caught);
}
}
};
if ("default".equals(dashboardId)) {
DashboardList.getDefault(new Project.NameKey(project), cb);
return;
}
c = dashboardId.indexOf(":");
if (0 <= c) {
final String ref = URL.decodeQueryString(dashboardId.substring(0, c));
final String path = URL.decodeQueryString(dashboardId.substring(c + 1));
DashboardList.get(new Project.NameKey(project), ref + ":" + path, cb);
return;
}
}
}
Gerrit.display(token, new NotFoundScreen());
}
private static void change(final String token) {
String rest = skip(token);
int c = rest.lastIndexOf(',');
String panel = null;
if (0 <= c) {
panel = rest.substring(c + 1);
rest = rest.substring(0, c);
}
Change.Id id;
int s = rest.indexOf('/');
if (0 <= s) {
id = Change.Id.parse(rest.substring(0, s));
rest = rest.substring(s + 1);
} else {
id = Change.Id.parse(rest);
rest = "";
}
if (rest.isEmpty()) {
Gerrit.display(token, panel== null //
? new ChangeScreen(id) //
: new NotFoundScreen());
return;
}
String psIdStr;
s = rest.indexOf('/');
if (0 <= s) {
psIdStr = rest.substring(0, s);
rest = rest.substring(s + 1);
} else {
psIdStr = rest;
rest = "";
}
PatchSet.Id base;
PatchSet.Id ps;
int dotdot = psIdStr.indexOf("..");
if (1 <= dotdot) {
base = new PatchSet.Id(id, Integer.parseInt(psIdStr.substring(0, dotdot)));
ps = new PatchSet.Id(id, Integer.parseInt(psIdStr.substring(dotdot + 2)));
} else {
base = null;
ps = new PatchSet.Id(id, Integer.parseInt(psIdStr));
}
if (!rest.isEmpty()) {
- Patch.Key p = new Patch.Key(ps, rest);
+ Patch.Key p = new Patch.Key(ps, KeyUtil.decode(rest));
patch(token, base, p, 0, null, null, panel);
} else {
if (panel == null) {
Gerrit.display(token, new ChangeScreen(ps));
} else if ("publish".equals(panel)) {
publish(ps);
} else {
Gerrit.display(token, new NotFoundScreen());
}
}
}
private static void publish(final PatchSet.Id ps) {
String token = toPublish(ps);
new AsyncSplit(token) {
public void onSuccess() {
Gerrit.display(token, select());
}
private Screen select() {
return new PublishCommentScreen(ps);
}
}.onSuccess();
}
public static void patch(String token, PatchSet.Id base, Patch.Key id,
int patchIndex, PatchSetDetail patchSetDetail,
PatchTable patchTable, PatchScreen.TopView topView) {
patch(token, base, id, patchIndex, patchSetDetail, patchTable, topView, null);
}
public static void patch(String token, PatchSet.Id base, Patch.Key id,
int patchIndex, PatchSetDetail patchSetDetail,
PatchTable patchTable, String panelType) {
patch(token, base, id, patchIndex, patchSetDetail, patchTable,
null, panelType);
}
public static void patch(String token, final PatchSet.Id baseId, final Patch.Key id,
final int patchIndex, final PatchSetDetail patchSetDetail,
final PatchTable patchTable, final PatchScreen.TopView topView,
final String panelType) {
final PatchScreen.TopView top = topView == null ?
Gerrit.getPatchScreenTopView() : topView;
GWT.runAsync(new AsyncSplit(token) {
public void onSuccess() {
Gerrit.display(token, select());
}
private Screen select() {
if (id != null) {
String panel = panelType;
if (panel == null) {
int c = token.lastIndexOf(',');
panel = 0 <= c ? token.substring(c + 1) : "";
}
if ("".equals(panel)) {
return new PatchScreen.SideBySide( //
id, //
patchIndex, //
patchSetDetail, //
patchTable, //
top, //
baseId //
);
} else if ("unified".equals(panel)) {
return new PatchScreen.Unified( //
id, //
patchIndex, //
patchSetDetail, //
patchTable, //
top, //
baseId //
);
}
}
return new NotFoundScreen();
}
});
}
private static void settings(String token) {
GWT.runAsync(new AsyncSplit(token) {
public void onSuccess() {
Gerrit.display(token, select());
}
private Screen select() {
if (matchExact(SETTINGS, token)) {
return new MyProfileScreen();
}
if (matchExact(SETTINGS_PREFERENCES, token)) {
return new MyPreferencesScreen();
}
if (matchExact(SETTINGS_PROJECTS, token)) {
return new MyWatchedProjectsScreen();
}
if (matchExact(SETTINGS_CONTACT, token)) {
return new MyContactInformationScreen();
}
if (matchExact(SETTINGS_SSHKEYS, token)) {
return new MySshKeysScreen();
}
if (matchExact(SETTINGS_WEBIDENT, token)) {
return new MyIdentitiesScreen();
}
if (matchExact(SETTINGS_HTTP_PASSWORD, token)) {
return new MyPasswordScreen();
}
if (matchExact(SETTINGS_MYGROUPS, token)) {
return new MyGroupsScreen();
}
if (matchExact(SETTINGS_AGREEMENTS, token)
&& Gerrit.getConfig().isUseContributorAgreements()) {
return new MyAgreementsScreen();
}
if (matchExact(REGISTER, token)
|| matchExact("/register/", token)
|| matchExact("register", token)) {
return new RegisterScreen(MINE);
} else if (matchPrefix("/register/", token)) {
return new RegisterScreen("/" + skip(token));
}
if (matchPrefix("/VE/", token) || matchPrefix("VE,", token))
return new ValidateEmailScreen(skip(token));
if (matchExact(SETTINGS_NEW_AGREEMENT, token))
return new NewAgreementScreen();
if (matchPrefix(SETTINGS_NEW_AGREEMENT + "/", token)) {
return new NewAgreementScreen(skip(token));
}
return new NotFoundScreen();
}
});
}
private static void admin(String token) {
GWT.runAsync(new AsyncSplit(token) {
public void onSuccess() {
if (matchExact(ADMIN_GROUPS, token)
|| matchExact("/admin/groups", token)) {
Gerrit.display(token, new GroupListScreen());
} else if (matchPrefix("/admin/groups/", token)) {
String rest = skip(token);
if (rest.startsWith("?")) {
Gerrit.display(token, new GroupListScreen(rest.substring(1)));
} else {
group();
}
} else if (matchPrefix("/admin/groups", token)) {
String rest = skip(token);
if (rest.startsWith("?")) {
Gerrit.display(token, new GroupListScreen(rest.substring(1)));
}
} else if (matchExact(ADMIN_PROJECTS, token)
|| matchExact("/admin/projects", token)) {
Gerrit.display(token, new ProjectListScreen());
} else if (matchPrefix("/admin/projects/", token)) {
String rest = skip(token);
if (rest.startsWith("?")) {
Gerrit.display(token, new ProjectListScreen(rest.substring(1)));
} else {
Gerrit.display(token, selectProject());
}
} else if (matchPrefix("/admin/projects", token)) {
String rest = skip(token);
if (rest.startsWith("?")) {
Gerrit.display(token, new ProjectListScreen(rest.substring(1)));
}
} else if (matchPrefix(ADMIN_PLUGINS, token)
|| matchExact("/admin/plugins", token)) {
Gerrit.display(token, new PluginListScreen());
} else if (matchExact(ADMIN_CREATE_PROJECT, token)
|| matchExact("/admin/create-project", token)) {
Gerrit.display(token, new CreateProjectScreen());
} else if (matchExact(ADMIN_CREATE_GROUP, token)
|| matchExact("/admin/create-group", token)) {
Gerrit.display(token, new CreateGroupScreen());
} else {
Gerrit.display(token, new NotFoundScreen());
}
}
private void group() {
final String panel;
final String group;
if (matchPrefix("/admin/groups/uuid-", token)) {
String p = skip(token);
int c = p.indexOf(',');
if (c < 0) {
group = p;
panel = null;
} else {
group = p.substring(0, c);
panel = p.substring(c + 1);
}
} else if (matchPrefix("/admin/groups/", token)) {
String p = skip(token);
int c = p.indexOf(',');
if (c < 0) {
group = p;
panel = null;
} else {
group = p.substring(0, c);
panel = p.substring(c + 1);
}
} else {
Gerrit.display(token, new NotFoundScreen());
return;
}
GroupApi.getGroupDetail(group, new GerritCallback<GroupInfo>() {
@Override
public void onSuccess(GroupInfo group) {
if (panel == null || panel.isEmpty()) {
// The token does not say which group screen should be shown,
// as default for internal groups show the members, as default
// for external and system groups show the info screen (since
// for external and system groups the members cannot be
// shown in the web UI).
//
if (AccountGroup.isInternalGroup(group.getGroupUUID())
&& !AccountGroup.isSystemGroup(group.getGroupUUID())) {
Gerrit.display(toGroup(group.getGroupId(), AccountGroupScreen.MEMBERS),
new AccountGroupMembersScreen(group, token));
} else {
Gerrit.display(toGroup(group.getGroupId(), AccountGroupScreen.INFO),
new AccountGroupInfoScreen(group, token));
}
} else if (AccountGroupScreen.INFO.equals(panel)) {
Gerrit.display(token, new AccountGroupInfoScreen(group, token));
} else if (AccountGroupScreen.MEMBERS.equals(panel)) {
Gerrit.display(token, new AccountGroupMembersScreen(group, token));
} else {
Gerrit.display(token, new NotFoundScreen());
}
}
});
}
private Screen selectProject() {
if (matchPrefix("/admin/projects/", token)) {
String rest = skip(token);
int c = rest.lastIndexOf(',');
if (c < 0) {
return new ProjectInfoScreen(Project.NameKey.parse(rest));
} else if (c == 0) {
return new NotFoundScreen();
}
Project.NameKey k = Project.NameKey.parse(rest.substring(0, c));
String panel = rest.substring(c + 1);
if (ProjectScreen.INFO.equals(panel)) {
return new ProjectInfoScreen(k);
}
if (ProjectScreen.BRANCH.equals(panel)) {
return new ProjectBranchesScreen(k);
}
if (ProjectScreen.ACCESS.equals(panel)) {
return new ProjectAccessScreen(k);
}
if (ProjectScreen.DASHBOARDS.equals(panel)) {
return new ProjectDashboardsScreen(k);
}
}
return new NotFoundScreen();
}
});
}
private static boolean matchExact(String want, String token) {
return token.equals(want);
}
private static int prefixlen;
private static boolean matchPrefix(String want, String token) {
if (token.startsWith(want)) {
prefixlen = want.length();
return true;
} else {
return false;
}
}
private static String skip(String token) {
return token.substring(prefixlen);
}
private static abstract class AsyncSplit implements RunAsyncCallback {
private final boolean isReloadUi;
protected final String token;
protected AsyncSplit(String token) {
this.isReloadUi = wasStartedByReloadUI;
this.token = token;
}
public final void onFailure(Throwable reason) {
if (!isReloadUi
&& "HTTP download failed with status 404".equals(reason.getMessage())) {
// The server was upgraded since we last download the main script,
// so the pointers to the splits aren't valid anymore. Force the
// page to reload itself and pick up the new code.
//
Gerrit.upgradeUI(token);
} else {
new ErrorDialog(reason).center();
}
}
}
}
| true | false | null | null |
diff --git a/xdbm-search/src/test/java/org/apache/directory/server/xdbm/GenericIndexTest.java b/xdbm-search/src/test/java/org/apache/directory/server/xdbm/GenericIndexTest.java
index 2ece57a9bd..1998246b15 100644
--- a/xdbm-search/src/test/java/org/apache/directory/server/xdbm/GenericIndexTest.java
+++ b/xdbm-search/src/test/java/org/apache/directory/server/xdbm/GenericIndexTest.java
@@ -1,353 +1,353 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.server.xdbm;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertNotNull;
import static junit.framework.Assert.assertNull;
import static org.junit.Assert.assertFalse;
import java.io.File;
import org.junit.Before;
import org.junit.Test;
/**
* Tests the {@link GenericIndex} class.
*
* @author <a href="mailto:[email protected]">Apache Directory Project</a>
* @version $Rev$, $Date$
*/
public class GenericIndexTest
{
GenericIndex<String, Long, Long> index;
@Before
public void setUp()
{
String tmpDir = System.getProperty( "java.io.tmpdir" );
index = new GenericIndex<String, Long, Long>( "cn", 42, new File( tmpDir ) );
}
@Test
public void testConstructor1()
{
index = new GenericIndex<String, Long, Long>( "cn" );
assertEquals( "cn", index.getAttributeId() );
assertEquals( GenericIndex.DEFAULT_INDEX_CACHE_SIZE, index.getCacheSize() );
assertNull( index.getWkDirPath() );
}
@Test
public void testConstructor2()
{
index = new GenericIndex<String, Long, Long>( "cn", 42 );
assertEquals( "cn", index.getAttributeId() );
assertEquals( 42, index.getCacheSize() );
assertNull( index.getWkDirPath() );
}
@Test
public void testConstructor3()
{
- String tmpDir = System.getProperty( "java.io.tmpdir" );
+ File tmpDir = new File(System.getProperty( "java.io.tmpdir" ));
- index = new GenericIndex<String, Long, Long>( "cn", 42, new File( tmpDir ) );
+ index = new GenericIndex<String, Long, Long>( "cn", 42, tmpDir );
assertEquals( "cn", index.getAttributeId() );
assertEquals( 42, index.getCacheSize() );
assertNotNull( index.getWkDirPath() );
- assertEquals( tmpDir, index.getWkDirPath().getPath() );
+ assertEquals( tmpDir.getPath(), index.getWkDirPath().getPath() );
}
@Test
public void testSetGetAttributeId()
{
index.setAttributeId( "sn" );
assertEquals( "sn", index.getAttributeId() );
index.setAttributeId( null );
assertNull( index.getAttributeId() );
}
@Test
public void testSetGetCacheSize()
{
index.setCacheSize( 0 );
assertEquals( 0, index.getCacheSize() );
index.setCacheSize( Integer.MAX_VALUE );
assertEquals( Integer.MAX_VALUE, index.getCacheSize() );
index.setCacheSize( Integer.MIN_VALUE );
assertEquals( Integer.MIN_VALUE, index.getCacheSize() );
}
@Test
public void testSetGetWkDirPath()
{
- String tmpDir = System.getProperty( "java.io.tmpdir" );
- String zzzDir = tmpDir + File.separator + "zzz";
+ File tmpDir = new File( System.getProperty( "java.io.tmpdir" ));
+ File zzzDir = new File( tmpDir, "zzz" );
- index.setWkDirPath( new File( zzzDir ) );
+ index.setWkDirPath( zzzDir );
assertNotNull( index.getWkDirPath() );
- assertEquals( zzzDir, index.getWkDirPath().getPath() );
+ assertEquals( zzzDir.getPath(), index.getWkDirPath().getPath() );
index.setWkDirPath( null );
assertNull( index.getWkDirPath() );
}
@Test(expected = UnsupportedOperationException.class)
public void testAdd() throws Exception
{
index.add( "test", 5L );
}
@Test(expected = UnsupportedOperationException.class)
public void testClose() throws Exception
{
index.close();
}
@Test(expected = UnsupportedOperationException.class)
public void testCount() throws Exception
{
index.count();
}
@Test(expected = UnsupportedOperationException.class)
public void testCountK() throws Exception
{
index.count( "test" );
}
@Test(expected = UnsupportedOperationException.class)
public void testDropID() throws Exception
{
index.drop( 5L );
}
@Test(expected = UnsupportedOperationException.class)
public void testDropKID() throws Exception
{
index.drop( "test", 5L );
}
@Test(expected = UnsupportedOperationException.class)
public void testForwardCursor() throws Exception
{
index.forwardCursor();
}
@Test(expected = UnsupportedOperationException.class)
public void testForwardCursorK() throws Exception
{
index.forwardCursor( "test" );
}
@Test(expected = UnsupportedOperationException.class)
public void testForwardLookup() throws Exception
{
index.forwardLookup( "test" );
}
@Test(expected = UnsupportedOperationException.class)
public void testForwardValueCursor() throws Exception
{
index.forwardValueCursor( "test" );
}
@Test(expected = UnsupportedOperationException.class)
public void testForwardK() throws Exception
{
index.forward( "test" );
}
@Test(expected = UnsupportedOperationException.class)
public void testForwardKID() throws Exception
{
index.forward( "test", 5L );
}
@Test(expected = UnsupportedOperationException.class)
public void testReverseID() throws Exception
{
index.reverse( 5L );
}
@Test(expected = UnsupportedOperationException.class)
public void testReverseIDK() throws Exception
{
index.reverse( 5L, "test" );
}
@Test(expected = UnsupportedOperationException.class)
public void testForwardGreaterOrEqK() throws Exception
{
index.forwardGreaterOrEq( "test" );
}
@Test(expected = UnsupportedOperationException.class)
public void testForwardGreaterOrEqKID() throws Exception
{
index.forwardGreaterOrEq( "test", 5L );
}
@Test(expected = UnsupportedOperationException.class)
public void testReverseGreaterOrEqID() throws Exception
{
index.reverseGreaterOrEq( 5L );
}
@Test(expected = UnsupportedOperationException.class)
public void testReverseGreaterOrEqIDK() throws Exception
{
index.reverseGreaterOrEq( 5L, "test" );
}
@Test(expected = UnsupportedOperationException.class)
public void testForwardLessOrEqK() throws Exception
{
index.forwardLessOrEq( "test" );
}
@Test(expected = UnsupportedOperationException.class)
public void testForwardLessOrEqKID() throws Exception
{
index.forwardLessOrEq( "test", 5L );
}
@Test(expected = UnsupportedOperationException.class)
public void testReverseLessOrEqID() throws Exception
{
index.reverseLessOrEq( 5L );
}
@Test(expected = UnsupportedOperationException.class)
public void testReverseLessOrEqIDK() throws Exception
{
index.reverseLessOrEq( 5L, "test" );
}
@Test(expected = UnsupportedOperationException.class)
public void testGetAttribute()
{
index.getAttribute();
}
@Test(expected = UnsupportedOperationException.class)
public void testGetNormalized() throws Exception
{
index.getNormalized( "test" );
}
@Test(expected = UnsupportedOperationException.class)
public void testGreaterThanCount() throws Exception
{
index.greaterThanCount( "test" );
}
@Test(expected = UnsupportedOperationException.class)
public void testIsCountExact()
{
index.isCountExact();
}
@Test(expected = UnsupportedOperationException.class)
public void testLessThanCount() throws Exception
{
index.lessThanCount( "test" );
}
@Test(expected = UnsupportedOperationException.class)
public void testReverseCursor() throws Exception
{
index.reverseCursor();
}
@Test(expected = UnsupportedOperationException.class)
public void testReverseCursorID() throws Exception
{
index.reverseCursor( 5L );
}
@Test(expected = UnsupportedOperationException.class)
public void testReverseLookup() throws Exception
{
index.reverseLookup( 5L );
}
@Test(expected = UnsupportedOperationException.class)
public void testReverseValueCursor() throws Exception
{
index.reverseValueCursor( 5L );
}
@Test(expected = UnsupportedOperationException.class)
public void testSync() throws Exception
{
index.sync();
}
@Test
public void testIsDupsEnabled()
{
assertFalse( index.isDupsEnabled() );
}
}
| false | false | null | null |
diff --git a/src/uk/org/ponder/rsf/renderer/RenderUtil.java b/src/uk/org/ponder/rsf/renderer/RenderUtil.java
index 6e83c81..aa3c2a0 100644
--- a/src/uk/org/ponder/rsf/renderer/RenderUtil.java
+++ b/src/uk/org/ponder/rsf/renderer/RenderUtil.java
@@ -1,201 +1,203 @@
/*
* Created on Jul 27, 2005
*/
package uk.org.ponder.rsf.renderer;
import java.util.Collections;
import java.util.Iterator;
import java.util.Map;
import uk.org.ponder.arrayutil.ArrayUtil;
import uk.org.ponder.rsf.components.ParameterList;
import uk.org.ponder.rsf.components.UIBasicListMember;
import uk.org.ponder.rsf.components.UIBoundList;
import uk.org.ponder.rsf.components.UIBoundString;
import uk.org.ponder.rsf.components.UIComponent;
import uk.org.ponder.rsf.components.UIParameter;
import uk.org.ponder.rsf.components.UISelect;
import uk.org.ponder.rsf.renderer.scr.BasicSCR;
import uk.org.ponder.rsf.renderer.scr.CollectingSCR;
import uk.org.ponder.rsf.renderer.scr.StaticComponentRenderer;
import uk.org.ponder.rsf.request.FossilizedConverter;
import uk.org.ponder.rsf.template.XMLLump;
import uk.org.ponder.rsf.template.XMLLumpComparator;
import uk.org.ponder.rsf.template.XMLLumpList;
import uk.org.ponder.rsf.template.XMLLumpMMap;
import uk.org.ponder.rsf.view.View;
import uk.org.ponder.streamutil.write.PrintOutputStream;
import uk.org.ponder.stringutil.CharWrap;
import uk.org.ponder.stringutil.URLEncoder;
import uk.org.ponder.stringutil.URLUtil;
import uk.org.ponder.util.Logger;
import uk.org.ponder.xml.XMLUtil;
import uk.org.ponder.xml.XMLWriter;
/**
* @author Antranig Basman ([email protected])
*
*/
public class RenderUtil {
public static int dumpTillLump(XMLLump[] lumps, int start, int limit,
PrintOutputStream target) {
// for (; start < limit; ++ start) {
// target.print(lumps[start].text);
// }
target.write(lumps[start].parent.buffer, lumps[start].start,
lumps[limit].start - lumps[start].start);
return limit;
}
/**
* Dump from template to output until either we reduce below
* <code>basedepth</code> recursion level, or we hit an rsf:id, or end of
* file. Return the lump index we reached. This has two uses, firstly from the
* base of the main scanning loop, and secondly from the "glue" scanning. The
* main scanning loop runs until we reduce BELOW RECURSION LEVEL OF PARENT,
* i.e. we output its closing tag and then return. The glue loop requires that
* we DO NOT OUTPUT THE CLOSING TAG OF PARENT because we may have some number
* of repetitive components still to render.
*/
public static int dumpScan(XMLLump[] lumps, int renderindex, int basedepth,
PrintOutputStream target, boolean closeparent, boolean insideleaf) {
int start = lumps[renderindex].start;
char[] buffer = lumps[renderindex].parent.buffer;
while (true) {
if (renderindex == lumps.length)
break;
XMLLump lump = lumps[renderindex];
if (lump.nestingdepth < basedepth)
break;
if (lump.rsfID != null) {
if (!insideleaf) break;
if (insideleaf && lump.nestingdepth > basedepth + (closeparent?0:1) ) {
Logger.log.warn("Error in component tree - leaf component found to contain further components - at " +
lump.toString());
}
else break;
}
// target.print(lump.text);
++renderindex;
}
// ASSUMPTIONS: close tags are ONE LUMP
if (!closeparent && lumps[renderindex].rsfID == null)
--renderindex;
int limit = (renderindex == lumps.length ? buffer.length
: lumps[renderindex].start);
target.write(buffer, start, limit - start);
return renderindex;
}
public static void dumpHiddenField(UIParameter todump, XMLWriter xmlw) {
xmlw.writeRaw("<input type=\"hidden\" ");
XMLUtil.dumpAttribute(todump.virtual? "id" : "name", todump.name, xmlw);
XMLUtil.dumpAttribute("value", todump.value, xmlw);
xmlw.writeRaw(" />\n");
}
public static String appendAttributes(String baseurl, String attributes) {
// Replace a leading & by ? in the attributes, if there are no
// existing attributes in the URL
// TODO: hop into the URL before any anchors
if (baseurl.indexOf('?') == -1 && attributes.length() > 0) {
attributes = "?" + attributes.substring(1);
}
return baseurl + attributes;
}
public static String makeURLAttributes(ParameterList params) {
CharWrap togo = new CharWrap();
for (int i = 0; i < params.size(); ++i) {
UIParameter param = params.parameterAt(i);
togo.append("&").append(URLEncoder.encode(param.name)).append("=")
.append(URLEncoder.encode(param.value));
}
return togo.toString();
}
/**
* "Unpacks" the supplied command link "name" (as encoded using the
* HTMLRenderSystem for submission controls) by treating it as a section of
* URL attribute stanzas. The key/value pairs encoded in it will be added to
* the supplied (modifiable) map.
*/
public static void unpackCommandLink(String longvalue, Map requestparams) {
String[] split = longvalue.split("[&=]");
// start at 1 since string will begin with &
if ((split.length % 2) == 0) {
Logger.log
.warn("Erroneous submission - odd number of parameters/values in "
+ longvalue);
return;
}
for (int i = 1; i < split.length; i += 2) {
String key = URLUtil.decodeURL(split[i]);
String value = URLUtil.decodeURL(split[i + 1]);
Logger.log.info("Unpacked command link key " + key + " value " + value);
String[] existing = (String[]) requestparams.get(key);
if (existing == null) {
requestparams.put(key, new String[] { value });
}
else {
String[] fused = (String[]) ArrayUtil.append(existing, value);
requestparams.put(key, fused);
}
}
}
public static UIComponent resolveListMember(View view, UIBasicListMember torendero) {
UIComponent parent = view.getComponent(torendero.parentFullID);
UIBoundList boundlist = parent instanceof UISelect? ((UISelect) parent).optionnames : (UIBoundList)parent;
- String value = boundlist.getValue()[torendero.choiceindex];
+ String[] valuelist = boundlist.getValue();
+ // Reference off the end of an array is not an error - it may be being dynamically expanded
+ String value = torendero.choiceindex < valuelist.length ? valuelist[torendero.choiceindex] : "";
String submittingname = boundlist.submittingname;
UIBoundString togo = new UIBoundString();
togo.setValue(value);
togo.submittingname = submittingname;
togo.willinput = true;
return togo;
}
public static String findCommandParams(Map requestparams) {
for (Iterator parit = requestparams.keySet().iterator(); parit.hasNext();) {
String key = (String) parit.next();
if (key.startsWith(FossilizedConverter.COMMAND_LINK_PARAMETERS))
return key;
}
return null;
}
public static int renderSCR(StaticComponentRenderer scr, XMLLump lump,
XMLWriter xmlw, XMLLumpMMap collecteds) {
if (scr instanceof BasicSCR) {
return ((BasicSCR) scr).render(lump, xmlw);
}
else {
CollectingSCR collector = (CollectingSCR) scr;
String[] tocollect = collector.getCollectingNames();
XMLLumpList collected = new XMLLumpList();
for (int i = 0; i < tocollect.length; ++i) {
XMLLumpList thiscollect = collecteds.headsForID(tocollect[i]);
if (thiscollect != null) {
collected.addAll(thiscollect);
}
}
return collector.render(lump, collected, xmlw);
}
}
public static boolean isFirstSCR(XMLLump lump, String scrname) {
XMLLump parent = lump.uplump;
String lookname = XMLLump.SCR_PREFIX + scrname;
XMLLumpList sames = new XMLLumpList();
sames.addAll(parent.downmap.headsForID(lookname));
Collections.sort(sames, XMLLumpComparator.instance());
return sames.get(0) == lump;
}
}
| true | false | null | null |
diff --git a/common/num/numirp/core/handlers/TickHandler.java b/common/num/numirp/core/handlers/TickHandler.java
index ec16efe..784d302 100644
--- a/common/num/numirp/core/handlers/TickHandler.java
+++ b/common/num/numirp/core/handlers/TickHandler.java
@@ -1,48 +1,48 @@
package num.numirp.core.handlers;
import java.util.EnumSet;
import java.util.Iterator;
import java.util.List;
import net.minecraft.client.Minecraft;
import net.minecraft.entity.player.EntityPlayer;
import num.numirp.core.util.ImageDownload;
import num.numirp.lib.Reference;
import cpw.mods.fml.common.ITickHandler;
import cpw.mods.fml.common.TickType;
public class TickHandler implements ITickHandler {
private static final Minecraft mc = Minecraft.getMinecraft();
@Override
public void tickStart(EnumSet<TickType> type, Object... tickData) {
if ((mc.theWorld != null) && (mc.theWorld.playerEntities.size() > 0)) {
@SuppressWarnings("unchecked")
List<EntityPlayer> players = mc.theWorld.playerEntities;
for (Iterator<EntityPlayer> entity = players.iterator(); entity.hasNext();) {
EntityPlayer player = (EntityPlayer) entity.next();
- if (player.cloakUrl.startsWith("http://skins.minecraft.net/MinecraftCloaks/")) {
+ if (player != null && player.cloakUrl != null && player.cloakUrl.startsWith("http://skins.minecraft.net/MinecraftCloaks/")) {
if (player.username.equalsIgnoreCase("Numerios") || player.username.equalsIgnoreCase("j_smart")) {
player.cloakUrl = Reference.DEVELOPER_CAPE_PATH;
mc.renderEngine.obtainImageData(player.cloakUrl, new ImageDownload());
}
}
}
}
}
@Override
public void tickEnd(EnumSet<TickType> type, Object... tickData) {
}
@Override
public EnumSet<TickType> ticks() {
return EnumSet.of(TickType.CLIENT);
}
@Override
public String getLabel() {
return "NumiRP.TickHandler";
}
}
| true | true | public void tickStart(EnumSet<TickType> type, Object... tickData) {
if ((mc.theWorld != null) && (mc.theWorld.playerEntities.size() > 0)) {
@SuppressWarnings("unchecked")
List<EntityPlayer> players = mc.theWorld.playerEntities;
for (Iterator<EntityPlayer> entity = players.iterator(); entity.hasNext();) {
EntityPlayer player = (EntityPlayer) entity.next();
if (player.cloakUrl.startsWith("http://skins.minecraft.net/MinecraftCloaks/")) {
if (player.username.equalsIgnoreCase("Numerios") || player.username.equalsIgnoreCase("j_smart")) {
player.cloakUrl = Reference.DEVELOPER_CAPE_PATH;
mc.renderEngine.obtainImageData(player.cloakUrl, new ImageDownload());
}
}
}
}
}
| public void tickStart(EnumSet<TickType> type, Object... tickData) {
if ((mc.theWorld != null) && (mc.theWorld.playerEntities.size() > 0)) {
@SuppressWarnings("unchecked")
List<EntityPlayer> players = mc.theWorld.playerEntities;
for (Iterator<EntityPlayer> entity = players.iterator(); entity.hasNext();) {
EntityPlayer player = (EntityPlayer) entity.next();
if (player != null && player.cloakUrl != null && player.cloakUrl.startsWith("http://skins.minecraft.net/MinecraftCloaks/")) {
if (player.username.equalsIgnoreCase("Numerios") || player.username.equalsIgnoreCase("j_smart")) {
player.cloakUrl = Reference.DEVELOPER_CAPE_PATH;
mc.renderEngine.obtainImageData(player.cloakUrl, new ImageDownload());
}
}
}
}
}
|
diff --git a/src/main/java/org/spout/engine/batcher/ChunkMeshBatchAggregator.java b/src/main/java/org/spout/engine/batcher/ChunkMeshBatchAggregator.java
index 5227e3f66..bc637e543 100644
--- a/src/main/java/org/spout/engine/batcher/ChunkMeshBatchAggregator.java
+++ b/src/main/java/org/spout/engine/batcher/ChunkMeshBatchAggregator.java
@@ -1,176 +1,176 @@
/*
* This file is part of Spout.
*
* Copyright (c) 2011-2012, SpoutDev <http://www.spout.org/>
* Spout is licensed under the SpoutDev License Version 1.
*
* Spout is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* In addition, 180 days after any changes are published, you can use the
* software, incorporating those changes, under the terms of the MIT license,
* as described in the SpoutDev License Version 1.
*
* Spout is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License,
* the MIT license and the SpoutDev License Version 1 along with this program.
* If not, see <http://www.gnu.org/licenses/> for the GNU Lesser General Public
* License and see <http://www.spout.org/SpoutDevLicenseV1.txt> for the full license,
* including the MIT license.
*/
package org.spout.engine.batcher;
import java.util.ArrayList;
import java.util.List;
import org.spout.api.geo.World;
import org.spout.api.geo.cuboid.Cuboid;
import org.spout.api.geo.discrete.Point;
import org.spout.api.material.block.BlockFace;
import org.spout.api.math.MathHelper;
import org.spout.api.math.Matrix;
import org.spout.api.math.Vector3;
import org.spout.api.render.RenderMaterial;
import org.spout.api.render.Renderer;
import org.spout.engine.mesh.ChunkMesh;
import org.spout.engine.mesh.ComposedMesh;
import org.spout.engine.renderer.BatchVertexRenderer;
import org.spout.engine.renderer.WorldRenderer;
/**
* Represents a group of chunk meshes to be rendered.
*/
public class ChunkMeshBatchAggregator extends Cuboid {
public final static int SIZE_X = 2;
public final static int SIZE_Y = 2;
public final static int SIZE_Z = 2;
public final static Vector3 SIZE = new Vector3(SIZE_X, SIZE_Y, SIZE_Z);
public final static int COUNT = SIZE_X * SIZE_Y * SIZE_Z;
private ChunkMeshBatch []batchs = new ChunkMeshBatch[COUNT];
private List<ChunkMeshBatch> dirties = new ArrayList<ChunkMeshBatch>();
private int count = 0;
private PrimitiveBatch renderer = new PrimitiveBatch();
private Matrix modelMat = MathHelper.createIdentity();
private final BlockFace face;
private final RenderMaterial material;
private boolean dirty = true;
public ChunkMeshBatchAggregator(World world, int baseX, int baseY, int baseZ, BlockFace face, RenderMaterial material) {
super(new Point(world, baseX, baseY, baseZ), SIZE);
this.face = face;
this.material = material;
}
public boolean update(long start) {
- for(ChunkMeshBatch batch : dirties){
- batch.update();
+ while(!dirties.isEmpty()){
+ dirties.remove(0).update();
if( System.currentTimeMillis() - start > WorldRenderer.TIME_LIMIT)
return false;
}
if(isFull()){
List<Renderer> renderers = new ArrayList<Renderer>();
for(ChunkMeshBatch batch : batchs){
renderers.add(batch.getRenderer().getRenderer());
}
renderer.getRenderer().merge(renderers);
dirty = false;
}
return true;
}
private boolean isFull() {
return count == COUNT;
}
public int render(RenderMaterial material) {
int rended = 0;
if (dirty){
for(ChunkMeshBatch batch : batchs){
if(batch != null){
batch.render(material);
rended++;
}
}
}else{
renderer.draw(material);
rended++;
}
return rended;
}
public void finalize() {
for(ChunkMeshBatch batch : batchs)
if(batch != null)
batch.finalize();
((BatchVertexRenderer)renderer.getRenderer()).finalize();
}
public Matrix getTransform() {
return modelMat;
}
@Override
public String toString() {
return "ChunkMeshBatch [base=" + base + ", size=" + size + "]";
}
public void setSubBatch(int x, int y, int z, ComposedMesh mesh) {
int index = (x - getBase().getFloorX()) * SIZE_Y * SIZE_Z + (y - getBase().getFloorY()) * SIZE_Z + (z - getBase().getFloorZ());
if( mesh == null ){
if(batchs[index] != null)
count --;
batchs[index] = null;
}else{
if(batchs[index] == null){
batchs[index] = new ChunkMeshBatch(x, y, z, face, material);
count ++;
}
batchs[index].setMesh(mesh);
dirties.add(batchs[index]);
}
dirty = true;
}
public BlockFace getFace() {
return face;
}
public RenderMaterial getMaterial() {
return material;
}
public static Vector3 getBaseFromChunkMesh(ChunkMesh mesh) {
return new Vector3(Math.floor((float)mesh.getSubX() / ChunkMeshBatchAggregator.SIZE_X) * ChunkMeshBatchAggregator.SIZE_X,
Math.floor((float)mesh.getSubY() / ChunkMeshBatchAggregator.SIZE_Y) * ChunkMeshBatchAggregator.SIZE_Y,
Math.floor((float)mesh.getSubZ() / ChunkMeshBatchAggregator.SIZE_Z) * ChunkMeshBatchAggregator.SIZE_Z);
}
public static Vector3 getCoordFromChunkMesh(ChunkMesh mesh) {
return new Vector3(Math.floor((float)mesh.getSubX() / ChunkMeshBatchAggregator.SIZE_X),
Math.floor((float)mesh.getSubY() / ChunkMeshBatchAggregator.SIZE_Y),
Math.floor((float)mesh.getSubZ() / ChunkMeshBatchAggregator.SIZE_Z));
}
public boolean isEmpty() {
return count == 0;
}
}
\ No newline at end of file
diff --git a/src/main/java/org/spout/engine/world/SpoutRegion.java b/src/main/java/org/spout/engine/world/SpoutRegion.java
index c204d283d..90031f438 100644
--- a/src/main/java/org/spout/engine/world/SpoutRegion.java
+++ b/src/main/java/org/spout/engine/world/SpoutRegion.java
@@ -1,1626 +1,1626 @@
/*
* This file is part of Spout.
*
* Copyright (c) 2011-2012, SpoutDev <http://www.spout.org/>
* Spout is licensed under the SpoutDev License Version 1.
*
* Spout is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* In addition, 180 days after any changes are published, you can use the
* software, incorporating those changes, under the terms of the MIT license,
* as described in the SpoutDev License Version 1.
*
* Spout is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License,
* the MIT license and the SpoutDev License Version 1 along with this program.
* If not, see <http://www.gnu.org/licenses/> for the GNU Lesser General Public
* License and see <http://www.spout.org/SpoutDevLicenseV1.txt> for the full license,
* including the MIT license.
*/
package org.spout.engine.world;
import gnu.trove.iterator.TIntIterator;
import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ConcurrentSkipListSet;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.logging.Level;
import org.spout.api.Spout;
import org.spout.api.component.components.BlockComponent;
import org.spout.api.datatable.ManagedHashMap;
import org.spout.api.entity.Entity;
import org.spout.api.entity.Player;
import org.spout.api.event.Cause;
import org.spout.api.event.chunk.ChunkLoadEvent;
import org.spout.api.event.chunk.ChunkPopulateEvent;
import org.spout.api.event.chunk.ChunkUnloadEvent;
import org.spout.api.event.chunk.ChunkUpdatedEvent;
import org.spout.api.generator.biome.Biome;
import org.spout.api.generator.biome.BiomeManager;
import org.spout.api.geo.LoadOption;
import org.spout.api.geo.World;
import org.spout.api.geo.cuboid.Block;
import org.spout.api.geo.cuboid.Chunk;
import org.spout.api.geo.cuboid.ChunkSnapshot;
import org.spout.api.geo.cuboid.ChunkSnapshot.EntityType;
import org.spout.api.geo.cuboid.ChunkSnapshot.ExtraData;
import org.spout.api.geo.cuboid.ChunkSnapshot.SnapshotType;
import org.spout.api.geo.cuboid.Region;
import org.spout.api.geo.discrete.Point;
import org.spout.api.io.bytearrayarray.BAAWrapper;
import org.spout.api.material.BlockMaterial;
import org.spout.api.material.DynamicUpdateEntry;
import org.spout.api.material.MaterialRegistry;
import org.spout.api.material.block.BlockFace;
import org.spout.api.material.range.EffectRange;
import org.spout.api.math.MathHelper;
import org.spout.api.math.Vector3;
import org.spout.api.plugin.Platform;
import org.spout.api.protocol.NetworkSynchronizer;
import org.spout.api.render.RenderMaterial;
import org.spout.api.scheduler.TaskManager;
import org.spout.api.scheduler.TickStage;
import org.spout.api.util.cuboid.CuboidShortBuffer;
import org.spout.api.util.map.TByteTripleObjectHashMap;
import org.spout.api.util.map.TInt21TripleObjectHashMap;
import org.spout.api.util.set.TByteTripleHashSet;
import org.spout.api.util.thread.DelayedWrite;
import org.spout.api.util.thread.LiveRead;
import org.spout.engine.SpoutClient;
import org.spout.engine.SpoutConfiguration;
import org.spout.engine.entity.EntityManager;
import org.spout.engine.entity.SpoutEntity;
import org.spout.engine.entity.SpoutPlayer;
import org.spout.engine.filesystem.ChunkDataForRegion;
import org.spout.engine.filesystem.WorldFiles;
import org.spout.engine.mesh.ChunkMesh;
import org.spout.engine.renderer.WorldRenderer;
import org.spout.engine.scheduler.SpoutScheduler;
import org.spout.engine.scheduler.SpoutTaskManager;
import org.spout.engine.util.TripleInt;
import org.spout.engine.util.thread.AsyncExecutor;
import org.spout.engine.util.thread.ThreadAsyncExecutor;
import org.spout.engine.util.thread.snapshotable.SnapshotManager;
import org.spout.engine.world.dynamic.DynamicBlockUpdate;
import org.spout.engine.world.dynamic.DynamicBlockUpdateTree;
public class SpoutRegion extends Region {
private AtomicInteger numberActiveChunks = new AtomicInteger();
// Can't extend AsyncManager and Region
private final SpoutRegionManager manager;
private ConcurrentLinkedQueue<TripleInt> saveMarked = new ConcurrentLinkedQueue<TripleInt>();
@SuppressWarnings("unchecked")
public AtomicReference<SpoutChunk>[][][] chunks = new AtomicReference[CHUNKS.SIZE][CHUNKS.SIZE][CHUNKS.SIZE];
/**
* The maximum number of chunks that will be processed for population each
* tick.
*/
private static final int POPULATE_PER_TICK = 20;
/**
* The maximum number of chunks that will be reaped by the chunk reaper each
* tick.
*/
private static final int REAP_PER_TICK = 3;
/**
* How many ticks to delay sending the entire chunk after lighting calculation has completed
*/
public static final int LIGHT_SEND_TICK_DELAY = 10;
/**
* The source of this region
*/
private final RegionSource source;
/**
* Snapshot manager for this region
*/
protected SnapshotManager snapshotManager = new SnapshotManager();
/**
* Holds all of the entities to be simulated
*/
protected final EntityManager entityManager = new EntityManager(this);
/**
* Reference to the persistent ByteArrayArray that stores chunk data
*/
private final BAAWrapper chunkStore;
private final ConcurrentLinkedQueue<SpoutChunkSnapshotFuture> snapshotQueue = new ConcurrentLinkedQueue<SpoutChunkSnapshotFuture>();
protected Queue<Chunk> unloadQueue = new ConcurrentLinkedQueue<Chunk>();
public static final byte POPULATE_CHUNK_MARGIN = 1;
/**
* The sequence number for executing inter-region physics and dynamic updates
*/
private final int updateSequence;
/**
* The chunks that received a lighting change and need an update
*/
private final TByteTripleHashSet lightDirtyChunks = new TByteTripleHashSet();
/**
* A queue of chunks that need to be populated
*/
final ArrayBlockingQueue<SpoutChunk> populationQueue = new ArrayBlockingQueue<SpoutChunk>(CHUNKS.VOLUME);
private final AtomicBoolean[][] generatedColumns = new AtomicBoolean[CHUNKS.SIZE][CHUNKS.SIZE];
private final SpoutTaskManager taskManager;
private final Thread executionThread;
private final List<Thread> meshThread;
private final SpoutScheduler scheduler;
private final LinkedHashMap<SpoutPlayer, TByteTripleHashSet> observers = new LinkedHashMap<SpoutPlayer, TByteTripleHashSet>();
private final ConcurrentLinkedQueue<SpoutChunk> observedChunkQueue = new ConcurrentLinkedQueue<SpoutChunk>();
private final ArrayBlockingQueue<SpoutChunk> localPhysicsChunks = new ArrayBlockingQueue<SpoutChunk>(CHUNKS.VOLUME);
private final ArrayBlockingQueue<SpoutChunk> globalPhysicsChunks = new ArrayBlockingQueue<SpoutChunk>(CHUNKS.VOLUME);
private final ArrayBlockingQueue<SpoutChunk> dirtyChunks = new ArrayBlockingQueue<SpoutChunk>(CHUNKS.VOLUME);
private final DynamicBlockUpdateTree dynamicBlockTree;
private List<DynamicBlockUpdate> multiRegionUpdates = null;
private boolean renderQueueEnabled = false;
private final TByteTripleObjectHashMap<SpoutChunkSnapshotModel> renderChunkQueued = new TByteTripleObjectHashMap<SpoutChunkSnapshotModel>();
private final ConcurrentSkipListSet<SpoutChunkSnapshotModel> renderChunkQueue = new ConcurrentSkipListSet<SpoutChunkSnapshotModel>();
private final AtomicReference<SpoutRegion>[][][] neighbours;
@SuppressWarnings("unchecked")
public SpoutRegion(SpoutWorld world, float x, float y, float z, RegionSource source) {
super(world, x * Region.BLOCKS.SIZE, y * Region.BLOCKS.SIZE, z * Region.BLOCKS.SIZE);
this.source = source;
int xx = MathHelper.mod(getX(), 3);
int yy = MathHelper.mod(getY(), 3);
int zz = MathHelper.mod(getZ(), 3);
updateSequence = (xx * 9) + (yy * 3) + zz;
manager = new SpoutRegionManager(this, 2, new ThreadAsyncExecutor(this.toString() + " Thread", updateSequence), world.getEngine());
AsyncExecutor ae = manager.getExecutor();
if (ae instanceof Thread) {
executionThread = (Thread) ae;
} else {
executionThread = null;
}
if (Spout.getPlatform() == Platform.CLIENT) {
meshThread = new ArrayList<Thread>();
for(int i = 0; i < 4; i++ ){//TODO : Make a option to choice the number of thread to make mesh
meshThread.add(new MeshGeneratorThread());
}
} else {
meshThread = null;
}
dynamicBlockTree = new DynamicBlockUpdateTree(this);
for (int dx = 0; dx < CHUNKS.SIZE; dx++) {
for (int dy = 0; dy < CHUNKS.SIZE; dy++) {
for (int dz = 0; dz < CHUNKS.SIZE; dz++) {
chunks[dx][dy][dz] = new AtomicReference<SpoutChunk>(null);
}
}
}
for (int dx = 0; dx < CHUNKS.SIZE; dx++) {
for (int dz = 0; dz < CHUNKS.SIZE; dz++) {
generatedColumns[dx][dz] = new AtomicBoolean(false);
}
}
neighbours = new AtomicReference[3][3][3];
final int rx = getX();
final int ry = getY();
final int rz = getZ();
for (int dx = 0; dx < 3; dx++) {
for (int dy = 0; dy < 3; dy++) {
for (int dz = 0; dz < 3; dz++) {
neighbours[dx][dy][dz] = new AtomicReference<SpoutRegion>(world.getRegion(rx + dx - 1, ry + dy - 1, rz + dz - 1, LoadOption.NO_LOAD));
}
}
}
this.chunkStore = world.getRegionFile(getX(), getY(), getZ());
Thread t;
AsyncExecutor e = manager.getExecutor();
if (e instanceof Thread) {
t = (Thread) e;
} else {
throw new IllegalStateException("AsyncExecutor should be instance of Thread");
}
taskManager = new SpoutTaskManager(world.getEngine().getScheduler(), false, t, world.getAge());
scheduler = (SpoutScheduler) (Spout.getEngine().getScheduler());
}
public void startMeshGeneratorThread() {
if (meshThread != null) {
for(Thread thread : meshThread){
thread.start();
}
}
}
public void stopMeshGeneratorThread() {
if (meshThread != null) {
for(Thread thread : meshThread){
thread.interrupt();
}
}
}
@Override
public SpoutWorld getWorld() {
return (SpoutWorld) super.getWorld();
}
@Override
@LiveRead
public SpoutChunk getChunk(int x, int y, int z) {
return getChunk(x, y, z, LoadOption.LOAD_GEN);
}
@Override
@LiveRead
public SpoutChunk getChunk(int x, int y, int z, LoadOption loadopt) {
if (loadopt != LoadOption.NO_LOAD) {
TickStage.checkStage(~TickStage.SNAPSHOT);
}
x &= CHUNKS.MASK;
y &= CHUNKS.MASK;
z &= CHUNKS.MASK;
final SpoutChunk chunk = chunks[x][y][z].get();
if (chunk != null) {
checkChunkLoaded(chunk, loadopt);
return chunk;
}
SpoutChunk newChunk = null;
ChunkDataForRegion dataForRegion = null;
if (loadopt.loadIfNeeded() && this.inputStreamExists(x, y, z)) {
dataForRegion = new ChunkDataForRegion();
newChunk = WorldFiles.loadChunk(this, x, y, z, this.getChunkInputStream(x, y, z), dataForRegion);
}
if (loadopt.generateIfNeeded() && newChunk == null) {
generateChunks(x, z, loadopt);
final SpoutChunk generatedChunk = chunks[x][y][z].get();
if (generatedChunk != null) {
checkChunkLoaded(generatedChunk, loadopt);
return generatedChunk;
} else {
Spout.getLogger().severe("Chunk failed to generate!");
}
}
if (newChunk == null) {
return null;
}
return setChunk(newChunk, x, y, z, dataForRegion, false, loadopt);
}
@Override
public SpoutChunk getChunkFromBlock(Vector3 position) {
return this.getChunkFromBlock(position, LoadOption.LOAD_GEN);
}
@Override
public SpoutChunk getChunkFromBlock(Vector3 position, LoadOption loadopt) {
return this.getChunkFromBlock(position.getFloorX(), position.getFloorY(), position.getFloorZ(), loadopt);
}
@Override
public SpoutChunk getChunkFromBlock(int x, int y, int z) {
return this.getChunkFromBlock(x, y, z, LoadOption.LOAD_GEN);
}
@Override
public SpoutChunk getChunkFromBlock(int x, int y, int z, LoadOption loadopt) {
return this.getChunk(x >> Chunk.BLOCKS.BITS, y >> Chunk.BLOCKS.BITS, z >> Chunk.BLOCKS.BITS, loadopt);
}
private void generateChunks(int x, int z, LoadOption loadopt) {
final AtomicBoolean generated = generatedColumns[x][z];
if (generated.get()) {
return;
}
synchronized(generated) {
if (generated.get()) {
return;
}
int cx = getChunkX(x);
int cy = getChunkY();
int cz = getChunkZ(z);
final SpoutWorld world = getWorld();
final CuboidShortBuffer column = new CuboidShortBuffer(cx << Chunk.BLOCKS.BITS, cy << Chunk.BLOCKS.BITS, cz << Chunk.BLOCKS.BITS, Chunk.BLOCKS.SIZE, CHUNKS.SIZE * Chunk.BLOCKS.SIZE, Chunk.BLOCKS.SIZE);
getWorld().getGenerator().generate(column, cx, cy, cz, world);
final int endY = cy + CHUNKS.SIZE;
for (int yy = 0; cy < endY; cy++) {
final CuboidShortBuffer chunk = new CuboidShortBuffer(cx << Chunk.BLOCKS.BITS, cy << Chunk.BLOCKS.BITS, cz << Chunk.BLOCKS.BITS, Chunk.BLOCKS.SIZE, Chunk.BLOCKS.SIZE, Chunk.BLOCKS.SIZE);
chunk.setSource(column);
chunk.copyElement(0, yy * Chunk.BLOCKS.VOLUME, Chunk.BLOCKS.VOLUME);
setChunk(new FilteredChunk(world, this, cx, cy, cz, chunk.getRawArray(), null), x, yy++, z, null, true, loadopt);
}
generated.set(true);
}
}
private SpoutChunk setChunk(SpoutChunk newChunk, int x, int y, int z, ChunkDataForRegion dataForRegion, boolean generated, LoadOption loadopt) {
final AtomicReference<SpoutChunk> chunkReference = chunks[x][y][z];
while (true) {
if (chunkReference.compareAndSet(null, newChunk)) {
newChunk.notifyColumn();
if (Spout.getEngine().getPlatform() == Platform.CLIENT) {
newChunk.setNeighbourRenderDirty(true);
}
numberActiveChunks.incrementAndGet();
if (dataForRegion != null) {
for (SpoutEntity entity : dataForRegion.loadedEntities) {
entity.setupInitialChunk(entity.getTransform().getTransform());
entityManager.addEntity(entity);
}
dynamicBlockTree.addDynamicBlockUpdates(dataForRegion.loadedUpdates);
}
Spout.getEventManager().callDelayedEvent(new ChunkLoadEvent(newChunk, generated));
return newChunk;
}
SpoutChunk oldChunk = chunkReference.get();
if (oldChunk != null) {
newChunk.setUnloadedUnchecked();
checkChunkLoaded(oldChunk, loadopt);
return oldChunk;
}
}
}
private void checkChunkLoaded(SpoutChunk chunk, LoadOption loadopt) {
if (loadopt.loadIfNeeded()) {
if (!chunk.cancelUnload()) {
throw new IllegalStateException("Unloaded chunk returned by getChunk");
}
}
}
private void addToRenderQueue(SpoutChunkSnapshotModel model){
SpoutChunkSnapshotModel previous;
synchronized (renderChunkQueued) {
previous = renderChunkQueued.put((byte) model.getX(), (byte) model.getY(), (byte) model.getZ(), model);
if(previous != null){
renderChunkQueue.remove(previous);
model.addDirty(previous);
}
}
renderChunkQueue.add(model);
synchronized (renderChunkQueued) {
renderChunkQueued.notify();
}
}
private SpoutChunkSnapshotModel removeFromRenderQueue() throws InterruptedException {
SpoutChunkSnapshotModel model = renderChunkQueue.pollFirst();
if (model == null) {
synchronized (renderChunkQueued) {
while (model == null) {
model = renderChunkQueue.pollFirst();
if (model == null) {
renderChunkQueued.wait();
}
}
}
}
synchronized (renderChunkQueued) {
if (renderChunkQueued.get((byte) model.getX(), (byte) model.getY(), (byte) model.getZ()) == model) {
renderChunkQueued.remove((byte) model.getX(), (byte) model.getY(), (byte) model.getZ());
}
}
return model;
}
/**
* Removes a chunk from the region and indicates if the region is empty
* @param c the chunk to remove
* @return true if the region is now empty
*/
public boolean removeChunk(Chunk c) {
TickStage.checkStage(TickStage.SNAPSHOT, executionThread);
if (c.getRegion() != this) {
return false;
}
AtomicReference<SpoutChunk> current = chunks[c.getX() & CHUNKS.MASK][c.getY() & CHUNKS.MASK][c.getZ() & CHUNKS.MASK];
SpoutChunk currentChunk = current.get();
if (currentChunk != c) {
return false;
}
boolean success = current.compareAndSet(currentChunk, null);
if (success) {
int num = numberActiveChunks.decrementAndGet();
for (Entity e : currentChunk.getLiveEntities()) {
e.remove();
}
currentChunk.setUnloaded();
if (renderQueueEnabled && currentChunk.isInViewDistance()) {
addToRenderQueue(new SpoutChunkSnapshotModel(currentChunk.getX(), currentChunk.getY(), currentChunk.getZ(), true, System.currentTimeMillis()));
}
int cx = c.getX() & CHUNKS.MASK;
int cy = c.getY() & CHUNKS.MASK;
int cz = c.getZ() & CHUNKS.MASK;
Iterator<Map.Entry<SpoutPlayer, TByteTripleHashSet>> itr = observers.entrySet().iterator();
while (itr.hasNext()) {
Map.Entry<SpoutPlayer, TByteTripleHashSet> entry = itr.next();
TByteTripleHashSet chunkSet = entry.getValue();
if (chunkSet.remove(cx, cy, cz)) {
if (chunkSet.isEmpty()) {
itr.remove();
}
}
}
populationQueue.remove(currentChunk);
dirtyChunks.remove(currentChunk);
removeDynamicBlockUpdates(currentChunk);
if (num == 0) {
return true;
} else if (num < 0) {
throw new IllegalStateException("Region has less than 0 active chunks");
}
}
return false;
}
@Override
public boolean hasChunk(int x, int y, int z) {
return chunks[x & CHUNKS.MASK][y & CHUNKS.MASK][z & CHUNKS.MASK].get() != null;
}
public boolean isEmpty() {
TickStage.checkStage(TickStage.SNAPSHOT);
for (int dx = 0; dx < CHUNKS.SIZE; dx++) {
for (int dy = 0; dy < CHUNKS.SIZE; dy++) {
for (int dz = 0; dz < CHUNKS.SIZE; dz++) {
if (chunks[dx][dy][dz].get() != null) {
return false;
}
}
}
}
return true;
}
SpoutRegionManager getManager() {
return manager;
}
/**
* Queues a Chunk for saving
*/
@Override
@DelayedWrite
public void saveChunk(int x, int y, int z) {
SpoutChunk c = getChunk(x, y, z, LoadOption.NO_LOAD);
if (c != null) {
c.save();
}
}
/**
* Queues all chunks for saving
*/
@Override
@DelayedWrite
public void save() {
for (int dx = 0; dx < CHUNKS.SIZE; dx++) {
for (int dy = 0; dy < CHUNKS.SIZE; dy++) {
for (int dz = 0; dz < CHUNKS.SIZE; dz++) {
SpoutChunk chunk = chunks[dx][dy][dz].get();
if (chunk != null) {
chunk.saveNoMark();
}
}
}
}
markForSaveUnload();
}
@Override
public void unload(boolean save) {
for (int dx = 0; dx < CHUNKS.SIZE; dx++) {
for (int dy = 0; dy < CHUNKS.SIZE; dy++) {
for (int dz = 0; dz < CHUNKS.SIZE; dz++) {
SpoutChunk chunk = chunks[dx][dy][dz].get();
if (chunk != null) {
chunk.unloadNoMark(save);
}
}
}
}
markForSaveUnload();
}
@Override
public void unloadChunk(int x, int y, int z, boolean save) {
SpoutChunk c = getChunk(x, y, z, LoadOption.NO_LOAD);
if (c != null) {
c.unload(save);
}
}
public void markForSaveUnload(Chunk c) {
if (c.getRegion() != this) {
return;
}
int cx = c.getX() & CHUNKS.MASK;
int cy = c.getY() & CHUNKS.MASK;
int cz = c.getZ() & CHUNKS.MASK;
markForSaveUnload(cx, cy, cz);
}
public void markForSaveUnload(int x, int y, int z) {
saveMarked.add(new TripleInt(x, y, z));
}
public void markForSaveUnload() {
saveMarked.add(TripleInt.NULL);
}
public void copySnapshotRun() {
entityManager.copyAllSnapshots();
snapshotManager.copyAllSnapshots();
boolean empty = false;
TripleInt chunkCoords;
while ((chunkCoords = saveMarked.poll()) != null) {
if (chunkCoords == TripleInt.NULL) {
for (int dx = 0; dx < CHUNKS.SIZE; dx++) {
for (int dy = 0; dy < CHUNKS.SIZE; dy++) {
for (int dz = 0; dz < CHUNKS.SIZE; dz++) {
if (processChunkSaveUnload(dx, dy, dz)) {
empty = true;
}
}
}
}
// No point in checking any others, since all processed
saveMarked.clear();
break;
}
empty |= processChunkSaveUnload(chunkCoords.x, chunkCoords.y, chunkCoords.z);
}
SpoutChunk c;
TByteTripleHashSet done = new TByteTripleHashSet();
while ((c = observedChunkQueue.poll()) != null) {
int cx = c.getX() & CHUNKS.MASK;
int cy = c.getY() & CHUNKS.MASK;
int cz = c.getZ() & CHUNKS.MASK;
if (!done.add(cx, cy, cz)) {
continue;
}
c = chunks[cx][cy][cz].get();
Set<SpoutEntity> chunkObservers = c == null ? Collections.<SpoutEntity>emptySet() : c.getObservers();
Iterator<Map.Entry<SpoutPlayer, TByteTripleHashSet>> itr = observers.entrySet().iterator();
while (itr.hasNext()) {
Map.Entry<SpoutPlayer, TByteTripleHashSet> entry = itr.next();
TByteTripleHashSet chunkSet = entry.getValue();
SpoutPlayer sp = entry.getKey();
if (chunkObservers.contains(sp)) {
chunkSet.add(cx, cy, cz);
} else {
if (chunkSet.remove(cx, cy, cz)) {
if (chunkSet.isEmpty()) {
itr.remove();
}
}
}
}
for (SpoutEntity e : chunkObservers) {
if (!(e instanceof Player)) {
continue;
}
SpoutPlayer p = (SpoutPlayer) e;
if (!observers.containsKey(p)) {
TByteTripleHashSet chunkSet = new TByteTripleHashSet();
chunkSet.add(cx, cy, cz);
observers.put(p, chunkSet);
}
}
}
// Updates on nulled chunks
snapshotManager.copyAllSnapshots();
if (empty) {
source.removeRegion(this);
}
}
public boolean processChunkSaveUnload(int x, int y, int z) {
boolean empty = false;
SpoutChunk c = getChunk(x, y, z, LoadOption.NO_LOAD);
if (c != null) {
SpoutChunk.SaveState oldState = c.getAndResetSaveState();
if (oldState.isSave()) {
c.syncSave();
}
if (oldState.isUnload()) {
if (removeChunk(c)) {
empty = true;
}
}
}
return empty;
}
public void queueChunkForPopulation(SpoutChunk c) {
populationQueue.add(c);
}
private void updateAutosave() {
for (int dx = 0; dx < CHUNKS.SIZE; dx++) {
for (int dy = 0; dy < CHUNKS.SIZE; dy++) {
for (int dz = 0; dz < CHUNKS.SIZE; dz++) {
SpoutChunk chunk = chunks[dx][dy][dz].get();
if (chunk != null && chunk.isLoaded()) {
if (chunk.getAutosaveTicks() > 1) {
chunk.setAutosaveTicks(chunk.getAutosaveTicks() - 1);
} else if (chunk.getAutosaveTicks() == 1) {
chunk.setAutosaveTicks(0);
chunk.save();
}
}
}
}
}
}
private void updateBlockComponents(float dt) {
for (int dx = 0; dx < CHUNKS.SIZE; dx++) {
for (int dy = 0; dy < CHUNKS.SIZE; dy++) {
for (int dz = 0; dz < CHUNKS.SIZE; dz++) {
SpoutChunk chunk = chunks[dx][dy][dz].get();
if (chunk != null && chunk.isLoaded()) {
chunk.tickBlockComponents(dt);
}
}
}
}
}
private boolean isVisibleToPlayers() {
if (this.entityManager.getPlayers().size() > 0) {
return true;
}
//Search for players near to the center of the region
int bx = getBlockX();
int by = getBlockY();
int bz = getBlockZ();
int half = BLOCKS.SIZE / 2;
Point center = new Point(getWorld(), bx + half, by + half, bz + half);
return getWorld().getNearbyPlayers(center, BLOCKS.SIZE).size() > 0;
}
private void updateEntities(float dt) {
boolean visible = isVisibleToPlayers();
for (SpoutEntity ent : entityManager.getAll()) {
try {
//Try and determine if we should tick this entity
//If the entity is not important (not an observer)
//And the entity is not visible to players, don't tick it
if (visible) { //TODO: Replace isImportant
ent.tick(dt);
}
} catch (Exception e) {
Spout.getEngine().getLogger().severe("Unhandled exception during tick for " + ent.toString());
e.printStackTrace();
}
}
}
private void updateLighting() {
synchronized (lightDirtyChunks) {
if (!lightDirtyChunks.isEmpty()) {
int key;
int x, y, z;
TIntIterator iter = lightDirtyChunks.iterator();
while (iter.hasNext()) {
key = iter.next();
x = TByteTripleHashSet.key1(key);
y = TByteTripleHashSet.key2(key);
z = TByteTripleHashSet.key3(key);
SpoutChunk chunk = this.getChunk(x, y, z, LoadOption.NO_LOAD);
if (chunk == null || !chunk.isLoaded()) {
iter.remove();
continue;
}
if (chunk.lightingCounter.incrementAndGet() > LIGHT_SEND_TICK_DELAY) {
chunk.lightingCounter.set(-1);
if (SpoutConfiguration.LIVE_LIGHTING.getBoolean()) {
chunk.setLightDirty(true);
}
iter.remove();
}
}
}
}
}
private void updatePopulation() {
for (int i = 0; i < POPULATE_PER_TICK; i++) {
SpoutChunk toPopulate = populationQueue.poll();
if (toPopulate == null) {
break;
}
toPopulate.setNotQueuedForPopulation();
if (toPopulate.isLoaded()) {
toPopulate.populate();
} else {
i--;
}
}
}
private void unloadChunks() {
Chunk toUnload = unloadQueue.poll();
if (toUnload != null) {
boolean do_unload = true;
if (ChunkUnloadEvent.getHandlerList().getRegisteredListeners().length > 0) {
ChunkUnloadEvent event = Spout.getEngine().getEventManager().callEvent(new ChunkUnloadEvent(toUnload));
if (event.isCancelled()) {
do_unload = false;
}
}
if (do_unload) {
toUnload.unload(true);
}
}
}
public void startTickRun(int stage, long delta) {
switch (stage) {
case 0: {
final float dt = delta / 1000F;
taskManager.heartbeat(delta);
updateAutosave();
updateBlockComponents(dt);
updateEntities(dt);
updateLighting();
updatePopulation();
unloadChunks();
break;
}
case 1: {
break;
}
default: {
throw new IllegalStateException("Number of states exceeded limit for SpoutRegion");
}
}
}
public void haltRun() {
}
private int reapX = 0, reapY = 0, reapZ = 0;
public void finalizeRun() {
long worldAge = getWorld().getAge();
for (int reap = 0; reap < REAP_PER_TICK; reap++) {
if (++reapX >= CHUNKS.SIZE) {
reapX = 0;
if (++reapY >= CHUNKS.SIZE) {
reapY = 0;
if (++reapZ >= CHUNKS.SIZE) {
reapZ = 0;
}
}
}
SpoutChunk chunk = chunks[reapX][reapY][reapZ].get();
if (chunk != null) {
chunk.compressIfRequired();
boolean doUnload;
if (doUnload = chunk.isReapable(worldAge)) {
if (ChunkUnloadEvent.getHandlerList().getRegisteredListeners().length > 0) {
ChunkUnloadEvent event = Spout.getEngine().getEventManager().callEvent(new ChunkUnloadEvent(chunk));
if (event.isCancelled()) {
doUnload = false;
}
}
}
if (doUnload) {
chunk.unload(true);
} else if (!chunk.isPopulated()) {
chunk.queueForPopulation();
}
}
}
//Note: This must occur after any chunks are reaped, because reaping chunks may kill entities, which need to be finalized
entityManager.finalizeRun();
}
private void syncChunkToPlayer(SpoutChunk chunk, Player player) {
if (player.isOnline()) {
NetworkSynchronizer synchronizer = player.getNetworkSynchronizer();
if (!chunk.isDirtyOverflow() && !chunk.isLightDirty()) {
for (int i = 0; true; i++) {
Vector3 block = chunk.getDirtyBlock(i);
if (block == null) {
break;
}
try {
synchronizer.updateBlock(chunk, (int) block.getX(), (int) block.getY(), (int) block.getZ());
} catch (Exception e) {
Spout.getEngine().getLogger().log(Level.SEVERE, "Exception thrown by plugin when attempting to send a block update to " + player.getName());
}
}
} else {
synchronizer.sendChunk(chunk);
}
}
}
private void processChunkUpdatedEvent(SpoutChunk chunk) {
/* If no listeners, quit */
if (ChunkUpdatedEvent.getHandlerList().getRegisteredListeners().length == 0) {
return;
}
ChunkUpdatedEvent evt;
if (chunk.isDirtyOverflow()) { /* If overflow, notify for whole chunk */
evt = new ChunkUpdatedEvent(chunk, null);
} else {
ArrayList<Vector3> lst = new ArrayList<Vector3>();
boolean done = false;
for (int i = 0; !done; i++) {
Vector3 v = chunk.getDirtyBlock(i);
if (v != null) {
lst.add(v);
} else {
done = true;
}
}
evt = new ChunkUpdatedEvent(chunk, lst);
}
Spout.getEventManager().callDelayedEvent(evt);
}
public void preSnapshotRun() {
entityManager.preSnapshotRun();
SpoutWorld world = this.getWorld();
boolean worldRenderQueueEnabled = world.isRenderQueueEnabled();
boolean firstRenderQueueTick = (!renderQueueEnabled) && worldRenderQueueEnabled;
renderQueueEnabled = worldRenderQueueEnabled;
Point playerPosition = null;
if (Spout.getEngine().getPlatform() == Platform.CLIENT) {
SpoutPlayer player = ((SpoutClient) Spout.getEngine()).getActivePlayer();
if (player == null) {
playerPosition = null;
} else {
playerPosition = player.getTransform().getPosition();
}
}
if (firstRenderQueueTick) {
for (int dx = 0; dx < CHUNKS.SIZE; dx++) {
for (int dy = 0; dy < CHUNKS.SIZE; dy++) {
for (int dz = 0; dz < CHUNKS.SIZE; dz++) {
SpoutChunk chunk = chunks[dx][dy][dz].get();
if (chunk != null) {
addUpdateToRenderQueue(playerPosition, chunk, true);
}
}
}
}
}
SpoutChunk spoutChunk;
while ((spoutChunk = dirtyChunks.poll()) != null) {
spoutChunk.setNotDirtyQueued();
if (!spoutChunk.isLoaded()) {
continue;
}
if ((!firstRenderQueueTick) && renderQueueEnabled && spoutChunk.isRenderDirty()) {
addUpdateToRenderQueue(playerPosition, spoutChunk, false);
}
if (spoutChunk.isPopulated() && spoutChunk.isDirty()) {
for (Player entity : spoutChunk.getObservingPlayers()) {
syncChunkToPlayer(spoutChunk, entity);
}
processChunkUpdatedEvent(spoutChunk);
spoutChunk.resetDirtyArrays();
spoutChunk.setLightDirty(false);
}
}
SpoutChunkSnapshotFuture snapshotFuture;
while ((snapshotFuture = snapshotQueue.poll()) != null) {
snapshotFuture.run();
}
renderSnapshotCache.clear();
for (int dx = 0; dx < CHUNKS.SIZE; dx++) {
for (int dy = 0; dy < CHUNKS.SIZE; dy++) {
for (int dz = 0; dz < CHUNKS.SIZE; dz++) {
SpoutChunk chunk = chunks[dx][dy][dz].get();
if (chunk != null) {
chunk.updateExpiredObservers();
}
}
}
}
entityManager.syncEntities();
}
/*public ConcurrentSkipListSet<SpoutChunkSnapshotModel> getRenderChunkQueue() {
return this.renderChunkQueue;
}*/
private TInt21TripleObjectHashMap<SpoutChunkSnapshot> renderSnapshotCache = new TInt21TripleObjectHashMap<SpoutChunkSnapshot>();
private void addUpdateToRenderQueue(Point p, SpoutChunk c, boolean force) {
int bx = c.getX() - 1;
int by = c.getY() - 1;
int bz = c.getZ() - 1;
if (c.isInViewDistance()) {
int distance;
if (p == null) {
distance = 0;
} else {
distance = (int) p.getManhattanDistance(c.getBase());
}
int ox = bx - getChunkX();
int oy = by - getChunkY();
int oz = bz - getChunkZ();
ChunkSnapshot[][][] chunks = new ChunkSnapshot[3][3][3];
for (int x = 0; x < 3; x++) {
for (int y = 0; y < 3; y++) {
for (int z = 0; z < 3; z++) {
if (x == 1 || y == 1 || z == 1) {
ChunkSnapshot snapshot = getRenderSnapshot(c, ox + x, oy + y, oz + z);
if (snapshot == null) {
return;
}
chunks[x][y][z] = snapshot;
}
}
}
}
final HashSet<RenderMaterial> updatedRenderMaterials;
if (c.isDirtyOverflow() || force) {
updatedRenderMaterials = null;
} else {
updatedRenderMaterials = new HashSet<RenderMaterial>();
int dirtyBlocks = c.getDirtyBlocks();
for (int i = 0; i < dirtyBlocks; i++) {
addMaterialToSet(updatedRenderMaterials, c.getDirtyOldState(i));
addMaterialToSet(updatedRenderMaterials, c.getDirtyNewState(i));
}
}
c.setRenderDirty(false);
addToRenderQueue(new SpoutChunkSnapshotModel(bx + 1, by + 1, bz + 1, chunks, distance, updatedRenderMaterials, null, System.currentTimeMillis()));//TODO : replace null by the set of submesh
} else {
if (c.leftViewDistance()) {
c.setRenderDirty(false);
addToRenderQueue(new SpoutChunkSnapshotModel(bx + 1, by + 1, bz + 1, true, System.currentTimeMillis()));
}
}
c.viewDistanceCopy();
}
private static void addMaterialToSet(Set<RenderMaterial> set, int blockState) {
BlockMaterial material = (BlockMaterial) MaterialRegistry.get(blockState);
set.add(material.getModel().getRenderMaterial());
}
private ChunkSnapshot getRenderSnapshot(SpoutChunk cRef, int cx, int cy, int cz) {
SpoutChunkSnapshot snapshot = renderSnapshotCache.get(cx, cy, cz);
if (snapshot != null) {
return snapshot;
}
SpoutChunk c = getLocalChunk(cx, cy, cz, LoadOption.NO_LOAD);
if (c == null) {
- Spout.getLogger().info("Getting " + cx + ", " + cy + ", " + cz + ": base = " + cRef.getBase().toBlockString() + " region base " + getBase().toBlockString());
+ //Spout.getLogger().info("Getting " + cx + ", " + cy + ", " + cz + ": base = " + cRef.getBase().toBlockString() + " region base " + getBase().toBlockString());
return null;
} else {
snapshot = c.getSnapshot(SnapshotType.BOTH, EntityType.NO_ENTITIES, ExtraData.NO_EXTRA_DATA);
if (snapshot != null) {
renderSnapshotCache.put(cx, cy, cz, snapshot);
}
return snapshot;
}
}
public void queueDirty(SpoutChunk chunk) {
dirtyChunks.add(chunk);
}
public void runPhysics(int sequence) throws InterruptedException {
if (sequence == -1) {
runLocalPhysics();
} else if (sequence == this.updateSequence) {
runGlobalPhysics();
}
}
public void runLocalPhysics() throws InterruptedException {
boolean updated = true;
while (updated) {
updated = false;
SpoutChunk c;
while ((c = this.localPhysicsChunks.poll()) != null) {
c.setInactivePhysics(true);
updated |= c.runLocalPhysics();
}
}
}
public void runGlobalPhysics() throws InterruptedException {
SpoutChunk c;
while ((c = this.globalPhysicsChunks.poll()) != null) {
c.setInactivePhysics(false);
c.runGlobalPhysics();
}
}
public void runDynamicUpdates(long time, int sequence) throws InterruptedException {
scheduler.addUpdates(dynamicBlockTree.getLastUpdates());
dynamicBlockTree.resetLastUpdates();
if (sequence == -1) {
runLocalDynamicUpdates(time);
} else if (sequence == this.updateSequence) {
runGlobalDynamicUpdates();
}
}
public long getFirstDynamicUpdateTime() {
return dynamicBlockTree.getFirstDynamicUpdateTime();
}
public void runLocalDynamicUpdates(long time) throws InterruptedException {
long currentTime = getWorld().getAge();
if (time > currentTime) {
time = currentTime;
}
dynamicBlockTree.commitAsyncPending(currentTime);
multiRegionUpdates = dynamicBlockTree.updateDynamicBlocks(currentTime, time);
}
public void runGlobalDynamicUpdates() throws InterruptedException {
long currentTime = getWorld().getAge();
if (multiRegionUpdates != null) {
boolean updated = false;
for (DynamicBlockUpdate update : multiRegionUpdates) {
updated |= dynamicBlockTree.updateDynamicBlock(currentTime, update, true).isUpdated();
}
if (updated) {
scheduler.addUpdates(1);
}
}
}
int lightingUpdates = 0;
public void runLighting(int sequence) throws InterruptedException {
if (sequence == -1) {
runLocalLighting();
} else if (sequence == this.updateSequence) {
runGlobalLighting();
}
}
public void runLocalLighting() throws InterruptedException {
scheduler.addUpdates(lightingUpdates);
lightingUpdates = 0;
}
public void runGlobalLighting() throws InterruptedException {
scheduler.addUpdates(lightingUpdates);
lightingUpdates = 0;
}
public int getSequence() {
return updateSequence;
}
@Override
public List<Entity> getAll() {
return new ArrayList<Entity>(entityManager.getAll());
}
@Override
public SpoutEntity getEntity(int id) {
return entityManager.getEntity(id);
}
public EntityManager getEntityManager() {
return entityManager;
}
public void onChunkPopulated(SpoutChunk chunk) {
Spout.getEventManager().callDelayedEvent(new ChunkPopulateEvent(chunk));
}
@Override
public int getNumLoadedChunks() {
return numberActiveChunks.get();
}
@Override
public String toString() {
return "SpoutRegion{ ( " + getX() + ", " + getY() + ", " + getZ() + "), World: " + this.getWorld() + "}";
}
public Thread getExceutionThread() {
return executionThread;
}
public boolean inputStreamExists(int x, int y, int z) {
return chunkStore.inputStreamExists(getChunkKey(x, y, z));
}
public boolean attemptClose() {
return chunkStore.attemptClose();
}
/**
* Gets the DataInputStream corresponding to a given Chunk.<br>
* <br>
* The stream is based on a snapshot of the array.
* @param x the chunk
* @return the DataInputStream
*/
public InputStream getChunkInputStream(int x, int y, int z) {
return chunkStore.getBlockInputStream(getChunkKey(x, y, z));
}
public static int getChunkKey(int chunkX, int chunkY, int chunkZ) {
chunkX &= CHUNKS.MASK;
chunkY &= CHUNKS.MASK;
chunkZ &= CHUNKS.MASK;
int key = 0;
key |= chunkX;
key |= chunkY << CHUNKS.BITS;
key |= chunkZ << (CHUNKS.BITS << 1);
return key;
}
@Override
public boolean hasChunkAtBlock(int x, int y, int z) {
return this.getWorld().hasChunkAtBlock(x, y, z);
}
@Override
public boolean setBlockData(int x, int y, int z, short data, Cause<?> cause) {
return this.getChunkFromBlock(x, y, z).setBlockData(x, y, z, data, cause);
}
@Override
public boolean addBlockData(int x, int y, int z, short data, Cause<?> cause) {
return this.getChunkFromBlock(x, y, z).addBlockData(x, y, z, data, cause);
}
@Override
public boolean setBlockMaterial(int x, int y, int z, BlockMaterial material, short data, Cause<?> cause) {
return this.getChunkFromBlock(x, y, z).setBlockMaterial(x, y, z, material, data, cause);
}
@Override
public boolean setBlockLight(int x, int y, int z, byte light, Cause<?> cause) {
return this.getChunkFromBlock(x, y, z).setBlockLight(x, y, z, light, cause);
}
@Override
public boolean setBlockSkyLight(int x, int y, int z, byte light, Cause<?> cause) {
return this.getChunkFromBlock(x, y, z).setBlockSkyLight(x, y, z, light, cause);
}
@Override
public short setBlockDataBits(int x, int y, int z, int bits, boolean set, Cause<?> cause) {
return this.getChunkFromBlock(x, y, z).setBlockDataBits(x, y, z, bits, set, cause);
}
@Override
public short setBlockDataBits(int x, int y, int z, int bits, Cause<?> cause) {
return this.getChunkFromBlock(x, y, z).setBlockDataBits(x, y, z, bits, cause);
}
@Override
public short clearBlockDataBits(int x, int y, int z, int bits, Cause<?> cause) {
return this.getChunkFromBlock(x, y, z).clearBlockDataBits(x, y, z, bits, cause);
}
@Override
public int getBlockDataField(int x, int y, int z, int bits) {
return this.getChunkFromBlock(x, y, z).getBlockDataField(x, y, z, bits);
}
@Override
public boolean isBlockDataBitSet(int x, int y, int z, int bits) {
return this.getChunkFromBlock(x, y, z).isBlockDataBitSet(x, y, z, bits);
}
@Override
public int setBlockDataField(int x, int y, int z, int bits, int value, Cause<?> cause) {
return this.getChunkFromBlock(x, y, z).setBlockDataField(x, y, z, bits, value, cause);
}
@Override
public int addBlockDataField(int x, int y, int z, int bits, int value, Cause<?> cause) {
return this.getChunkFromBlock(x, y, z).addBlockDataField(x, y, z, bits, value, cause);
}
@Override
public BlockComponent getBlockComponent(int x, int y, int z) {
return this.getChunkFromBlock(x, y, z).getBlockComponent(x, y, z);
}
@Override
public void queueBlockPhysics(int x, int y, int z, EffectRange range) {
queueBlockPhysics(x, y, z, range, null);
}
public void queueBlockPhysics(int x, int y, int z, EffectRange range, BlockMaterial oldMaterial) {
SpoutChunk c = getChunkFromBlock(x, y, z, LoadOption.NO_LOAD);
if (c != null) {
c.queueBlockPhysics(x, y, z, range, oldMaterial);
}
}
@Override
public void updateBlockPhysics(int x, int y, int z) {
updateBlockPhysics(x, y, z, null);
}
public void updateBlockPhysics(int x, int y, int z, BlockMaterial oldMaterial) {
SpoutChunk c = getChunkFromBlock(x, y, z, LoadOption.NO_LOAD);
if (c != null) {
c.updateBlockPhysics(x, y, z, oldMaterial);
}
}
protected void reportChunkLightDirty(int x, int y, int z) {
synchronized (lightDirtyChunks) {
lightDirtyChunks.add(x & CHUNKS.MASK, y & CHUNKS.MASK, z & CHUNKS.MASK);
}
}
@Override
public Biome getBiome(int x, int y, int z) {
return this.getWorld().getBiome(x, y, z);
}
@Override
public Block getBlock(int x, int y, int z) {
return this.getWorld().getBlock(x, y, z);
}
@Override
public Block getBlock(float x, float y, float z) {
return this.getWorld().getBlock(x, y, z);
}
@Override
public Block getBlock(Vector3 position) {
return this.getWorld().getBlock(position);
}
@Override
public int getBlockFullState(int x, int y, int z) {
return this.getChunkFromBlock(x, y, z).getBlockFullState(x, y, z);
}
@Override
public BlockMaterial getBlockMaterial(int x, int y, int z) {
return this.getChunkFromBlock(x, y, z).getBlockMaterial(x, y, z);
}
@Override
public short getBlockData(int x, int y, int z) {
return this.getChunkFromBlock(x, y, z).getBlockData(x, y, z);
}
@Override
public byte getBlockLight(int x, int y, int z) {
return this.getChunkFromBlock(x, y, z).getBlockLight(x, y, z);
}
@Override
public byte getBlockSkyLight(int x, int y, int z) {
return this.getChunkFromBlock(x, y, z).getBlockSkyLight(x, y, z);
}
@Override
public byte getBlockSkyLightRaw(int x, int y, int z) {
return getChunkFromBlock(x, y, z).getBlockSkyLightRaw(x, y, z);
}
@Override
public boolean compareAndSetData(int x, int y, int z, int expect, short data, Cause<?> cause) {
return this.getChunkFromBlock(x, y, z).compareAndSetData(x, y, z, expect, data, cause);
}
@Override
public List<Player> getPlayers() {
return entityManager.getPlayers();
}
/**
* Test if region file exists
* @param world world
* @param x region x coordinate
* @param y region y coordinate
* @param z region z coordinate
* @return true if exists, false if doesn't exist
*/
public static boolean regionFileExists(World world, int x, int y, int z) {
File worldDirectory = world.getDirectory();
File regionDirectory = new File(worldDirectory, "region");
File regionFile = new File(regionDirectory, "reg" + x + "_" + y + "_" + z + ".spr");
return regionFile.exists();
}
@Override
public TaskManager getTaskManager() {
return taskManager;
}
public void markObserverDirty(SpoutChunk chunk) {
observedChunkQueue.add(chunk);
}
@Override
public void resetDynamicBlock(int x, int y, int z) {
dynamicBlockTree.resetBlockUpdates(x, y, z);
}
@Override
public void syncResetDynamicBlock(int x, int y, int z) {
dynamicBlockTree.syncResetBlockUpdates(x, y, z);
}
@Override
public DynamicUpdateEntry queueDynamicUpdate(int x, int y, int z, long nextUpdate, int data) {
return dynamicBlockTree.queueBlockUpdates(x, y, z, nextUpdate, data);
}
@Override
public DynamicUpdateEntry queueDynamicUpdate(int x, int y, int z, long nextUpdate) {
return dynamicBlockTree.queueBlockUpdates(x, y, z, nextUpdate);
}
@Override
public DynamicUpdateEntry queueDynamicUpdate(int x, int y, int z) {
return dynamicBlockTree.queueBlockUpdates(x, y, z);
}
// TODO - save needs to call this method
public List<DynamicBlockUpdate> getDynamicBlockUpdates(Chunk c) {
Set<DynamicBlockUpdate> updates = dynamicBlockTree.getDynamicBlockUpdates(c);
int size = updates == null ? 0 : updates.size();
List<DynamicBlockUpdate> list = new ArrayList<DynamicBlockUpdate>(size);
if (updates != null) {
list.addAll(updates);
}
return list;
}
public boolean removeDynamicBlockUpdates(Chunk c) {
boolean removed = dynamicBlockTree.removeDynamicBlockUpdates(c);
return removed;
}
public void addSnapshotFuture(SpoutChunkSnapshotFuture future) {
snapshotQueue.add(future);
}
public void setPhysicsActive(SpoutChunk chunk, boolean local) {
try {
if (local) {
localPhysicsChunks.add(chunk);
} else {
globalPhysicsChunks.add(chunk);
}
} catch (IllegalStateException ise) {
throw new IllegalStateException("Physics chunk queue exceeded capacity", ise);
}
}
public void unlinkNeighbours() {
TickStage.checkStage(TickStage.SNAPSHOT);
final int rx = getX();
final int ry = getY();
final int rz = getZ();
final SpoutWorld world = getWorld();
for (int dx = 0; dx < 3; dx++) {
for (int dy = 0; dy < 3; dy++) {
for (int dz = 0; dz < 3; dz++) {
SpoutRegion region = world.getRegion(rx + dx - 1, ry + dy - 1, rz + dz - 1, LoadOption.NO_LOAD);
if (region != null) {
region.unlinkNeighbour(this);
}
}
}
}
}
private void unlinkNeighbour(SpoutRegion r) {
for (int dx = 0; dx < 3; dx++) {
for (int dy = 0; dy < 3; dy++) {
for (int dz = 0; dz < 3; dz++) {
neighbours[dx][dy][dz].compareAndSet(r, null);
}
}
}
}
public SpoutRegion getLocalRegion(BlockFace face, LoadOption loadopt) {
Vector3 offset = face.getOffset();
return getLocalRegion(offset.getFloorX() + 1, offset.getFloorY() + 1, offset.getFloorZ() + 1, loadopt);
}
public SpoutRegion getLocalRegion(int dx, int dy, int dz, LoadOption loadopt) {
if (loadopt != LoadOption.NO_LOAD) {
TickStage.checkStage(~TickStage.SNAPSHOT);
}
AtomicReference<SpoutRegion> ref = neighbours[dx][dy][dz];
SpoutRegion region = ref.get();
if (region == null) {
region = getWorld().getRegion(getX() + dx - 1, getY() + dy - 1, getZ() + dz - 1, loadopt);
ref.compareAndSet(null, region);
}
return region;
}
public SpoutChunk getLocalChunk(Chunk c, BlockFace face, LoadOption loadopt) {
Vector3 offset = face.getOffset();
return getLocalChunk(c, offset.getFloorX(), offset.getFloorY(), offset.getFloorZ(), loadopt);
}
public SpoutChunk getLocalChunk(Chunk c, int ox, int oy, int oz, LoadOption loadopt) {
return getLocalChunk(c.getX(), c.getY(), c.getZ(), ox, oy, oz, loadopt);
}
public SpoutChunk getLocalChunk(int x, int y, int z, int ox, int oy, int oz, LoadOption loadopt) {
x &= CHUNKS.MASK;
y &= CHUNKS.MASK;
z &= CHUNKS.MASK;
x += ox;
y += oy;
z += oz;
return getLocalChunk(x, y, z, loadopt);
}
public SpoutChunk getLocalChunk(int x, int y, int z, LoadOption loadopt) {
int dx = 1 + (x >> CHUNKS.BITS);
int dy = 1 + (y >> CHUNKS.BITS);
int dz = 1 + (z >> CHUNKS.BITS);
SpoutRegion region = getLocalRegion(dx, dy, dz, loadopt);
if (region == null) {
return null;
}
return region.getChunk(x, y, z, loadopt);
}
public void addChunk(int x, int y, int z, short[] blockIds, short[] blockData, byte[] blockLight, byte[] skyLight, BiomeManager biomes) {
x &= BLOCKS.MASK;
y &= BLOCKS.MASK;
z &= BLOCKS.MASK;
SpoutChunk chunk = chunks[x >> Region.CHUNKS.BITS][y >> Region.CHUNKS.BITS][z >> Region.CHUNKS.BITS].get();
if (chunk != null) {
chunk.unload(false);
}
SpoutChunk newChunk = new FilteredChunk(getWorld(), this, getBlockX() | x, getBlockY() | y, getBlockZ() | z, SpoutChunk.PopulationState.POPULATED, blockIds, blockData, skyLight, blockLight, new ManagedHashMap());
setChunk(newChunk, x, y, z, null, true, LoadOption.LOAD_GEN);
}
private class MeshGeneratorThread extends Thread {
private WorldRenderer renderer = null;
public MeshGeneratorThread() {
super(SpoutRegion.this.toString() + " Mesh Generation Thread");
this.setDaemon(true);
}
public void run() {
while (renderer == null) {
renderer = ((SpoutClient) Spout.getEngine()).getWorldRenderer();
if (renderer == null) {
try {
Thread.sleep(100);
} catch (InterruptedException ie) {
return;
}
}
}
while (!Thread.interrupted()) {
try {
SpoutChunkSnapshotModel model;
while( ( model = removeFromRenderQueue() ) != null){
handle(model);
Thread.sleep(20);
}
} catch (InterruptedException ie) {
break;
}
}
SpoutChunkSnapshotModel model;
boolean done = false;
while (!done) {
try {
model = removeFromRenderQueue();
if (model != null) {
handle(model);
} else {
done = true;
}
} catch (InterruptedException e) {
}
}
}
private void handle(SpoutChunkSnapshotModel model) {
for(ChunkMesh mesh : ChunkMesh.getChunkMeshs(model)){
mesh.update();
renderer.addMeshToBatchQueue(mesh);
}
}
}
}
| false | false | null | null |
diff --git a/core/src/main/java/hudson/org/apache/tools/ant/taskdefs/cvslib/ChangeLogParser.java b/core/src/main/java/hudson/org/apache/tools/ant/taskdefs/cvslib/ChangeLogParser.java
index 756a31e..b0e18b1 100644
--- a/core/src/main/java/hudson/org/apache/tools/ant/taskdefs/cvslib/ChangeLogParser.java
+++ b/core/src/main/java/hudson/org/apache/tools/ant/taskdefs/cvslib/ChangeLogParser.java
@@ -1,357 +1,358 @@
/*
* Copyright 2002-2004 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package hudson.org.apache.tools.ant.taskdefs.cvslib;
// patched to work around http://issues.apache.org/bugzilla/show_bug.cgi?id=38583
import org.apache.tools.ant.Project;
import org.apache.commons.io.FileUtils;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.io.File;
import java.io.IOException;
/**
* A class used to parse the output of the CVS log command.
*
* @version $Revision$ $Date$
*/
class ChangeLogParser {
//private static final int GET_ENTRY = 0;
private static final int GET_FILE = 1;
private static final int GET_DATE = 2;
private static final int GET_COMMENT = 3;
private static final int GET_REVISION = 4;
private static final int GET_PREVIOUS_REV = 5;
private static final int GET_SYMBOLIC_NAMES = 6;
/**
* input format for dates read in from cvs log.
*
* Some users reported that they see different formats,
* so this is extended from original Ant version to cover different formats.
*/
private static final SimpleDateFormat[] c_inputDate
= new SimpleDateFormat[]{
new SimpleDateFormat("yyyy/MM/dd HH:mm:ss Z"),
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z"),
new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"),
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"),
};
static {
TimeZone utc = TimeZone.getTimeZone("UTC");
for (SimpleDateFormat df : c_inputDate) {
df.setTimeZone(utc);
}
}
//The following is data used while processing stdout of CVS command
private String m_file;
private String m_fullName;
private String m_date;
private String m_author;
private String m_comment;
private String m_revision;
private String m_previousRevision;
/**
* All branches available on the current file.
* Keyed by branch revision prefix (like "1.2.3." if files in the branch have revision numbers like
* "1.2.3.4") and the value is the branch name.
*/
private final Map<String,String> branches = new HashMap<String,String>();
/**
* True if the log record indicates deletion;
*/
private boolean m_dead;
private int m_status = GET_FILE;
/** rcs entries */
private final Hashtable<String,CVSEntry> m_entries = new Hashtable<String,CVSEntry>();
private final ChangeLogTask owner;
public ChangeLogParser(ChangeLogTask owner) {
this.owner = owner;
}
/**
* Get a list of rcs entries as an array.
*
* @return a list of rcs entries as an array
*/
CVSEntry[] getEntrySetAsArray() {
final CVSEntry[] array = new CVSEntry[ m_entries.size() ];
Enumeration e = m_entries.elements();
int i = 0;
while (e.hasMoreElements()) {
array[i++] = (CVSEntry) e.nextElement();
}
return array;
}
private boolean dead = false;
/**
* Receive notification about the process writing
* to standard output.
*/
public void stdout(final String line) {
if(dead)
return;
try {
switch(m_status) {
case GET_FILE:
// make sure attributes are reset when
// working on a 'new' file.
reset();
processFile(line);
break;
case GET_SYMBOLIC_NAMES:
processSymbolicName(line);
break;
case GET_REVISION:
processRevision(line);
break;
case GET_DATE:
processDate(line);
break;
case GET_COMMENT:
processComment(line);
break;
case GET_PREVIOUS_REV:
processGetPreviousRevision(line);
break;
}
} catch (Exception e) {
// we don't know how to handle the input any more. don't accept any more input
dead = true;
}
}
/**
* Process a line while in "GET_COMMENT" state.
*
* @param line the line
*/
private void processComment(final String line) {
final String lineSeparator = System.getProperty("line.separator");
if (line.startsWith("======")) {
//We have ended changelog for that particular file
//so we can save it
final int end
= m_comment.length() - lineSeparator.length(); //was -1
m_comment = m_comment.substring(0, end);
saveEntry();
m_status = GET_FILE;
} else if (line.startsWith("----------------------------")) {
final int end
= m_comment.length() - lineSeparator.length(); //was -1
m_comment = m_comment.substring(0, end);
m_status = GET_PREVIOUS_REV;
} else {
m_comment += line + lineSeparator;
}
}
/**
* Process a line while in "GET_FILE" state.
*
* @param line the line
*/
private void processFile(final String line) {
if (line.startsWith("Working file:")) {
m_file = line.substring(14, line.length());
try {
File repo = new File(new File(owner.getDir(), m_file), "../CVS/Repository");
String module = FileUtils.readFileToString(repo, null);// not sure what encoding CVS uses.
- m_fullName = '/'+module.trim()+'/'+m_file;
+ String simpleName = m_file.substring(m_file.lastIndexOf('/')+1);
+ m_fullName = '/'+module.trim()+'/'+simpleName;
} catch (IOException e) {
// failed to read
m_fullName = null;
}
m_status = GET_SYMBOLIC_NAMES;
}
}
/**
* Obtains the revision name list
*/
private void processSymbolicName(String line) {
if (line.startsWith("\t")) {
line = line.trim();
int idx = line.lastIndexOf(':');
if(idx<0) {
// ???
return;
}
String symbol = line.substring(0,idx);
Matcher m = DOT_PATTERN.matcher(line.substring(idx + 2));
if(!m.matches())
return; // not a branch name
branches.put(m.group(1)+m.group(3)+'.',symbol);
} else
if (line.startsWith("keyword substitution:")) {
m_status = GET_REVISION;
}
}
private static final Pattern DOT_PATTERN = Pattern.compile("(([0-9]+\\.)+)0\\.([0-9]+)");
/**
* Process a line while in "REVISION" state.
*
* @param line the line
*/
private void processRevision(final String line) {
if (line.startsWith("revision")) {
m_revision = line.substring(9);
m_status = GET_DATE;
} else if (line.startsWith("======")) {
//There was no revisions in this changelog
//entry so lets move unto next file
m_status = GET_FILE;
}
}
/**
* Process a line while in "DATE" state.
*
* @param line the line
*/
private void processDate(final String line) {
if (line.startsWith("date:")) {
int idx = line.indexOf(";");
m_date = line.substring(6, idx);
String lineData = line.substring(idx + 1);
m_author = lineData.substring(10, lineData.indexOf(";"));
m_status = GET_COMMENT;
m_dead = lineData.indexOf("state: dead;")!=-1;
//Reset comment to empty here as we can accumulate multiple lines
//in the processComment method
m_comment = "";
}
}
/**
* Process a line while in "GET_PREVIOUS_REVISION" state.
*
* @param line the line
*/
private void processGetPreviousRevision(final String line) {
if (!line.startsWith("revision")) {
throw new IllegalStateException("Unexpected line from CVS: "
+ line);
}
m_previousRevision = line.substring(9);
saveEntry();
m_revision = m_previousRevision;
m_status = GET_DATE;
}
/**
* Utility method that saves the current entry.
*/
private void saveEntry() {
final String entryKey = m_date + m_author + m_comment;
CVSEntry entry;
if (!m_entries.containsKey(entryKey)) {
entry = new CVSEntry(parseDate(m_date), m_author, m_comment);
m_entries.put(entryKey, entry);
} else {
entry = m_entries.get(entryKey);
}
String branch = findBranch(m_revision);
owner.log("Recorded a change: "+m_date+','+m_author+','+m_revision+"(branch="+branch+"),"+m_comment,Project.MSG_VERBOSE);
entry.addFile(m_file, m_fullName, m_revision, m_previousRevision, branch, m_dead);
}
/**
* Finds the branch name that matches the revision, or null if not found.
*/
private String findBranch(String revision) {
if(revision==null) return null; // defensive check
for (Entry<String,String> e : branches.entrySet()) {
if(revision.startsWith(e.getKey()) && revision.substring(e.getKey().length()).indexOf('.')==-1)
return e.getValue();
}
return null;
}
/**
* Parse date out from expected format.
*
* @param date the string holding dat
* @return the date object or null if unknown date format
*/
private Date parseDate(String date) {
for (SimpleDateFormat df : c_inputDate) {
try {
return df.parse(date);
} catch (ParseException e) {
// try next if one fails
}
}
// nothing worked
owner.log("Failed to parse "+date+"\n", Project.MSG_ERR);
//final String message = REZ.getString( "changelog.bat-date.error", date );
//getContext().error( message );
return null;
}
/**
* reset all internal attributes except status.
*/
private void reset() {
m_file = null;
m_fullName = null;
m_date = null;
m_author = null;
m_comment = null;
m_revision = null;
m_previousRevision = null;
m_dead = false;
branches.clear();
}
}
| true | false | null | null |
diff --git a/modules/org.restlet.gwt/src/org/restlet/gwt/internal/Engine.java b/modules/org.restlet.gwt/src/org/restlet/gwt/internal/Engine.java
index df932134a..b0427cd4d 100644
--- a/modules/org.restlet.gwt/src/org/restlet/gwt/internal/Engine.java
+++ b/modules/org.restlet.gwt/src/org/restlet/gwt/internal/Engine.java
@@ -1,707 +1,699 @@
/**
* Copyright 2005-2008 Noelios Technologies.
*
* The contents of this file are subject to the terms of the following open
* source licenses: LGPL 3.0 or LGPL 2.1 or CDDL 1.0 (the "Licenses"). You can
* select the license that you prefer but you may not use this file except in
* compliance with one of these Licenses.
*
* You can obtain a copy of the LGPL 3.0 license at
* http://www.gnu.org/licenses/lgpl-3.0.html
*
* You can obtain a copy of the LGPL 2.1 license at
* http://www.gnu.org/licenses/lgpl-2.1.html
*
* You can obtain a copy of the CDDL 1.0 license at
* http://www.sun.com/cddl/cddl.html
*
* See the Licenses for the specific language governing permissions and
* limitations under the Licenses.
*
* Alternatively, you can obtain a royaltee free commercial license with less
* limitations, transferable or non-transferable, directly at
* http://www.noelios.com/products/restlet-engine
*
* Restlet is a registered trademark of Noelios Technologies.
*/
package org.restlet.gwt.internal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import org.restlet.gwt.Client;
import org.restlet.gwt.data.CharacterSet;
import org.restlet.gwt.data.ClientInfo;
import org.restlet.gwt.data.Cookie;
import org.restlet.gwt.data.CookieSetting;
import org.restlet.gwt.data.Dimension;
import org.restlet.gwt.data.Form;
import org.restlet.gwt.data.Language;
import org.restlet.gwt.data.MediaType;
import org.restlet.gwt.data.Parameter;
import org.restlet.gwt.data.Preference;
import org.restlet.gwt.data.Product;
import org.restlet.gwt.data.Protocol;
import org.restlet.gwt.data.Response;
import org.restlet.gwt.internal.http.ContentType;
import org.restlet.gwt.internal.http.CookieReader;
import org.restlet.gwt.internal.http.CookieUtils;
import org.restlet.gwt.internal.http.GwtHttpClientHelper;
import org.restlet.gwt.internal.http.HttpClientCall;
import org.restlet.gwt.internal.http.HttpClientConverter;
import org.restlet.gwt.internal.http.HttpUtils;
import org.restlet.gwt.internal.util.FormUtils;
import org.restlet.gwt.resource.Representation;
import org.restlet.gwt.resource.Variant;
/**
* Restlet factory supported by the engine.
*
* @author Jerome Louvel
*/
public class Engine extends org.restlet.gwt.util.Engine {
/** Complete version. */
@SuppressWarnings("hiding")
public static final String VERSION = org.restlet.gwt.util.Engine.VERSION;
/** Complete version header. */
public static final String VERSION_HEADER = "Noelios-Restlet-Engine/"
+ VERSION;
- /**
- * Returns the registered Noelios Restlet engine.
- *
- * @return The registered Noelios Restlet engine.
- */
- public static Engine getInstance() {
- return (Engine) org.restlet.gwt.util.Engine.getInstance();
- }
/**
* Registers a new Noelios Restlet Engine.
*
* @return The registered engine.
*/
public static Engine register() {
return register(true);
}
/**
* Registers a new Noelios Restlet Engine.
*
* @param discoverConnectors
* True if connectors should be automatically discovered.
* @return The registered engine.
*/
public static Engine register(boolean discoverConnectors) {
final Engine result = new Engine(discoverConnectors);
org.restlet.gwt.util.Engine.setInstance(result);
return result;
}
/** List of available client connectors. */
private List<ClientHelper> registeredClients;
/**
* Constructor that will automatically attempt to discover connectors.
*/
public Engine() {
this(true);
}
/**
* Constructor.
*
* @param discoverHelpers
* True if helpers should be automatically discovered.
*/
public Engine(boolean discoverHelpers) {
this.registeredClients = new ArrayList<ClientHelper>();
if (discoverHelpers) {
getRegisteredClients().add(new GwtHttpClientHelper(null));
}
}
/**
* Copies the given header parameters into the given {@link Response}.
*
* @param responseHeaders
* The headers to copy.
* @param response
* The response to update. Must contain a {@link Representation}
* to copy the representation headers in it.
* @see org.restlet.util.Engine#copyResponseHeaders(java.lang.Iterable,
* org.restlet.data.Response)
*/
@Override
public void copyResponseHeaders(Iterable<Parameter> responseHeaders,
Response response) {
HttpClientConverter.copyResponseTransportHeaders(responseHeaders,
response);
HttpClientCall.copyResponseEntityHeaders(responseHeaders, response
.getEntity());
}
@Override
public ClientHelper createHelper(Client client) {
ClientHelper result = null;
if (client.getProtocols().size() > 0) {
ClientHelper connector = null;
for (final Iterator<ClientHelper> iter = getRegisteredClients()
.iterator(); (result == null) && iter.hasNext();) {
connector = iter.next();
if (connector.getProtocols().containsAll(client.getProtocols())) {
// Not very dynamic but works as we only have one helper
// available currently
result = new GwtHttpClientHelper(client);
}
}
if (result == null) {
// Couldn't find a matching connector
final StringBuilder sb = new StringBuilder();
sb
.append("No available client connector supports the required protocols: ");
for (final Protocol p : client.getProtocols()) {
sb.append("'").append(p.getName()).append("' ");
}
sb
.append(". Please add the JAR of a matching connector to your classpath.");
System.err.println(sb.toString());
}
}
return result;
}
@Override
public String formatCookie(Cookie cookie) throws IllegalArgumentException {
return CookieUtils.format(cookie);
}
@Override
public String formatCookieSetting(CookieSetting cookieSetting)
throws IllegalArgumentException {
return CookieUtils.format(cookieSetting);
}
@Override
public String formatDimensions(Collection<Dimension> dimensions) {
return HttpUtils.createVaryHeader(dimensions);
}
@Override
public String formatUserAgent(List<Product> products)
throws IllegalArgumentException {
final StringBuilder builder = new StringBuilder();
for (final Iterator<Product> iterator = products.iterator(); iterator
.hasNext();) {
final Product product = iterator.next();
if ((product.getName() == null)
|| (product.getName().length() == 0)) {
throw new IllegalArgumentException(
"Product name cannot be null.");
}
builder.append(product.getName());
if (product.getVersion() != null) {
builder.append("/").append(product.getVersion());
}
if (product.getComment() != null) {
builder.append(" (").append(product.getComment()).append(")");
}
if (iterator.hasNext()) {
builder.append(" ");
}
}
return builder.toString();
}
@Override
public Variant getPreferredVariant(ClientInfo client,
List<Variant> variants, Language defaultLanguage) {
if (variants == null) {
return null;
}
List<Language> variantLanguages = null;
MediaType variantMediaType = null;
boolean compatibleLanguage = false;
boolean compatibleMediaType = false;
Variant currentVariant = null;
Variant bestVariant = null;
Preference<Language> currentLanguagePref = null;
Preference<Language> bestLanguagePref = null;
Preference<MediaType> currentMediaTypePref = null;
Preference<MediaType> bestMediaTypePref = null;
float bestQuality = 0;
float bestLanguageScore = 0;
float bestMediaTypeScore = 0;
// If no language preference is defined or even none matches, we
// want to make sure that at least a variant can be returned.
// Based on experience, it appears that browsers are often
// misconfigured and don't expose all the languages actually
// understood by end users.
// Thus, a few other preferences are added to the user's ones:
// - primary languages inferred from and sorted according to the
// user's preferences with quality between 0.005 and 0.006
// - default language (if any) with quality 0.003
// - primary language of the default language (if available) with
// quality 0.002
// - all languages with quality 0.001
List<Preference<Language>> languagePrefs = client
.getAcceptedLanguages();
final List<Preference<Language>> primaryLanguagePrefs = new ArrayList<Preference<Language>>();
// A default language preference is defined with a better weight
// than the "All languages" preference
final Preference<Language> defaultLanguagePref = ((defaultLanguage == null) ? null
: new Preference<Language>(defaultLanguage, 0.003f));
final Preference<Language> allLanguagesPref = new Preference<Language>(
Language.ALL, 0.001f);
if (languagePrefs.isEmpty()) {
// All languages accepted.
languagePrefs.add(new Preference<Language>(Language.ALL));
} else {
// Get the primary language preferences that are not currently
// accepted by the client
final List<String> list = new ArrayList<String>();
for (final Preference<Language> preference : languagePrefs) {
final Language language = preference.getMetadata();
if (!language.getSubTags().isEmpty()) {
if (!list.contains(language.getPrimaryTag())) {
list.add(language.getPrimaryTag());
primaryLanguagePrefs.add(new Preference<Language>(
new Language(language.getPrimaryTag()),
0.005f + (0.001f * preference.getQuality())));
}
}
}
// If the default language is a "primary" language but is not
// present in the list of all primary languages, add it.
if ((defaultLanguage != null)
&& !defaultLanguage.getSubTags().isEmpty()) {
if (!list.contains(defaultLanguage.getPrimaryTag())) {
primaryLanguagePrefs.add(new Preference<Language>(
new Language(defaultLanguage.getPrimaryTag()),
0.002f));
}
}
}
// Client preferences are altered
languagePrefs.addAll(primaryLanguagePrefs);
if (defaultLanguagePref != null) {
languagePrefs.add(defaultLanguagePref);
// In this case, if the client adds the "all languages"
// preference, the latter is removed, in order to support the
// default preference defined by the server
final List<Preference<Language>> list = new ArrayList<Preference<Language>>();
for (final Preference<Language> preference : languagePrefs) {
final Language language = preference.getMetadata();
if (!language.equals(Language.ALL)) {
list.add(preference);
}
}
languagePrefs = list;
}
languagePrefs.add(allLanguagesPref);
// For each available variant, we will compute the negotiation score
// which depends on both language and media type scores.
for (final Iterator<Variant> iter1 = variants.iterator(); iter1
.hasNext();) {
currentVariant = iter1.next();
variantLanguages = currentVariant.getLanguages();
variantMediaType = currentVariant.getMediaType();
// All languages of the current variant are scored.
for (final Language variantLanguage : variantLanguages) {
// For each language preference defined in the call
// Calculate the score and remember the best scoring
// preference
for (final Iterator<Preference<Language>> iter2 = languagePrefs
.iterator(); (variantLanguage != null)
&& iter2.hasNext();) {
currentLanguagePref = iter2.next();
final float currentScore = getScore(variantLanguage,
currentLanguagePref.getMetadata());
final boolean compatiblePref = (currentScore != -1.0f);
// 3) Do we have a better preference?
// currentScore *= currentPref.getQuality();
if (compatiblePref
&& ((bestLanguagePref == null) || (currentScore > bestLanguageScore))) {
bestLanguagePref = currentLanguagePref;
bestLanguageScore = currentScore;
}
}
}
// Are the preferences compatible with the current variant
// language?
compatibleLanguage = (variantLanguages.isEmpty())
|| (bestLanguagePref != null);
// If no media type preference is defined, assume that all media
// types are acceptable
final List<Preference<MediaType>> mediaTypePrefs = client
.getAcceptedMediaTypes();
if (mediaTypePrefs.size() == 0) {
mediaTypePrefs.add(new Preference<MediaType>(MediaType.ALL));
}
// For each media range preference defined in the call
// Calculate the score and remember the best scoring preference
for (final Iterator<Preference<MediaType>> iter2 = mediaTypePrefs
.iterator(); compatibleLanguage && iter2.hasNext();) {
currentMediaTypePref = iter2.next();
final float currentScore = getScore(variantMediaType,
currentMediaTypePref.getMetadata());
final boolean compatiblePref = (currentScore != -1.0f);
// 3) Do we have a better preference?
// currentScore *= currentPref.getQuality();
if (compatiblePref
&& ((bestMediaTypePref == null) || (currentScore > bestMediaTypeScore))) {
bestMediaTypePref = currentMediaTypePref;
bestMediaTypeScore = currentScore;
}
}
// Are the preferences compatible with the current media type?
compatibleMediaType = (variantMediaType == null)
|| (bestMediaTypePref != null);
if (compatibleLanguage && compatibleMediaType) {
// Do we have a compatible media type?
float currentQuality = 0;
if (bestLanguagePref != null) {
currentQuality += (bestLanguagePref.getQuality() * 10F);
} else if (!variantLanguages.isEmpty()) {
currentQuality += 0.1F * 10F;
}
if (bestMediaTypePref != null) {
// So, let's conclude on the current variant, its
// quality
currentQuality += bestMediaTypePref.getQuality();
}
if (bestVariant == null) {
bestVariant = currentVariant;
bestQuality = currentQuality;
} else if (currentQuality > bestQuality) {
bestVariant = currentVariant;
bestQuality = currentQuality;
}
}
// Reset the preference variables
bestLanguagePref = null;
bestLanguageScore = 0;
bestMediaTypePref = null;
bestMediaTypeScore = 0;
}
return bestVariant;
}
/**
* Returns the list of available client connectors.
*
* @return The list of available client connectors.
*/
public List<ClientHelper> getRegisteredClients() {
return this.registeredClients;
}
/**
* Returns a matching score between 2 Languages
*
* @param variantLanguage
* @param preferenceLanguage
* @return the positive matching score or -1 if the languages are not
* compatible
*/
private float getScore(Language variantLanguage, Language preferenceLanguage) {
float score = 0.0f;
boolean compatibleLang = true;
// 1) Compare the main tag
if (variantLanguage.getPrimaryTag().equalsIgnoreCase(
preferenceLanguage.getPrimaryTag())) {
score += 100;
} else if (!preferenceLanguage.getPrimaryTag().equals("*")) {
compatibleLang = false;
} else if (!preferenceLanguage.getSubTags().isEmpty()) {
// Only "*" is an acceptable language range
compatibleLang = false;
} else {
// The valid "*" range has the lowest valid score
score++;
}
if (compatibleLang) {
// 2) Compare the sub tags
if ((preferenceLanguage.getSubTags().isEmpty())
|| (variantLanguage.getSubTags().isEmpty())) {
if (variantLanguage.getSubTags().isEmpty()
&& preferenceLanguage.getSubTags().isEmpty()) {
score += 10;
} else {
// Don't change the score
}
} else {
final int maxSize = Math.min(preferenceLanguage.getSubTags()
.size(), variantLanguage.getSubTags().size());
for (int i = 0; (i < maxSize) && compatibleLang; i++) {
if (preferenceLanguage.getSubTags().get(i)
.equalsIgnoreCase(
variantLanguage.getSubTags().get(i))) {
// Each subtag contribution to the score
// is getting less and less important
score += Math.pow(10, 1 - i);
} else {
// SubTags are different
compatibleLang = false;
}
}
}
}
return (compatibleLang ? score : -1.0f);
}
/**
* Returns a matching score between 2 Media types
*
* @param variantMediaType
* @param preferenceMediaType
* @return the positive matching score or -1 if the media types are not
* compatible
*/
private float getScore(MediaType variantMediaType,
MediaType preferenceMediaType) {
float score = 0.0f;
boolean comptabibleMediaType = true;
// 1) Compare the main types
if (preferenceMediaType.getMainType().equals(
variantMediaType.getMainType())) {
score += 1000;
} else if (!preferenceMediaType.getMainType().equals("*")) {
comptabibleMediaType = false;
} else if (!preferenceMediaType.getSubType().equals("*")) {
// Ranges such as "*/html" are not supported
// Only "*/*" is acceptable in this case
comptabibleMediaType = false;
}
if (comptabibleMediaType) {
// 2) Compare the sub types
if (variantMediaType.getSubType().equals(
preferenceMediaType.getSubType())) {
score += 100;
} else if (!preferenceMediaType.getSubType().equals("*")) {
// Sub-type are different
comptabibleMediaType = false;
}
if (comptabibleMediaType
&& (variantMediaType.getParameters() != null)) {
// 3) Compare the parameters
// If current media type is compatible with the
// current media range then the parameters need to
// be checked too
for (final Parameter currentParam : variantMediaType
.getParameters()) {
if (isParameterFound(currentParam, preferenceMediaType)) {
score++;
}
}
}
}
return (comptabibleMediaType ? score : -1.0f);
}
/**
* Indicates if the searched parameter is specified in the given media
* range.
*
* @param searchedParam
* The searched parameter.
* @param mediaRange
* The media range to inspect.
* @return True if the searched parameter is specified in the given media
* range.
*/
private boolean isParameterFound(Parameter searchedParam,
MediaType mediaRange) {
boolean result = false;
for (final Iterator<Parameter> iter = mediaRange.getParameters()
.iterator(); !result && iter.hasNext();) {
result = searchedParam.equals(iter.next());
}
return result;
}
@Override
public void parse(Form form, Representation webForm) {
if (webForm != null) {
FormUtils.parse(form, webForm);
}
}
@Override
public void parse(Form form, String queryString, CharacterSet characterSet,
boolean decode, char separator) {
if ((queryString != null) && !queryString.equals("")) {
FormUtils.parse(form, queryString, characterSet, decode, separator);
}
}
@Override
public MediaType parseContentType(String contentType)
throws IllegalArgumentException {
try {
return ContentType.parseContentType(contentType);
} catch (final Exception e) {
throw new IllegalArgumentException("The content type string \""
+ contentType + "\" can not be parsed: " + e.getMessage());
}
}
@Override
public Cookie parseCookie(String cookie) throws IllegalArgumentException {
final CookieReader cr = new CookieReader(cookie);
try {
return cr.readCookie();
} catch (final Exception e) {
throw new IllegalArgumentException("Could not read the cookie");
}
}
@Override
public CookieSetting parseCookieSetting(String cookieSetting)
throws IllegalArgumentException {
final CookieReader cr = new CookieReader(cookieSetting);
try {
return cr.readCookieSetting();
} catch (final Exception e) {
throw new IllegalArgumentException(
"Could not read the cookie setting");
}
}
@Override
public List<Product> parseUserAgent(String userAgent)
throws IllegalArgumentException {
final List<Product> result = new ArrayList<Product>();
if (userAgent != null) {
String token = null;
String version = null;
String comment = null;
final char[] tab = userAgent.trim().toCharArray();
StringBuilder tokenBuilder = new StringBuilder();
StringBuilder versionBuilder = null;
StringBuilder commentBuilder = null;
int index = 0;
boolean insideToken = true;
boolean insideVersion = false;
boolean insideComment = false;
for (index = 0; index < tab.length; index++) {
final char c = tab[index];
if (insideToken) {
if (((c >= 'a') && (c <= 'z'))
|| ((c >= 'A') && (c <= 'Z')) || (c == ' ')) {
tokenBuilder.append(c);
} else {
token = tokenBuilder.toString().trim();
insideToken = false;
if (c == '/') {
insideVersion = true;
versionBuilder = new StringBuilder();
} else if (c == '(') {
insideComment = true;
commentBuilder = new StringBuilder();
}
}
} else {
if (insideVersion) {
if (c != ' ') {
versionBuilder.append(c);
} else {
insideVersion = false;
version = versionBuilder.toString();
}
} else {
if (c == '(') {
insideComment = true;
commentBuilder = new StringBuilder();
} else {
if (insideComment) {
if (c == ')') {
insideComment = false;
comment = commentBuilder.toString();
result.add(new Product(token, version,
comment));
insideToken = true;
tokenBuilder = new StringBuilder();
} else {
commentBuilder.append(c);
}
} else {
result.add(new Product(token, version, null));
insideToken = true;
tokenBuilder = new StringBuilder();
tokenBuilder.append(c);
}
}
}
}
}
if (insideComment) {
comment = commentBuilder.toString();
result.add(new Product(token, version, comment));
} else {
if (insideVersion) {
version = versionBuilder.toString();
result.add(new Product(token, version, null));
} else {
if (insideToken && (tokenBuilder.length() > 0)) {
token = tokenBuilder.toString();
result.add(new Product(token, null, null));
}
}
}
}
return result;
}
}
| true | false | null | null |
diff --git a/test/policy/WSSPolicyTesterAsymm.java b/test/policy/WSSPolicyTesterAsymm.java
index 988dd2e8a..c2ee748ad 100644
--- a/test/policy/WSSPolicyTesterAsymm.java
+++ b/test/policy/WSSPolicyTesterAsymm.java
@@ -1,425 +1,425 @@
/*
* Copyright 2004,2005 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package policy;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Vector;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.UnsupportedCallbackException;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.apache.axis.Message;
import org.apache.axis.MessageContext;
import org.apache.axis.client.AxisClient;
import org.apache.axis.configuration.NullProvider;
import org.apache.axis.message.SOAPEnvelope;
import org.apache.axis.utils.XMLUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ws.security.SOAPConstants;
import org.apache.ws.security.WSConstants;
import org.apache.ws.security.WSEncryptionPart;
import org.apache.ws.security.WSPasswordCallback;
import org.apache.ws.security.WSSecurityEngine;
import org.apache.ws.security.components.crypto.Crypto;
import org.apache.ws.security.components.crypto.CryptoFactory;
import org.apache.ws.security.message.WSSecEncrypt;
import org.apache.ws.security.message.WSSecHeader;
import org.apache.ws.security.message.WSSecTimestamp;
import org.apache.ws.security.message.WSSecSignature;
import org.apache.ws.security.policy.Constants;
import org.apache.ws.security.policy.WSS4JPolicyBuilder;
import org.apache.ws.security.policy.WSS4JPolicyData;
import org.apache.ws.security.policy.WSS4JPolicyToken;
import org.apache.ws.security.policy.WSSPolicyException;
import org.apache.ws.security.policy.model.RootPolicyEngineData;
import org.apache.ws.security.policy.parser.WSSPolicyProcessor;
import org.apache.ws.security.util.WSSecurityUtil;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import wssec.SOAPUtil;
public class WSSPolicyTesterAsymm extends TestCase implements CallbackHandler {
private static Log log = LogFactory.getLog(WSSPolicyTesterAsymm.class);
static final String soapMsg = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
+ "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">"
+ " <soapenv:Body>"
+ " <ns1:testMethod xmlns:ns1=\"uri:LogTestService2\"></ns1:testMethod>"
+ " </soapenv:Body>" + "</soapenv:Envelope>";
static final WSSecurityEngine secEngine = new WSSecurityEngine();
static final Crypto crypto = CryptoFactory.getInstance();
static final Crypto cryptoSKI = CryptoFactory
.getInstance("cryptoSKI.properties");
MessageContext msgContext;
Message message;
/**
* Policy Tester constructor.
*
* @param name
* name of the test
*/
public WSSPolicyTesterAsymm(String name) {
super(name);
}
/**
* JUnit suite <p/>
*
* @return a junit test suite
*/
public static Test suite() {
return new TestSuite(WSSPolicyTesterAsymm.class);
}
/**
* Main method
*
* @param args
* command line args
*/
public static void main(String[] args) {
junit.textui.TestRunner.run(suite());
}
/**
* Setup method.
*
* Initializes an Axis 1 environment to process SOAP messages
*
* @throws Exception
* Thrown when there is a problem in setup
*/
protected void setUp() throws Exception {
AxisClient tmpEngine = new AxisClient(new NullProvider());
msgContext = new MessageContext(tmpEngine);
message = getSOAPMessage();
}
/**
* Constructs a soap envelope.
*
* @return A SOAP envelope
* @throws Exception
* if there is any problem constructing the soap envelope
*/
protected Message getSOAPMessage() throws Exception {
InputStream in = new ByteArrayInputStream(soapMsg.getBytes());
Message msg = new Message(in);
msg.setMessageContext(msgContext);
return msg;
}
public void testerAsymm() {
try {
WSSPolicyProcessor processor = new WSSPolicyProcessor();
if (!processor.setup()) {
return;
}
String[] files = new String[2];
files[0] = "test/policy/SecurityPolicyBindingsAsymmTest.xml";
files[1] = "test/policy/SecurityPolicyMsgTest.xml";
processor.go(files);
RootPolicyEngineData rootPolicyEngineData = (RootPolicyEngineData) processor.secProcessorContext
.popPolicyEngineData();
assertNotNull("RootPolicyEngineData missing", rootPolicyEngineData);
ArrayList peds = rootPolicyEngineData.getTopLevelPEDs();
log.debug("Number of top level PolicyEngineData: " + peds.size());
WSS4JPolicyData wpd = WSS4JPolicyBuilder.build(peds);
createMessageAsymm(wpd);
} catch (NoSuchMethodException e) {
e.printStackTrace();
fail(e.getMessage());
} catch (WSSPolicyException e) {
e.printStackTrace();
fail(e.getMessage());
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}
private void createMessageAsymm(WSS4JPolicyData wpd) throws Exception {
log.info("Before create Message assym....");
SOAPEnvelope unsignedEnvelope = message.getSOAPEnvelope();
/*
* First get the SOAP envelope as document, then create a security
* header and insert into the document (Envelope)
*/
Document doc = unsignedEnvelope.getAsDocument();
SOAPConstants soapConstants = WSSecurityUtil.getSOAPConstants(doc
.getDocumentElement());
WSSecHeader secHeader = new WSSecHeader();
secHeader.insertSecurityHeader(doc);
Vector sigParts = new Vector();
Vector encPartsInternal = new Vector();
Vector encPartsExternal = new Vector();
/*
* Check is a timestamp is required. If yes create one and add its Id to
* signed parts. According to WSP a timestamp must be signed
*/
WSSecTimestamp timestamp = null;
if (wpd.isIncludeTimestamp()) {
timestamp = new WSSecTimestamp();
timestamp.prepare(doc);
sigParts.add(new WSEncryptionPart(timestamp.getId()));
}
/*
* Check for a recipient token. If one is avaliable use it as token to
* encrypt data to the recipient. This is according to WSP
* specification. Most of the data is extracted from the
* WSS4JPolicyData, only the user info (name/alias of the certificate in
* the keystore) must be provided by some other means.
*/
WSSecEncrypt recEncrypt = null;
WSS4JPolicyToken recToken = null;
if ((recToken = wpd.getRecipientToken()) != null) {
recEncrypt = new WSSecEncrypt();
recEncrypt.setUserInfo("wss4jcert");
- recEncrypt.setKeyIdentifierType(recToken.getEncKeyIdentifier());
+ recEncrypt.setKeyIdentifierType(recToken.getKeyIdentifier());
recEncrypt.setSymmetricEncAlgorithm(recToken.getEncAlgorithm());
recEncrypt.setKeyEnc(recToken.getEncTransportAlgorithm());
recEncrypt.prepare(doc, cryptoSKI);
}
/*
* Check for an initiator token. If one is avaliable use it as token to
* sign data. This is according to WSP specification. Most of the data
* is extracted from the WSS4JPolicyData, only the user info (name/alias
* of the certificate in the keystore) must be provided by some other
* means.
*
* If SignatureProtection is enabled add the signature to the encrypted
* parts vector. In any case the signature must be in the internal
* ReferenceList (this list is a child of the EncryptedKey element).
*
* If TokenProtection is enabled add an appropriate signature reference.
*
* TODO Check / enable for STRTransform
*/
WSSecSignature iniSignature = null;
WSS4JPolicyToken iniToken = null;
if ((iniToken = wpd.getInitiatorToken()) != null) {
iniSignature = new WSSecSignature();
iniSignature.setUserInfo("16c73ab6-b892-458f-abf5-2f875f74882e",
"security");
- iniSignature.setKeyIdentifierType(iniToken.getSigKeyIdentifier());
+ iniSignature.setKeyIdentifierType(iniToken.getKeyIdentifier());
iniSignature.setSignatureAlgorithm(iniToken.getSigAlgorithm());
iniSignature.prepare(doc, crypto, secHeader);
if (wpd.isSignatureProtection()) {
encPartsInternal.add(new WSEncryptionPart(iniSignature.getId(),
"Element"));
}
if (wpd.isTokenProtection()) {
sigParts.add(new WSEncryptionPart("Token", null, null));
}
}
Element body = WSSecurityUtil.findBodyElement(doc, soapConstants);
if (body == null) {
System.out
.println("No SOAP Body found - illegal message structure. Processing terminated");
return;
}
WSEncryptionPart bodyPart = new WSEncryptionPart("Body", soapConstants
.getEnvelopeURI(), "Content");
/*
* Check the protection order. If Encrypt before signing then first take
* all parts and elements to encrypt and encrypt them. Take their ids
* after encryption and put them to the parts to be signed.
*
*/
Element externRefList = null;
if (Constants.ENCRYPT_BEFORE_SIGNING.equals(wpd.getProtectionOrder())) {
/*
* Process Body: it sign and encrypt: first encrypt the body, insert
* the body to the parts to be signed.
*
* If just to be signed: add the plain Body to the parts to be
* signed
*/
if (wpd.isSignBody()) {
if (wpd.isEncryptBody()) {
Vector parts = new Vector();
parts.add(bodyPart);
externRefList = recEncrypt.encryptForExternalRef(
externRefList, parts);
sigParts.add(bodyPart);
} else {
sigParts.add(bodyPart);
}
}
/*
* Here we need to handle signed/encrypted parts:
*
* Get all parts that need to be encrypted _and_ signed, encrypt
* them, get ids of thier encrypted data elements and add these ids
* to the parts to be signed
*
* Then encrypt the remaining parts that don't need to be signed.
*
* Then add the remaining parts that don't nedd to be encrypted to
* the parts to be signed.
*
* Similar handling for signed/encrypted elements (compare XPath
* strings?)
*
* After all elements are encrypted put the external refernce list
* to the security header. is at the bottom of the security header)
*/
recEncrypt.addExternalRefElement(externRefList, secHeader);
/*
* Now handle the supporting tokens - according to OASIS WSP
* supporting tokens are not part of a Binding assertion but a top
* level assertion similar to Wss11 or SignedParts. If supporting
* tokens are available their BST elements have to be added later
* (probably prepended to the initiator token - see below)
*/
/*
* Now add the various elements to the header. We do a strict layout
* here.
*
*/
/*
* Prepend Signature to the supporting tokens that sign the primary
* signature
*/
iniSignature.prependToHeader(secHeader);
/*
* This prepends a possible initiator token to the security header
*/
iniSignature.prependBSTElementToHeader(secHeader);
/*
* Here prepend BST elements of supporting tokens
* (EndorsingSupportTokens), then prepend supporting token that do
* not sign the primary signature but are signed by the primary
* signature. Take care of the TokenProtection protery!?
*/
/*
* Add the encrypted key element and then the associated BST element
* recipient token)
*/
recEncrypt.prependToHeader(secHeader);
recEncrypt.prependBSTElementToHeader(secHeader);
/*
* Now we are ready to per Signature processing.
*
* First the primary Signature then supporting tokens (Signatures)
* that sign the primary Signature.
*/
timestamp.prependToHeader(secHeader);
iniSignature.addReferencesToSign(sigParts, secHeader);
iniSignature.computeSignature();
Element internRef = recEncrypt.encryptForInternalRef(null,
encPartsInternal);
recEncrypt.addInternalRefElement(internRef);
} else {
System.out.println("SignBeforeEncrypt needs to be implemented");
}
log.info("After creating Message asymm....");
/*
* convert the resulting document into a message first. The
* toSOAPMessage() method performs the necessary c14n call to properly
* set up the signed document and convert it into a SOAP message. Check
* that the contents can't be read (cheching if we can find a specific
* substring). After that we extract it as a document again for further
* processing.
*/
Message encryptedMsg = (Message) SOAPUtil.toSOAPMessage(doc);
if (log.isDebugEnabled()) {
log.debug("Processed message");
XMLUtils.PrettyElementToWriter(encryptedMsg.getSOAPEnvelope()
.getAsDOM(), new PrintWriter(System.out));
}
String encryptedString = encryptedMsg.getSOAPPartAsString();
assertTrue(encryptedString.indexOf("LogTestService2") == -1 ? true
: false);
// encryptedDoc = encryptedMsg.getSOAPEnvelope().getAsDocument();
verify(doc);
}
/**
* Verifies the soap envelope <p/>
*
* @param envelope
* @throws Exception
* Thrown when there is a problem in verification
*/
private void verify(Document doc) throws Exception {
secEngine.processSecurityHeader(doc, null, this, crypto, cryptoSKI);
SOAPUtil.updateSOAPMessage(doc, message);
String decryptedString = message.getSOAPPartAsString();
assertTrue(decryptedString.indexOf("LogTestService2") > 0 ? true
: false);
}
public void handle(Callback[] callbacks) throws IOException,
UnsupportedCallbackException {
for (int i = 0; i < callbacks.length; i++) {
if (callbacks[i] instanceof WSPasswordCallback) {
WSPasswordCallback pc = (WSPasswordCallback) callbacks[i];
/*
* here call a function/method to lookup the password for the
* given identifier (e.g. a user name or keystore alias) e.g.:
* pc.setPassword(passStore.getPassword(pc.getIdentfifier)) for
* Testing we supply a fixed name here.
*/
pc.setPassword("security");
} else {
throw new UnsupportedCallbackException(callbacks[i],
"Unrecognized Callback");
}
}
}
}
| false | true | private void createMessageAsymm(WSS4JPolicyData wpd) throws Exception {
log.info("Before create Message assym....");
SOAPEnvelope unsignedEnvelope = message.getSOAPEnvelope();
/*
* First get the SOAP envelope as document, then create a security
* header and insert into the document (Envelope)
*/
Document doc = unsignedEnvelope.getAsDocument();
SOAPConstants soapConstants = WSSecurityUtil.getSOAPConstants(doc
.getDocumentElement());
WSSecHeader secHeader = new WSSecHeader();
secHeader.insertSecurityHeader(doc);
Vector sigParts = new Vector();
Vector encPartsInternal = new Vector();
Vector encPartsExternal = new Vector();
/*
* Check is a timestamp is required. If yes create one and add its Id to
* signed parts. According to WSP a timestamp must be signed
*/
WSSecTimestamp timestamp = null;
if (wpd.isIncludeTimestamp()) {
timestamp = new WSSecTimestamp();
timestamp.prepare(doc);
sigParts.add(new WSEncryptionPart(timestamp.getId()));
}
/*
* Check for a recipient token. If one is avaliable use it as token to
* encrypt data to the recipient. This is according to WSP
* specification. Most of the data is extracted from the
* WSS4JPolicyData, only the user info (name/alias of the certificate in
* the keystore) must be provided by some other means.
*/
WSSecEncrypt recEncrypt = null;
WSS4JPolicyToken recToken = null;
if ((recToken = wpd.getRecipientToken()) != null) {
recEncrypt = new WSSecEncrypt();
recEncrypt.setUserInfo("wss4jcert");
recEncrypt.setKeyIdentifierType(recToken.getEncKeyIdentifier());
recEncrypt.setSymmetricEncAlgorithm(recToken.getEncAlgorithm());
recEncrypt.setKeyEnc(recToken.getEncTransportAlgorithm());
recEncrypt.prepare(doc, cryptoSKI);
}
/*
* Check for an initiator token. If one is avaliable use it as token to
* sign data. This is according to WSP specification. Most of the data
* is extracted from the WSS4JPolicyData, only the user info (name/alias
* of the certificate in the keystore) must be provided by some other
* means.
*
* If SignatureProtection is enabled add the signature to the encrypted
* parts vector. In any case the signature must be in the internal
* ReferenceList (this list is a child of the EncryptedKey element).
*
* If TokenProtection is enabled add an appropriate signature reference.
*
* TODO Check / enable for STRTransform
*/
WSSecSignature iniSignature = null;
WSS4JPolicyToken iniToken = null;
if ((iniToken = wpd.getInitiatorToken()) != null) {
iniSignature = new WSSecSignature();
iniSignature.setUserInfo("16c73ab6-b892-458f-abf5-2f875f74882e",
"security");
iniSignature.setKeyIdentifierType(iniToken.getSigKeyIdentifier());
iniSignature.setSignatureAlgorithm(iniToken.getSigAlgorithm());
iniSignature.prepare(doc, crypto, secHeader);
if (wpd.isSignatureProtection()) {
encPartsInternal.add(new WSEncryptionPart(iniSignature.getId(),
"Element"));
}
if (wpd.isTokenProtection()) {
sigParts.add(new WSEncryptionPart("Token", null, null));
}
}
Element body = WSSecurityUtil.findBodyElement(doc, soapConstants);
if (body == null) {
System.out
.println("No SOAP Body found - illegal message structure. Processing terminated");
return;
}
WSEncryptionPart bodyPart = new WSEncryptionPart("Body", soapConstants
.getEnvelopeURI(), "Content");
/*
* Check the protection order. If Encrypt before signing then first take
* all parts and elements to encrypt and encrypt them. Take their ids
* after encryption and put them to the parts to be signed.
*
*/
Element externRefList = null;
if (Constants.ENCRYPT_BEFORE_SIGNING.equals(wpd.getProtectionOrder())) {
/*
* Process Body: it sign and encrypt: first encrypt the body, insert
* the body to the parts to be signed.
*
* If just to be signed: add the plain Body to the parts to be
* signed
*/
if (wpd.isSignBody()) {
if (wpd.isEncryptBody()) {
Vector parts = new Vector();
parts.add(bodyPart);
externRefList = recEncrypt.encryptForExternalRef(
externRefList, parts);
sigParts.add(bodyPart);
} else {
sigParts.add(bodyPart);
}
}
/*
* Here we need to handle signed/encrypted parts:
*
* Get all parts that need to be encrypted _and_ signed, encrypt
* them, get ids of thier encrypted data elements and add these ids
* to the parts to be signed
*
* Then encrypt the remaining parts that don't need to be signed.
*
* Then add the remaining parts that don't nedd to be encrypted to
* the parts to be signed.
*
* Similar handling for signed/encrypted elements (compare XPath
* strings?)
*
* After all elements are encrypted put the external refernce list
* to the security header. is at the bottom of the security header)
*/
recEncrypt.addExternalRefElement(externRefList, secHeader);
/*
* Now handle the supporting tokens - according to OASIS WSP
* supporting tokens are not part of a Binding assertion but a top
* level assertion similar to Wss11 or SignedParts. If supporting
* tokens are available their BST elements have to be added later
* (probably prepended to the initiator token - see below)
*/
/*
* Now add the various elements to the header. We do a strict layout
* here.
*
*/
/*
* Prepend Signature to the supporting tokens that sign the primary
* signature
*/
iniSignature.prependToHeader(secHeader);
/*
* This prepends a possible initiator token to the security header
*/
iniSignature.prependBSTElementToHeader(secHeader);
/*
* Here prepend BST elements of supporting tokens
* (EndorsingSupportTokens), then prepend supporting token that do
* not sign the primary signature but are signed by the primary
* signature. Take care of the TokenProtection protery!?
*/
/*
* Add the encrypted key element and then the associated BST element
* recipient token)
*/
recEncrypt.prependToHeader(secHeader);
recEncrypt.prependBSTElementToHeader(secHeader);
/*
* Now we are ready to per Signature processing.
*
* First the primary Signature then supporting tokens (Signatures)
* that sign the primary Signature.
*/
timestamp.prependToHeader(secHeader);
iniSignature.addReferencesToSign(sigParts, secHeader);
iniSignature.computeSignature();
Element internRef = recEncrypt.encryptForInternalRef(null,
encPartsInternal);
recEncrypt.addInternalRefElement(internRef);
} else {
System.out.println("SignBeforeEncrypt needs to be implemented");
}
log.info("After creating Message asymm....");
/*
* convert the resulting document into a message first. The
* toSOAPMessage() method performs the necessary c14n call to properly
* set up the signed document and convert it into a SOAP message. Check
* that the contents can't be read (cheching if we can find a specific
* substring). After that we extract it as a document again for further
* processing.
*/
Message encryptedMsg = (Message) SOAPUtil.toSOAPMessage(doc);
if (log.isDebugEnabled()) {
log.debug("Processed message");
XMLUtils.PrettyElementToWriter(encryptedMsg.getSOAPEnvelope()
.getAsDOM(), new PrintWriter(System.out));
}
String encryptedString = encryptedMsg.getSOAPPartAsString();
assertTrue(encryptedString.indexOf("LogTestService2") == -1 ? true
: false);
// encryptedDoc = encryptedMsg.getSOAPEnvelope().getAsDocument();
verify(doc);
}
| private void createMessageAsymm(WSS4JPolicyData wpd) throws Exception {
log.info("Before create Message assym....");
SOAPEnvelope unsignedEnvelope = message.getSOAPEnvelope();
/*
* First get the SOAP envelope as document, then create a security
* header and insert into the document (Envelope)
*/
Document doc = unsignedEnvelope.getAsDocument();
SOAPConstants soapConstants = WSSecurityUtil.getSOAPConstants(doc
.getDocumentElement());
WSSecHeader secHeader = new WSSecHeader();
secHeader.insertSecurityHeader(doc);
Vector sigParts = new Vector();
Vector encPartsInternal = new Vector();
Vector encPartsExternal = new Vector();
/*
* Check is a timestamp is required. If yes create one and add its Id to
* signed parts. According to WSP a timestamp must be signed
*/
WSSecTimestamp timestamp = null;
if (wpd.isIncludeTimestamp()) {
timestamp = new WSSecTimestamp();
timestamp.prepare(doc);
sigParts.add(new WSEncryptionPart(timestamp.getId()));
}
/*
* Check for a recipient token. If one is avaliable use it as token to
* encrypt data to the recipient. This is according to WSP
* specification. Most of the data is extracted from the
* WSS4JPolicyData, only the user info (name/alias of the certificate in
* the keystore) must be provided by some other means.
*/
WSSecEncrypt recEncrypt = null;
WSS4JPolicyToken recToken = null;
if ((recToken = wpd.getRecipientToken()) != null) {
recEncrypt = new WSSecEncrypt();
recEncrypt.setUserInfo("wss4jcert");
recEncrypt.setKeyIdentifierType(recToken.getKeyIdentifier());
recEncrypt.setSymmetricEncAlgorithm(recToken.getEncAlgorithm());
recEncrypt.setKeyEnc(recToken.getEncTransportAlgorithm());
recEncrypt.prepare(doc, cryptoSKI);
}
/*
* Check for an initiator token. If one is avaliable use it as token to
* sign data. This is according to WSP specification. Most of the data
* is extracted from the WSS4JPolicyData, only the user info (name/alias
* of the certificate in the keystore) must be provided by some other
* means.
*
* If SignatureProtection is enabled add the signature to the encrypted
* parts vector. In any case the signature must be in the internal
* ReferenceList (this list is a child of the EncryptedKey element).
*
* If TokenProtection is enabled add an appropriate signature reference.
*
* TODO Check / enable for STRTransform
*/
WSSecSignature iniSignature = null;
WSS4JPolicyToken iniToken = null;
if ((iniToken = wpd.getInitiatorToken()) != null) {
iniSignature = new WSSecSignature();
iniSignature.setUserInfo("16c73ab6-b892-458f-abf5-2f875f74882e",
"security");
iniSignature.setKeyIdentifierType(iniToken.getKeyIdentifier());
iniSignature.setSignatureAlgorithm(iniToken.getSigAlgorithm());
iniSignature.prepare(doc, crypto, secHeader);
if (wpd.isSignatureProtection()) {
encPartsInternal.add(new WSEncryptionPart(iniSignature.getId(),
"Element"));
}
if (wpd.isTokenProtection()) {
sigParts.add(new WSEncryptionPart("Token", null, null));
}
}
Element body = WSSecurityUtil.findBodyElement(doc, soapConstants);
if (body == null) {
System.out
.println("No SOAP Body found - illegal message structure. Processing terminated");
return;
}
WSEncryptionPart bodyPart = new WSEncryptionPart("Body", soapConstants
.getEnvelopeURI(), "Content");
/*
* Check the protection order. If Encrypt before signing then first take
* all parts and elements to encrypt and encrypt them. Take their ids
* after encryption and put them to the parts to be signed.
*
*/
Element externRefList = null;
if (Constants.ENCRYPT_BEFORE_SIGNING.equals(wpd.getProtectionOrder())) {
/*
* Process Body: it sign and encrypt: first encrypt the body, insert
* the body to the parts to be signed.
*
* If just to be signed: add the plain Body to the parts to be
* signed
*/
if (wpd.isSignBody()) {
if (wpd.isEncryptBody()) {
Vector parts = new Vector();
parts.add(bodyPart);
externRefList = recEncrypt.encryptForExternalRef(
externRefList, parts);
sigParts.add(bodyPart);
} else {
sigParts.add(bodyPart);
}
}
/*
* Here we need to handle signed/encrypted parts:
*
* Get all parts that need to be encrypted _and_ signed, encrypt
* them, get ids of thier encrypted data elements and add these ids
* to the parts to be signed
*
* Then encrypt the remaining parts that don't need to be signed.
*
* Then add the remaining parts that don't nedd to be encrypted to
* the parts to be signed.
*
* Similar handling for signed/encrypted elements (compare XPath
* strings?)
*
* After all elements are encrypted put the external refernce list
* to the security header. is at the bottom of the security header)
*/
recEncrypt.addExternalRefElement(externRefList, secHeader);
/*
* Now handle the supporting tokens - according to OASIS WSP
* supporting tokens are not part of a Binding assertion but a top
* level assertion similar to Wss11 or SignedParts. If supporting
* tokens are available their BST elements have to be added later
* (probably prepended to the initiator token - see below)
*/
/*
* Now add the various elements to the header. We do a strict layout
* here.
*
*/
/*
* Prepend Signature to the supporting tokens that sign the primary
* signature
*/
iniSignature.prependToHeader(secHeader);
/*
* This prepends a possible initiator token to the security header
*/
iniSignature.prependBSTElementToHeader(secHeader);
/*
* Here prepend BST elements of supporting tokens
* (EndorsingSupportTokens), then prepend supporting token that do
* not sign the primary signature but are signed by the primary
* signature. Take care of the TokenProtection protery!?
*/
/*
* Add the encrypted key element and then the associated BST element
* recipient token)
*/
recEncrypt.prependToHeader(secHeader);
recEncrypt.prependBSTElementToHeader(secHeader);
/*
* Now we are ready to per Signature processing.
*
* First the primary Signature then supporting tokens (Signatures)
* that sign the primary Signature.
*/
timestamp.prependToHeader(secHeader);
iniSignature.addReferencesToSign(sigParts, secHeader);
iniSignature.computeSignature();
Element internRef = recEncrypt.encryptForInternalRef(null,
encPartsInternal);
recEncrypt.addInternalRefElement(internRef);
} else {
System.out.println("SignBeforeEncrypt needs to be implemented");
}
log.info("After creating Message asymm....");
/*
* convert the resulting document into a message first. The
* toSOAPMessage() method performs the necessary c14n call to properly
* set up the signed document and convert it into a SOAP message. Check
* that the contents can't be read (cheching if we can find a specific
* substring). After that we extract it as a document again for further
* processing.
*/
Message encryptedMsg = (Message) SOAPUtil.toSOAPMessage(doc);
if (log.isDebugEnabled()) {
log.debug("Processed message");
XMLUtils.PrettyElementToWriter(encryptedMsg.getSOAPEnvelope()
.getAsDOM(), new PrintWriter(System.out));
}
String encryptedString = encryptedMsg.getSOAPPartAsString();
assertTrue(encryptedString.indexOf("LogTestService2") == -1 ? true
: false);
// encryptedDoc = encryptedMsg.getSOAPEnvelope().getAsDocument();
verify(doc);
}
|
diff --git a/SeleniumGridExtras/src/test/java/com/groupon/seleniumgridextras/RebootNodeTest.java b/SeleniumGridExtras/src/test/java/com/groupon/seleniumgridextras/RebootNodeTest.java
index 25fa1e9..06dbbd8 100644
--- a/SeleniumGridExtras/src/test/java/com/groupon/seleniumgridextras/RebootNodeTest.java
+++ b/SeleniumGridExtras/src/test/java/com/groupon/seleniumgridextras/RebootNodeTest.java
@@ -1,85 +1,85 @@
/**
* Copyright (c) 2013, Groupon, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of GROUPON nor the names of its contributors may be
* used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* Created with IntelliJ IDEA.
* User: Dima Kovalenko (@dimacus) && Darko Marinov
* Date: 5/10/13
* Time: 4:06 PM
*/
package com.groupon.seleniumgridextras;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class RebootNodeTest {
private ExecuteOSTask task;
private String windowsCommand;
@Before
public void setUp() throws Exception {
task = new RebootNode();
windowsCommand = "shutdown -r -t 1 -f";
}
@Test
public void testGetDescription() throws Exception {
assertEquals("Restart the host node", task.getDescription());
}
@Test
public void testGetEndpoint() throws Exception {
assertEquals("/reboot", task.getEndpoint());
}
@Test
public void testgetWindowsCommand() throws Exception {
assertEquals(windowsCommand, task.getWindowsCommand());
}
@Test
public void testgetMacCommand() throws Exception {
assertEquals(
- "{\"exit_code\":1,\"error\":[\"This task was not implemented on Mac OS X com.groupon.RebootNode\"],\"out\":[]}",
+ "{\"exit_code\":1,\"error\":[\"This task was not implemented on Mac OS X com.groupon.seleniumgridextras.RebootNode\"],\"out\":[]}",
task.getLinuxCommand());
}
@Test
public void testgetLinuxCommand() throws Exception {
assertEquals(
- "{\"exit_code\":1,\"error\":[\"This task was not implemented on Mac OS X com.groupon.RebootNode\"],\"out\":[]}",
+ "{\"exit_code\":1,\"error\":[\"This task was not implemented on Mac OS X com.groupon.seleniumgridextras.RebootNode\"],\"out\":[]}",
task.getLinuxCommand());
}
}
diff --git a/SeleniumGridExtras/src/test/java/com/groupon/seleniumgridextras/ScreenshotTest.java b/SeleniumGridExtras/src/test/java/com/groupon/seleniumgridextras/ScreenshotTest.java
index 56e0ea3..d5fb5ab 100644
--- a/SeleniumGridExtras/src/test/java/com/groupon/seleniumgridextras/ScreenshotTest.java
+++ b/SeleniumGridExtras/src/test/java/com/groupon/seleniumgridextras/ScreenshotTest.java
@@ -1,96 +1,96 @@
/**
* Copyright (c) 2013, Groupon, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of GROUPON nor the names of its contributors may be
* used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* Created with IntelliJ IDEA.
* User: Dima Kovalenko (@dimacus) && Darko Marinov
* Date: 5/10/13
* Time: 4:06 PM
*/
package com.groupon.seleniumgridextras;
import org.junit.Before;
import org.junit.Test;
import java.util.LinkedList;
import java.util.List;
import static org.junit.Assert.assertEquals;
public class ScreenshotTest {
private ExecuteOSTask task;
@Before
public void setUp() throws Exception {
task = new Screenshot();
}
@Test
public void testGetEndpoint() throws Exception {
assertEquals("/screenshot", task.getEndpoint());
}
@Test
public void testGetDescription() throws Exception {
assertEquals("Take a full OS screen Screen Shot of the node", task.getDescription());
}
@Test
public void testGetDependencies() throws Exception {
List<String> actualDependencies = task.getDependencies();
List<String> expectedDependencies = new LinkedList<String>();
- expectedDependencies.add("com.groupon.ExposeDirectory");
+ expectedDependencies.add("com.groupon.seleniumgridextras.ExposeDirectory");
assertEquals(expectedDependencies, actualDependencies);
}
@Test
public void testGetJsonResponse() throws Exception {
assertEquals(
"{\"exit_code\":1,\"error\":[],\"file\":[\"\"],\"image\":[\"\"],\"file_type\":[\"PNG\"],\"out\":[]}",
task.getJsonResponse().toString());
}
@Test
public void testAPIDescription() throws Exception {
assertEquals("Base64 URL Encoded (ISO-8859-1) string of the image",
task.getJsonResponse().getKeyDescriptions().get("image"));
assertEquals("Type of file returned (PNG/JPG/GIF)",
task.getJsonResponse().getKeyDescriptions().get("file_type"));
assertEquals("Name of the file saved on the Node's HD",
task.getJsonResponse().getKeyDescriptions().get("file"));
assertEquals(6, task.getJsonResponse().getKeyDescriptions().keySet().size());
}
}
diff --git a/SeleniumGridExtras/src/test/java/com/groupon/seleniumgridextras/UpgradeWebdriverTest.java b/SeleniumGridExtras/src/test/java/com/groupon/seleniumgridextras/UpgradeWebdriverTest.java
index 96f52a9..b28c428 100644
--- a/SeleniumGridExtras/src/test/java/com/groupon/seleniumgridextras/UpgradeWebdriverTest.java
+++ b/SeleniumGridExtras/src/test/java/com/groupon/seleniumgridextras/UpgradeWebdriverTest.java
@@ -1,95 +1,95 @@
/**
* Copyright (c) 2013, Groupon, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of GROUPON nor the names of its contributors may be
* used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* Created with IntelliJ IDEA.
* User: Dima Kovalenko (@dimacus) && Darko Marinov
* Date: 5/10/13
* Time: 4:06 PM
*/
package com.groupon.seleniumgridextras;
import org.junit.Before;
import org.junit.Test;
import java.util.LinkedList;
import java.util.List;
import static org.junit.Assert.assertEquals;
public class UpgradeWebdriverTest {
public ExecuteOSTask task;
@Before
public void setUp() throws Exception {
task = new UpgradeWebdriver();
}
@Test
public void testGetEndpoint() throws Exception {
assertEquals("/upgrade_webdriver", task.getEndpoint());
}
@Test
public void testGetDescription() throws Exception {
assertEquals("Downloads a version of WebDriver jar to node, and upgrades the setting to use new version on restart", task.getDescription());
}
// @Test
// public void testExecute() throws Exception {
//
// }
//
// @Test
// public void testExecute() throws Exception {
//
// }
@Test
public void testGetDependencies() throws Exception {
List<String> expected = new LinkedList();
- expected.add("com.groupon.DownloadWebdriver");
+ expected.add("com.groupon.seleniumgridextras.DownloadWebdriver");
assertEquals(expected, task.getDependencies());
}
@Test
public void testGetJsonResponse() throws Exception {
}
@Test
public void testGetAcceptedParams() throws Exception {
assertEquals("(Required) - Version of WebDriver to download, such as 2.33.0",
task.getAcceptedParams().get("version"));
assertEquals(1, task.getAcceptedParams().keySet().size());
}
}
| false | false | null | null |
diff --git a/cloud-disco-demo-web-ui/src/main/java/org/coderthoughts/cloud/demo/webui/impl/MyServlet.java b/cloud-disco-demo-web-ui/src/main/java/org/coderthoughts/cloud/demo/webui/impl/MyServlet.java
index 725f379..b5e52a1 100644
--- a/cloud-disco-demo-web-ui/src/main/java/org/coderthoughts/cloud/demo/webui/impl/MyServlet.java
+++ b/cloud-disco-demo-web-ui/src/main/java/org/coderthoughts/cloud/demo/webui/impl/MyServlet.java
@@ -1,79 +1,87 @@
package org.coderthoughts.cloud.demo.webui.impl;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;
import java.util.TreeMap;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.coderthoughts.cloud.demo.api.TestService;
import org.coderthoughts.cloud.framework.service.api.OSGiFramework;
import org.osgi.framework.BundleContext;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceReference;
public class MyServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private final BundleContext bundleContext;
MyServlet(BundleContext context) {
bundleContext = context;
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
out.println("<html><head><title>Test Web UI</title></head><body>");
printFrameworks(out);
printTestServices(out);
out.println("</body></html>");
out.close();
}
private void printFrameworks(PrintWriter out) {
out.println("<H2>Frameworks in the Cloud Ecosystem</H2>");
try {
- for (ServiceReference ref : bundleContext.getServiceReferences(OSGiFramework.class.getName(), null)) {
+ ServiceReference[] refs = bundleContext.getServiceReferences(OSGiFramework.class.getName(), null);
+ if (refs == null)
+ return;
+
+ for (ServiceReference ref : refs) {
Map<String, Object> sortedProps = new TreeMap<String, Object>();
for (String key : ref.getPropertyKeys()) {
if (!key.startsWith("org."))
// Don't display all they props to keep things tidy
continue;
sortedProps.put(key, ref.getProperty(key));
}
out.println("OSGi Framework<UL>");
for (String key : sortedProps.keySet()) {
out.println("<li>" + key + " - " + sortedProps.get(key) + "</li>");
}
out.println("</UL>");
}
} catch (InvalidSyntaxException e) {
e.printStackTrace();
}
}
private void printTestServices(PrintWriter out) {
out.println("<H2>TestService instances available</H2>");
try {
- for (ServiceReference ref : bundleContext.getServiceReferences(TestService.class.getName(), null)) {
+ ServiceReference[] refs = bundleContext.getServiceReferences(TestService.class.getName(), null);
+ if (refs == null)
+ return;
+
+ for (ServiceReference ref : refs) {
TestService svc = (TestService) bundleContext.getService(ref);
out.println("TestService instance<ul>");
out.println("<li>invoking: " + svc.doit("Hi there"));
out.println("</li></ul>");
bundleContext.ungetService(ref);
}
} catch (InvalidSyntaxException e) {
e.printStackTrace();
}
}
}
| false | false | null | null |
diff --git a/be.norio.twunch.android/src/be/norio/twunch/android/TwunchActivity.java b/be.norio.twunch.android/src/be/norio/twunch/android/TwunchActivity.java
index c8e605b..e74a983 100644
--- a/be.norio.twunch.android/src/be/norio/twunch/android/TwunchActivity.java
+++ b/be.norio.twunch.android/src/be/norio/twunch/android/TwunchActivity.java
@@ -1,290 +1,292 @@
/**
* Copyright 2010-2011 Norio bvba
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package be.norio.twunch.android;
import greendroid.app.GDActivity;
import greendroid.widget.ActionBarItem;
import greendroid.widget.ActionBarItem.Type;
import java.util.Arrays;
import java.util.Date;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.provider.BaseColumns;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Nickname;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.Data;
import android.provider.ContactsContract.QuickContact;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.TextView;
import com.cyrilmottier.android.greendroid.R;
import com.google.android.apps.analytics.GoogleAnalyticsTracker;
public class TwunchActivity extends GDActivity {
public static String PARAMETER_ID = "id";
private final static int MENU_MAP = 0;
private final static int MENU_REGISTER = 1;
private final static int MENU_SHARE = 2;
private static String[] columns = new String[] { BaseColumns._ID, TwunchManager.COLUMN_TITLE, TwunchManager.COLUMN_ADDRESS,
TwunchManager.COLUMN_DATE, TwunchManager.COLUMN_NUMPARTICIPANTS, TwunchManager.COLUMN_LATITUDE,
TwunchManager.COLUMN_LONGITUDE, TwunchManager.COLUMN_PARTICIPANTS, TwunchManager.COLUMN_NOTE, TwunchManager.COLUMN_LINK };
private static final int COLUMN_DISPLAY_TITLE = 1;
private static final int COLUMN_DISPLAY_ADDRESS = 2;
private static final int COLUMN_DISPLAY_DATE = 3;
private static final int COLUMN_DISPLAY_NUMPARTICIPANTS = 4;
private static final int COLUMN_DISPLAY_LATITUDE = 5;
private static final int COLUMN_DISPLAY_LONGITUDE = 6;
private static final int COLUMN_DISPLAY_PARTICIPANTS = 7;
private static final int COLUMN_DISPLAY_NOTE = 8;
private static final int COLUMN_DISPLAY_LINK = 9;
DatabaseHelper dbHelper;
SQLiteDatabase db;
Cursor cursor;
String[] participants;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GoogleAnalyticsTracker.getInstance().trackPageView("Twunch");
setActionBarContentView(R.layout.twunch);
addActionBarItem(Type.Add);
addActionBarItem(Type.Share);
addActionBarItem(Type.Locate);
dbHelper = new DatabaseHelper(this);
db = dbHelper.getReadableDatabase();
cursor = db.query(TwunchManager.TABLE_NAME, columns,
BaseColumns._ID + " = " + String.valueOf(getIntent().getIntExtra(PARAMETER_ID, 0)), null, null, null, null);
cursor.moveToFirst();
TwunchManager.getInstance().setTwunchRead(this, cursor.getInt(0));
// Title
((TextView) findViewById(R.id.twunchTitle)).setText(cursor.getString(COLUMN_DISPLAY_TITLE));
// Address
((TextView) findViewById(R.id.twunchAddress)).setText(cursor.getString(COLUMN_DISPLAY_ADDRESS));
// Distance
Float distance = TwunchManager.getInstance().getDistanceToTwunch(this, cursor.getFloat(COLUMN_DISPLAY_LATITUDE),
cursor.getFloat(COLUMN_DISPLAY_LONGITUDE));
((TextView) findViewById(R.id.twunchDistance)).setText(String.format(getString(R.string.distance), distance));
findViewById(R.id.twunchDistance).setVisibility(distance == null ? View.GONE : View.VISIBLE);
findViewById(R.id.twunchDistanceSeparator).setVisibility(distance == null ? View.GONE : View.VISIBLE);
// Date
((TextView) findViewById(R.id.twunchDate)).setText(String.format(
getString(R.string.date),
DateUtils.formatDateTime(this, cursor.getLong(COLUMN_DISPLAY_DATE), DateUtils.FORMAT_SHOW_WEEKDAY
| DateUtils.FORMAT_SHOW_DATE),
DateUtils.formatDateTime(this, cursor.getLong(COLUMN_DISPLAY_DATE), DateUtils.FORMAT_SHOW_TIME)));
// Days
- int days = (int) ((cursor.getLong(COLUMN_DISPLAY_DATE) - new Date().getTime()) / 1000 / 60 / 60 / 24);
+ // TODO: This is not the most smart/correct way to calculate the number of
+ // days between 2 dates
+ int days = (int) Math.ceil(((cursor.getLong(COLUMN_DISPLAY_DATE) - new Date().getTime()) / 1000 / 60 / 60 / 24) + 0.5);
((TextView) findViewById(R.id.twunchDays)).setText(days == 0 ? getString(R.string.today) : String.format(getResources()
.getQuantityString(R.plurals.days_to_twunch, days), days));
// Note
TextView noteView = ((TextView) findViewById(R.id.twunchNote));
if (cursor.getString(COLUMN_DISPLAY_NOTE) == null || cursor.getString(COLUMN_DISPLAY_NOTE).length() == 0) {
noteView.setVisibility(View.GONE);
} else {
noteView.setText(cursor.getString(COLUMN_DISPLAY_NOTE));
noteView.setVisibility(View.VISIBLE);
}
// Number of participants
((TextView) findViewById(R.id.twunchNumberParticipants)).setText(String.format(
getResources().getQuantityString(R.plurals.numberOfParticipants, cursor.getInt(COLUMN_DISPLAY_NUMPARTICIPANTS)),
cursor.getInt(COLUMN_DISPLAY_NUMPARTICIPANTS)));
// Participants
GridView participantsView = ((GridView) findViewById(R.id.twunchParticipants));
participants = cursor.getString(COLUMN_DISPLAY_PARTICIPANTS).split(" ");
Arrays.sort(participants, String.CASE_INSENSITIVE_ORDER);
participantsView.setAdapter(new ContactAdapter(this));
// participantsView.setText(cursor.getString(COLUMN_DISPLAY_PARTICIPANTS));
// Linkify.addLinks(participantsView, Pattern.compile("@([A-Za-z0-9-_]+)"),
// "http://twitter.com/");
}
private class ContactAdapter extends BaseAdapter {
private final Context context;
public ContactAdapter(Context c) {
context = c;
}
@Override
public int getCount() {
return participants.length;
}
@Override
public Object getItem(int position) {
return participants[position];
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
final TextView textView;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
textView = (TextView) inflater.inflate(R.layout.participant, null);
} else {
textView = (TextView) convertView;
}
textView.setText("@" + participants[position]);
textView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String[] projection = new String[] { ContactsContract.Contacts._ID, ContactsContract.Contacts.LOOKUP_KEY };
Cursor rawTwitterContact = getContentResolver().query(Data.CONTENT_URI, projection, Nickname.NAME + " = ?",
new String[] { participants[position] }, null);
if (rawTwitterContact.getCount() > 0) {
// Show the QuickContact action bar
rawTwitterContact.moveToFirst();
final Uri contactUri = Uri.withAppendedPath(Contacts.CONTENT_LOOKUP_URI,
rawTwitterContact.getString(rawTwitterContact.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY)));
QuickContact.showQuickContact(context, textView, contactUri, ContactsContract.QuickContact.MODE_LARGE, null);
} else {
// Show the twitter profile
final Intent myIntent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse("http://twitter.com/"
+ participants[position]));
startActivity(myIntent);
}
}
});
return textView;
}
}
/*
* (non-Javadoc)
*
* @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
*/
@Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, MENU_REGISTER, 0, R.string.button_register).setIcon(R.drawable.ic_menu_add);
menu.add(0, MENU_SHARE, 0, R.string.menu_share).setIcon(R.drawable.ic_menu_share);
menu.add(0, MENU_MAP, 0, R.string.button_map).setIcon(R.drawable.ic_menu_mapmode);
return super.onCreateOptionsMenu(menu);
}
/*
* (non-Javadoc)
*
* @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem)
*/
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_MAP:
doMap();
return true;
case MENU_REGISTER:
doRegister();
return true;
case MENU_SHARE:
doShare();
return true;
}
return false;
}
/**
* Show the location of this Twunch on a map.
*/
private void doMap() {
final Intent myIntent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse("http://maps.google.com/maps?q="
+ cursor.getDouble(COLUMN_DISPLAY_LATITUDE) + "," + cursor.getDouble(COLUMN_DISPLAY_LONGITUDE)));
startActivity(myIntent);
}
/**
* Register for this Twunch.
*/
private void doRegister() {
final Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(
Intent.EXTRA_TEXT,
String.format(getString(R.string.register_text), cursor.getString(COLUMN_DISPLAY_TITLE),
cursor.getString(COLUMN_DISPLAY_LINK)));
startActivity(Intent.createChooser(intent, getString(R.string.register_title)));
}
/**
* Share information about this Twunch.
*/
private void doShare() {
final Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(
Intent.EXTRA_TEXT,
String.format(
getString(R.string.share_text),
cursor.getString(COLUMN_DISPLAY_TITLE),
DateUtils.formatDateTime(this, cursor.getLong(COLUMN_DISPLAY_DATE), DateUtils.FORMAT_SHOW_WEEKDAY
| DateUtils.FORMAT_SHOW_DATE),
DateUtils.formatDateTime(this, cursor.getLong(COLUMN_DISPLAY_DATE), DateUtils.FORMAT_SHOW_TIME),
cursor.getString(COLUMN_DISPLAY_LINK)));
intent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.share_subject));
intent.putExtra(Intent.EXTRA_EMAIL, "");
startActivity(Intent.createChooser(intent, getString(R.string.share_title)));
}
@Override
public boolean onHandleActionBarItemClick(ActionBarItem item, int position) {
switch (position) {
case 0:
doRegister();
break;
case 1:
doShare();
break;
case 2:
doMap();
break;
default:
return false;
}
return true;
}
}
diff --git a/be.norio.twunch.android/src/be/norio/twunch/android/TwunchesActivity.java b/be.norio.twunch.android/src/be/norio/twunch/android/TwunchesActivity.java
index 12bba60..feb0990 100644
--- a/be.norio.twunch.android/src/be/norio/twunch/android/TwunchesActivity.java
+++ b/be.norio.twunch.android/src/be/norio/twunch/android/TwunchesActivity.java
@@ -1,301 +1,303 @@
/**
* Copyright 2010-2011 Norio bvba
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package be.norio.twunch.android;
import greendroid.app.GDActivity;
import greendroid.widget.ActionBarItem;
import greendroid.widget.LoaderActionBarItem;
import java.util.Date;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Typeface;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.provider.BaseColumns;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CursorAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.cyrilmottier.android.greendroid.R;
import com.google.android.apps.analytics.GoogleAnalyticsTracker;
public class TwunchesActivity extends GDActivity {
private final static int MENU_ABOUT = 0;
private final static int MENU_REFRESH = 1;
private final static int MENU_MARK_READ = 2;
ListView mListView;
DatabaseHelper dbHelper;
SQLiteDatabase db;
Cursor cursor;
LocationManager locationManager;
LocationListener locationListener;
private static String[] columns = new String[] { BaseColumns._ID, TwunchManager.COLUMN_TITLE, TwunchManager.COLUMN_ADDRESS,
TwunchManager.COLUMN_DATE, TwunchManager.COLUMN_NUMPARTICIPANTS, TwunchManager.COLUMN_LATITUDE,
TwunchManager.COLUMN_LONGITUDE, TwunchManager.COLUMN_NEW };
private static final int COLUMN_DISPLAY_TITLE = 1;
private static final int COLUMN_DISPLAY_ADDRESS = 2;
private static final int COLUMN_DISPLAY_DATE = 3;
private static final int COLUMN_DISPLAY_NUMPARTICIPANTS = 4;
private static final int COLUMN_DISPLAY_LATITUDE = 5;
private static final int COLUMN_DISPLAY_LONGITUDE = 6;
private static final int COLUMN_DISPLAY_NEW = 7;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GoogleAnalyticsTracker.getInstance().start(TwunchApplication.TRACKER_ID, 60, this);
GoogleAnalyticsTracker.getInstance().trackPageView("Twunches");
setActionBarContentView(R.layout.twunch_list);
addActionBarItem(greendroid.widget.ActionBarItem.Type.Refresh);
mListView = (ListView) findViewById(R.id.twunchesList);
mListView.setEmptyView(findViewById(R.id.noTwunches));
dbHelper = new DatabaseHelper(this);
db = dbHelper.getReadableDatabase();
cursor = db.query(TwunchManager.TABLE_NAME, columns, null, null, null, null, TwunchManager.COLUMN_DATE + ","
+ TwunchManager.COLUMN_NUMPARTICIPANTS + " DESC");
startManagingCursor(cursor);
mListView.setAdapter(new TwunchCursorAdapter(this, cursor));
mListView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView l, View v, int position, long id) {
Intent intent = new Intent();
intent.setComponent(new ComponentName(v.getContext(), TwunchActivity.class));
intent.putExtra(TwunchActivity.PARAMETER_ID, ((Cursor) l.getAdapter().getItem(position)).getInt(0));
startActivity(intent);
}
});
// Acquire a reference to the system Location Manager
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
// Define a listener that responds to location updates
locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
cursor.requery();
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// Do nothing
}
public void onProviderEnabled(String provider) {
// Do nothing
}
public void onProviderDisabled(String provider) {
// Do nothing
}
};
refreshTwunches(false);
}
class TwunchCursorAdapter extends CursorAdapter {
public TwunchCursorAdapter(Context context, Cursor c) {
super(context, c);
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
// Title
((TextView) view.findViewById(R.id.twunchTitle)).setText(cursor.getString(COLUMN_DISPLAY_TITLE));
// Address
((TextView) view.findViewById(R.id.twunchAddress)).setText(cursor.getString(COLUMN_DISPLAY_ADDRESS));
((TextView) view.findViewById(R.id.twunchAddress)).setTypeface(null,
cursor.getInt(COLUMN_DISPLAY_NEW) == 1 ? Typeface.BOLD : Typeface.NORMAL);
// Distance
Float distance = TwunchManager.getInstance().getDistanceToTwunch(view.getContext(),
cursor.getFloat(COLUMN_DISPLAY_LATITUDE), cursor.getFloat(COLUMN_DISPLAY_LONGITUDE));
((TextView) view.findViewById(R.id.twunchDistance)).setText(String.format(view.getContext().getString(R.string.distance),
distance));
view.findViewById(R.id.twunchDistance).setVisibility(distance == null ? View.INVISIBLE : View.VISIBLE);
// Date
((TextView) view.findViewById(R.id.twunchDate)).setText(String.format(
view.getContext().getString(R.string.date),
DateUtils.formatDateTime(view.getContext(), cursor.getLong(COLUMN_DISPLAY_DATE), DateUtils.FORMAT_SHOW_WEEKDAY
| DateUtils.FORMAT_SHOW_DATE),
DateUtils.formatDateTime(view.getContext(), cursor.getLong(COLUMN_DISPLAY_DATE), DateUtils.FORMAT_SHOW_TIME)));
((TextView) view.findViewById(R.id.twunchDate)).setTypeface(null, cursor.getInt(COLUMN_DISPLAY_NEW) == 1 ? Typeface.BOLD
: Typeface.NORMAL);
// Days
- int days = (int) ((cursor.getLong(COLUMN_DISPLAY_DATE) - new Date().getTime()) / 1000 / 60 / 60 / 24);
+ // TODO: This is not the most smart/correct way to calculate the number of
+ // days between 2 dates
+ int days = (int) Math.ceil(((cursor.getLong(COLUMN_DISPLAY_DATE) - new Date().getTime()) / 1000 / 60 / 60 / 24) + 0.5);
((TextView) view.findViewById(R.id.twunchDays)).setText(days == 0 ? getString(R.string.today) : String.format(
getResources().getQuantityString(R.plurals.days_to_twunch, days), days));
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
final LayoutInflater inflater = LayoutInflater.from(context);
return inflater.inflate(R.layout.twunch_list_item, parent, false);
}
}
@Override
protected void onDestroy() {
super.onDestroy();
GoogleAnalyticsTracker.getInstance().dispatch();
GoogleAnalyticsTracker.getInstance().stop();
dbHelper.close();
}
/*
* (non-Javadoc)
*
* @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
*/
@Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, MENU_REFRESH, 0, R.string.menu_refresh).setIcon(R.drawable.ic_menu_refresh);
menu.add(0, MENU_MARK_READ, 0, R.string.menu_mark_read).setIcon(R.drawable.ic_menu_mark_read);
menu.add(0, MENU_ABOUT, 0, R.string.menu_about).setIcon(android.R.drawable.ic_menu_info_details);
return super.onCreateOptionsMenu(menu);
}
/*
* (non-Javadoc)
*
* @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem)
*/
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_ABOUT:
Intent intent = new Intent();
intent.setComponent(new ComponentName(this, AboutActivity.class));
startActivity(intent);
return true;
case MENU_REFRESH:
refreshTwunches(true);
return true;
case MENU_MARK_READ:
TwunchManager.getInstance().setAllTwunchesRead(this);
cursor.requery();
return true;
}
return false;
}
public void refreshTwunches(boolean force) {
long lastSync = db.compileStatement("select max(" + TwunchManager.COLUMN_SYNCED + ") from " + TwunchManager.TABLE_NAME)
.simpleQueryForLong();
if (lastSync != 0 && !force) {
return;
}
((LoaderActionBarItem) getActionBar().getItem(0)).setLoading(true);
final GDActivity thisActivity = this;
final Handler handler = new Handler();
final Runnable onDownloadSuccess = new Runnable() {
@Override
public void run() {
cursor.requery();
((LoaderActionBarItem) getActionBar().getItem(0)).setLoading(false);
Toast.makeText(getApplicationContext(), getString(R.string.download_done), Toast.LENGTH_SHORT).show();
}
};
final Runnable onDownloadFailure = new Runnable() {
@Override
public void run() {
((LoaderActionBarItem) getActionBar().getItem(0)).setLoading(false);
AlertDialog.Builder builder = new AlertDialog.Builder(thisActivity);
builder.setMessage(R.string.download_error);
builder.setCancelable(false);
builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Do nothing
}
});
builder.create().show();
}
};
new Thread() {
@Override
public void run() {
try {
TwunchManager.getInstance().syncTwunches(thisActivity);
handler.post(onDownloadSuccess);
} catch (Exception e) {
e.printStackTrace();
handler.post(onDownloadFailure);
}
}
}.start();
}
@Override
public boolean onHandleActionBarItemClick(ActionBarItem item, int position) {
if (position == 0) {
refreshTwunches(true);
return true;
}
return false;
}
/*
* (non-Javadoc)
*
* @see android.app.Activity#onPause()
*/
@Override
protected void onPause() {
super.onPause();
// Stop listening for location updates
locationManager.removeUpdates(locationListener);
}
/*
* (non-Javadoc)
*
* @see android.app.Activity#onResume()
*/
@Override
protected void onResume() {
super.onResume();
// Start listening for location updates
locationManager
.requestLocationUpdates(locationManager.getBestProvider(new Criteria(), true), 300000, 500, locationListener);
}
}
\ No newline at end of file
| false | false | null | null |
diff --git a/src/freemail/FreemailPlugin.java b/src/freemail/FreemailPlugin.java
index 3a5a41b..98ab44b 100644
--- a/src/freemail/FreemailPlugin.java
+++ b/src/freemail/FreemailPlugin.java
@@ -1,162 +1,165 @@
/*
* FreemailPlugin.java
* This file is part of Freemail, copyright (C) 2006 Dave Baker
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
* USA
*
*/
package freemail;
import java.io.IOException;
+import freenet.clients.http.PageNode;
import freenet.pluginmanager.FredPlugin;
import freenet.pluginmanager.FredPluginHTTP;
import freenet.pluginmanager.FredPluginThreadless;
import freenet.pluginmanager.FredPluginVersioned;
import freenet.pluginmanager.PluginHTTPException;
import freenet.pluginmanager.PluginRespirator;
import freenet.support.HTMLNode;
import freenet.support.api.HTTPRequest;
// although we have threads, we still 'implement' FredPluginThreadless because our runPlugin method
// returns rather than just continuing to run for the lifetime of the plugin.
public class FreemailPlugin extends Freemail implements FredPlugin, FredPluginHTTP,
FredPluginThreadless, FredPluginVersioned {
private PluginRespirator pluginResp;
public FreemailPlugin() throws IOException {
super(CFGFILE);
}
public String getVersion() {
return getVersionString();
}
public void runPlugin(PluginRespirator pr) {
pluginResp = pr;
startFcp(true);
startWorkers(true);
startServers(true);
}
public String handleHTTPGet(HTTPRequest request) throws PluginHTTPException {
- HTMLNode pageNode = pluginResp.getPageMaker().getPageNode("Freemail plugin", false, null);
- HTMLNode contentNode = pluginResp.getPageMaker().getContentNode(pageNode);
+ PageNode page = pluginResp.getPageMaker().getPageNode("Freemail plugin", false, null);
+ HTMLNode pageNode = page.outer;
+ HTMLNode contentNode = page.content;
HTMLNode addBox = contentNode.addChild("div", "class", "infobox");
addBox.addChild("div", "class", "infobox-header", "Add account");
HTMLNode boxContent = addBox.addChild("div", "class", "infobox-content");
HTMLNode form = pluginResp.addFormChild(boxContent, "", "addAccountForm");
HTMLNode table = form.addChild("table", "class", "plugintable");
HTMLNode tableRowName = table.addChild("tr");
tableRowName.addChild("td", "IMAP Name");
tableRowName.addChild("td").addChild("input", new String[] { "type", "name", "value", "size" }, new String[] { "text", "name", "", "30" });
HTMLNode tableRowPassword = table.addChild("tr");
tableRowPassword.addChild("td", "IMAP Password");
tableRowPassword.addChild("td").addChild("input", new String[] { "type", "name", "value", "size" }, new String[] { "password", "password", "", "30" });
HTMLNode tableRowDomain = table.addChild("tr");
tableRowDomain.addChild("td", "Shortname (Freenet Domain)");
tableRowDomain.addChild("td").addChild("input", new String[] { "type", "name", "value", "size" }, new String[] { "text", "domain", "", "30" });
HTMLNode tableRowSubmit = table.addChild("tr");
tableRowSubmit.addChild("td");
tableRowSubmit.addChild("td").addChild("input", new String[] { "type", "name", "value" }, new String[] { "submit", "add", "Add account"});
HTMLNode helpContent = addBox.addChild("div", "class", "infobox-content");
helpContent.addChild("#",
"The 'IMAP Name' and 'IMAP Password'"
+ " values will be your security"
+ " credentials for getting your Freenet"
+ " mail.");
helpContent.addChild("br");
helpContent.addChild("#",
"The 'Shortname (Freenet Domain)' will"
+ " become the significant part of your"
+ " email address.");
return pageNode.generate();
}
public String handleHTTPPost(HTTPRequest request) throws PluginHTTPException {
- HTMLNode pageNode = pluginResp.getPageMaker().getPageNode("Freemail plugin", false, null);
- HTMLNode contentNode = pluginResp.getPageMaker().getContentNode(pageNode);
+ PageNode page = pluginResp.getPageMaker().getPageNode("Freemail plugin", false, null);
+ HTMLNode pageNode = page.outer;
+ HTMLNode contentNode = page.content;
String add = request.getPartAsString("add", 100);
String name = request.getPartAsString("name", 100);
String password = request.getPartAsString("password", 100);
String domain = request.getPartAsString("domain", 100);
if(add.equals("Add account")) {
if(!(name.equals("") || password.equals(""))) {
try {
FreemailAccount newAccount = getAccountManager().createAccount(name);
AccountManager.changePassword(newAccount, password);
boolean tryShortAddress = false;
boolean shortAddressWorked = false;
if(!domain.equals("")) {
tryShortAddress = true;
shortAddressWorked = AccountManager.addShortAddress(newAccount, domain);
}
startWorker(newAccount, true);
HTMLNode successBox = contentNode.addChild("div", "class", "infobox infobox-success");
successBox.addChild("div", "class", "infobox-header", "Account Created");
// TODO: This is not the world's best into message, but it's only temporary (hopefully...)
HTMLNode text = successBox.addChild("div", "class", "infobox-content");
text.addChild("#", "The account ");
text.addChild("i", name);
String shortAddrMsg = "";
if (tryShortAddress && ! shortAddressWorked) {
shortAddrMsg = ", but your short address could NOT be created";
}
text.addChild("#", " was created successfully"+shortAddrMsg+".");
text.addChild("br");
text.addChild("br");
text.addChild("#", "You now need to configure your email client to send and receive email through "
+ "Freemail using IMAP and SMTP. Freemail uses ports 3143 and 3025 for these "
+ "respectively by default.");
} catch (IOException ioe) {
HTMLNode errorBox = contentNode.addChild("div", "class", "infobox infobox-error");
errorBox.addChild("div", "class", "infobox-header", "IO Error");
errorBox.addChild("div", "class", "infobox-content", "Couldn't create account. Please check write access to Freemail's working directory. If you want to overwrite your account, delete the appropriate directory manually in 'data' first. Freemail will intentionally not overwrite it. Error: "+ioe.getMessage());
} catch (Exception e) {
HTMLNode errorBox = contentNode.addChild("div", "class", "infobox-error");
errorBox.addChild("div", "class", "infobox-header", "Error");
errorBox.addChild("div", "class", "infobox-content", "Couldn't change password for "+name+". "+e.getMessage());
}
// XXX: There doesn't seem to be a way to get (or set) our root in the web interface,
// so we'll just have to assume it's this and won't change
contentNode.addChild("a", "href", "/plugins/freemail.FreemailPlugin",
"Freemail Home");
} else {
HTMLNode errorBox = contentNode.addChild("div", "class", "infobox infobox-error");
errorBox.addChild("div", "class", "infobox-header", "Error");
errorBox.addChild("div", "class", "infobox-content", "Couldn't create account, name or password is missing");
}
}
return pageNode.generate();
}
public String handleHTTPPut(HTTPRequest request) throws PluginHTTPException {
return null;
}
}
| false | false | null | null |
diff --git a/src/main/java/uk/org/cowgill/james/jircd/commands/Who.java b/src/main/java/uk/org/cowgill/james/jircd/commands/Who.java
index 48ff455..7b3c5b3 100644
--- a/src/main/java/uk/org/cowgill/james/jircd/commands/Who.java
+++ b/src/main/java/uk/org/cowgill/james/jircd/commands/Who.java
@@ -1,232 +1,228 @@
/*
Copyright 2011 James Cowgill
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package uk.org.cowgill.james.jircd.commands;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
import uk.org.cowgill.james.jircd.Channel;
import uk.org.cowgill.james.jircd.ChannelMemberMode;
import uk.org.cowgill.james.jircd.Client;
import uk.org.cowgill.james.jircd.Command;
import uk.org.cowgill.james.jircd.IRCMask;
import uk.org.cowgill.james.jircd.Message;
import uk.org.cowgill.james.jircd.Permissions;
import uk.org.cowgill.james.jircd.Server;
/**
* The WHO command - displays information about clients
*
* @author James
*/
public class Who implements Command
{
@Override
public void run(Client client, Message msg)
{
//Get mask
String mask;
boolean operOnly = false;
if(msg.paramCount() == 0)
{
//Force everyone
mask = "*";
}
else
{
//Use given mask
mask = msg.getParam(0);
if(mask.equals("0"))
{
mask = "*";
}
//Check opers only
operOnly = (msg.paramCount() >= 2 && msg.getParam(1).equals("o"));
}
//See invisible peoples
boolean seeInvisible = client.hasPermission(Permissions.seeInvisible);
//Check for chanel
if(mask.charAt(0) == '#')
{
//Print channel members
Channel channel = Server.getServer().getChannel(mask);
if(channel != null)
{
//Print channel members
boolean allSeeing = (channel.lookupMember(client) != null) || seeInvisible;
//Send replies
for(Map.Entry<Client, ChannelMemberMode> other : channel.getMembers().entrySet())
{
//Can see client?
if(allSeeing || findCommonChannel(client, other.getKey()) != null)
Who.sendWhoMsg(client, other.getKey(), channel, other.getValue());
}
}
}
else
{
//Search all clients
Collection<Client> clients;
if(operOnly)
- {
- clients = Server.getServer().getRegisteredClients();
- }
- else
- {
clients = Server.getServer().getIRCOperators();
- }
+ else
+ clients = Server.getServer().getRegisteredClients();
//Do windcard test on all clients in the list
for(Client other : clients)
{
//Check visibility
Channel commonChannel = findCommonChannel(client, other);
if(commonChannel != null || !other.isModeSet('i') || client == other || seeInvisible)
{
if(IRCMask.wildcardCompare(other.id.nick, mask) ||
IRCMask.wildcardCompare(other.id.user, mask) ||
IRCMask.wildcardCompare(other.id.host, mask) ||
IRCMask.wildcardCompare(other.realName, mask))
{
//Send this client
sendWhoMsg(client, other, commonChannel, null);
}
}
}
}
//Send end reply
client.send(client.newNickMessage("315").
appendParam(mask).appendParam("End of /WHO list"));
}
@Override
public int getMinParameters()
{
return 0;
}
@Override
public String getName()
{
return "WHO";
}
@Override
public int getFlags() { return FLAG_NORMAL; }
/**
* Sends a WHO reply to client
*
* @param client client to reply to
* @param other client information is read from
* @param channel common channel (or null if no common channel)
* @param chanMode other's channel mode (or null to find mode)
*/
private static void sendWhoMsg(Client client, Client other, Channel channel, ChannelMemberMode chanMode)
{
//Calculate channel name and mode
String chanName = "*";
if(channel != null)
{
//Get name
chanName = channel.getName();
//Get mode
if(chanMode == null)
{
chanMode = channel.lookupMember(other);
}
}
//Send reply
StringBuilder info = new StringBuilder();
if(other.isAway())
{
info.append('G');
}
else
{
info.append('H');
}
//IRC op prefix
if(other.isModeSet('o') || other.isModeSet('O'))
{
info.append('*');
}
//Chan op prefix
if(chanMode != null)
{
info.append(chanMode.toPrefixString(true));
}
//Final send
client.send(client.newNickMessage("352").
appendParam(chanName).
appendParam(other.id.user).
appendParam(other.id.host).
appendParam(Server.getServer().getConfig().serverName).
appendParam(other.id.nick).
appendParam(info.toString()).
appendParam("0 " + other.realName));
}
/**
* Attempts to find a common channel between 2 clients
*
* @param clientA first client
* @param clientB second client
* @return the common channel or null if there is no common channel
*/
private static Channel findCommonChannel(Client clientA, Client clientB)
{
Set<Channel> chansA = clientA.getChannels();
Set<Channel> chansB = clientB.getChannels();
//Swap so clientB has most channels
if(chansA.size() > chansB.size())
{
Set<Channel> tmp = chansA;
chansB = chansA;
chansA = tmp;
}
//Search for common channels
for(Channel channel : chansA)
{
if(chansB.contains(channel))
{
return channel;
}
}
return null;
}
}
| false | false | null | null |
diff --git a/src/test/java/org/hampelratte/svdrp/util/TimerParserTest.java b/src/test/java/org/hampelratte/svdrp/util/TimerParserTest.java
index 835e127..96e9219 100644
--- a/src/test/java/org/hampelratte/svdrp/util/TimerParserTest.java
+++ b/src/test/java/org/hampelratte/svdrp/util/TimerParserTest.java
@@ -1,221 +1,221 @@
/* $Id$
*
* Copyright (c) 2005, Henrik Niehaus & Lazy Bones development team
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of the project (Lazy Bones) nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package org.hampelratte.svdrp.util;
import static org.junit.Assert.*;
import java.util.Calendar;
import java.util.List;
import org.hampelratte.svdrp.responses.highlevel.VDRTimer;
import org.junit.Before;
import org.junit.Test;
public class TimerParserTest {
private static int day = 1;
static {
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_MONTH, 1);
day = cal.get(Calendar.DAY_OF_MONTH);
}
private final String timerData =
"1 1:1:"+day+":1945:2030:43:67:Doppel|Punkt:Mehrzeilige|nichtssagende|Beschreibung der Sendung mit Doppel:Punkt.\n" +
"2 2:1:2010-11-02:1945:2030:50:50:Tagesschau~Tagesschau am 2.11.2010:\n" +
"3 4:1:MTWTF--:2225:2310:50:50:Tagesthemen:\n" +
"4 8:2:MTWTFSS@"+day+":2130:2227:50:50:heute-journal:\n" +
"5 0:2:M-----S@2010-12-31:2330:0030:50:50:Happy New Year:\n" +
"6 13:2:--W----@2010-11-02:2330:0011:50:50:Ganz spät:";
private List<VDRTimer> timers;
@Before
public void parseTimers() {
timers = TimerParser.parse(timerData);
}
@Test
public void testState() {
assertTrue(timers.get(0).hasState(VDRTimer.ACTIVE));
assertTrue(timers.get(1).hasState(VDRTimer.INSTANT_TIMER));
assertTrue(timers.get(2).hasState(VDRTimer.VPS));
assertTrue(timers.get(3).hasState(VDRTimer.RECORDING));
assertTrue(timers.get(4).hasState(VDRTimer.INACTIVE));
assertTrue(timers.get(5).hasState(VDRTimer.ACTIVE));
assertTrue(timers.get(5).hasState(VDRTimer.VPS));
assertTrue(timers.get(5).hasState(VDRTimer.RECORDING));
assertFalse(timers.get(5).hasState(VDRTimer.INACTIVE));
assertFalse(timers.get(5).hasState(VDRTimer.INSTANT_TIMER));
}
@Test
public void testNumber() {
for (int i = 0; i < timers.size(); i++) {
assertEquals(i+1, timers.get(i).getID());
}
}
@Test
public void testChannel() {
assertEquals(1, timers.get(0).getChannelNumber());
assertEquals(2, timers.get(5).getChannelNumber());
}
@Test
public void testDayParsing() {
VDRTimer timer = timers.get(0);
assertEquals(day, timer.getStartTime().get(Calendar.DAY_OF_MONTH));
}
@Test
public void testDateParsing() {
VDRTimer timer = timers.get(1);
assertEquals(2, timer.getStartTime().get(Calendar.DAY_OF_MONTH));
assertEquals(10, timer.getStartTime().get(Calendar.MONTH)); // 10 because Calendar begins counting with 0 for months
assertEquals(2010, timer.getStartTime().get(Calendar.YEAR));
}
@Test
public void testRepeatingDays() {
VDRTimer timer = timers.get(2);
assertTrue(timer.isRepeating());
assertEquals("MTWTF--", timer.getDayString());
assertTrue(timer.getRepeatingDays()[0]);
assertTrue(timer.getRepeatingDays()[1]);
assertTrue(timer.getRepeatingDays()[2]);
assertTrue(timer.getRepeatingDays()[3]);
assertTrue(timer.getRepeatingDays()[4]);
assertFalse(timer.getRepeatingDays()[5]);
assertFalse(timer.getRepeatingDays()[6]);
}
@Test
public void testRepeatingTimerStartingOnDay() {
VDRTimer timer = timers.get(3);
assertTrue(timer.isRepeating());
- assertEquals(4, timer.getStartTime().get(Calendar.DAY_OF_MONTH));
+ assertEquals(day, timer.getStartTime().get(Calendar.DAY_OF_MONTH));
assertTrue(timer.getRepeatingDays()[0]);
assertTrue(timer.getRepeatingDays()[1]);
assertTrue(timer.getRepeatingDays()[2]);
assertTrue(timer.getRepeatingDays()[3]);
assertTrue(timer.getRepeatingDays()[4]);
assertTrue(timer.getRepeatingDays()[5]);
assertTrue(timer.getRepeatingDays()[6]);
}
@Test
public void testRepeatingTimerStartingOnDate() {
VDRTimer timer = timers.get(4);
assertTrue(timer.isRepeating());
assertEquals(31, timer.getStartTime().get(Calendar.DAY_OF_MONTH));
assertEquals(11, timer.getStartTime().get(Calendar.MONTH)); // 11 because Calendar begins counting with 0 for months
assertEquals(2010, timer.getStartTime().get(Calendar.YEAR));
assertTrue(timer.getRepeatingDays()[0]);
assertFalse(timer.getRepeatingDays()[1]);
assertFalse(timer.getRepeatingDays()[2]);
assertFalse(timer.getRepeatingDays()[3]);
assertFalse(timer.getRepeatingDays()[4]);
assertFalse(timer.getRepeatingDays()[5]);
assertTrue(timer.getRepeatingDays()[6]);
}
@Test
public void testLastToNextDay() {
VDRTimer timer = timers.get(5);
assertEquals(2, timer.getStartTime().get(Calendar.DAY_OF_MONTH));
assertEquals(10, timer.getStartTime().get(Calendar.MONTH)); // 10 because Calendar begins counting with 0 for months
assertEquals(2010, timer.getStartTime().get(Calendar.YEAR));
assertEquals(23, timer.getStartTime().get(Calendar.HOUR_OF_DAY));
assertEquals(30, timer.getStartTime().get(Calendar.MINUTE));
assertEquals(3, timer.getEndTime().get(Calendar.DAY_OF_MONTH));
assertEquals(10, timer.getEndTime().get(Calendar.MONTH)); // 10 because Calendar begins counting with 0 for months
assertEquals(2010, timer.getEndTime().get(Calendar.YEAR));
assertEquals(0, timer.getEndTime().get(Calendar.HOUR_OF_DAY));
assertEquals(11, timer.getEndTime().get(Calendar.MINUTE));
}
@Test
public void testLastToNextYear() {
VDRTimer timer = timers.get(4);
assertEquals(31, timer.getStartTime().get(Calendar.DAY_OF_MONTH));
assertEquals(11, timer.getStartTime().get(Calendar.MONTH)); // 11 because Calendar begins counting with 0 for months
assertEquals(2010, timer.getStartTime().get(Calendar.YEAR));
assertEquals(23, timer.getStartTime().get(Calendar.HOUR_OF_DAY));
assertEquals(30, timer.getStartTime().get(Calendar.MINUTE));
assertEquals(1, timer.getEndTime().get(Calendar.DAY_OF_MONTH));
assertEquals(0, timer.getEndTime().get(Calendar.MONTH)); // 0 because Calendar begins counting with 0 for months
assertEquals(2011, timer.getEndTime().get(Calendar.YEAR));
assertEquals(0, timer.getEndTime().get(Calendar.HOUR_OF_DAY));
assertEquals(30, timer.getEndTime().get(Calendar.MINUTE));
}
@Test
public void testPrio() {
assertEquals(43, timers.get(0).getPriority());
}
@Test
public void testLifetime() {
assertEquals(67, timers.get(0).getLifetime());
}
@Test
public void testTitle() {
assertEquals("Doppel:Punkt", timers.get(0).getTitle());
assertEquals("Tagesschau am 2.11.2010", timers.get(1).getTitle());
}
@Test
public void testPath() {
assertEquals("", timers.get(0).getPath());
assertEquals("Tagesschau", timers.get(1).getPath());
}
@Test
public void testFile() {
assertEquals("Doppel|Punkt", timers.get(0).getFile());
assertEquals("Tagesschau~Tagesschau am 2.11.2010", timers.get(1).getFile());
}
@Test
public void testDescription() {
assertEquals("Mehrzeilige\nnichtssagende\nBeschreibung der Sendung mit Doppel:Punkt.", timers.get(0).getDescription());
}
@Test
public void testToNEWT() {
assertEquals("1:1:"+day+":1945:2030:43:67:Doppel|Punkt:Mehrzeilige|nichtssagende|Beschreibung der Sendung mit Doppel:Punkt.", timers.get(0).toNEWT());
}
}
| true | false | null | null |
diff --git a/activemq-core/src/main/java/org/apache/activemq/broker/region/BaseDestination.java b/activemq-core/src/main/java/org/apache/activemq/broker/region/BaseDestination.java
index a2d3914a5..9b44f9df8 100755
--- a/activemq-core/src/main/java/org/apache/activemq/broker/region/BaseDestination.java
+++ b/activemq-core/src/main/java/org/apache/activemq/broker/region/BaseDestination.java
@@ -1,367 +1,373 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.broker.region;
+import java.io.IOException;
import org.apache.activemq.broker.Broker;
import org.apache.activemq.broker.BrokerService;
import org.apache.activemq.broker.ConnectionContext;
import org.apache.activemq.command.ActiveMQDestination;
import org.apache.activemq.command.ProducerInfo;
import org.apache.activemq.store.MessageStore;
import org.apache.activemq.usage.MemoryUsage;
import org.apache.activemq.usage.SystemUsage;
import org.apache.activemq.usage.Usage;
/**
* @version $Revision: 1.12 $
*/
public abstract class BaseDestination implements Destination {
/**
* The default number of messages to page in to the destination
* from persistent storage
*/
public static final int DEFAULT_PAGE_SIZE=100;
protected final ActiveMQDestination destination;
protected final Broker broker;
protected final MessageStore store;
protected SystemUsage systemUsage;
protected MemoryUsage memoryUsage;
private boolean producerFlowControl = true;
private int maxProducersToAudit=1024;
private int maxAuditDepth=2048;
private boolean enableAudit=true;
private int maxPageSize=DEFAULT_PAGE_SIZE;
private boolean useCache=true;
private int minimumMessageSize=1024;
private boolean lazyDispatch=false;
private boolean advisoryForSlowConsumers;
private boolean advisdoryForFastProducers;
private boolean advisoryForDiscardingMessages;
private boolean advisoryWhenFull;
private boolean advisoryForDelivery;
private boolean advisoryForConsumed;
protected final DestinationStatistics destinationStatistics = new DestinationStatistics();
protected final BrokerService brokerService;
protected final Broker regionBroker;
/**
* @param broker
* @param store
* @param destination
* @param parentStats
* @throws Exception
*/
public BaseDestination(BrokerService brokerService,MessageStore store, ActiveMQDestination destination, DestinationStatistics parentStats) throws Exception {
this.brokerService = brokerService;
this.broker=brokerService.getBroker();
this.store=store;
this.destination=destination;
// let's copy the enabled property from the parent DestinationStatistics
this.destinationStatistics.setEnabled(parentStats.isEnabled());
this.destinationStatistics.setParent(parentStats);
this.systemUsage = brokerService.getProducerSystemUsage();
this.memoryUsage = new MemoryUsage(systemUsage.getMemoryUsage(), destination.toString());
this.memoryUsage.setUsagePortion(1.0f);
this.regionBroker = brokerService.getRegionBroker();
}
/**
* initialize the destination
* @throws Exception
*/
public void initialize() throws Exception {
// Let the store know what usage manager we are using so that he can
// flush messages to disk when usage gets high.
if (store != null) {
store.setMemoryUsage(this.memoryUsage);
}
}
/**
* @return the producerFlowControl
*/
public boolean isProducerFlowControl() {
return producerFlowControl;
}
/**
* @param producerFlowControl the producerFlowControl to set
*/
public void setProducerFlowControl(boolean producerFlowControl) {
this.producerFlowControl = producerFlowControl;
}
/**
* @return the maxProducersToAudit
*/
public int getMaxProducersToAudit() {
return maxProducersToAudit;
}
/**
* @param maxProducersToAudit the maxProducersToAudit to set
*/
public void setMaxProducersToAudit(int maxProducersToAudit) {
this.maxProducersToAudit = maxProducersToAudit;
}
/**
* @return the maxAuditDepth
*/
public int getMaxAuditDepth() {
return maxAuditDepth;
}
/**
* @param maxAuditDepth the maxAuditDepth to set
*/
public void setMaxAuditDepth(int maxAuditDepth) {
this.maxAuditDepth = maxAuditDepth;
}
/**
* @return the enableAudit
*/
public boolean isEnableAudit() {
return enableAudit;
}
/**
* @param enableAudit the enableAudit to set
*/
public void setEnableAudit(boolean enableAudit) {
this.enableAudit = enableAudit;
}
public void addProducer(ConnectionContext context, ProducerInfo info) throws Exception{
destinationStatistics.getProducers().increment();
}
public void removeProducer(ConnectionContext context, ProducerInfo info) throws Exception{
destinationStatistics.getProducers().decrement();
}
public final MemoryUsage getMemoryUsage() {
return memoryUsage;
}
public DestinationStatistics getDestinationStatistics() {
return destinationStatistics;
}
public ActiveMQDestination getActiveMQDestination() {
return destination;
}
public final String getName() {
return getActiveMQDestination().getPhysicalName();
}
public final MessageStore getMessageStore() {
return store;
}
public final boolean isActive() {
return destinationStatistics.getConsumers().getCount() != 0 ||
destinationStatistics.getProducers().getCount() != 0;
}
public int getMaxPageSize() {
return maxPageSize;
}
public void setMaxPageSize(int maxPageSize) {
this.maxPageSize = maxPageSize;
}
public boolean isUseCache() {
return useCache;
}
public void setUseCache(boolean useCache) {
this.useCache = useCache;
}
public int getMinimumMessageSize() {
return minimumMessageSize;
}
public void setMinimumMessageSize(int minimumMessageSize) {
this.minimumMessageSize = minimumMessageSize;
}
public boolean isLazyDispatch() {
return lazyDispatch;
}
public void setLazyDispatch(boolean lazyDispatch) {
this.lazyDispatch = lazyDispatch;
}
protected long getDestinationSequenceId() {
return regionBroker.getBrokerSequenceId();
}
/**
* @return the advisoryForSlowConsumers
*/
public boolean isAdvisoryForSlowConsumers() {
return advisoryForSlowConsumers;
}
/**
* @param advisoryForSlowConsumers the advisoryForSlowConsumers to set
*/
public void setAdvisoryForSlowConsumers(boolean advisoryForSlowConsumers) {
this.advisoryForSlowConsumers = advisoryForSlowConsumers;
}
/**
* @return the advisoryForDiscardingMessages
*/
public boolean isAdvisoryForDiscardingMessages() {
return advisoryForDiscardingMessages;
}
/**
* @param advisoryForDiscardingMessages the advisoryForDiscardingMessages to set
*/
public void setAdvisoryForDiscardingMessages(
boolean advisoryForDiscardingMessages) {
this.advisoryForDiscardingMessages = advisoryForDiscardingMessages;
}
/**
* @return the advisoryWhenFull
*/
public boolean isAdvisoryWhenFull() {
return advisoryWhenFull;
}
/**
* @param advisoryWhenFull the advisoryWhenFull to set
*/
public void setAdvisoryWhenFull(boolean advisoryWhenFull) {
this.advisoryWhenFull = advisoryWhenFull;
}
/**
* @return the advisoryForDelivery
*/
public boolean isAdvisoryForDelivery() {
return advisoryForDelivery;
}
/**
* @param advisoryForDelivery the advisoryForDelivery to set
*/
public void setAdvisoryForDelivery(boolean advisoryForDelivery) {
this.advisoryForDelivery = advisoryForDelivery;
}
/**
* @return the advisoryForConsumed
*/
public boolean isAdvisoryForConsumed() {
return advisoryForConsumed;
}
/**
* @param advisoryForConsumed the advisoryForConsumed to set
*/
public void setAdvisoryForConsumed(boolean advisoryForConsumed) {
this.advisoryForConsumed = advisoryForConsumed;
}
/**
* @return the advisdoryForFastProducers
*/
public boolean isAdvisdoryForFastProducers() {
return advisdoryForFastProducers;
}
/**
* @param advisdoryForFastProducers the advisdoryForFastProducers to set
*/
public void setAdvisdoryForFastProducers(boolean advisdoryForFastProducers) {
this.advisdoryForFastProducers = advisdoryForFastProducers;
}
/**
* called when message is consumed
* @param context
* @param messageReference
*/
public void messageConsumed(ConnectionContext context, MessageReference messageReference) {
if (advisoryForConsumed) {
broker.messageConsumed(context, messageReference);
}
}
/**
* Called when message is delivered to the broker
* @param context
* @param messageReference
*/
public void messageDelivered(ConnectionContext context, MessageReference messageReference) {
if(advisoryForDelivery) {
broker.messageDelivered(context, messageReference);
}
}
/**
* Called when a message is discarded - e.g. running low on memory
* This will happen only if the policy is enabled - e.g. non durable topics
* @param context
* @param messageReference
*/
public void messageDiscarded(ConnectionContext context, MessageReference messageReference) {
if (advisoryForDiscardingMessages) {
broker.messageDiscarded(context, messageReference);
}
}
/**
* Called when there is a slow consumer
* @param context
* @param subs
*/
public void slowConsumer(ConnectionContext context, Subscription subs) {
if(advisoryForSlowConsumers) {
broker.slowConsumer(context, this, subs);
}
}
/**
* Called to notify a producer is too fast
* @param context
* @param producerInfo
*/
public void fastProducer(ConnectionContext context,ProducerInfo producerInfo) {
if(advisdoryForFastProducers) {
broker.fastProducer(context, producerInfo);
}
}
/**
* Called when a Usage reaches a limit
* @param context
* @param usage
*/
public void isFull(ConnectionContext context,Usage usage) {
if(advisoryWhenFull) {
broker.isFull(context,this, usage);
}
}
+
+ public void dispose(ConnectionContext context) throws IOException {
+ destinationStatistics.setParent(null);
+ this.memoryUsage.stop();
+ }
}
diff --git a/activemq-core/src/main/java/org/apache/activemq/broker/region/Queue.java b/activemq-core/src/main/java/org/apache/activemq/broker/region/Queue.java
index 247b674e9..ba043f780 100755
--- a/activemq-core/src/main/java/org/apache/activemq/broker/region/Queue.java
+++ b/activemq-core/src/main/java/org/apache/activemq/broker/region/Queue.java
@@ -1,1230 +1,1230 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.broker.region;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.locks.ReentrantLock;
import javax.jms.InvalidSelectorException;
import javax.jms.JMSException;
import org.apache.activemq.broker.BrokerService;
import org.apache.activemq.broker.ConnectionContext;
import org.apache.activemq.broker.ProducerBrokerExchange;
import org.apache.activemq.broker.region.cursors.PendingMessageCursor;
import org.apache.activemq.broker.region.cursors.StoreQueueCursor;
import org.apache.activemq.broker.region.cursors.VMPendingMessageCursor;
import org.apache.activemq.broker.region.group.MessageGroupHashBucketFactory;
import org.apache.activemq.broker.region.group.MessageGroupMap;
import org.apache.activemq.broker.region.group.MessageGroupMapFactory;
import org.apache.activemq.broker.region.group.MessageGroupSet;
import org.apache.activemq.broker.region.policy.DeadLetterStrategy;
import org.apache.activemq.broker.region.policy.DispatchPolicy;
import org.apache.activemq.broker.region.policy.RoundRobinDispatchPolicy;
import org.apache.activemq.broker.region.policy.SharedDeadLetterStrategy;
import org.apache.activemq.command.ActiveMQDestination;
import org.apache.activemq.command.ConsumerId;
import org.apache.activemq.command.ExceptionResponse;
import org.apache.activemq.command.Message;
import org.apache.activemq.command.MessageAck;
import org.apache.activemq.command.MessageId;
import org.apache.activemq.command.ProducerAck;
import org.apache.activemq.command.ProducerInfo;
import org.apache.activemq.command.Response;
import org.apache.activemq.filter.BooleanExpression;
import org.apache.activemq.filter.MessageEvaluationContext;
import org.apache.activemq.filter.NonCachedMessageEvaluationContext;
import org.apache.activemq.selector.SelectorParser;
import org.apache.activemq.store.MessageRecoveryListener;
import org.apache.activemq.store.MessageStore;
import org.apache.activemq.thread.DeterministicTaskRunner;
import org.apache.activemq.thread.Task;
import org.apache.activemq.thread.TaskRunner;
import org.apache.activemq.thread.TaskRunnerFactory;
import org.apache.activemq.transaction.Synchronization;
import org.apache.activemq.util.BrokerSupport;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* The Queue is a List of MessageEntry objects that are dispatched to matching
* subscriptions.
*
* @version $Revision: 1.28 $
*/
public class Queue extends BaseDestination implements Task {
protected static final Log LOG = LogFactory.getLog(Queue.class);
protected TaskRunnerFactory taskFactory;
protected TaskRunner taskRunner;
protected final List<Subscription> consumers = new ArrayList<Subscription>(50);
protected PendingMessageCursor messages;
private final LinkedHashMap<MessageId,QueueMessageReference> pagedInMessages = new LinkedHashMap<MessageId,QueueMessageReference>();
private MessageGroupMap messageGroupOwners;
private DispatchPolicy dispatchPolicy = new RoundRobinDispatchPolicy();
private DeadLetterStrategy deadLetterStrategy = new SharedDeadLetterStrategy();
private MessageGroupMapFactory messageGroupMapFactory = new MessageGroupHashBucketFactory();
private final Object sendLock = new Object();
private ExecutorService executor;
protected final LinkedList<Runnable> messagesWaitingForSpace = new LinkedList<Runnable>();
private final ReentrantLock dispatchLock = new ReentrantLock();
private boolean useConsumerPriority=true;
private boolean strictOrderDispatch=false;
private QueueDispatchSelector dispatchSelector;
private boolean optimizedDispatch=false;
private final Runnable sendMessagesWaitingForSpaceTask = new Runnable() {
public void run() {
wakeup();
}
};
private final Object iteratingMutex = new Object() {};
private static final Comparator<Subscription>orderedCompare = new Comparator<Subscription>() {
public int compare(Subscription s1, Subscription s2) {
//We want the list sorted in descending order
return s2.getConsumerInfo().getPriority() - s1.getConsumerInfo().getPriority();
}
};
public Queue(BrokerService brokerService, final ActiveMQDestination destination, MessageStore store,DestinationStatistics parentStats,
TaskRunnerFactory taskFactory) throws Exception {
super(brokerService, store, destination, parentStats);
this.taskFactory=taskFactory;
this.dispatchSelector=new QueueDispatchSelector(destination);
}
public void initialize() throws Exception {
if (this.messages == null) {
if (destination.isTemporary() || broker == null || store == null) {
this.messages = new VMPendingMessageCursor();
} else {
this.messages = new StoreQueueCursor(broker, this);
}
}
// If a VMPendingMessageCursor don't use the default Producer System Usage
// since it turns into a shared blocking queue which can lead to a network deadlock.
// If we are ccursoring to disk..it's not and issue because it does not block due
// to large disk sizes.
if( messages instanceof VMPendingMessageCursor ) {
this.systemUsage = brokerService.getSystemUsage();
memoryUsage.setParent(systemUsage.getMemoryUsage());
}
if (isOptimizedDispatch()) {
this.taskRunner = taskFactory.createTaskRunner(this, "TempQueue: " + destination.getPhysicalName());
}else {
this.executor = Executors.newSingleThreadExecutor(new ThreadFactory() {
public Thread newThread(Runnable runnable) {
Thread thread = new Thread(runnable, "QueueThread:"+destination);
thread.setDaemon(true);
thread.setPriority(Thread.NORM_PRIORITY);
return thread;
}
});
this.taskRunner = new DeterministicTaskRunner(this.executor,this);
}
super.initialize();
if (store != null) {
// Restore the persistent messages.
messages.setSystemUsage(systemUsage);
messages.setEnableAudit(isEnableAudit());
messages.setMaxAuditDepth(getMaxAuditDepth());
messages.setMaxProducersToAudit(getMaxProducersToAudit());
messages.setUseCache(isUseCache());
if (messages.isRecoveryRequired()) {
store.recover(new MessageRecoveryListener() {
public boolean recoverMessage(Message message) {
// Message could have expired while it was being
// loaded..
if (broker.isExpired(message)) {
broker.messageExpired(createConnectionContext(), message);
destinationStatistics.getMessages().decrement();
return true;
}
if (hasSpace()) {
message.setRegionDestination(Queue.this);
synchronized (messages) {
try {
messages.addMessageLast(message);
} catch (Exception e) {
LOG.fatal("Failed to add message to cursor", e);
}
}
destinationStatistics.getMessages().increment();
return true;
}
return false;
}
public boolean recoverMessageReference(MessageId messageReference) throws Exception {
throw new RuntimeException("Should not be called.");
}
public boolean hasSpace() {
return true;
}
});
}else {
int messageCount = store.getMessageCount();
destinationStatistics.getMessages().setCount(messageCount);
}
}
}
class RecoveryDispatch {
public ArrayList<QueueMessageReference> messages;
public Subscription subscription;
}
LinkedList<RecoveryDispatch> recoveries = new LinkedList<RecoveryDispatch>();
public void addSubscription(ConnectionContext context, Subscription sub) throws Exception {
dispatchLock.lock();
try {
sub.add(context, this);
destinationStatistics.getConsumers().increment();
// MessageEvaluationContext msgContext = new NonCachedMessageEvaluationContext();
// needs to be synchronized - so no contention with dispatching
synchronized (consumers) {
addToConsumerList(sub);
if (sub.getConsumerInfo().isExclusive()) {
Subscription exclusiveConsumer = dispatchSelector.getExclusiveConsumer();
if(exclusiveConsumer==null) {
exclusiveConsumer=sub;
}else if (sub.getConsumerInfo().getPriority() > exclusiveConsumer.getConsumerInfo().getPriority()){
exclusiveConsumer=sub;
}
dispatchSelector.setExclusiveConsumer(exclusiveConsumer);
}
}
// synchronize with dispatch method so that no new messages are sent
// while
// setting up a subscription. avoid out of order messages,
// duplicates
// etc.
doPageIn(false);
// msgContext.setDestination(destination);
synchronized (pagedInMessages) {
RecoveryDispatch rd = new RecoveryDispatch();
rd.messages = new ArrayList<QueueMessageReference>(pagedInMessages.values());
rd.subscription = sub;
recoveries.addLast(rd);
}
if( sub instanceof QueueBrowserSubscription ) {
((QueueBrowserSubscription)sub).incrementQueueRef();
}
// System.out.println(new Date()+": Locked pagedInMessages: "+sub.getConsumerInfo().getConsumerId());
// // Add all the matching messages in the queue to the
// // subscription.
//
// for (QueueMessageReference node:pagedInMessages.values()){
// if (!node.isDropped() && !node.isAcked() && (!node.isDropped() ||sub.getConsumerInfo().isBrowser())) {
// msgContext.setMessageReference(node);
// if (sub.matches(node, msgContext)) {
// sub.add(node);
// }
// }
// }
//
// }
wakeup();
}finally {
dispatchLock.unlock();
}
}
public void removeSubscription(ConnectionContext context, Subscription sub)
throws Exception {
destinationStatistics.getConsumers().decrement();
dispatchLock.lock();
try {
// synchronize with dispatch method so that no new messages are sent
// while
// removing up a subscription.
synchronized (consumers) {
removeFromConsumerList(sub);
if (sub.getConsumerInfo().isExclusive()) {
Subscription exclusiveConsumer = dispatchSelector
.getExclusiveConsumer();
if (exclusiveConsumer == sub) {
exclusiveConsumer = null;
for (Subscription s : consumers) {
if (s.getConsumerInfo().isExclusive()
&& (exclusiveConsumer == null
|| s.getConsumerInfo().getPriority() > exclusiveConsumer
.getConsumerInfo().getPriority())) {
exclusiveConsumer = s;
}
}
dispatchSelector.setExclusiveConsumer(exclusiveConsumer);
}
}
ConsumerId consumerId = sub.getConsumerInfo().getConsumerId();
MessageGroupSet ownedGroups = getMessageGroupOwners()
.removeConsumer(consumerId);
// redeliver inflight messages
List<QueueMessageReference> list = new ArrayList<QueueMessageReference>();
for (MessageReference ref : sub.remove(context, this)) {
QueueMessageReference qmr = (QueueMessageReference)ref;
qmr.incrementRedeliveryCounter();
if( qmr.getLockOwner()==sub ) {
qmr.unlock();
qmr.incrementRedeliveryCounter();
}
list.add(qmr);
}
if (!list.isEmpty() && !consumers.isEmpty()) {
doDispatch(list);
}
}
if (consumers.isEmpty()) {
messages.gc();
}
wakeup();
}finally {
dispatchLock.unlock();
}
}
public void send(final ProducerBrokerExchange producerExchange, final Message message) throws Exception {
final ConnectionContext context = producerExchange.getConnectionContext();
// There is delay between the client sending it and it arriving at the
// destination.. it may have expired.
message.setRegionDestination(this);
final ProducerInfo producerInfo = producerExchange.getProducerState().getInfo();
final boolean sendProducerAck = !message.isResponseRequired() && producerInfo.getWindowSize() > 0 && !context.isInRecoveryMode();
if (message.isExpired()) {
broker.getRoot().messageExpired(context, message);
//message not added to stats yet
//destinationStatistics.getMessages().decrement();
if (sendProducerAck) {
ProducerAck ack = new ProducerAck(producerInfo.getProducerId(), message.getSize());
context.getConnection().dispatchAsync(ack);
}
return;
}
if(memoryUsage.isFull()) {
isFull(context, memoryUsage);
fastProducer(context, producerInfo);
if (isProducerFlowControl() && context.isProducerFlowControl()) {
if (systemUsage.isSendFailIfNoSpace()) {
throw new javax.jms.ResourceAllocationException("SystemUsage memory limit reached");
}
// We can avoid blocking due to low usage if the producer is sending
// a sync message or
// if it is using a producer window
if (producerInfo.getWindowSize() > 0 || message.isResponseRequired()) {
synchronized (messagesWaitingForSpace) {
messagesWaitingForSpace.add(new Runnable() {
public void run() {
try {
// While waiting for space to free up... the
// message may have expired.
if (broker.isExpired(message)) {
broker.messageExpired(context, message);
//message not added to stats yet
//destinationStatistics.getMessages().decrement();
} else {
doMessageSend(producerExchange, message);
}
if (sendProducerAck) {
ProducerAck ack = new ProducerAck(producerInfo.getProducerId(), message.getSize());
context.getConnection().dispatchAsync(ack);
} else {
Response response = new Response();
response.setCorrelationId(message.getCommandId());
context.getConnection().dispatchAsync(response);
}
} catch (Exception e) {
if (!sendProducerAck && !context.isInRecoveryMode()) {
ExceptionResponse response = new ExceptionResponse(e);
response.setCorrelationId(message.getCommandId());
context.getConnection().dispatchAsync(response);
}
}
}
});
// If the user manager is not full, then the task will not
// get called..
if (!memoryUsage.notifyCallbackWhenNotFull(sendMessagesWaitingForSpaceTask)) {
// so call it directly here.
sendMessagesWaitingForSpaceTask.run();
}
context.setDontSendReponse(true);
return;
}
} else {
// Producer flow control cannot be used, so we have do the flow
// control at the broker
// by blocking this thread until there is space available.
while (!memoryUsage.waitForSpace(1000)) {
if (context.getStopping().get()) {
throw new IOException("Connection closed, send aborted.");
}
}
// The usage manager could have delayed us by the time
// we unblock the message could have expired..
if (message.isExpired()) {
if (LOG.isDebugEnabled()) {
LOG.debug("Expired message: " + message);
}
broker.getRoot().messageExpired(context, message);
return;
}
}
}
}
doMessageSend(producerExchange, message);
if (sendProducerAck) {
ProducerAck ack = new ProducerAck(producerInfo.getProducerId(), message.getSize());
context.getConnection().dispatchAsync(ack);
}
}
void doMessageSend(final ProducerBrokerExchange producerExchange, final Message message) throws IOException, Exception {
final ConnectionContext context = producerExchange.getConnectionContext();
synchronized (sendLock) {
if (store != null && message.isPersistent()) {
if (isProducerFlowControl() && context.isProducerFlowControl() ) {
if (systemUsage.isSendFailIfNoSpace() && systemUsage.getStoreUsage().isFull()) {
throw new javax.jms.ResourceAllocationException("Usage Manager Store is Full");
}
}
while (!systemUsage.getStoreUsage().waitForSpace(1000)) {
if (context.getStopping().get()) {
throw new IOException(
"Connection closed, send aborted.");
}
}
message.getMessageId().setBrokerSequenceId(getDestinationSequenceId());
store.addMessage(context, message);
}
}
if (context.isInTransaction()) {
// If this is a transacted message.. increase the usage now so that
// a big TX does not blow up
// our memory. This increment is decremented once the tx finishes..
message.incrementReferenceCount();
context.getTransaction().addSynchronization(new Synchronization() {
public void afterCommit() throws Exception {
try {
// It could take while before we receive the commit
// op, by that time the message could have expired..
if (broker.isExpired(message)) {
broker.messageExpired(context, message);
//message not added to stats yet
//destinationStatistics.getMessages().decrement();
return;
}
sendMessage(context, message);
} finally {
message.decrementReferenceCount();
}
}
@Override
public void afterRollback() throws Exception {
message.decrementReferenceCount();
}
});
} else {
// Add to the pending list, this takes care of incrementing the
// usage manager.
sendMessage(context, message);
}
}
public void dispose(ConnectionContext context) throws IOException {
+ super.dispose(context);
if (store != null) {
store.removeAllMessages(context);
}
- destinationStatistics.setParent(null);
}
public void gc(){
}
public void acknowledge(ConnectionContext context, Subscription sub, MessageAck ack, MessageReference node) throws IOException {
messageConsumed(context, node);
if (store != null && node.isPersistent()) {
// the original ack may be a ranged ack, but we are trying to delete
// a specific
// message store here so we need to convert to a non ranged ack.
if (ack.getMessageCount() > 0) {
// Dup the ack
MessageAck a = new MessageAck();
ack.copy(a);
ack = a;
// Convert to non-ranged.
ack.setFirstMessageId(node.getMessageId());
ack.setLastMessageId(node.getMessageId());
ack.setMessageCount(1);
}
store.removeMessage(context, ack);
}
}
Message loadMessage(MessageId messageId) throws IOException {
Message msg = store.getMessage(messageId);
if (msg != null) {
msg.setRegionDestination(this);
}
return msg;
}
public String toString() {
int size = 0;
synchronized (messages) {
size = messages.size();
}
return "Queue: destination=" + destination.getPhysicalName() + ", subscriptions=" + consumers.size() + ", memory=" + memoryUsage.getPercentUsage() + "%, size=" + size
+ ", in flight groups=" + messageGroupOwners;
}
public void start() throws Exception {
if (memoryUsage != null) {
memoryUsage.start();
}
messages.start();
doPageIn(false);
}
public void stop() throws Exception{
if (taskRunner != null) {
taskRunner.shutdown();
}
if (this.executor != null) {
this.executor.shutdownNow();
}
if (messages != null) {
messages.stop();
}
if (memoryUsage != null) {
memoryUsage.stop();
}
}
// Properties
// -------------------------------------------------------------------------
public ActiveMQDestination getActiveMQDestination() {
return destination;
}
public MessageGroupMap getMessageGroupOwners() {
if (messageGroupOwners == null) {
messageGroupOwners = getMessageGroupMapFactory().createMessageGroupMap();
}
return messageGroupOwners;
}
public DispatchPolicy getDispatchPolicy() {
return dispatchPolicy;
}
public void setDispatchPolicy(DispatchPolicy dispatchPolicy) {
this.dispatchPolicy = dispatchPolicy;
}
public DeadLetterStrategy getDeadLetterStrategy() {
return deadLetterStrategy;
}
public void setDeadLetterStrategy(DeadLetterStrategy deadLetterStrategy) {
this.deadLetterStrategy = deadLetterStrategy;
}
public MessageGroupMapFactory getMessageGroupMapFactory() {
return messageGroupMapFactory;
}
public void setMessageGroupMapFactory(MessageGroupMapFactory messageGroupMapFactory) {
this.messageGroupMapFactory = messageGroupMapFactory;
}
public PendingMessageCursor getMessages() {
return this.messages;
}
public void setMessages(PendingMessageCursor messages) {
this.messages = messages;
}
public boolean isUseConsumerPriority() {
return useConsumerPriority;
}
public void setUseConsumerPriority(boolean useConsumerPriority) {
this.useConsumerPriority = useConsumerPriority;
}
public boolean isStrictOrderDispatch() {
return strictOrderDispatch;
}
public void setStrictOrderDispatch(boolean strictOrderDispatch) {
this.strictOrderDispatch = strictOrderDispatch;
}
public boolean isOptimizedDispatch() {
return optimizedDispatch;
}
public void setOptimizedDispatch(boolean optimizedDispatch) {
this.optimizedDispatch = optimizedDispatch;
}
// Implementation methods
// -------------------------------------------------------------------------
private QueueMessageReference createMessageReference(Message message) {
QueueMessageReference result = new IndirectMessageReference(message);
return result;
}
public Message[] browse() {
List<Message> l = new ArrayList<Message>();
try {
doPageIn(true);
} catch (Exception e) {
LOG.error("caught an exception browsing " + this, e);
}
synchronized (pagedInMessages) {
for (QueueMessageReference node:pagedInMessages.values()){
node.incrementReferenceCount();
try {
Message m = node.getMessage();
if (m != null) {
l.add(m);
}
} catch (IOException e) {
LOG.error("caught an exception browsing " + this, e);
} finally {
node.decrementReferenceCount();
}
}
}
synchronized (messages) {
try {
messages.reset();
while (messages.hasNext()) {
try {
MessageReference r = messages.next();
r.incrementReferenceCount();
try {
Message m = r.getMessage();
if (m != null) {
l.add(m);
}
} finally {
r.decrementReferenceCount();
}
} catch (IOException e) {
LOG.error("caught an exception brwsing " + this, e);
}
}
} finally {
messages.release();
}
}
return l.toArray(new Message[l.size()]);
}
public Message getMessage(String messageId) {
synchronized (messages) {
try {
messages.reset();
while (messages.hasNext()) {
try {
MessageReference r = messages.next();
if (messageId.equals(r.getMessageId().toString())) {
r.incrementReferenceCount();
try {
Message m = r.getMessage();
if (m != null) {
return m;
}
} finally {
r.decrementReferenceCount();
}
break;
}
} catch (IOException e) {
LOG.error("got an exception retrieving message " + messageId);
}
}
} finally {
messages.release();
}
}
return null;
}
public void purge() throws Exception {
ConnectionContext c = createConnectionContext();
List<MessageReference> list = null;
do {
pageInMessages();
synchronized (pagedInMessages) {
list = new ArrayList<MessageReference>(pagedInMessages.values());
}
for (MessageReference ref : list) {
try {
QueueMessageReference r = (QueueMessageReference) ref;
removeMessage(c,(IndirectMessageReference) r);
} catch (IOException e) {
}
}
} while (!pagedInMessages.isEmpty() || this.destinationStatistics.getMessages().getCount() > 0);
gc();
}
/**
* Removes the message matching the given messageId
*/
public boolean removeMessage(String messageId) throws Exception {
return removeMatchingMessages(createMessageIdFilter(messageId), 1) > 0;
}
/**
* Removes the messages matching the given selector
*
* @return the number of messages removed
*/
public int removeMatchingMessages(String selector) throws Exception {
return removeMatchingMessages(selector, -1);
}
/**
* Removes the messages matching the given selector up to the maximum number
* of matched messages
*
* @return the number of messages removed
*/
public int removeMatchingMessages(String selector, int maximumMessages) throws Exception {
return removeMatchingMessages(createSelectorFilter(selector), maximumMessages);
}
/**
* Removes the messages matching the given filter up to the maximum number
* of matched messages
*
* @return the number of messages removed
*/
public int removeMatchingMessages(MessageReferenceFilter filter, int maximumMessages) throws Exception {
int movedCounter = 0;
Set<MessageReference> set = new CopyOnWriteArraySet<MessageReference>();
ConnectionContext context = createConnectionContext();
do {
pageInMessages();
synchronized (pagedInMessages) {
set.addAll(pagedInMessages.values());
}
List <MessageReference>list = new ArrayList<MessageReference>(set);
for (MessageReference ref : list) {
IndirectMessageReference r = (IndirectMessageReference) ref;
if (filter.evaluate(context, r)) {
removeMessage(context, r);
set.remove(r);
if (++movedCounter >= maximumMessages
&& maximumMessages > 0) {
return movedCounter;
}
}
}
} while (set.size() < this.destinationStatistics.getMessages().getCount());
return movedCounter;
}
/**
* Copies the message matching the given messageId
*/
public boolean copyMessageTo(ConnectionContext context, String messageId, ActiveMQDestination dest) throws Exception {
return copyMatchingMessages(context, createMessageIdFilter(messageId), dest, 1) > 0;
}
/**
* Copies the messages matching the given selector
*
* @return the number of messages copied
*/
public int copyMatchingMessagesTo(ConnectionContext context, String selector, ActiveMQDestination dest) throws Exception {
return copyMatchingMessagesTo(context, selector, dest, -1);
}
/**
* Copies the messages matching the given selector up to the maximum number
* of matched messages
*
* @return the number of messages copied
*/
public int copyMatchingMessagesTo(ConnectionContext context, String selector, ActiveMQDestination dest, int maximumMessages) throws Exception {
return copyMatchingMessages(context, createSelectorFilter(selector), dest, maximumMessages);
}
/**
* Copies the messages matching the given filter up to the maximum number of
* matched messages
*
* @return the number of messages copied
*/
public int copyMatchingMessages(ConnectionContext context, MessageReferenceFilter filter, ActiveMQDestination dest, int maximumMessages) throws Exception {
int movedCounter = 0;
int count = 0;
Set<MessageReference> set = new CopyOnWriteArraySet<MessageReference>();
do {
int oldMaxSize=getMaxPageSize();
setMaxPageSize((int) this.destinationStatistics.getMessages().getCount());
pageInMessages();
setMaxPageSize(oldMaxSize);
synchronized (pagedInMessages) {
set.addAll(pagedInMessages.values());
}
List <MessageReference>list = new ArrayList<MessageReference>(set);
for (MessageReference ref : list) {
IndirectMessageReference r = (IndirectMessageReference) ref;
if (filter.evaluate(context, r)) {
r.incrementReferenceCount();
try {
Message m = r.getMessage();
BrokerSupport.resend(context, m, dest);
if (++movedCounter >= maximumMessages
&& maximumMessages > 0) {
return movedCounter;
}
} finally {
r.decrementReferenceCount();
}
}
count++;
}
} while (count < this.destinationStatistics.getMessages().getCount());
return movedCounter;
}
/**
* Moves the message matching the given messageId
*/
public boolean moveMessageTo(ConnectionContext context, String messageId, ActiveMQDestination dest) throws Exception {
return moveMatchingMessagesTo(context, createMessageIdFilter(messageId), dest, 1) > 0;
}
/**
* Moves the messages matching the given selector
*
* @return the number of messages removed
*/
public int moveMatchingMessagesTo(ConnectionContext context, String selector, ActiveMQDestination dest) throws Exception {
return moveMatchingMessagesTo(context, selector, dest, -1);
}
/**
* Moves the messages matching the given selector up to the maximum number
* of matched messages
*/
public int moveMatchingMessagesTo(ConnectionContext context, String selector, ActiveMQDestination dest, int maximumMessages) throws Exception {
return moveMatchingMessagesTo(context, createSelectorFilter(selector), dest, maximumMessages);
}
/**
* Moves the messages matching the given filter up to the maximum number of
* matched messages
*/
public int moveMatchingMessagesTo(ConnectionContext context,MessageReferenceFilter filter, ActiveMQDestination dest,int maximumMessages) throws Exception {
int movedCounter = 0;
Set<MessageReference> set = new CopyOnWriteArraySet<MessageReference>();
do {
pageInMessages();
synchronized (pagedInMessages) {
set.addAll(pagedInMessages.values());
}
List <MessageReference>list = new ArrayList<MessageReference>(set);
for (MessageReference ref:list) {
IndirectMessageReference r = (IndirectMessageReference) ref;
if (filter.evaluate(context, r)) {
// We should only move messages that can be locked.
r.incrementReferenceCount();
try {
Message m = r.getMessage();
BrokerSupport.resend(context, m, dest);
removeMessage(context, r);
set.remove(r);
if (++movedCounter >= maximumMessages
&& maximumMessages > 0) {
return movedCounter;
}
} finally {
r.decrementReferenceCount();
}
}
}
} while (set.size() < this.destinationStatistics.getMessages().getCount());
return movedCounter;
}
RecoveryDispatch getNextRecoveryDispatch() {
synchronized (pagedInMessages) {
if( recoveries.isEmpty() ) {
return null;
}
return recoveries.removeFirst();
}
}
protected boolean isRecoveryDispatchEmpty() {
synchronized (pagedInMessages) {
return recoveries.isEmpty();
}
}
/**
* @return true if we would like to iterate again
* @see org.apache.activemq.thread.Task#iterate()
*/
public boolean iterate() {
synchronized(iteratingMutex) {
RecoveryDispatch rd;
while ((rd = getNextRecoveryDispatch()) != null) {
try {
MessageEvaluationContext msgContext = new NonCachedMessageEvaluationContext();
msgContext.setDestination(destination);
for (QueueMessageReference node : rd.messages) {
if (!node.isDropped() && !node.isAcked() && (!node.isDropped() || rd.subscription.getConsumerInfo().isBrowser())) {
msgContext.setMessageReference(node);
if (rd.subscription.matches(node, msgContext)) {
rd.subscription.add(node);
}
}
}
if( rd.subscription instanceof QueueBrowserSubscription ) {
((QueueBrowserSubscription)rd.subscription).decrementQueueRef();
}
} catch (Exception e) {
e.printStackTrace();
}
}
boolean result = false;
synchronized (messages) {
result = !messages.isEmpty();
}
if (result) {
try {
pageInMessages(false);
} catch (Throwable e) {
LOG.error("Failed to page in more queue messages ", e);
}
}
synchronized(messagesWaitingForSpace) {
while (!messagesWaitingForSpace.isEmpty() && !memoryUsage.isFull()) {
Runnable op = messagesWaitingForSpace.removeFirst();
op.run();
}
}
return false;
}
}
protected MessageReferenceFilter createMessageIdFilter(final String messageId) {
return new MessageReferenceFilter() {
public boolean evaluate(ConnectionContext context, MessageReference r) {
return messageId.equals(r.getMessageId().toString());
}
};
}
protected MessageReferenceFilter createSelectorFilter(String selector) throws InvalidSelectorException {
final BooleanExpression selectorExpression = new SelectorParser().parse(selector);
return new MessageReferenceFilter() {
public boolean evaluate(ConnectionContext context, MessageReference r) throws JMSException {
MessageEvaluationContext messageEvaluationContext = context.getMessageEvaluationContext();
messageEvaluationContext.setMessageReference(r);
if (messageEvaluationContext.getDestination() == null) {
messageEvaluationContext.setDestination(getActiveMQDestination());
}
return selectorExpression.matches(messageEvaluationContext);
}
};
}
protected void removeMessage(ConnectionContext c, QueueMessageReference r) throws IOException {
MessageAck ack = new MessageAck();
ack.setAckType(MessageAck.STANDARD_ACK_TYPE);
ack.setDestination(destination);
ack.setMessageID(r.getMessageId());
removeMessage(c, null, r, ack);
}
protected void removeMessage(ConnectionContext context,Subscription sub,final QueueMessageReference reference,MessageAck ack) throws IOException {
reference.setAcked(true);
// This sends the ack the the journal..
acknowledge(context, sub, ack, reference);
if (!ack.isInTransaction()) {
reference.drop();
destinationStatistics.getMessages().decrement();
synchronized(pagedInMessages) {
pagedInMessages.remove(reference.getMessageId());
}
wakeup();
} else {
context.getTransaction().addSynchronization(new Synchronization() {
public void afterCommit() throws Exception {
reference.drop();
destinationStatistics.getMessages().decrement();
synchronized(pagedInMessages) {
pagedInMessages.remove(reference.getMessageId());
}
wakeup();
}
public void afterRollback() throws Exception {
reference.setAcked(false);
}
});
}
}
public void messageExpired(ConnectionContext context, PrefetchSubscription prefetchSubscription, MessageReference reference) {
((QueueMessageReference)reference).drop();
// Not sure.. perhaps we should forge an ack to remove the message from the store.
// acknowledge(context, sub, ack, reference);
destinationStatistics.getMessages().decrement();
synchronized(pagedInMessages) {
pagedInMessages.remove(reference.getMessageId());
}
wakeup();
}
protected ConnectionContext createConnectionContext() {
ConnectionContext answer = new ConnectionContext(new NonCachedMessageEvaluationContext());
answer.setBroker(this.broker);
answer.getMessageEvaluationContext().setDestination(getActiveMQDestination());
return answer;
}
final void sendMessage(final ConnectionContext context, Message msg) throws Exception {
if (!msg.isPersistent() && messages.getSystemUsage() != null) {
messages.getSystemUsage().getTempUsage().waitForSpace();
}
synchronized(messages) {
messages.addMessageLast(msg);
}
destinationStatistics.getEnqueues().increment();
destinationStatistics.getMessages().increment();
messageDelivered(context, msg);
wakeup();
}
public void wakeup() {
if (optimizedDispatch) {
iterate();
}else {
try {
taskRunner.wakeup();
} catch (InterruptedException e) {
LOG.warn("Task Runner failed to wakeup ", e);
}
}
}
private List<QueueMessageReference> doPageIn(boolean force) throws Exception {
List<QueueMessageReference> result = null;
dispatchLock.lock();
try{
int toPageIn = (getMaxPageSize()+(int)destinationStatistics.getInflight().getCount()) - pagedInMessages.size();
if (isLazyDispatch()&& !force) {
// Only page in the minimum number of messages which can be dispatched immediately.
toPageIn = Math.min(getConsumerMessageCountBeforeFull(), toPageIn);
}
if ((force || !consumers.isEmpty()) && toPageIn > 0) {
messages.setMaxBatchSize(toPageIn);
int count = 0;
result = new ArrayList<QueueMessageReference>(toPageIn);
synchronized (messages) {
try {
messages.reset();
while (messages.hasNext() && count < toPageIn) {
MessageReference node = messages.next();
node.incrementReferenceCount();
messages.remove();
if (!broker.isExpired(node)) {
QueueMessageReference ref = createMessageReference(node.getMessage());
result.add(ref);
count++;
} else {
broker.messageExpired(createConnectionContext(),
node);
destinationStatistics.getMessages().decrement();
}
}
} finally {
messages.release();
}
}
synchronized (pagedInMessages) {
for(QueueMessageReference ref:result) {
pagedInMessages.put(ref.getMessageId(), ref);
}
}
}
}finally {
dispatchLock.unlock();
}
return result;
}
private void doDispatch(List<QueueMessageReference> list) throws Exception {
if (list != null) {
List<Subscription> consumers;
dispatchLock.lock();
try {
synchronized (this.consumers) {
consumers = new ArrayList<Subscription>(this.consumers);
}
for (MessageReference node : list) {
Subscription target = null;
List<Subscription> targets = null;
for (Subscription s : consumers) {
if (dispatchSelector.canSelect(s, node)) {
if (!s.isFull()) {
s.add(node);
target = s;
break;
} else {
if (targets == null) {
targets = new ArrayList<Subscription>();
}
targets.add(s);
}
}
}
if (target == null && targets != null) {
// pick the least loaded to add the message too
for (Subscription s : targets) {
if (target == null
|| target.getInFlightUsage() > s.getInFlightUsage()) {
target = s;
}
}
if (target != null) {
target.add(node);
}
}
if (target != null && !strictOrderDispatch && consumers.size() > 1 &&
!dispatchSelector.isExclusiveConsumer(target)) {
synchronized (this.consumers) {
if( removeFromConsumerList(target) ) {
addToConsumerList(target);
consumers = new ArrayList<Subscription>(this.consumers);
}
}
}
}
} finally {
dispatchLock.unlock();
}
}
}
private void pageInMessages() throws Exception {
pageInMessages(true);
}
protected void pageInMessages(boolean force) throws Exception {
doDispatch(doPageIn(force));
}
private void addToConsumerList(Subscription sub) {
if (useConsumerPriority) {
consumers.add(sub);
Collections.sort(consumers, orderedCompare);
} else {
consumers.add(sub);
}
}
private boolean removeFromConsumerList(Subscription sub) {
return consumers.remove(sub);
}
private int getConsumerMessageCountBeforeFull() throws Exception {
int total = 0;
boolean zeroPrefetch = false;
synchronized (consumers) {
for (Subscription s : consumers) {
PrefetchSubscription ps = (PrefetchSubscription) s;
zeroPrefetch |= ps.getPrefetchSize() == 0;
int countBeforeFull = ps.countBeforeFull();
total += countBeforeFull;
}
}
if (total==0 && zeroPrefetch){
total=1;
}
return total;
}
}
diff --git a/activemq-core/src/main/java/org/apache/activemq/broker/region/Topic.java b/activemq-core/src/main/java/org/apache/activemq/broker/region/Topic.java
index a94f0e7ed..893fad335 100755
--- a/activemq-core/src/main/java/org/apache/activemq/broker/region/Topic.java
+++ b/activemq-core/src/main/java/org/apache/activemq/broker/region/Topic.java
@@ -1,649 +1,649 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.broker.region;
import java.io.IOException;
import java.util.LinkedList;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CopyOnWriteArraySet;
import org.apache.activemq.advisory.AdvisorySupport;
import org.apache.activemq.broker.BrokerService;
import org.apache.activemq.broker.ConnectionContext;
import org.apache.activemq.broker.ProducerBrokerExchange;
import org.apache.activemq.broker.region.policy.DeadLetterStrategy;
import org.apache.activemq.broker.region.policy.DispatchPolicy;
import org.apache.activemq.broker.region.policy.FixedSizedSubscriptionRecoveryPolicy;
import org.apache.activemq.broker.region.policy.NoSubscriptionRecoveryPolicy;
import org.apache.activemq.broker.region.policy.SharedDeadLetterStrategy;
import org.apache.activemq.broker.region.policy.SimpleDispatchPolicy;
import org.apache.activemq.broker.region.policy.SubscriptionRecoveryPolicy;
import org.apache.activemq.command.ActiveMQDestination;
import org.apache.activemq.command.ActiveMQTopic;
import org.apache.activemq.command.ExceptionResponse;
import org.apache.activemq.command.Message;
import org.apache.activemq.command.MessageAck;
import org.apache.activemq.command.MessageId;
import org.apache.activemq.command.ProducerAck;
import org.apache.activemq.command.ProducerInfo;
import org.apache.activemq.command.Response;
import org.apache.activemq.command.SubscriptionInfo;
import org.apache.activemq.filter.MessageEvaluationContext;
import org.apache.activemq.filter.NonCachedMessageEvaluationContext;
import org.apache.activemq.state.ProducerState;
import org.apache.activemq.store.MessageRecoveryListener;
import org.apache.activemq.store.TopicMessageStore;
import org.apache.activemq.thread.Task;
import org.apache.activemq.thread.TaskRunner;
import org.apache.activemq.thread.TaskRunnerFactory;
import org.apache.activemq.thread.Valve;
import org.apache.activemq.transaction.Synchronization;
import org.apache.activemq.util.SubscriptionKey;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* The Topic is a destination that sends a copy of a message to every active
* Subscription registered.
*
* @version $Revision: 1.21 $
*/
public class Topic extends BaseDestination implements Task{
protected static final Log LOG = LogFactory.getLog(Topic.class);
private final TopicMessageStore topicStore;
protected final CopyOnWriteArrayList<Subscription> consumers = new CopyOnWriteArrayList<Subscription>();
protected final Valve dispatchValve = new Valve(true);
private DispatchPolicy dispatchPolicy = new SimpleDispatchPolicy();
private SubscriptionRecoveryPolicy subscriptionRecoveryPolicy;
private boolean sendAdvisoryIfNoConsumers;
private DeadLetterStrategy deadLetterStrategy = new SharedDeadLetterStrategy();
private final ConcurrentHashMap<SubscriptionKey, DurableTopicSubscription> durableSubcribers = new ConcurrentHashMap<SubscriptionKey, DurableTopicSubscription>();
private final TaskRunner taskRunner;
private final LinkedList<Runnable> messagesWaitingForSpace = new LinkedList<Runnable>();
private final Runnable sendMessagesWaitingForSpaceTask = new Runnable() {
public void run() {
try {
Topic.this.taskRunner.wakeup();
} catch (InterruptedException e) {
}
};
};
public Topic(BrokerService brokerService, ActiveMQDestination destination, TopicMessageStore store, DestinationStatistics parentStats,
TaskRunnerFactory taskFactory) throws Exception {
super(brokerService, store, destination, parentStats);
this.topicStore=store;
//set default subscription recovery policy
if (destination.isTemporary() || AdvisorySupport.isAdvisoryTopic(destination) ){
subscriptionRecoveryPolicy= new NoSubscriptionRecoveryPolicy();
}else{
//set the default
subscriptionRecoveryPolicy= new FixedSizedSubscriptionRecoveryPolicy();
}
this.taskRunner = taskFactory.createTaskRunner(this, "Topic " + destination.getPhysicalName());
}
public void initialize() throws Exception{
super.initialize();
if (store != null) {
int messageCount = store.getMessageCount();
destinationStatistics.getMessages().setCount(messageCount);
}
}
public boolean lock(MessageReference node, LockOwner sub) {
return true;
}
public void addSubscription(ConnectionContext context, final Subscription sub) throws Exception {
sub.add(context, this);
destinationStatistics.getConsumers().increment();
if (!sub.getConsumerInfo().isDurable()) {
// Do a retroactive recovery if needed.
if (sub.getConsumerInfo().isRetroactive()) {
// synchronize with dispatch method so that no new messages are
// sent
// while we are recovering a subscription to avoid out of order
// messages.
dispatchValve.turnOff();
try {
synchronized (consumers) {
consumers.add(sub);
}
subscriptionRecoveryPolicy.recover(context, this, sub);
} finally {
dispatchValve.turnOn();
}
} else {
synchronized (consumers) {
consumers.add(sub);
}
}
} else {
DurableTopicSubscription dsub = (DurableTopicSubscription)sub;
durableSubcribers.put(dsub.getSubscriptionKey(), dsub);
}
}
public void removeSubscription(ConnectionContext context, Subscription sub) throws Exception {
if (!sub.getConsumerInfo().isDurable()) {
destinationStatistics.getConsumers().decrement();
synchronized (consumers) {
consumers.remove(sub);
}
}
sub.remove(context, this);
}
public void deleteSubscription(ConnectionContext context, SubscriptionKey key) throws IOException {
if (topicStore != null) {
topicStore.deleteSubscription(key.clientId, key.subscriptionName);
Object removed = durableSubcribers.remove(key);
if (removed != null) {
destinationStatistics.getConsumers().decrement();
}
}
}
public void activate(ConnectionContext context, final DurableTopicSubscription subscription) throws Exception {
// synchronize with dispatch method so that no new messages are sent
// while
// we are recovering a subscription to avoid out of order messages.
dispatchValve.turnOff();
try {
synchronized (consumers) {
consumers.add(subscription);
}
if (topicStore == null) {
return;
}
// Recover the durable subscription.
String clientId = subscription.getSubscriptionKey().getClientId();
String subscriptionName = subscription.getSubscriptionKey().getSubscriptionName();
String selector = subscription.getConsumerInfo().getSelector();
SubscriptionInfo info = topicStore.lookupSubscription(clientId, subscriptionName);
if (info != null) {
// Check to see if selector changed.
String s1 = info.getSelector();
if (s1 == null ^ selector == null || (s1 != null && !s1.equals(selector))) {
// Need to delete the subscription
topicStore.deleteSubscription(clientId, subscriptionName);
info = null;
}
}
// Do we need to create the subscription?
if(info==null){
info=new SubscriptionInfo();
info.setClientId(clientId);
info.setSelector(selector);
info.setSubscriptionName(subscriptionName);
info.setDestination(getActiveMQDestination());
// Thi destination is an actual destination id.
info.setSubscribedDestination(subscription.getConsumerInfo().getDestination());
// This destination might be a pattern
topicStore.addSubsciption(info,subscription.getConsumerInfo().isRetroactive());
}
final MessageEvaluationContext msgContext = new NonCachedMessageEvaluationContext();
msgContext.setDestination(destination);
if (subscription.isRecoveryRequired()) {
topicStore.recoverSubscription(clientId, subscriptionName, new MessageRecoveryListener() {
public boolean recoverMessage(Message message) throws Exception {
message.setRegionDestination(Topic.this);
try {
msgContext.setMessageReference(message);
if (subscription.matches(message, msgContext)) {
subscription.add(message);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} catch (IOException e) {
// TODO: Need to handle this better.
e.printStackTrace();
}
return true;
}
public boolean recoverMessageReference(MessageId messageReference) throws Exception {
throw new RuntimeException("Should not be called.");
}
public boolean hasSpace() {
return true;
}
});
}
} finally {
dispatchValve.turnOn();
}
}
public void deactivate(ConnectionContext context, DurableTopicSubscription sub) throws Exception {
synchronized (consumers) {
consumers.remove(sub);
}
sub.remove(context, this);
}
protected void recoverRetroactiveMessages(ConnectionContext context, Subscription subscription) throws Exception {
if (subscription.getConsumerInfo().isRetroactive()) {
subscriptionRecoveryPolicy.recover(context, this, subscription);
}
}
public void send(final ProducerBrokerExchange producerExchange, final Message message) throws Exception {
final ConnectionContext context = producerExchange.getConnectionContext();
final ProducerInfo producerInfo = producerExchange.getProducerState().getInfo();
final boolean sendProducerAck = !message.isResponseRequired() && producerInfo.getWindowSize() > 0 && !context.isInRecoveryMode();
// There is delay between the client sending it and it arriving at the
// destination.. it may have expired.
if (broker.isExpired(message)) {
broker.messageExpired(context, message);
destinationStatistics.getMessages().decrement();
if (sendProducerAck) {
ProducerAck ack = new ProducerAck(producerInfo.getProducerId(), message.getSize());
context.getConnection().dispatchAsync(ack);
}
return;
}
if(memoryUsage.isFull()) {
isFull(context, memoryUsage);
fastProducer(context, producerInfo);
if (isProducerFlowControl() && context.isProducerFlowControl()) {
if (systemUsage.isSendFailIfNoSpace()) {
throw new javax.jms.ResourceAllocationException("Usage Manager memory limit reached");
}
// We can avoid blocking due to low usage if the producer is sending
// a sync message or
// if it is using a producer window
if (producerInfo.getWindowSize() > 0 || message.isResponseRequired()) {
synchronized (messagesWaitingForSpace) {
messagesWaitingForSpace.add(new Runnable() {
public void run() {
try {
// While waiting for space to free up... the
// message may have expired.
if (broker.isExpired(message)) {
broker.messageExpired(context, message);
//destinationStatistics.getEnqueues().increment();
//destinationStatistics.getMessages().decrement();
} else {
doMessageSend(producerExchange, message);
}
if (sendProducerAck) {
ProducerAck ack = new ProducerAck(producerInfo.getProducerId(), message.getSize());
context.getConnection().dispatchAsync(ack);
} else {
Response response = new Response();
response.setCorrelationId(message.getCommandId());
context.getConnection().dispatchAsync(response);
}
} catch (Exception e) {
if (!sendProducerAck && !context.isInRecoveryMode()) {
ExceptionResponse response = new ExceptionResponse(e);
response.setCorrelationId(message.getCommandId());
context.getConnection().dispatchAsync(response);
}
}
}
});
// If the user manager is not full, then the task will not
// get called..
if (!memoryUsage.notifyCallbackWhenNotFull(sendMessagesWaitingForSpaceTask)) {
// so call it directly here.
sendMessagesWaitingForSpaceTask.run();
}
context.setDontSendReponse(true);
return;
}
} else {
// Producer flow control cannot be used, so we have do the flow
// control at the broker
// by blocking this thread until there is space available.
int count = 0;
while (!memoryUsage.waitForSpace(1000)) {
if (context.getStopping().get()) {
throw new IOException("Connection closed, send aborted.");
}
if (count > 2 && context.isInTransaction()) {
count =0;
int size = context.getTransaction().size();
LOG.warn("Waiting for space to send transacted message - transaction elements = " + size + " need more space to commit. Message = " + message);
}
}
// The usage manager could have delayed us by the time
// we unblock the message could have expired..
if (message.isExpired()) {
if (LOG.isDebugEnabled()) {
LOG.debug("Expired message: " + message);
}
return;
}
}
}
}
doMessageSend(producerExchange, message);
messageDelivered(context, message);
if (sendProducerAck) {
ProducerAck ack = new ProducerAck(producerInfo.getProducerId(), message.getSize());
context.getConnection().dispatchAsync(ack);
}
}
/**
* do send the message - this needs to be synchronized to ensure messages are stored AND dispatched in
* the right order
* @param producerExchange
* @param message
* @throws IOException
* @throws Exception
*/
synchronized void doMessageSend(
final ProducerBrokerExchange producerExchange, final Message message)
throws IOException, Exception {
final ConnectionContext context = producerExchange
.getConnectionContext();
message.setRegionDestination(this);
message.getMessageId().setBrokerSequenceId(getDestinationSequenceId());
if (topicStore != null && message.isPersistent()
&& !canOptimizeOutPersistence()) {
if (isProducerFlowControl() && context.isProducerFlowControl() ) {
if (systemUsage.isSendFailIfNoSpace() && systemUsage.getStoreUsage().isFull()) {
throw new javax.jms.ResourceAllocationException("Usage Manager Store is Full");
}
}
while (!systemUsage.getStoreUsage().waitForSpace(1000)) {
if (context.getStopping().get()) {
throw new IOException("Connection closed, send aborted.");
}
}
topicStore.addMessage(context, message);
}
message.incrementReferenceCount();
if (context.isInTransaction()) {
context.getTransaction().addSynchronization(new Synchronization() {
public void afterCommit() throws Exception {
// It could take while before we receive the commit
// operration.. by that time the message could have
// expired..
if (broker.isExpired(message)) {
broker.messageExpired(context, message);
message.decrementReferenceCount();
//destinationStatistics.getEnqueues().increment();
//destinationStatistics.getMessages().decrement();
return;
}
try {
dispatch(context, message);
} finally {
message.decrementReferenceCount();
}
}
});
} else {
try {
dispatch(context, message);
} finally {
message.decrementReferenceCount();
}
}
}
private boolean canOptimizeOutPersistence() {
return durableSubcribers.size() == 0;
}
public String toString() {
return "Topic: destination=" + destination.getPhysicalName() + ", subscriptions=" + consumers.size();
}
public void acknowledge(ConnectionContext context, Subscription sub, final MessageAck ack, final MessageReference node) throws IOException {
if (topicStore != null && node.isPersistent()) {
DurableTopicSubscription dsub = (DurableTopicSubscription)sub;
SubscriptionKey key = dsub.getSubscriptionKey();
topicStore.acknowledge(context, key.getClientId(), key.getSubscriptionName(), node.getMessageId());
}
messageConsumed(context, node);
}
public void dispose(ConnectionContext context) throws IOException {
+ super.dispose(context);
if (topicStore != null) {
topicStore.removeAllMessages(context);
}
- destinationStatistics.setParent(null);
}
public void gc() {
}
public Message loadMessage(MessageId messageId) throws IOException {
return topicStore != null ? topicStore.getMessage(messageId) : null;
}
public void start() throws Exception {
this.subscriptionRecoveryPolicy.start();
if (memoryUsage != null) {
memoryUsage.start();
}
}
public void stop() throws Exception {
if (taskRunner != null) {
taskRunner.shutdown();
}
this.subscriptionRecoveryPolicy.stop();
if (memoryUsage != null) {
memoryUsage.stop();
}
}
public Message[] browse() {
final Set<Message> result = new CopyOnWriteArraySet<Message>();
try {
if (topicStore != null) {
topicStore.recover(new MessageRecoveryListener() {
public boolean recoverMessage(Message message) throws Exception {
result.add(message);
return true;
}
public boolean recoverMessageReference(MessageId messageReference) throws Exception {
return true;
}
public boolean hasSpace() {
return true;
}
});
Message[] msgs = subscriptionRecoveryPolicy.browse(getActiveMQDestination());
if (msgs != null) {
for (int i = 0; i < msgs.length; i++) {
result.add(msgs[i]);
}
}
}
} catch (Throwable e) {
LOG.warn("Failed to browse Topic: " + getActiveMQDestination().getPhysicalName(), e);
}
return result.toArray(new Message[result.size()]);
}
public boolean iterate() {
synchronized(messagesWaitingForSpace) {
while (!memoryUsage.isFull() && !messagesWaitingForSpace.isEmpty()) {
Runnable op = messagesWaitingForSpace.removeFirst();
op.run();
}
}
return false;
}
// Properties
// -------------------------------------------------------------------------
public DispatchPolicy getDispatchPolicy() {
return dispatchPolicy;
}
public void setDispatchPolicy(DispatchPolicy dispatchPolicy) {
this.dispatchPolicy = dispatchPolicy;
}
public SubscriptionRecoveryPolicy getSubscriptionRecoveryPolicy() {
return subscriptionRecoveryPolicy;
}
public void setSubscriptionRecoveryPolicy(SubscriptionRecoveryPolicy subscriptionRecoveryPolicy) {
this.subscriptionRecoveryPolicy = subscriptionRecoveryPolicy;
}
public boolean isSendAdvisoryIfNoConsumers() {
return sendAdvisoryIfNoConsumers;
}
public void setSendAdvisoryIfNoConsumers(boolean sendAdvisoryIfNoConsumers) {
this.sendAdvisoryIfNoConsumers = sendAdvisoryIfNoConsumers;
}
public DeadLetterStrategy getDeadLetterStrategy() {
return deadLetterStrategy;
}
public void setDeadLetterStrategy(DeadLetterStrategy deadLetterStrategy) {
this.deadLetterStrategy = deadLetterStrategy;
}
// Implementation methods
// -------------------------------------------------------------------------
public final void wakeup() {
}
protected void dispatch(final ConnectionContext context, Message message) throws Exception {
destinationStatistics.getMessages().increment();
destinationStatistics.getEnqueues().increment();
dispatchValve.increment();
try {
if (!subscriptionRecoveryPolicy.add(context, message)) {
return;
}
synchronized (consumers) {
if (consumers.isEmpty()) {
onMessageWithNoConsumers(context, message);
return;
}
}
MessageEvaluationContext msgContext = context.getMessageEvaluationContext();
msgContext.setDestination(destination);
msgContext.setMessageReference(message);
if (!dispatchPolicy.dispatch(message, msgContext, consumers)) {
onMessageWithNoConsumers(context, message);
}
} finally {
dispatchValve.decrement();
}
}
/**
* Provides a hook to allow messages with no consumer to be processed in
* some way - such as to send to a dead letter queue or something..
*/
protected void onMessageWithNoConsumers(ConnectionContext context, Message message) throws Exception {
if (!message.isPersistent()) {
if (sendAdvisoryIfNoConsumers) {
// allow messages with no consumers to be dispatched to a dead
// letter queue
if (!AdvisorySupport.isAdvisoryTopic(destination)) {
// The original destination and transaction id do not get
// filled when the message is first sent,
// it is only populated if the message is routed to another
// destination like the DLQ
if (message.getOriginalDestination() != null) {
message.setOriginalDestination(message.getDestination());
}
if (message.getOriginalTransactionId() != null) {
message.setOriginalTransactionId(message.getTransactionId());
}
ActiveMQTopic advisoryTopic = AdvisorySupport.getNoTopicConsumersAdvisoryTopic(destination);
message.setDestination(advisoryTopic);
message.setTransactionId(null);
// Disable flow control for this since since we don't want
// to block.
boolean originalFlowControl = context.isProducerFlowControl();
try {
context.setProducerFlowControl(false);
ProducerBrokerExchange producerExchange = new ProducerBrokerExchange();
producerExchange.setMutable(false);
producerExchange.setConnectionContext(context);
producerExchange.setProducerState(new ProducerState(new ProducerInfo()));
context.getBroker().send(producerExchange, message);
} finally {
context.setProducerFlowControl(originalFlowControl);
}
}
}
}
}
public void messageExpired(ConnectionContext context, PrefetchSubscription prefetchSubscription, MessageReference node) {
// TODO Auto-generated method stub
}
}
| false | false | null | null |
diff --git a/x10.compiler/src/polyglot/ast/New_c.java b/x10.compiler/src/polyglot/ast/New_c.java
index 2c8f4349d..1f332602a 100644
--- a/x10.compiler/src/polyglot/ast/New_c.java
+++ b/x10.compiler/src/polyglot/ast/New_c.java
@@ -1,412 +1,410 @@
/*
* This file is part of the Polyglot extensible compiler framework.
*
* Copyright (c) 2000-2006 Polyglot project group, Cornell University
* Copyright (c) 2006 IBM Corporation
*
*/
package polyglot.ast;
import java.util.*;
import polyglot.frontend.Globals;
import polyglot.frontend.Goal;
import polyglot.types.*;
import polyglot.util.*;
import polyglot.visit.*;
import x10.errors.Errors;
import x10.ast.X10New;
import x10.types.X10ClassDef;
import x10.types.X10ConstructorInstance;
/**
* A <code>New</code> is an immutable representation of the use of the
* <code>new</code> operator to create a new instance of a class. In
* addition to the type of the class being created, a <code>New</code> has a
* list of arguments to be passed to the constructor of the object and an
* optional <code>ClassBody</code> used to support anonymous classes.
*/
public abstract class New_c extends Expr_c implements X10New
{
protected Expr qualifier;
protected TypeNode tn;
protected List<Expr> arguments;
protected ClassBody body;
protected ConstructorInstance ci;
protected X10ClassDef anonType;
public New_c(Position pos, Expr qualifier, TypeNode tn, List<Expr> arguments, ClassBody body) {
super(pos);
assert(tn != null && arguments != null); // qualifier and body may be null
this.qualifier = qualifier;
this.tn = tn;
this.arguments = TypedList.copyAndCheck(arguments, Expr.class, true);
this.body = body;
}
public List<Def> defs() {
if (body != null) {
return Collections.<Def>singletonList(anonType);
}
return Collections.<Def>emptyList();
}
/** Get the qualifier expression of the allocation. */
public Expr qualifier() {
return this.qualifier;
}
/** Set the qualifier expression of the allocation. */
public X10New qualifier(Expr qualifier) {
New_c n = (New_c) copy();
n.qualifier = qualifier;
return n;
}
/** Get the type we are instantiating. */
public TypeNode objectType() {
return this.tn;
}
/** Set the type we are instantiating. */
public X10New objectType(TypeNode tn) {
New_c n = (New_c) copy();
n.tn = tn;
return n;
}
public X10ClassDef anonType() {
return (X10ClassDef) this.anonType;
}
public X10New anonType(X10ClassDef anonType) {
if (anonType == this.anonType) return this;
New_c n = (New_c) copy();
n.anonType = anonType;
return n;
}
public ConstructorInstance procedureInstance() {
return constructorInstance();
}
public X10ConstructorInstance constructorInstance() {
return (X10ConstructorInstance)this.ci;
}
public New procedureInstance(ProcedureInstance<? extends ProcedureDef> pi) {
return constructorInstance((ConstructorInstance) pi);
}
public X10New constructorInstance(ConstructorInstance ci) {
if (ci == this.ci) return this;
New_c n = (New_c) copy();
n.ci = ci;
return n;
}
public List<Expr> arguments() {
return this.arguments;
}
public ProcedureCall arguments(List<Expr> arguments) {
New_c n = (New_c) copy();
n.arguments = TypedList.copyAndCheck(arguments, Expr.class, true);
return n;
}
public ClassBody body() {
return this.body;
}
public X10New body(ClassBody body) {
New_c n = (New_c) copy();
n.body = body;
return n;
}
/** Reconstruct the expression. */
protected New_c reconstruct(Expr qualifier, TypeNode tn, List<Expr> arguments, ClassBody body) {
if (qualifier != this.qualifier || tn != this.tn || ! CollectionUtil.allEqual(arguments, this.arguments) || body != this.body) {
New_c n = (New_c) copy();
n.tn = tn;
n.qualifier = qualifier;
n.arguments = TypedList.copyAndCheck(arguments, Expr.class, true);
n.body = body;
return n;
}
return this;
}
/** Visit the children of the expression. */
public abstract Node visitChildren(NodeVisitor v);
public Context enterChildScope(Node child, Context c) {
if (child == body && anonType != null && body != null) {
c = c.pushClass(anonType, anonType.asType());
}
return super.enterChildScope(child, c);
}
Goal enable = null;
public Node buildTypesOverride(TypeBuilder tb) {
TypeSystem ts = tb.typeSystem();
New_c n = this;
ConstructorInstance ci = ts.createConstructorInstance(position(), new ErrorRef_c<ConstructorDef>(ts, position(), "Cannot get ConstructorDef before type-checking new expression."));
n = (New_c) n.constructorInstance(ci);
Expr qual = (Expr) n.visitChild(n.qualifier(), tb);
TypeNode objectType = (TypeNode) n.visitChild(n.objectType(), tb);
List<Expr> arguments = n.visitList(n.arguments(), tb);
ClassBody body = null;
if (n.body() != null) {
TypeBuilder tb2 = tb.pushAnonClass(position());
X10ClassDef type = tb2.currentClass();
type.superType(objectType.typeRef());
n = (New_c) n.anonType(type);
body = (ClassBody) n.visitChild(n.body(), tb2);
}
n = n.reconstruct(qual, objectType, arguments, body);
return n.type(ts.unknownType(position()));
}
public abstract New_c typeCheckObjectType(TypeChecker childtc);
@Override
public Node typeCheckOverride(Node parent, ContextVisitor tc) {
TypeChecker childtc;
NodeVisitor childv = tc.enter(parent, this);
if (childv instanceof TypeChecker) {
childtc = (TypeChecker) childv;
}
else {
return this;
}
New_c n = typeCheckHeader(childtc);
ClassBody body = (ClassBody) n.visitChild(n.body, childtc);
n = (New_c) n.body(body);
- n = (New_c) tc.leave(parent, this, n, childtc);
-
- return n;
+ return tc.leave(parent, this, n, childtc);
}
protected New_c typeCheckHeader(TypeChecker childtc) {
TypeSystem ts = childtc.typeSystem();
New_c n = this;
n = n.typeCheckObjectType(childtc);
Expr qualifier = n.qualifier;
TypeNode tn = n.tn;
List<Expr> arguments = n.arguments;
ClassBody body = n.body;
if (body != null) {
Ref<? extends Type> ct = tn.typeRef();
ClassDef anonType = n.anonType();
assert anonType != null;
if (! ct.get().toClass().flags().isInterface()) {
anonType.superType(ct);
}
else {
anonType.superType(Types.<Type>ref(ts.Object()));
assert anonType.interfaces().isEmpty() || anonType.interfaces().get(0) == ct;
if (anonType.interfaces().isEmpty())
anonType.addInterface(ct);
}
}
arguments = visitList(arguments, childtc);
n = n.reconstruct(qualifier, tn, arguments, body);
return n;
}
/**
* @param ar
* @param ct
* @throws SemanticException
*/
protected abstract New findQualifier(TypeChecker ar, ClassType ct);
public abstract Node typeCheck(ContextVisitor tc);
protected void typeCheckNested(ContextVisitor tc) throws SemanticException {
if (qualifier != null) {
// We have not disambiguated the type node yet.
// Get the qualifier type first.
Type qt = qualifier.type();
if (! qt.isClass()) {
throw new SemanticException("Cannot instantiate member class of a non-class type.", qualifier.position());
}
// Disambiguate the type node as a member of the qualifier type.
ClassType ct = tn.type().toClass();
// According to JLS2 15.9.1, the class type being
// instantiated must be inner.
if (! ct.isInnerClass()) {
if (!(qualifier instanceof Special)) // Yoav added "this" qualifier for non-static anonymous classes
throw new SemanticException("Cannot provide a containing instance for non-inner class " + ct.fullName() + ".", qualifier.position());
}
}
else {
ClassType ct = tn.type().toClass();
if (ct.isMember()) {
for (ClassType t = ct; t.isMember(); t = t.outer()) {
if (! t.flags().isStatic()) {
throw new SemanticException("Cannot allocate non-static member class \"" +t + "\".", position());
}
}
}
}
}
protected void typeCheckFlags(ContextVisitor tc) throws SemanticException {
ClassType ct = tn.type().toClass();
if (this.body == null) {
if (ct.flags().isInterface()) {
throw new SemanticException("Cannot instantiate an interface.", position());
}
if (ct.flags().isAbstract()) {
throw new SemanticException("Cannot instantiate an abstract class.", position());
}
}
else {
if (ct.flags().isFinal()) {
throw new SemanticException("Cannot create an anonymous subclass of a final class.", position());
}
if (ct.flags().isInterface() && ! arguments.isEmpty()) {
throw new SemanticException("Cannot pass arguments to an anonymous class that implements an interface.",arguments.get(0).position());
}
}
}
@Override
public Node conformanceCheck(ContextVisitor tc) {
if (body == null) {
return this;
}
// Check that the anonymous class implements all abstract methods that it needs to.
try {
TypeSystem ts = tc.typeSystem();
ts.checkClassConformance(anonType.asType(), enterChildScope(body, tc.context()));
} catch (SemanticException e) {
Errors.issue(tc.job(), e, this);
}
return this;
}
/** Get the precedence of the expression. */
public Precedence precedence() {
return Precedence.LITERAL;
}
public String toString() {
return (qualifier != null ? (qualifier.toString() + ".") : "") +
"new " + tn + "(...)" + (body != null ? " " + body : "");
}
protected void printQualifier(CodeWriter w, PrettyPrinter tr) {
if (qualifier != null) {
print(qualifier, w, tr);
w.write(".");
}
}
protected void printArgs(CodeWriter w, PrettyPrinter tr) {
w.write("(");
w.allowBreak(2, 2, "", 0);
w.begin(0);
for (Iterator<Expr> i = arguments.iterator(); i.hasNext();) {
Expr e = i.next();
print(e, w, tr);
if (i.hasNext()) {
w.write(",");
w.allowBreak(0);
}
}
w.end();
w.write(")");
}
protected void printBody(CodeWriter w, PrettyPrinter tr) {
if (body != null) {
w.write(" {");
print(body, w, tr);
w.write("}");
}
}
public void prettyPrint(CodeWriter w, PrettyPrinter tr) {
printQualifier(w, tr);
w.write("new ");
// We need to be careful when pretty printing "new" expressions for
// member classes. For the expression "e.new C()" where "e" has
// static type "T", the TypeNode for "C" is actually the type "T.C".
// But, if we print "T.C", the post compiler will try to lookup "T"
// in "T". Instead, we print just "C".
if (qualifier != null) {
w.write(tn.nameString());
}
else {
print(tn, w, tr);
}
printArgs(w, tr);
printBody(w, tr);
}
public Term firstChild() {
return qualifier != null ? (Term) qualifier : tn;
}
public <S> List<S> acceptCFG(CFGBuilder v, List<S> succs) {
if (qualifier != null) {
v.visitCFG(qualifier, tn, ENTRY);
}
if (body() != null) {
v.visitCFG(tn, listChild(arguments, body()), ENTRY);
v.visitCFGList(arguments, body(), ENTRY);
v.visitCFG(body(), this, EXIT);
} else {
if (!arguments.isEmpty()) {
v.visitCFG(tn, listChild(arguments, null), ENTRY);
v.visitCFGList(arguments, this, EXIT);
} else {
v.visitCFG(tn, this, EXIT);
}
}
return succs;
}
}
diff --git a/x10.compiler/src/x10/ast/X10New_c.java b/x10.compiler/src/x10/ast/X10New_c.java
index d9d340437..26ad3759f 100644
--- a/x10.compiler/src/x10/ast/X10New_c.java
+++ b/x10.compiler/src/x10/ast/X10New_c.java
@@ -1,764 +1,774 @@
/*
* This file is part of the X10 project (http://x10-lang.org).
*
* This file is licensed to You under the Eclipse Public License (EPL);
* You may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.opensource.org/licenses/eclipse-1.0.php
*
* (C) Copyright IBM Corporation 2006-2010.
*/
package x10.ast;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import polyglot.ast.AmbTypeNode;
import polyglot.ast.CanonicalTypeNode;
import polyglot.ast.ClassBody;
import polyglot.ast.Expr;
import polyglot.ast.New;
import polyglot.ast.New_c;
import polyglot.ast.Node;
import polyglot.ast.NodeFactory;
import polyglot.ast.TypeNode;
import polyglot.ast.ProcedureCall;
import polyglot.types.ClassDef;
import polyglot.types.ClassType;
import polyglot.types.CodeDef;
import polyglot.types.ConstructorDef;
import polyglot.types.ConstructorInstance;
import polyglot.types.Context;
import polyglot.types.Flags;
import polyglot.types.Matcher;
import polyglot.types.Name;
import polyglot.types.QName;
import polyglot.types.Ref;
import polyglot.types.SemanticException;
import polyglot.types.Type;
import polyglot.types.TypeSystem;
import polyglot.types.Types;
import polyglot.util.CodeWriter;
import polyglot.util.CollectionUtil; import x10.util.CollectionFactory;
import polyglot.util.InternalCompilerError;
import polyglot.util.Pair;
import polyglot.util.Position;
import polyglot.util.TypedList;
import polyglot.visit.ContextVisitor;
import polyglot.visit.NodeVisitor;
import polyglot.visit.PrettyPrinter;
import polyglot.visit.TypeBuilder;
import polyglot.visit.TypeChecker;
import x10.constraint.XTerms;
import x10.constraint.XVar;
import x10.errors.Errors;
import x10.errors.Warnings;
import x10.extension.X10Del;
import x10.extension.X10Del_c;
import x10.extension.X10Ext;
import x10.types.ConstrainedType;
import x10.types.ParameterType;
import x10.types.ThisDef;
import x10.types.TypeParamSubst;
import x10.types.X10ClassDef;
import x10.types.X10ClassType;
import x10.types.X10ConstructorInstance;
import x10.types.X10MemberDef;
import polyglot.types.Context;
import x10.types.X10ParsedClassType;
import polyglot.types.TypeSystem;
import polyglot.types.ProcedureDef;
import polyglot.types.ProcedureInstance;
import polyglot.types.TypeSystem_c;
import polyglot.types.NoMemberException;
import x10.types.checker.Converter;
import x10.types.checker.PlaceChecker;
import x10.types.constraints.CConstraint;
import x10.types.constraints.QualifiedVar;
import x10.types.constraints.TypeConstraint;
import x10.visit.X10TypeChecker;
/**
* new C[T](e)
*
* @author nystrom
*/
public class X10New_c extends New_c implements X10New {
public X10New_c(Position pos, boolean newOmitted, Expr qualifier, TypeNode tn, List<TypeNode> typeArguments, List<Expr> arguments, ClassBody body) {
super(pos, qualifier, tn, arguments, body);
this.typeArguments = TypedList.copyAndCheck(typeArguments, TypeNode.class, true);
this.newOmitted = newOmitted;
}
private boolean newOmitted = false;
public boolean newOmitted() {
return newOmitted;
}
public X10New newOmitted(boolean val) {
X10New_c n = (X10New_c) copy();
n.newOmitted = val;
return n;
}
@Override
public Node visitChildren(NodeVisitor v) {
Expr qualifier = (Expr) visitChild(this.qualifier, v);
TypeNode tn = (TypeNode) visitChild(this.tn, v);
List<TypeNode> typeArguments = visitList(this.typeArguments, v);
List<Expr> arguments = visitList(this.arguments, v);
ClassBody body = (ClassBody) visitChild(this.body, v);
X10New_c n = (X10New_c) typeArguments(typeArguments);
Node result = n.reconstruct(qualifier, tn, arguments, body);
return result;
}
@Override
public X10New anonType(X10ClassDef anonType) {
return super.anonType(anonType);
}
@Override
public X10New arguments(List<Expr> arguments) {
return (X10New) super.arguments(arguments);
}
@Override
public X10New body(ClassBody body) {
return (X10New) super.body(body);
}
@Override
public X10New constructorInstance(ConstructorInstance ci) {
return (X10New) super.constructorInstance(ci);
}
@Override
public X10New objectType(TypeNode tn) {
return (X10New) super.objectType(tn);
}
@Override
public X10New qualifier(Expr qualifier) {
return (X10New) super.qualifier(qualifier);
}
@Override
public Node buildTypesOverride(TypeBuilder tb) {
X10New_c n = (X10New_c) super.buildTypesOverride(tb);
List<TypeNode> typeArgs = n.visitList(n.typeArguments(), tb);
n = (X10New_c) n.typeArguments(typeArgs);
n = (X10New_c) X10Del_c.visitAnnotations(n, tb);
return n;
}
List<TypeNode> typeArguments;
public List<TypeNode> typeArguments() {
return typeArguments;
}
public X10New typeArguments(List<TypeNode> args) {
if (args == this.typeArguments) return this;
X10New_c n = (X10New_c) copy();
n.typeArguments = new ArrayList<TypeNode>(args);
return n;
}
@Override
protected X10New_c typeCheckHeader(TypeChecker childtc) {
X10New_c n = (X10New_c) super.typeCheckHeader(childtc);
List<TypeNode> typeArguments = visitList(n.typeArguments(), childtc);
n = (X10New_c) n.typeArguments(typeArguments);
if (n.body() != null) {
Ref<? extends Type> ct = n.objectType().typeRef();
ClassDef anonType = n.anonType();
assert anonType != null;
TypeSystem ts = (TypeSystem) childtc.typeSystem();
Flags flags = ct.get().toClass().flags();
if (!flags.isInterface()) {
anonType.superType(ct);
}
else /*if (flags.isValue()) {
anonType.superType(Types.<Type> ref(ts.Value()));
anonType.setInterfaces(Collections.<Ref<? extends Type>> singletonList(ct));
}
else */{
anonType.superType(Types.<Type> ref(ts.Object()));
anonType.setInterfaces(Collections.<Ref<? extends Type>> singletonList(ct));
}
assert anonType.superType() != null;
assert anonType.interfaces().size() <= 1;
}
return n;
}
@Override
public Node typeCheckOverride(Node parent, ContextVisitor tc) {
Node n = super.typeCheckOverride(parent, tc);
NodeVisitor childtc = tc.enter(parent, n);
List<AnnotationNode> oldAnnotations = ((X10Ext) ext()).annotations();
if (oldAnnotations == null || oldAnnotations.isEmpty()) {
return n;
}
List<AnnotationNode> newAnnotations = node().visitList(oldAnnotations, childtc);
if (! CollectionUtil.allEqual(oldAnnotations, newAnnotations)) {
return ((X10Del) n.del()).annotations(newAnnotations);
}
return n;
}
/**
* @param ar
* @param ct
*/
protected X10New findQualifier(TypeChecker ar, ClassType ct) {
// If we're instantiating a non-static member class, add a "this"
// qualifier.
NodeFactory nf = ar.nodeFactory();
TypeSystem ts = ar.typeSystem();
Context c = ar.context();
// Search for the outer class of the member. The outer class is
// not just ct.outer(); it may be a subclass of ct.outer().
Type outer = null;
Name name = ct.name();
ClassType t = c.currentClass();
// We're in one scope too many.
if (t == anonType) {
t = (ClassType) t.container();
}
// Search all enclosing classes for the type.
while (t != null) {
try {
Type mt = ts.findMemberType(t, name, c);
if (mt instanceof ClassType) {
ClassType cmt = (ClassType) mt;
if (cmt.def() == ct.def()) {
outer = t;
break;
}
}
}
catch (SemanticException e) {
}
t = t.outer();
}
if (outer == null) {
Errors.issue(ar.job(),
new Errors.CouldNotFindNonStaticMemberClass(name, position()));
outer = c.currentClass();
}
// Create the qualifier.
Expr q;
Position cg = Position.compilerGenerated(position());
if (outer.typeEquals(c.currentClass(), ar.context())) {
q = nf.This(cg);
}
else {
q = nf.This(cg, nf.CanonicalTypeNode(cg, outer));
}
q = q.type(outer);
return qualifier(q);
}
protected Name getName(TypeNode tn) {
if (tn instanceof CanonicalTypeNode) {
if (tn.type().isClass()) {
return tn.type().toClass().name();
} else {
return null;
}
}
if (tn instanceof AmbTypeNode) {
return ((AmbTypeNode) tn).name().id();
}
if (tn instanceof AmbDepTypeNode) {
return getName(((AmbDepTypeNode) tn).base());
}
return null;
}
public X10New_c typeCheckObjectType(TypeChecker childtc) {
NodeFactory nf = (NodeFactory) childtc.nodeFactory();
TypeSystem ts = childtc.typeSystem();
Context c = childtc.context();
X10New_c n = this;
// Override to associate the type args with the type rather than with
// the constructor.
Expr qualifier = n.qualifier;
TypeNode tn = n.tn;
List<Expr> arguments = n.arguments;
ClassBody body = n.body;
List<TypeNode> typeArguments = n.typeArguments;
typeArguments = n.visitList(typeArguments, childtc);
qualifier = (Expr) n.visitChild(qualifier, childtc);
if (!(tn instanceof CanonicalTypeNode)) {
Name name = getName(tn);
Type t;
if (qualifier == null) {
if (typeArguments.size() > 0) {
if (tn instanceof AmbTypeNode) {
AmbTypeNode atn = (AmbTypeNode) tn;
tn = nf.AmbDepTypeNode(atn.position(), atn.prefix(), atn.name(), typeArguments, Collections.<Expr>emptyList(), null);
tn = tn.typeRef(atn.typeRef());
}
}
tn = (TypeNode) n.visitChild(tn, childtc);
t = tn.type();
}
else {
if (!(tn instanceof AmbTypeNode) || ((AmbTypeNode) tn).prefix() != null) {
Errors.issue(childtc.job(),
new Errors.OnlySimplyNameMemberClassMayBeInstantiated(tn.position()));
}
if (!qualifier.type().isClass()) {
Errors.issue(childtc.job(),
new Errors.CannotInstantiateMemberClass(n.position()));
}
tn = nf.CanonicalTypeNode(tn.position(), tn.typeRef());
// We have to disambiguate the type node as if it were a member of
// the static type, outer, of the qualifier.
try {
t = ts.findMemberType(Types.baseType(qualifier.type()), name, c);
} catch (SemanticException e) {
t = ts.unknownType(tn.position());
if (!qualifier.type().isClass()) {
qualifier = null; // will fake it
}
}
}
t = ts.expandMacros(t);
CConstraint xc = Types.xclause(t);
t = Types.baseType(t);
if (!(t instanceof X10ClassType)) {
if (name == null)
name = Name.makeFresh();
QName outer = qualifier == null ? null : qualifier.type().toClass().fullName();
QName qname = QName.make(outer, name);
t = ts.createFakeClass(qname, new Errors.CannotInstantiateType(tn.type(), position()));
}
X10ClassType ct = (X10ClassType) t;
if (qualifier == null && ct.isMember() && !ct.flags().isStatic()) {
final X10New_c newC = (X10New_c) n.objectType(tn);
X10New k = newC.findQualifier(childtc, ct);
tn = k.objectType();
qualifier = (Expr) k.visitChild(k.qualifier(), childtc);
}
if (typeArguments.size() > 0) {
List<Type> typeArgs = new ArrayList<Type>(typeArguments.size());
for (TypeNode tan : typeArguments) {
typeArgs.add(tan.type());
}
if (typeArgs.size() != ct.x10Def().typeParameters().size()) {
Errors.issue(childtc.job(),
new Errors.CannotInstantiateType(ct, n.position()));
// TODO: fake missing args or delete extra args
}
ct = ct.typeArguments(typeArgs);
}
t = Types.xclause(ct, xc);
((Ref<Type>) tn.typeRef()).update(t);
}
n = (X10New_c) n.reconstruct(qualifier, tn, arguments, body);
// [IP] Should retain the type argument nodes, even if the type is resolved.
//n = (X10New_c) n.typeArguments(Collections.EMPTY_LIST);
return n;
}
public static interface MatcherMaker<PI> {
public Matcher<PI> matcher(Type ct, List<Type> typeArgs, List<Type> argTypes);
}
public static Pair<ConstructorInstance, List<Expr>> tryImplicitConversions(X10ProcedureCall n, ContextVisitor tc,
Type targetType, List<Type> argTypes) throws SemanticException {
final TypeSystem_c ts = (TypeSystem_c) tc.typeSystem();
final Context context = tc.context();
List<ConstructorInstance> methods = ts.findAcceptableConstructors(targetType, ts.ConstructorMatcher(targetType, Collections.EMPTY_LIST,argTypes, context, true));
return Converter.tryImplicitConversions(n, tc, targetType, methods, new MatcherMaker<ConstructorInstance>() {
public Matcher<ConstructorInstance> matcher(Type ct, List<Type> typeArgs, List<Type> argTypes) {
return ts.ConstructorMatcher(ct, argTypes, context);
}
});
}
public Node typeCheck(ContextVisitor tc) {
final TypeSystem xts = (TypeSystem) tc.typeSystem();
// ///////////////////////////////////////////////////////////////////
// Inline the super call here and handle type arguments.
// ///////////////////////////////////////////////////////////////////
// [IP] The type arguments are retained for later use.
//assert (this.typeArguments().size() == 0) : position().toString();
SemanticException error = null;
List<Type> argTypes = new ArrayList<Type>(this.arguments.size());
for (Expr e : this.arguments) {
//Type argType = PlaceChecker.ReplaceHereByPlaceTerm((Type) e.type(), (X10Context) tc.context());
Type argType = e.type();
argTypes.add(argType);
}
Position pos = position();
try {
typeCheckFlags(tc);
} catch (SemanticException e) {
Errors.issue(tc.job(), e, this);
if (error == null) { error = e; }
}
try {
typeCheckNested(tc);
} catch (SemanticException e) {
Errors.issue(tc.job(), e, this);
if (error == null) { error = e; }
}
X10New_c result = this;
Type t = result.objectType().type();
X10ClassType ct = (X10ClassType) Types.baseType(t);
X10ConstructorInstance ci;
List<Expr> args;
Pair<ConstructorInstance, List<Expr>> p = findConstructor(tc, result, ct, argTypes, result.anonType());
ci = (X10ConstructorInstance) p.fst();
args = p.snd();
if (ci.error() != null) {
Errors.issue(tc.job(), ci.error(), this);
} else if (error != null) {
ci = ci.error(error);
}
X10ParsedClassType container = (X10ParsedClassType) ci.container();
if (!ct.x10Def().typeParameters().isEmpty() && (ct.typeArguments() == null || ct.typeArguments().isEmpty())) {
t = new TypeParamSubst(xts, container.typeArguments(), container.x10Def().typeParameters()).reinstantiate(t);
result = (X10New_c) result.objectType(result.objectType().typeRef(Types.ref(t)));
}
try {
Types.checkMissingParameters(result.objectType());
} catch (SemanticException e) {
Errors.issue(tc.job(), e, result.objectType());
}
TypeSystem ts = (TypeSystem) tc.typeSystem();
Type tp = ci.returnType();
final Context context = tc.context();
tp = PlaceChecker.ReplaceHereByPlaceTerm(tp, context);
Type tp1 = Types.instantiateTypeParametersExplicitly(tp);
Type t1 = Types.instantiateTypeParametersExplicitly(t);
if (ts.hasUnknown(tp1)) {
SemanticException e = new SemanticException("Inconsistent constructor return type", pos);
Errors.issue(tc.job(), e, this);
if (ci.error() == null) {
ci = ci.error(e);
}
}
+ boolean doCoercion = false;
if (!ts.hasUnknown(tp) && !ts.isSubtype(tp1, t1, context)) {
- SemanticException e = Errors.NewIncompatibleType.make(result.type(tp1), t1, tc, pos);
- Errors.issue(tc.job(), e, this);
- if (ci.error() == null) {
- ci = ci.error(e);
+ Expr newNewExpr = Converter.attemptCoercion(tc, result.type(tp1), t1);
+ if (newNewExpr != null) {
+ // I cann't keep newNewExpr, because result is still going to be modified (and I cannot do this check later because ci might be modified and it is stored in result)
+ // so, sadly, I have to call attemptCoercion twice.
+ doCoercion = true;
+ } else {
+ SemanticException e = Errors.NewIncompatibleType.make(result.type(tp1), t1, tc, pos);
+ Errors.issue(tc.job(), e, this);
+ if (ci.error() == null) {
+ ci = ci.error(e);
+ }
}
}
// Copy the method instance so we can modify it.
//tp = ((X10Type) tp).setFlags(X10Flags.ROOTED);
ci = ci.returnType(tp);
ci = result.adjustCI(ci, tc, qualifier());
try {
checkWhereClause(ci, pos, context);
} catch (SemanticException e) {
if (ci.error() == null) { ci = ci.error(e); }
}
result = (X10New_c) result.constructorInstance(ci);
result = (X10New_c) result.arguments(args);
Type type = ci.returnType();
if (result.body() != null) {
// If creating an anonymous class, we need to adjust the type
// to be based on anonType rather than on the supertype.
ClassDef anonTypeDef = result.anonType();
Type anonType = anonTypeDef.asType();
type = Types.xclause(Types.baseType(anonType), Types.xclause(type));
// Capture "this" for anonymous classes in a non-static context
if (!context.inStaticContext()) {
CodeDef code = context.currentCode();
if (code instanceof X10MemberDef) {
ThisDef thisDef = ((X10MemberDef) code).thisDef();
if (null == thisDef) {
throw new InternalCompilerError(position(), "X10New_c.typeCheck: thisDef is null for containing code " +code);
}
assert (thisDef != null);
context.recordCapturedVariable(thisDef.asInstance());
}
}
}
result = (X10New_c) result.type(type);
- return result;
+ return doCoercion ?
+ Converter.attemptCoercion(tc, result, t1) :
+ result;
}
/**
* Looks up a constructor with given name and argument types.
*/
public static Pair<ConstructorInstance,List<Expr>> findConstructor(ContextVisitor tc, X10ProcedureCall n,
Type targetType, List<Type> actualTypes) {
return findConstructor(tc, n, targetType, actualTypes, null);
}
public static Pair<ConstructorInstance,List<Expr>> findConstructor(ContextVisitor tc, X10ProcedureCall n,
Type targetType, List<Type> actualTypes, X10ClassDef anonType) {
X10ConstructorInstance ci;
TypeSystem xts = tc.typeSystem();
Context context = (Context) tc.context();
boolean haveUnknown = xts.hasUnknown(targetType);
for (Type t : actualTypes) {
if (xts.hasUnknown(t)) haveUnknown = true;
}
SemanticException error = null;
try {
return findConstructor(tc, context, n, targetType, actualTypes, anonType);
} catch (SemanticException e) {
error = e;
}
// If not returned yet, fake the constructor instance.
Collection<X10ConstructorInstance> cis = null;
try {
cis = findConstructors(tc, targetType, actualTypes);
} catch (SemanticException e) {
if (error == null) error = e;
}
// See if all matches have the same return type, and save that to avoid losing information.
Type rt = null;
if (cis != null) {
for (X10ConstructorInstance xci : cis) {
if (rt == null) {
rt = xci.returnType();
} else if (!xts.typeEquals(rt, xci.returnType(), context)) {
if (xts.typeBaseEquals(rt, xci.returnType(), context)) {
rt = Types.baseType(rt);
} else {
rt = null;
break;
}
}
}
}
if (haveUnknown)
error = new SemanticException(); // null message
ci = xts.createFakeConstructor(targetType.toClass(), Flags.PUBLIC, actualTypes, error);
if (rt != null) ci = ci.returnType(rt);
return new Pair<ConstructorInstance, List<Expr>>(ci, n.arguments());
}
private static Pair<ConstructorInstance,List<Expr>> findConstructor(ContextVisitor tc, Context xc,
X10ProcedureCall n, Type targetType, List<Type> argTypes, X10ClassDef anonType) throws SemanticException {
X10ConstructorInstance ci = null;
TypeSystem xts = (TypeSystem) tc.typeSystem();
X10ClassType ct = (X10ClassType) targetType;
try {
if (!ct.flags().isInterface()) {
Context c = tc.context();
if (anonType != null) {
c = c.pushClass(anonType, anonType.asType());
}
List<Type> typeArgs = ct.typeArguments();
if (typeArgs == null) {
typeArgs = Collections.<Type>emptyList();
}
ci = xts.findConstructor(targetType, xts.ConstructorMatcher(targetType, typeArgs, argTypes, c));
}
else {
ConstructorDef dci = xts.defaultConstructor(n.position(), Types.<ClassType> ref(ct));
ci = (X10ConstructorInstance) dci.asInstance();
}
// Force type inference when a constructor is invoked with no type arguments from an instance method of the same class
List<Type> tas = ct.typeArguments();
List<ParameterType> tps = ct.x10Def().typeParameters();
if (!tps.isEmpty() && (tas == null || tas.isEmpty())) {
throw new Errors.TypeIsMissingParameters(ct, tps, n.position());
}
return new Pair<ConstructorInstance, List<Expr>>(ci, n.arguments());
}
catch (SemanticException e) {
e.setPosition(n.position());
// only if we didn't find any methods, try coercions.
if (!(e instanceof NoMemberException)) {
throw e;
}
// Now, try to find the method with implicit conversions, making
// them explicit.
try {
Pair<ConstructorInstance, List<Expr>> p = tryImplicitConversions(n, tc, targetType, argTypes);
return p;
}
catch (SemanticException e2) {
throw e;
}
}
//TypeSystem_c.ConstructorMatcher matcher = xts.ConstructorMatcher(targetType, argTypes, xc);
//throw new Errors.MethodOrStaticConstructorNotFound(matcher, n.position());
}
private static Collection<X10ConstructorInstance> findConstructors(ContextVisitor tc, Type targetType,
List<Type> actualTypes) throws SemanticException {
TypeSystem xts = tc.typeSystem();
Context context = (Context) tc.context();
if (targetType == null) {
// TODO
return Collections.emptyList();
}
return xts.findConstructors(targetType, xts.ConstructorMatcher(targetType, actualTypes, context));
}
private static void checkWhereClause(X10ConstructorInstance ci, Position pos, Context context) throws SemanticException {
if (ci != null) {
CConstraint guard = ci.guard();
TypeConstraint tguard = ci.typeGuard();
if ((guard != null && !guard.consistent()) || (tguard != null && !tguard.consistent(context))) {
throw new SemanticException("Constructor guard not satisfied by caller.", pos);
}
}
}
/*
* Compute the new resulting type for the method call by replacing this and
* any argument variables that occur in the rettype depclause with new
* variables whose types are determined by the static type of the receiver
* and the actual arguments to the call.
*
* Also self.$$here==here.
* Add self!=null.
*/
private X10ConstructorInstance adjustCI(X10ConstructorInstance xci, ContextVisitor tc, Expr outer) {
if (xci == null)
return (X10ConstructorInstance) this.ci;
Type type = xci.returnType();
if (outer != null) {
type = Types.addInOuterClauses(type, outer.type());
} else {
// this could still be a local class, and the outer this has to be captured.
Type baseType = Types.baseType(type);
if (baseType instanceof X10ClassType) {
X10ClassType ct = (X10ClassType) baseType;
if (ct.isLocal()) {
Type outerT = ct.outer();
CConstraint c = new CConstraint();
Type outerTB = Types.baseType(outerT);
if (outerTB instanceof X10ClassType) {
X10ClassType outerct = (X10ClassType) outerTB;
c.addSelfBinding(outerct.def().thisVar());
outerT = Types.xclause(outerT, c);
type = Types.addInOuterClauses(type, outerT);
}
}
}
}
TypeSystem ts = (TypeSystem) tc.typeSystem();
if (ts.isStructType(type))
return xci;
// Add self.home == here to the return type.
// Add this even in 2.1 -- the place where this object is created
// is tracked in the type through a fake field "$$here".
// This field does not exist at runtime in the object -- but that does not
// prevent the compiler from imagining that it exists.
ConstrainedType type1 = Types.toConstrainedType(type);
type1 = (ConstrainedType) PlaceChecker.AddIsHereClause(type1, tc.context());
// Add self != null
type1 = (ConstrainedType) Types.addDisBinding(type1, Types.selfVar(type1), XTerms.NULL);
if (! Types.consistent(type1))
Errors.issue(tc.job(), new Errors.InconsistentType(type1, xci.position()));
xci = (X10ConstructorInstance) xci.returnType(type1);
return xci;
}
// TODO: Move down into New_c
public void dump(CodeWriter w) {
super.dump(w);
if (ci != null) {
w.allowBreak(4, " ");
w.begin(0);
w.write("(instance " + ci + ")");
w.end();
}
w.allowBreak(4, " ");
w.begin(0);
w.write("(arguments " + arguments + ")");
w.end();
}
public void prettyPrint(CodeWriter w, PrettyPrinter tr) {
for (Iterator<AnnotationNode> i = (((X10Ext) this.ext()).annotations()).iterator(); i.hasNext(); ) {
AnnotationNode an = i.next();
an.prettyPrint(w, tr);
w.allowBreak(0, " ");
}
super.prettyPrint(w, tr);
}
}
diff --git a/x10.compiler/src/x10/util/RunTestSuite.java b/x10.compiler/src/x10/util/RunTestSuite.java
index e33bd094c..2703e8747 100644
--- a/x10.compiler/src/x10/util/RunTestSuite.java
+++ b/x10.compiler/src/x10/util/RunTestSuite.java
@@ -1,555 +1,556 @@
package x10.util;
import polyglot.frontend.Compiler;
import polyglot.types.Types;
import polyglot.util.SilentErrorQueue;
import polyglot.util.Position;
import polyglot.util.ErrorInfo;
import x10.util.CollectionFactory;
import polyglot.main.Main;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Comparator;
import java.lang.*;
import java.lang.StringBuilder;
import x10.parser.AutoGenSentences;
import x10.X10CompilerOptions;
/**
* This program is intended to be used to determine if on a given test
* suite there is a difference between errors produced by one version
* of the X10 compiler and another. This
* program is intended to help in situations in which the first
* version of the compiler does not completely pass the tests,
* producing some errors or failing instead. The compiler writer can
* add various <em>markers</em> into the source code for the tests
* specifying whether an error is expected on this line or not,
* whether the compiler should not parse a given line, whether the
* compiler crashes on a given file etc. This program then checks the
* errors it gets against these markers and emits an error only if the
* error it receives is not accounted for by the markers.
* <p> Here is how this program is typically used. A version of the
* compiler is considered stable if <code>RunTestSuite</code> runs on
* a given test suite without producing errors. Note: This does not
* mean that the compiler successfully handles the given tests -- just
* that the errors/crashes it produces have been accounted for by appropriate
* markers in the source code for the tests.
* Now make some changes to the compiler and run
* <code>RunTestSuite</code> again. If it produces errors, then you
* know that your code changes have caused new errors to arise. Fix
* your code so that <code>RunTestSuite</code> reports no errors. Now
* you know that your code is producing exactly the same errors as the
* stable version of the compiler.
*<p> Again, this does not mean that your new compiler has no errors,
*just that it has no <em>new</em> errors. At some point you need to
*go and fix the existing errors, and remove the corresponding markers
*from the <code>*.x10</code> files.
* <p> In more detail, this program reads a bunch of x10 files and
* runs the front end on them, taps the <code>ErrorQueue</code>,
* extracts line number information from error messages, and
* compares these errors with error markers in the file and verify
* that all errors are expected.
*
* <p> <code>RunTestSuite</code> accepts all the flags that the X10
* compiler accepts (and uses them in the same way) except that
* instead of accepting a list of <code>*.x10</code> files, it
* requires a directory (or comma-separated list of directories) to be
* provided as the first argument. From these directories it collects
* all <code>*.x10</code> files.
*
* Property flags are passed with:
* java -DFLAG=SOMETHING
*
* <p>The property flag <code>SEPARATE_COMPILER</code> can be set
* to <code>false<code> to force <code>RunTestSuite</code> to use the same
* compiler object for multiple tests. In general this runs the tests
* much faster, but is still a bit brittle (may yield errors when
* compiling each test with a separate compiler object would not).
*
* <p> The property flag <code>QUIET</code> can be set to
* <code>true</code> to run in quiet mode. In this mode various
* warnings and helpful messages are not printed out.
*
* <p> The property flag <code>SHOW_EXPECTED_ERRORS</code> prints all
* the errors (even the expected errors).
* This is useful if we want to diff the output of the compiler to make
* sure the error messages are exactly the same.
*
* <p> The property flag <code>SHOW_RUNTIMES</code> prints runtime for the entire suite and for each file.
*
*
* <p> Five kinds of error markers can be inserted in <code>*.x10</code> files:
* <ul>
* <li><code>ERR</code> - marks an error or warning
* <li><code>ShouldNotBeERR<code> - the compiler reports an error, but
* it shouldn't
* <li><code>ShouldBeErr</code> - the compiler doesn't report an
* error, but it should
* <li><code>COMPILER_CRASHES</code> - the compiler currently crashes
* on this file
* <li><code>SHOULD_NOT_PARSE</code> - the compiler should report
* parsing and lexing errors on this file
* </ul>
* <p> Multiple markers (even of the same kind) may appear on the
* same line. Thus if a line is marked with <code>ShouldNotBeErr
* ShouldNotBeErr</code>, the test runner complains if the compiler
* does not produce two errors on this line.
* <p>The first 3 markers (<code>ERR, ShouldNotBeERR, ShouldBeErr</code>)
* can come in the form of annotations (<code>@ERR</code>) or in the
* form of comments (<code>// ERR</code>) The last two
* (<code>COMPILER_CRASHES,SHOULD_NOT_PARSE</code>) must be a comment.
*
* <p> Annotations are replaced with errors by a compiler phase called
* <code>ErrChecker</code> that happens immediately after parsing.
* <p> The problem with annotations currently
* are:
* <ol>
<li>You can't put annotations on statement expressions, i.e.,
* <code> @ERR i=3;</code>
* doesn't parse
* However, you can write:
* <code>@ERR {i=3;}</code>
*
*
* By default we run the compiler with VERBOSE_CHECKS.
* If the file contains the line:
//OPTIONS: -STATIC_CHECKS
* then we run it with STATIC_CHECKS.
* Some directories are permenantly excluded from the test suite
* (see EXCLUDE_DIRS and EXCLUDE_FILES fields)
* For example, "AutoGen" direcotry contains really big files that takes a long time to compile,
* or LangSpec contains some problematic files I can't fix because they are auto-generated.
</ul>
*/
public class RunTestSuite {
public static String getProp(String name, String defVal) {
final String val = System.getProperty(name); // I prefer System.getProperty over getenv because you see the properties on the command line for the java (it's not something you set on the outside)
System.out.println("getProperty("+name+")="+val);
return val==null ? defVal : val;
}
public static boolean getBoolProp(String name) {
final String val = getProp(name,null);
return val!=null && (val.equalsIgnoreCase("t") || val.equalsIgnoreCase("true"));
}
public static boolean SEPARATE_COMPILER = getBoolProp("SEPARATE_COMPILER");
public static boolean SHOW_EXPECTED_ERRORS = getBoolProp("SHOW_EXPECTED_ERRORS");
public static boolean SHOW_RUNTIMES = getBoolProp("SHOW_RUNTIMES");
public static boolean SKIP_CRASHES = getBoolProp("SKIP_CRASHES");
public static boolean QUIET = !SHOW_EXPECTED_ERRORS && getBoolProp("QUIET");
public static String SOURCE_PATH_SEP = File.pathSeparator; // on MAC the separator is ":" and on windows it is ";"
public static String LANGSPEC = "LangSpec"; // in LangSpec directory we ignore multiple errors on the same line (so one ERR marker matches any number of errors)
private static void println(String s) {
if (!QUIET) {
System.out.println(s);
System.out.flush();
}
}
private static int EXIT_CODE = 0;
private static java.lang.StringBuilder ALL_ERRORS = new StringBuilder();
private static void err(String s) {
EXIT_CODE = 1;
System.err.println(s);
System.err.flush();
ALL_ERRORS.append(s).append("\n");
}
//_MustFailCompile means the compilation should fail.
//_MustFailTimeout means that when running the file it will have an infinite loop
private static final String[] EXCLUDE_FILES_WITH_SUFFIX = {
//"_MustFailCompile.x10",
};
private static final String[] EXCLUDE_DIRS = {
"LangSpec", // Bard has too many errors...
+ "UByte","UShort","ULong", // Somebody duplicated all the files (without package names), so I only test those in UInt
"WorkStealing", // it has copies of existing tests
"AutoGen", // it takes too long to compile these files
"NOT_WORKING", // to exclude some benchmarks: https://x10.svn.sourceforge.net/svnroot/x10/benchmarks/trunk
};
private static final String[] EXCLUDE_FILES = {
// difference on MAC and PC (on PC the compiler crashes on AssertionError, on MAC it outputs this error: Semantic Error: Type definition type static TypedefOverloading06_MustFailCompile.A = x10.lang.String has the same name as member class TypedefOverloading06_MustFailCompile.A.
"TypedefOverloading04_MustFailCompile.x10",
"TypedefOverloading06_MustFailCompile.x10",
"TypedefOverloading08_MustFailCompile.x10",
"TypedefOverloading10_MustFailCompile.x10",
"TypedefNew11_MustFailCompile.x10",
"TypedefBasic2.x10",
// LangSpec is auto-generated, so I can't fix those files to make a clean test suite
"Classes250.x10","Classes160.x10","Classes170.x10",
"Interfaces3l4a.x10", "Interfaces_static_val.x10", "Types2y3i.x10", "Types6a9m.x10",
"InnerClasses5p9v.x10","Packages5t5g.x10","Stimulus.x10","Statements51.x10", "ClassCtor30_MustFailCompile.x10", "ThisEscapingViaAt_MustFailCompile.x10",
};
private static final String[] EXCLUDE_FILES_WITH = {
};
private static final String[] INCLUDE_ONLY_FILES_WITH = {
//"_MustFailCompile.x10",
};
public static final int MAX_ERR_QUEUE = 10000;
static {
Arrays.sort(EXCLUDE_FILES);
Arrays.sort(EXCLUDE_DIRS);
}
private static boolean shouldIgnoreDir(String name) {
if (Arrays.binarySearch(EXCLUDE_DIRS,name)>=0) return true;
return false;
}
private static boolean shouldIgnoreFile(String name) {
if (Arrays.binarySearch(EXCLUDE_FILES,name)>=0) return true;
for (String suffix : EXCLUDE_FILES_WITH_SUFFIX)
if (name.endsWith(suffix))
return true;
for (String mid : EXCLUDE_FILES_WITH)
if (name.contains(mid))
return true;
if (INCLUDE_ONLY_FILES_WITH.length>0) {
for (String mid : INCLUDE_ONLY_FILES_WITH)
if (name.contains(mid))
return false;
return true;
}
return false;
}
private static final int MAX_FILES_NUM = Integer.MAX_VALUE; // Change it if you want to process only a small number of files
public static void Assert(boolean val, String msg) {
if (!val) throw new RuntimeException(msg);
}
public static void checkAssertionsEnabled() {
boolean isEA = true;
try {
assert false : "Test if assertion work";
isEA = false;
} catch (Throwable e) {}
if (!isEA) throw new RuntimeException("You must run RunTestSuite with assertions enabled, i.e., java -ea RunTestSuite ...");
}
/**
* Finds all *.x10 files in all sub-directories, and compiles them.
* @param args
* The first argument is the directory to search all the *.x10 files.
* E.g.,
* C:\cygwin\home\Yoav\intellij\sourceforge\x10.runtime\src-x10
* C:\cygwin\home\Yoav\intellij\sourceforge\x10.tests
* @throws Throwable Can be a failed assertion or missing file.
*/
public static void main(String[] args) throws Throwable {
checkAssertionsEnabled();
Assert(args.length>0, "The first command line argument must be an x10 filename or a comma separated list of the directories.\n"+
"E.g.,\n"+
"C:\\cygwin\\home\\Yoav\\intellij\\sourceforge\\x10.tests,C:\\cygwin\\home\\Yoav\\intellij\\sourceforge\\x10.dist\\samples,C:\\cygwin\\home\\Yoav\\intellij\\sourceforge\\x10.runtime\\src-x10");
List<String> remainingArgs = new ArrayList<String>(Arrays.asList(args));
remainingArgs.remove(0);
for (String s : args) {
if (s.contains("STATIC_CHECKS") || s.contains("VERBOSE_CHECKS"))
throw new RuntimeException("You should run the test suite without -VERBOSE_CHECKS or -STATIC_CHECKS");
}
if (SEPARATE_COMPILER)
println("Running each file with a separate (new) compiler object, so it's less efficient but more stable.");
ArrayList<File> files = new ArrayList<File>(10);
for (String dirStr : args[0].split(",")) {
if (dirStr.endsWith(".x10")) {
final File dir = new File(dirStr);
Assert(dir.isFile(), "File does not exist: "+dirStr);
files.add(getCanonicalFile(dir));
} else {
File dir = new File(dirStr);
Assert(dir.isDirectory(), "The first command line argument must be a directory or x10 file, and you passed: "+dir);
int before = files.size();
recurse(dir,files);
if (before==files.size()) println("Warning: Didn't find any .x10 files to compile in any subdirectory of "+dir);
}
}
ArrayList<FileSummary> summaries = new ArrayList<FileSummary>();
java.util.Map<String,File> fileName2File = CollectionFactory.newHashMap();
for (File f : files) {
FileSummary fileSummary = analyzeFile(f);
summaries.add(fileSummary);
String name = f.getName();
if (fileName2File.containsKey(name))
println("Warning: Found two files with the same name in different directories. This maybe confusing and might cause problems in the classpath.\n\tfile1="+fileName2File.get(name)+"\n\tfile2="+f);
else
fileName2File.put(name,f);
}
// adding the directories of the files to -sourcepath (in case they refer to other files that are not compiled, e.g., if we decide to compile the files one by one)
// I'm also adding parent folders to support packages (see T3.x10)
LinkedHashSet<String> directories = new LinkedHashSet<String>();
for (FileSummary f : summaries) {
int index = -1;
while ((index = f.fileName.indexOf('/',index+1))!=-1) {
directories.add(f.fileName.substring(0, index));
}
}
String dirs = "";
for (String dir : directories)
dirs += SOURCE_PATH_SEP+dir;
remainingArgs.add("-sourcepath");
remainingArgs.add(dirs);
remainingArgs.add("-CHECK_ERR_MARKERS"); // make sure we check @ERR annotations
remainingArgs.add("-CHECK_INVARIANTS");
println("sourcepath is: "+dirs);
println("Arguments are:"+remainingArgs);
long start = System.currentTimeMillis();
for (FileSummary f : summaries) {
compileFile(f,remainingArgs);
}
// report remaining errors that were not matched in any file
printRemaining(null);
if (SHOW_RUNTIMES) println("Total running time to compile all files="+(System.currentTimeMillis()-start));
if (EXIT_CODE!=0) System.out.println("Summary of all errors:\n\n"+ALL_ERRORS);
System.out.println("\n\n\n\n\n"+ (EXIT_CODE==0 ? "SUCCESS" : "FAILED") + "\n\n\n");
System.exit(EXIT_CODE);
}
private static void printRemaining(File file) {
for (Iterator<ErrorInfo> it = remainingErrors.iterator(); it.hasNext();) {
ErrorInfo err = it.next();
final Position pos = err.getPosition();
if (file==null || pos==null || isInFile(pos,file)) {
it.remove();
err((err.getErrorKind()==ErrorInfo.WARNING ? "Warning":"ERROR")+" in position:\n"+ pos +"\nMessage: "+err+"\n");
}
}
}
private static int count(String s, String sub) {
final int len = sub.length();
int index=-len, res=0;
while ((index=s.indexOf(sub,index+len))>=0) res++;
return res;
}
public static ArrayList<ErrorInfo> runCompiler(String[] newArgs) {
return runCompiler(newArgs,false,false);
}
private static SilentErrorQueue errQueue = new SilentErrorQueue(MAX_ERR_QUEUE,"TestSuiteErrQueue");
private static Main MAIN = new Main();
private static Compiler COMPILER;
public static ArrayList<ErrorInfo> runCompiler(String[] newArgs, boolean COMPILER_CRASHES, boolean STATIC_CHECKS) {
errQueue.getErrors().clear();
LinkedHashSet<String> sources = new LinkedHashSet<String>();
final Compiler comp = MAIN.getCompiler(newArgs, null, errQueue, sources);
if (SEPARATE_COMPILER || COMPILER==null)
COMPILER = comp;
X10CompilerOptions opts = (X10CompilerOptions) COMPILER.sourceExtension().getOptions();
opts.x10_config.STATIC_CHECKS = STATIC_CHECKS;
opts.x10_config.VERBOSE_CHECKS = !STATIC_CHECKS;
opts.x10_config.VERBOSE = true;
long start = System.currentTimeMillis();
Throwable err = null;
try {
if (COMPILER_CRASHES && SKIP_CRASHES) {
err = new RuntimeException("We do not want to compile crashes when SKIP_CRASHES=true");
} else
COMPILER.compileFiles(sources);
} catch (Throwable e) {
err = e;
}
if (COMPILER_CRASHES) {
if (err==null) err("We expected the compiler to crash, but it didn't :) Remove the 'COMPILER_CRASHES' marker from file "+newArgs[0]);
} else {
if (err!=null) {
err("Compiler crashed for args="+Arrays.toString(newArgs)+" with exception:");
err.printStackTrace();
}
}
if (SHOW_RUNTIMES) println("Compiler running time="+(System.currentTimeMillis()-start));
final ArrayList<ErrorInfo> res = (ArrayList<ErrorInfo>) errQueue.getErrors();
Assert(res.size()<MAX_ERR_QUEUE, "We passed the maximum number of errors!");
return res;
}
static class LineSummary {
int lineNo;
int errCount;
// todo: add todo, ShouldNotBeERR, ShouldBeErr statistics.
}
static class FileSummary {
final File file;
final String fileName;
FileSummary(File f) {
file = f;
fileName = f.getAbsolutePath().replace('\\','/');
}
boolean STATIC_CHECKS = false;
boolean COMPILER_CRASHES;
boolean SHOULD_NOT_PARSE;
ArrayList<String> options = new ArrayList<String>();
ArrayList<LineSummary> lines = new ArrayList<LineSummary>();
}
private static FileSummary analyzeFile(File file) throws IOException {
FileSummary res = new FileSummary(file);
final ArrayList<String> lines = AutoGenSentences.readFile(file);
int lineNum = 0;
for (String line : lines) {
lineNum++;
if (line.contains("COMPILER_CRASHES")) res.COMPILER_CRASHES = true;
if (line.contains("SHOULD_NOT_PARSE")) res.SHOULD_NOT_PARSE = true;
int optionsIndex = line.indexOf("OPTIONS:");
if (optionsIndex>=0) {
final String option = line.substring(optionsIndex + "OPTIONS:".length()).trim();
res.options.add(option);
if (option.equals("-STATIC_CHECKS"))
res.STATIC_CHECKS = true;
}
line = line.trim();
int commentIndex = line.indexOf("//");
if (commentIndex>0) { // if the line contains just a comment, then we ignore it.
int errIndex = line.indexOf("ERR");
boolean isERR = errIndex!=-1;
if (isERR && commentIndex<errIndex) {
LineSummary lineSummary = new LineSummary();
lineSummary.lineNo = lineNum;
lineSummary.errCount = count(line,"ERR");
res.lines.add(lineSummary);
}
}
}
return res;
}
private static void compileFile(FileSummary summary, List<String> args) throws IOException {
File file = summary.file;
boolean STATIC_CHECKS = summary.STATIC_CHECKS; // all the files without ERR markers are done in my batch, using STATIC_CHECKS (cause they shouldn't have any errors)
// Now running polyglot
List<String> allArgs = new ArrayList<String>();
allArgs.add(summary.fileName);
allArgs.addAll(args);
String[] newArgs = allArgs.toArray(new String[allArgs.size()+2]);
newArgs[newArgs.length-2] = STATIC_CHECKS ? "-STATIC_CHECKS" : "-VERBOSE_CHECKS";
newArgs[newArgs.length-1] = STATIC_CHECKS ? "-VERBOSE_CHECKS=false" : "-STATIC_CHECKS=false";
println("Running: "+ summary.fileName);
ArrayList<ErrorInfo> errors = runCompiler(newArgs, summary.COMPILER_CRASHES, STATIC_CHECKS);
// remove SHOULD_BE_ERR_MARKER and
// parsing errors (if SHOULD_NOT_PARSE)
// treating @ERR and @ShouldNotBeERR as if it were a comment (adding a LineSummary)
boolean didFailCompile = false;
for (Iterator<ErrorInfo> it = errors.iterator(); it.hasNext(); ) {
ErrorInfo info = it.next();
final int kind = info.getErrorKind();
if (ErrorInfo.isErrorKind(kind))
didFailCompile = true;
if ((kind==ErrorInfo.SHOULD_BE_ERR_MARKER) ||
(summary.SHOULD_NOT_PARSE && (kind==ErrorInfo.LEXICAL_ERROR || kind==ErrorInfo.SYNTAX_ERROR)))
it.remove();
final Position position = info.getPosition();
if (kind==ErrorInfo.ERR_MARKER || kind==ErrorInfo.SHOULD_NOT_BE_ERR_MARKER) {
it.remove();
int lineNo = position.line();
LineSummary foundLine = null;
for (LineSummary lineSummary : summary.lines)
if (lineNo==lineSummary.lineNo) {
foundLine = lineSummary;
break;
}
if (foundLine==null) {
foundLine = new LineSummary();
foundLine.lineNo = lineNo;
summary.lines.add(foundLine);
}
foundLine.errCount++;
}
}
if (didFailCompile!=summary.fileName.endsWith("_MustFailCompile.x10") && !summary.fileName.contains("TorontoSuite")) {
println("WARNING: "+ summary.fileName+" "+(didFailCompile ? "FAILED":"SUCCESSFULLY")+" compiled, therefore it should "+(didFailCompile?"":"NOT ")+"end with _MustFailCompile.x10. "+(summary.lines.isEmpty()?"":"It did have @ERR markers but they might match warnings."));
}
errors.addAll(remainingErrors);
remainingErrors.clear();
// Now checking the errors reported are correct and match ERR markers
// 1. find all ERR markers that don't have a corresponding error
for (LineSummary lineSummary : summary.lines) {
// try to find the matching error
int expectedErrCount = lineSummary.errCount;
int lineNum = lineSummary.lineNo;
int foundErrCount = 0;
ArrayList<ErrorInfo> errorsFound = new ArrayList<ErrorInfo>(expectedErrCount);
for (Iterator<ErrorInfo> it=errors.iterator(); it.hasNext(); ) {
ErrorInfo err = it.next();
final Position position = err.getPosition();
if (position!=null && isInFile(position,file) && position.line()==lineNum) {
// found it!
errorsFound.add(err);
it.remove();
if (SHOW_EXPECTED_ERRORS)
println("Found error in position="+position+" err: "+ err);
foundErrCount++;
}
}
if (expectedErrCount!=foundErrCount &&
// we try to have at most 1 error in a line when writing the tests, but sometimes an error cascades into multiple ones
(expectedErrCount<2 || foundErrCount<2)) { // if the compiler reports more than 2 errors, and we marked more than 2, then it's too many errors on one line and it marks the fact the compiler went crazy and issues too many wrong errors.
if (foundErrCount>1 && expectedErrCount==1 && summary.fileName.contains(LANGSPEC)) {
// nothing to do - a single ERR marker in LangSpec match multiple errors
} else
err("File "+file+" has "+expectedErrCount+" ERR markers on line "+lineNum+", but the compiler reported "+ foundErrCount+" errors on that line! errorsFound=\n"+errorsFound);
}
}
// 2. report all the remaining errors that didn't have a matching ERR marker
remainingErrors.addAll(errors);
printRemaining(file);
// todo: check that for each file (without errors) we generated a *.class file, and load them and run their main method (except for the ones with _MustFailTimeout)
}
static boolean isInFile(Position position, File file) {
return new File(position.file()).equals(file);
}
static ArrayList<ErrorInfo> remainingErrors = new ArrayList<ErrorInfo>(); // sometimes when compiling one file it uses another that has an ERR marker, so we keep those errors so we will match them to ERR markers in the other file (e.g., Activity.x10 uses HashMap.x10 that has an ERR marker for a warning)
private static void recurse(File dir, ArrayList<File> files) {
if (files.size()>=MAX_FILES_NUM) return;
// sort the result, so the output is identical for diff purposes (see SHOW_EXPECTED_ERRORS)
final File[] filesInDir = dir.listFiles();
Arrays.sort(filesInDir, new Comparator<File>() {
public int compare(File o1, File o2) {
return o1.getName().compareTo(o2.getName()); // comparing o1.compareTo(o2) directly is different on MAC and PC (on MAC: Array1DCodeGen.x10 < Array1b.x10, and on PC it's reverse)
}
});
for (File f : filesInDir) {
String name = f.getName();
final boolean isDir = f.isDirectory();
if (!isDir && shouldIgnoreFile(name)) continue;
if (isDir && shouldIgnoreDir(name)) continue;
if (files.size()>=MAX_FILES_NUM) return;
if (isDir)
recurse(f, files);
else {
if (name.endsWith(".x10")) {
files.add(getCanonicalFile(f));
}
}
}
}
private static File getCanonicalFile(File f) {
try {
return f.getCanonicalFile();
} catch (java.io.IOException e) {
return f;
}
}
}
| false | false | null | null |
diff --git a/tests/org.eclipse.emf.eef.non-reg.edit/src-gen/org/eclipse/emf/eef/nonreg/parts/SitePropertiesEditionPart.java b/tests/org.eclipse.emf.eef.non-reg.edit/src-gen/org/eclipse/emf/eef/nonreg/parts/SitePropertiesEditionPart.java
index 917754a35..33de41fd9 100644
--- a/tests/org.eclipse.emf.eef.non-reg.edit/src-gen/org/eclipse/emf/eef/nonreg/parts/SitePropertiesEditionPart.java
+++ b/tests/org.eclipse.emf.eef.non-reg.edit/src-gen/org/eclipse/emf/eef/nonreg/parts/SitePropertiesEditionPart.java
@@ -1,63 +1,62 @@
/**
* Generated with Acceleo
*/
package org.eclipse.emf.eef.nonreg.parts;
-import org.eclipse.emf.eef.runtime.api.parts.IPropertiesEditionPart;
-
-// Start of user code for imports
+//Start of user code for imports
+import org.eclipse.emf.eef.runtime.api.parts.IPropertiesEditionPart;
// End of user code
/**
*
*/
public interface SitePropertiesEditionPart {
/**
* @return the NamedElement referenced view
*/
public IPropertiesEditionPart getNamedElementReferencedView();
/**
* @return the name
*/
public String getName();
/**
* Defines a new name
* @param newValue the new name to set
*/
public void setName(String newValue);
public void setMessageForName(String msg, int msgLevel);
public void unsetMessageForName();
/**
* @return the documentation
*/
public String getDocumentation();
/**
* Defines a new documentation
* @param newValue the new documentation to set
*/
public void setDocumentation(String newValue);
public void setMessageForDocumentation(String msg, int msgLevel);
public void unsetMessageForDocumentation();
// Start of user code for additional methods
// End of user code
}
diff --git a/tests/org.eclipse.emf.eef.non-reg.edit/src-gen/org/eclipse/emf/eef/nonreg/parts/TopicPropertiesEditionPart.java b/tests/org.eclipse.emf.eef.non-reg.edit/src-gen/org/eclipse/emf/eef/nonreg/parts/TopicPropertiesEditionPart.java
index 703b3cec7..a38ddea5f 100644
--- a/tests/org.eclipse.emf.eef.non-reg.edit/src-gen/org/eclipse/emf/eef/nonreg/parts/TopicPropertiesEditionPart.java
+++ b/tests/org.eclipse.emf.eef.non-reg.edit/src-gen/org/eclipse/emf/eef/nonreg/parts/TopicPropertiesEditionPart.java
@@ -1,63 +1,63 @@
/**
* Generated with Acceleo
*/
package org.eclipse.emf.eef.nonreg.parts;
-import org.eclipse.emf.eef.runtime.api.parts.IPropertiesEditionPart;
// Start of user code for imports
+import org.eclipse.emf.eef.runtime.api.parts.IPropertiesEditionPart;
// End of user code
/**
*
*/
public interface TopicPropertiesEditionPart {
/**
* @return the description
*/
public String getDescription();
/**
* Defines a new description
* @param newValue the new description to set
*/
public void setDescription(String newValue);
public void setMessageForDescription(String msg, int msgLevel);
public void unsetMessageForDescription();
/**
* @return the DocumentedElement referenced view
*/
public IPropertiesEditionPart getDocumentedElementReferencedView();
/**
* @return the documentation
*/
public String getDocumentation();
/**
* Defines a new documentation
* @param newValue the new documentation to set
*/
public void setDocumentation(String newValue);
public void setMessageForDocumentation(String msg, int msgLevel);
public void unsetMessageForDocumentation();
// Start of user code for additional methods
// End of user code
}
| false | false | null | null |
diff --git a/client-ui/src/main/java/com/thinkparity/ophelia/browser/application/browser/display/renderer/tab/panel/PanelCellListModel.java b/client-ui/src/main/java/com/thinkparity/ophelia/browser/application/browser/display/renderer/tab/panel/PanelCellListModel.java
index 0c30935e5..5a2c910cf 100755
--- a/client-ui/src/main/java/com/thinkparity/ophelia/browser/application/browser/display/renderer/tab/panel/PanelCellListModel.java
+++ b/client-ui/src/main/java/com/thinkparity/ophelia/browser/application/browser/display/renderer/tab/panel/PanelCellListModel.java
@@ -1,345 +1,346 @@
/**
* Created On: 16-Dec-06 1:18:16 AM
* $Id$
*/
package com.thinkparity.ophelia.browser.application.browser.display.renderer.tab.panel;
import java.text.MessageFormat;
import java.util.List;
import javax.swing.DefaultListModel;
import javax.swing.KeyStroke;
import javax.swing.event.ListDataEvent;
import javax.swing.event.ListDataListener;
import com.thinkparity.ophelia.browser.application.browser.display.avatar.tab.TabDelegate;
import com.thinkparity.ophelia.browser.application.browser.display.renderer.tab.DefaultTabPanel;
import com.thinkparity.ophelia.browser.util.localization.Localization;
/**
* @author [email protected]
* @version $Revision$
*/
public class PanelCellListModel implements PanelSelectionManager{
/** The default selected row when the content changes. */
private static final int DEFAULT_SELECTED_ROW_PAGING;
/** The default selected row when the content changes. */
private static final int DEFAULT_SELECTED_ROW_START;
/** A session key pattern for the data listener. */
private static final String SK_LIST_DATA_LISTENER_PATTERN;
/** A session key pattern for the list's selected index. */
private static final String SK_LIST_SELECTED_CELL_PATTERN;
static {
DEFAULT_SELECTED_ROW_PAGING = 1;
DEFAULT_SELECTED_ROW_START = 0;
SK_LIST_DATA_LISTENER_PATTERN = "PanelCellListModel#getSavedListDataListener({0}:{1})";
SK_LIST_SELECTED_CELL_PATTERN = "PanelCellListModel#getSavedSelectedCell({0}:{1})";
}
/** The list manager. */
private final PanelCellListManager listManager;
/** The list model <code>DefaultListModel</code>. */
private final DefaultListModel listModel;
/** The list name */
private final String listName;
/** The selection. */
private int selectedIndex;
/** The tab panel */
private final DefaultTabPanel tabPanel;
/**
* Create a PanelCellListModel.
*
* Handles the model of visible panel cells, including
* selection index and next/previous buttons, for a list
* of Cells.
*
* @param tabPanel
* A <code>DefaultTabPanel</code> invoker.
* @param listName
* A list name <code>String</code>.
* @param localization
* A <code>Localization</code>.
* @param visibleRows
* The number of visible rows.
* @param firstJLabel
* The first <code>JLabel</code>.
* @param previousJLabel
* The previous <code>JLabel</code>.
* @param countJLabel
* The count <code>JLabel</code>.
* @param nextJLabel
* The next <code>JLabel</code>.
* @param lastJLabel
* The last <code>JLabel</code>.
*/
public PanelCellListModel(
final DefaultTabPanel tabPanel,
final String listName,
final Localization localization,
final int visibleRows,
final javax.swing.JLabel firstJLabel,
final javax.swing.JLabel previousJLabel,
final javax.swing.JLabel countJLabel,
final javax.swing.JLabel nextJLabel,
final javax.swing.JLabel lastJLabel) {
super();
this.tabPanel = tabPanel;
this.listName = listName;
listModel = new DefaultListModel();
listManager = new PanelCellListManager(this, localization,
visibleRows, firstJLabel, previousJLabel, countJLabel,
nextJLabel, lastJLabel, Boolean.TRUE);
selectedIndex = -1;
}
/**
* Get the index of the cell in the list model.
*
* @param cell
* A <code>Cell</code>.
* @return The index of the cell in the list model.
*/
public int getIndexOf(final Cell cell) {
return listModel.indexOf(cell);
}
/**
* Get the list model.
*
* @return The <code>DefaultListModel</code>.
*/
public DefaultListModel getListModel() {
return listModel;
}
/**
* Get the selected cell.
*
* @return The selected <code>Cell</code>.
*/
public Cell getSelectedCell() {
if (isSelectionEmpty()) {
return null;
} else {
return (Cell)listModel.get(selectedIndex);
}
}
/**
* Get the selected index.
*
* @return The selected index <code>int</code>.
*/
public int getSelectedIndex() {
return selectedIndex;
}
/**
* Initialize the list model with a list of cells.
*
* @param cells
* A List of <code>? extends Cell</code>.
*/
public void initialize(final List<? extends Cell> cells) {
listManager.initialize(cells);
installDataListener();
if (isSavedSelectedCell()) {
setSelectedCell(getSavedSelectedCell());
} else {
int initialSelectedIndex = DEFAULT_SELECTED_ROW_START;
if (initialSelectedIndex >= cells.size()) {
initialSelectedIndex = 0;
}
setSelectedIndex(initialSelectedIndex);
}
+ tabPanel.panelCellSelectionChanged(getSelectedCell());
}
/**
* @see com.thinkparity.ophelia.browser.application.browser.display.renderer.tab.panel.PanelSelectionManager#isSelected(com.thinkparity.ophelia.browser.application.browser.display.renderer.tab.panel.Cell)
*/
public Boolean isSelected(final Cell cell) {
return (!isSelectionEmpty() && selectedIndex == getIndexOf(cell));
}
/**
* Determine if the selection is empty.
*
* @return true if the selection is empty.
*/
public Boolean isSelectionEmpty() {
return (selectedIndex < 0);
}
/**
* Process a key stroke.
*
* @param keyStroke
* A <code>KeyStroke</code>.
*/
public void processKeyStroke(final KeyStroke keyStroke) {
listManager.processKeyStroke(keyStroke);
}
/**
* Select a cell.
*
* @param cell
* A <code>Cell</code>.
*/
public void setSelectedCell(final Cell cell) {
final int page = listManager.getPageContainingCell(cell);
if (0 <= page) {
listManager.showPage(page);
}
setSelectedIndex(listModel.indexOf(cell));
}
/**
* Select the cell by index.
* NOTE All cell selection goes through this method.
*
* @param selectedIndex
* The selected index <code>int</code>.
*/
public void setSelectedIndex(final int selectedIndex) {
final int oldSelectedIndex = this.selectedIndex;
this.selectedIndex = selectedIndex;
if (oldSelectedIndex != selectedIndex && !isSelectionEmpty()) {
final Cell selectedCell = getSelectedCell();
tabPanel.panelCellSelectionChanged(selectedCell);
saveSelectedCell(selectedCell);
}
selectPanel();
}
/**
* Show the first page.
*/
public void showFirstPage() {
listManager.showPage(0);
}
/**
* Get the saved list data listener.
*
* @return The saved <code>ListDataListener</code>.
*/
private ListDataListener getSavedListDataListener() {
return (ListDataListener) tabPanel.getAttribute(MessageFormat.format(
SK_LIST_DATA_LISTENER_PATTERN, tabPanel.getId(), listName));
}
/**
* Get the saved selected cell.
*
* @return The saved selected <code>Cell</code>.
*/
private Cell getSavedSelectedCell() {
final String selectedCellId =
(String) tabPanel.getAttribute(MessageFormat.format(
SK_LIST_SELECTED_CELL_PATTERN, tabPanel.getId(), listName));
for (final Cell cell : listManager.getCells()) {
if (cell.getId().equals(selectedCellId)) {
return cell;
}
}
return null;
}
/**
* Install the data listener.
*/
private void installDataListener() {
if (null == getSavedListDataListener()) {
final ListDataListener listener = new ListDataListener() {
/**
* @see javax.swing.event.ListDataListener#contentsChanged(javax.swing.event.ListDataEvent)
*/
public void contentsChanged(final ListDataEvent e) {
setDefaultSelectedIndex();
}
/**
* @see javax.swing.event.ListDataListener#intervalAdded(javax.swing.event.ListDataEvent)
*/
public void intervalAdded(final ListDataEvent e) {
setDefaultSelectedIndex();
}
/**
* @see javax.swing.event.ListDataListener#intervalRemoved(javax.swing.event.ListDataEvent)
*/
public void intervalRemoved(final ListDataEvent e) {
setSelectedIndex(-1);
}
};
listModel.addListDataListener(listener);
saveListDataListener(listener);
}
}
/**
* Determine if there is a saved selected cell.
*
* @return true if there is a saved selected cell.
*/
private Boolean isSavedSelectedCell() {
return (null != getSavedSelectedCell());
}
/**
* Save the list data listener.
*
* @param listDataListener
* The <code>ListDataListener</code>.
*/
private void saveListDataListener(final ListDataListener listDataListener) {
tabPanel.setAttribute(MessageFormat.format(
SK_LIST_DATA_LISTENER_PATTERN, tabPanel.getId(), listName),
listDataListener);
}
/**
* Save the selected cell.
*
* @param selectedCell
* The selected <code>Cell</code>.
*/
private void saveSelectedCell(final Cell selectedCell) {
tabPanel.setAttribute(MessageFormat.format(
SK_LIST_SELECTED_CELL_PATTERN, tabPanel.getId(), listName),
selectedCell.getId());
}
/**
* Select the panel.
*/
private void selectPanel() {
// This is done so other panels will deselect when there is activity in
// the expanded panel. Note also that the null check is because this method
// may get called during initialization before the delegate is set up.
final TabDelegate delegate = tabPanel.getTabDelegate();
if (null != delegate) {
delegate.selectPanel(tabPanel);
}
}
/**
* Set the default selected index (for paging).
*/
private void setDefaultSelectedIndex() {
int initialSelectedIndex = DEFAULT_SELECTED_ROW_PAGING;
if (initialSelectedIndex >= listModel.size()) {
initialSelectedIndex = 0;
}
setSelectedIndex(initialSelectedIndex);
}
}
diff --git a/local/browser/src/main/java/com/thinkparity/ophelia/browser/application/browser/display/renderer/tab/panel/PanelCellListModel.java b/local/browser/src/main/java/com/thinkparity/ophelia/browser/application/browser/display/renderer/tab/panel/PanelCellListModel.java
index 0c30935e5..5a2c910cf 100755
--- a/local/browser/src/main/java/com/thinkparity/ophelia/browser/application/browser/display/renderer/tab/panel/PanelCellListModel.java
+++ b/local/browser/src/main/java/com/thinkparity/ophelia/browser/application/browser/display/renderer/tab/panel/PanelCellListModel.java
@@ -1,345 +1,346 @@
/**
* Created On: 16-Dec-06 1:18:16 AM
* $Id$
*/
package com.thinkparity.ophelia.browser.application.browser.display.renderer.tab.panel;
import java.text.MessageFormat;
import java.util.List;
import javax.swing.DefaultListModel;
import javax.swing.KeyStroke;
import javax.swing.event.ListDataEvent;
import javax.swing.event.ListDataListener;
import com.thinkparity.ophelia.browser.application.browser.display.avatar.tab.TabDelegate;
import com.thinkparity.ophelia.browser.application.browser.display.renderer.tab.DefaultTabPanel;
import com.thinkparity.ophelia.browser.util.localization.Localization;
/**
* @author [email protected]
* @version $Revision$
*/
public class PanelCellListModel implements PanelSelectionManager{
/** The default selected row when the content changes. */
private static final int DEFAULT_SELECTED_ROW_PAGING;
/** The default selected row when the content changes. */
private static final int DEFAULT_SELECTED_ROW_START;
/** A session key pattern for the data listener. */
private static final String SK_LIST_DATA_LISTENER_PATTERN;
/** A session key pattern for the list's selected index. */
private static final String SK_LIST_SELECTED_CELL_PATTERN;
static {
DEFAULT_SELECTED_ROW_PAGING = 1;
DEFAULT_SELECTED_ROW_START = 0;
SK_LIST_DATA_LISTENER_PATTERN = "PanelCellListModel#getSavedListDataListener({0}:{1})";
SK_LIST_SELECTED_CELL_PATTERN = "PanelCellListModel#getSavedSelectedCell({0}:{1})";
}
/** The list manager. */
private final PanelCellListManager listManager;
/** The list model <code>DefaultListModel</code>. */
private final DefaultListModel listModel;
/** The list name */
private final String listName;
/** The selection. */
private int selectedIndex;
/** The tab panel */
private final DefaultTabPanel tabPanel;
/**
* Create a PanelCellListModel.
*
* Handles the model of visible panel cells, including
* selection index and next/previous buttons, for a list
* of Cells.
*
* @param tabPanel
* A <code>DefaultTabPanel</code> invoker.
* @param listName
* A list name <code>String</code>.
* @param localization
* A <code>Localization</code>.
* @param visibleRows
* The number of visible rows.
* @param firstJLabel
* The first <code>JLabel</code>.
* @param previousJLabel
* The previous <code>JLabel</code>.
* @param countJLabel
* The count <code>JLabel</code>.
* @param nextJLabel
* The next <code>JLabel</code>.
* @param lastJLabel
* The last <code>JLabel</code>.
*/
public PanelCellListModel(
final DefaultTabPanel tabPanel,
final String listName,
final Localization localization,
final int visibleRows,
final javax.swing.JLabel firstJLabel,
final javax.swing.JLabel previousJLabel,
final javax.swing.JLabel countJLabel,
final javax.swing.JLabel nextJLabel,
final javax.swing.JLabel lastJLabel) {
super();
this.tabPanel = tabPanel;
this.listName = listName;
listModel = new DefaultListModel();
listManager = new PanelCellListManager(this, localization,
visibleRows, firstJLabel, previousJLabel, countJLabel,
nextJLabel, lastJLabel, Boolean.TRUE);
selectedIndex = -1;
}
/**
* Get the index of the cell in the list model.
*
* @param cell
* A <code>Cell</code>.
* @return The index of the cell in the list model.
*/
public int getIndexOf(final Cell cell) {
return listModel.indexOf(cell);
}
/**
* Get the list model.
*
* @return The <code>DefaultListModel</code>.
*/
public DefaultListModel getListModel() {
return listModel;
}
/**
* Get the selected cell.
*
* @return The selected <code>Cell</code>.
*/
public Cell getSelectedCell() {
if (isSelectionEmpty()) {
return null;
} else {
return (Cell)listModel.get(selectedIndex);
}
}
/**
* Get the selected index.
*
* @return The selected index <code>int</code>.
*/
public int getSelectedIndex() {
return selectedIndex;
}
/**
* Initialize the list model with a list of cells.
*
* @param cells
* A List of <code>? extends Cell</code>.
*/
public void initialize(final List<? extends Cell> cells) {
listManager.initialize(cells);
installDataListener();
if (isSavedSelectedCell()) {
setSelectedCell(getSavedSelectedCell());
} else {
int initialSelectedIndex = DEFAULT_SELECTED_ROW_START;
if (initialSelectedIndex >= cells.size()) {
initialSelectedIndex = 0;
}
setSelectedIndex(initialSelectedIndex);
}
+ tabPanel.panelCellSelectionChanged(getSelectedCell());
}
/**
* @see com.thinkparity.ophelia.browser.application.browser.display.renderer.tab.panel.PanelSelectionManager#isSelected(com.thinkparity.ophelia.browser.application.browser.display.renderer.tab.panel.Cell)
*/
public Boolean isSelected(final Cell cell) {
return (!isSelectionEmpty() && selectedIndex == getIndexOf(cell));
}
/**
* Determine if the selection is empty.
*
* @return true if the selection is empty.
*/
public Boolean isSelectionEmpty() {
return (selectedIndex < 0);
}
/**
* Process a key stroke.
*
* @param keyStroke
* A <code>KeyStroke</code>.
*/
public void processKeyStroke(final KeyStroke keyStroke) {
listManager.processKeyStroke(keyStroke);
}
/**
* Select a cell.
*
* @param cell
* A <code>Cell</code>.
*/
public void setSelectedCell(final Cell cell) {
final int page = listManager.getPageContainingCell(cell);
if (0 <= page) {
listManager.showPage(page);
}
setSelectedIndex(listModel.indexOf(cell));
}
/**
* Select the cell by index.
* NOTE All cell selection goes through this method.
*
* @param selectedIndex
* The selected index <code>int</code>.
*/
public void setSelectedIndex(final int selectedIndex) {
final int oldSelectedIndex = this.selectedIndex;
this.selectedIndex = selectedIndex;
if (oldSelectedIndex != selectedIndex && !isSelectionEmpty()) {
final Cell selectedCell = getSelectedCell();
tabPanel.panelCellSelectionChanged(selectedCell);
saveSelectedCell(selectedCell);
}
selectPanel();
}
/**
* Show the first page.
*/
public void showFirstPage() {
listManager.showPage(0);
}
/**
* Get the saved list data listener.
*
* @return The saved <code>ListDataListener</code>.
*/
private ListDataListener getSavedListDataListener() {
return (ListDataListener) tabPanel.getAttribute(MessageFormat.format(
SK_LIST_DATA_LISTENER_PATTERN, tabPanel.getId(), listName));
}
/**
* Get the saved selected cell.
*
* @return The saved selected <code>Cell</code>.
*/
private Cell getSavedSelectedCell() {
final String selectedCellId =
(String) tabPanel.getAttribute(MessageFormat.format(
SK_LIST_SELECTED_CELL_PATTERN, tabPanel.getId(), listName));
for (final Cell cell : listManager.getCells()) {
if (cell.getId().equals(selectedCellId)) {
return cell;
}
}
return null;
}
/**
* Install the data listener.
*/
private void installDataListener() {
if (null == getSavedListDataListener()) {
final ListDataListener listener = new ListDataListener() {
/**
* @see javax.swing.event.ListDataListener#contentsChanged(javax.swing.event.ListDataEvent)
*/
public void contentsChanged(final ListDataEvent e) {
setDefaultSelectedIndex();
}
/**
* @see javax.swing.event.ListDataListener#intervalAdded(javax.swing.event.ListDataEvent)
*/
public void intervalAdded(final ListDataEvent e) {
setDefaultSelectedIndex();
}
/**
* @see javax.swing.event.ListDataListener#intervalRemoved(javax.swing.event.ListDataEvent)
*/
public void intervalRemoved(final ListDataEvent e) {
setSelectedIndex(-1);
}
};
listModel.addListDataListener(listener);
saveListDataListener(listener);
}
}
/**
* Determine if there is a saved selected cell.
*
* @return true if there is a saved selected cell.
*/
private Boolean isSavedSelectedCell() {
return (null != getSavedSelectedCell());
}
/**
* Save the list data listener.
*
* @param listDataListener
* The <code>ListDataListener</code>.
*/
private void saveListDataListener(final ListDataListener listDataListener) {
tabPanel.setAttribute(MessageFormat.format(
SK_LIST_DATA_LISTENER_PATTERN, tabPanel.getId(), listName),
listDataListener);
}
/**
* Save the selected cell.
*
* @param selectedCell
* The selected <code>Cell</code>.
*/
private void saveSelectedCell(final Cell selectedCell) {
tabPanel.setAttribute(MessageFormat.format(
SK_LIST_SELECTED_CELL_PATTERN, tabPanel.getId(), listName),
selectedCell.getId());
}
/**
* Select the panel.
*/
private void selectPanel() {
// This is done so other panels will deselect when there is activity in
// the expanded panel. Note also that the null check is because this method
// may get called during initialization before the delegate is set up.
final TabDelegate delegate = tabPanel.getTabDelegate();
if (null != delegate) {
delegate.selectPanel(tabPanel);
}
}
/**
* Set the default selected index (for paging).
*/
private void setDefaultSelectedIndex() {
int initialSelectedIndex = DEFAULT_SELECTED_ROW_PAGING;
if (initialSelectedIndex >= listModel.size()) {
initialSelectedIndex = 0;
}
setSelectedIndex(initialSelectedIndex);
}
}
| false | false | null | null |
diff --git a/src/com/jetbrains/crucible/vcs/VcsUtils.java b/src/com/jetbrains/crucible/vcs/VcsUtils.java
index b9196c8..c5fd065 100644
--- a/src/com/jetbrains/crucible/vcs/VcsUtils.java
+++ b/src/com/jetbrains/crucible/vcs/VcsUtils.java
@@ -1,51 +1,51 @@
package com.jetbrains.crucible.vcs;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vcs.FilePathImpl;
import com.intellij.openapi.vcs.VcsException;
import com.intellij.openapi.vcs.history.VcsRevisionNumber;
import com.intellij.openapi.vcs.versionBrowser.CommittedChangeList;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.ThrowableRunnable;
import com.intellij.util.ui.VcsSynchronousProgressWrapper;
import git4idea.GitRevisionNumber;
import git4idea.changes.GitCommittedChangeList;
import git4idea.history.GitHistoryUtils;
-import git4idea.history.browser.GitCommit;
+import git4idea.history.browser.GitHeavyCommit;
import git4idea.history.browser.SymbolicRefs;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Collections;
import java.util.Date;
import java.util.List;
/**
* User: ktisha
*/
public class VcsUtils {
private VcsUtils() {}
@Nullable
public static CommittedChangeList loadRevisionsFromGit(@NotNull final Project project, final VirtualFile vf, final VcsRevisionNumber number) {
final CommittedChangeList[] list = new CommittedChangeList[1];
final ThrowableRunnable<VcsException> runnable = new ThrowableRunnable<VcsException>() {
@Override
public void run() throws VcsException {
final FilePathImpl filePath = new FilePathImpl(vf);
- final List<GitCommit> gitCommits =
+ final List<GitHeavyCommit> gitCommits =
GitHistoryUtils.commitsDetails(project, filePath, new SymbolicRefs(), Collections.singletonList(number.asString()));
if (gitCommits.size() != 1) {
return;
}
- final GitCommit gitCommit = gitCommits.get(0);
+ final GitHeavyCommit gitCommit = gitCommits.get(0);
CommittedChangeList commit = new GitCommittedChangeList(gitCommit.getDescription() + " (" + gitCommit.getShortHash().getString() + ")",
gitCommit.getDescription(), gitCommit.getAuthor(), (GitRevisionNumber)number,
new Date(gitCommit.getAuthorTime()), gitCommit.getChanges(), true);
list[0] = commit;
}
};
final boolean success = VcsSynchronousProgressWrapper.wrap(runnable, project, "Load revision contents");
return success ? list[0] : null;
}
}
| false | false | null | null |
diff --git a/src/com/android/music/AlbumBrowserActivity.java b/src/com/android/music/AlbumBrowserActivity.java
index 781530f..6e04476 100644
--- a/src/com/android/music/AlbumBrowserActivity.java
+++ b/src/com/android/music/AlbumBrowserActivity.java
@@ -1,685 +1,688 @@
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR 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.music;
import android.app.ListActivity;
import android.app.SearchManager;
import android.content.AsyncQueryHandler;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.media.MediaFile;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.Adapter;
import android.widget.AlphabetIndexer;
import android.widget.CursorAdapter;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SectionIndexer;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import java.text.Collator;
public class AlbumBrowserActivity extends ListActivity
implements View.OnCreateContextMenuListener, MusicUtils.Defs, ServiceConnection
{
private String mCurrentAlbumId;
private String mCurrentAlbumName;
private String mCurrentArtistNameForAlbum;
boolean mIsUnknownArtist;
boolean mIsUnknownAlbum;
private AlbumListAdapter mAdapter;
private boolean mAdapterSent;
private final static int SEARCH = CHILD_MENU_BASE;
private static int mLastListPosCourse = -1;
private static int mLastListPosFine = -1;
public AlbumBrowserActivity()
{
}
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle icicle)
{
if (icicle != null) {
mCurrentAlbumId = icicle.getString("selectedalbum");
mArtistId = icicle.getString("artist");
} else {
mArtistId = getIntent().getStringExtra("artist");
}
super.onCreate(icicle);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
MusicUtils.bindToService(this, this);
IntentFilter f = new IntentFilter();
f.addAction(Intent.ACTION_MEDIA_SCANNER_STARTED);
f.addAction(Intent.ACTION_MEDIA_SCANNER_FINISHED);
f.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
f.addDataScheme("file");
registerReceiver(mScanListener, f);
setContentView(R.layout.media_picker_activity);
MusicUtils.updateButtonBar(this, R.id.albumtab);
ListView lv = getListView();
lv.setOnCreateContextMenuListener(this);
lv.setTextFilterEnabled(true);
mAdapter = (AlbumListAdapter) getLastNonConfigurationInstance();
if (mAdapter == null) {
//Log.i("@@@", "starting query");
mAdapter = new AlbumListAdapter(
getApplication(),
this,
R.layout.track_list_item,
mAlbumCursor,
new String[] {},
new int[] {});
setListAdapter(mAdapter);
setTitle(R.string.working_albums);
getAlbumCursor(mAdapter.getQueryHandler(), null);
} else {
mAdapter.setActivity(this);
setListAdapter(mAdapter);
mAlbumCursor = mAdapter.getCursor();
if (mAlbumCursor != null) {
init(mAlbumCursor);
} else {
getAlbumCursor(mAdapter.getQueryHandler(), null);
}
}
}
@Override
public Object onRetainNonConfigurationInstance() {
mAdapterSent = true;
return mAdapter;
}
@Override
public void onSaveInstanceState(Bundle outcicle) {
// need to store the selected item so we don't lose it in case
// of an orientation switch. Otherwise we could lose it while
// in the middle of specifying a playlist to add the item to.
outcicle.putString("selectedalbum", mCurrentAlbumId);
outcicle.putString("artist", mArtistId);
super.onSaveInstanceState(outcicle);
}
@Override
public void onDestroy() {
ListView lv = getListView();
if (lv != null) {
mLastListPosCourse = lv.getFirstVisiblePosition();
- mLastListPosFine = lv.getChildAt(0).getTop();
+ View cv = lv.getChildAt(0);
+ if (cv != null) {
+ mLastListPosFine = cv.getTop();
+ }
}
MusicUtils.unbindFromService(this);
// If we have an adapter and didn't send it off to another activity yet, we should
// close its cursor, which we do by assigning a null cursor to it. Doing this
// instead of closing the cursor directly keeps the framework from accessing
// the closed cursor later.
if (!mAdapterSent && mAdapter != null) {
mAdapter.changeCursor(null);
}
// Because we pass the adapter to the next activity, we need to make
// sure it doesn't keep a reference to this activity. We can do this
// by clearing its DatasetObservers, which setListAdapter(null) does.
setListAdapter(null);
mAdapter = null;
unregisterReceiver(mScanListener);
super.onDestroy();
}
@Override
public void onResume() {
super.onResume();
IntentFilter f = new IntentFilter();
f.addAction(MediaPlaybackService.META_CHANGED);
f.addAction(MediaPlaybackService.QUEUE_CHANGED);
registerReceiver(mTrackListListener, f);
mTrackListListener.onReceive(null, null);
MusicUtils.setSpinnerState(this);
}
private BroadcastReceiver mTrackListListener = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
getListView().invalidateViews();
MusicUtils.updateNowPlaying(AlbumBrowserActivity.this);
}
};
private BroadcastReceiver mScanListener = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
MusicUtils.setSpinnerState(AlbumBrowserActivity.this);
mReScanHandler.sendEmptyMessage(0);
if (intent.getAction().equals(Intent.ACTION_MEDIA_UNMOUNTED)) {
MusicUtils.clearAlbumArtCache();
}
}
};
private Handler mReScanHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (mAdapter != null) {
getAlbumCursor(mAdapter.getQueryHandler(), null);
}
}
};
@Override
public void onPause() {
unregisterReceiver(mTrackListListener);
mReScanHandler.removeCallbacksAndMessages(null);
super.onPause();
}
public void init(Cursor c) {
if (mAdapter == null) {
return;
}
mAdapter.changeCursor(c); // also sets mAlbumCursor
if (mAlbumCursor == null) {
MusicUtils.displayDatabaseError(this);
closeContextMenu();
mReScanHandler.sendEmptyMessageDelayed(0, 1000);
return;
}
// restore previous position
if (mLastListPosCourse >= 0) {
getListView().setSelectionFromTop(mLastListPosCourse, mLastListPosFine);
mLastListPosCourse = -1;
}
MusicUtils.hideDatabaseError(this);
MusicUtils.updateButtonBar(this, R.id.albumtab);
setTitle();
}
private void setTitle() {
CharSequence fancyName = "";
if (mAlbumCursor != null && mAlbumCursor.getCount() > 0) {
mAlbumCursor.moveToFirst();
fancyName = mAlbumCursor.getString(
mAlbumCursor.getColumnIndex(MediaStore.Audio.Albums.ARTIST));
if (fancyName == null || fancyName.equals(MediaFile.UNKNOWN_STRING))
fancyName = getText(R.string.unknown_artist_name);
}
if (mArtistId != null && fancyName != null)
setTitle(fancyName);
else
setTitle(R.string.albums_title);
}
@Override
public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo menuInfoIn) {
menu.add(0, PLAY_SELECTION, 0, R.string.play_selection);
SubMenu sub = menu.addSubMenu(0, ADD_TO_PLAYLIST, 0, R.string.add_to_playlist);
MusicUtils.makePlaylistMenu(this, sub);
menu.add(0, DELETE_ITEM, 0, R.string.delete_item);
AdapterContextMenuInfo mi = (AdapterContextMenuInfo) menuInfoIn;
mAlbumCursor.moveToPosition(mi.position);
mCurrentAlbumId = mAlbumCursor.getString(mAlbumCursor.getColumnIndexOrThrow(MediaStore.Audio.Albums._ID));
mCurrentAlbumName = mAlbumCursor.getString(mAlbumCursor.getColumnIndexOrThrow(MediaStore.Audio.Albums.ALBUM));
mCurrentArtistNameForAlbum = mAlbumCursor.getString(
mAlbumCursor.getColumnIndexOrThrow(MediaStore.Audio.Albums.ARTIST));
mIsUnknownArtist = mCurrentArtistNameForAlbum == null ||
mCurrentArtistNameForAlbum.equals(MediaFile.UNKNOWN_STRING);
mIsUnknownAlbum = mCurrentAlbumName == null ||
mCurrentAlbumName.equals(MediaFile.UNKNOWN_STRING);
if (mIsUnknownAlbum) {
menu.setHeaderTitle(getString(R.string.unknown_album_name));
} else {
menu.setHeaderTitle(mCurrentAlbumName);
}
if (!mIsUnknownAlbum || !mIsUnknownArtist) {
menu.add(0, SEARCH, 0, R.string.search_title);
}
}
@Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case PLAY_SELECTION: {
// play the selected album
long [] list = MusicUtils.getSongListForAlbum(this, Long.parseLong(mCurrentAlbumId));
MusicUtils.playAll(this, list, 0);
return true;
}
case QUEUE: {
long [] list = MusicUtils.getSongListForAlbum(this, Long.parseLong(mCurrentAlbumId));
MusicUtils.addToCurrentPlaylist(this, list);
return true;
}
case NEW_PLAYLIST: {
Intent intent = new Intent();
intent.setClass(this, CreatePlaylist.class);
startActivityForResult(intent, NEW_PLAYLIST);
return true;
}
case PLAYLIST_SELECTED: {
long [] list = MusicUtils.getSongListForAlbum(this, Long.parseLong(mCurrentAlbumId));
long playlist = item.getIntent().getLongExtra("playlist", 0);
MusicUtils.addToPlaylist(this, list, playlist);
return true;
}
case DELETE_ITEM: {
long [] list = MusicUtils.getSongListForAlbum(this, Long.parseLong(mCurrentAlbumId));
String f = getString(R.string.delete_album_desc);
String desc = String.format(f, mCurrentAlbumName);
Bundle b = new Bundle();
b.putString("description", desc);
b.putLongArray("items", list);
Intent intent = new Intent();
intent.setClass(this, DeleteItems.class);
intent.putExtras(b);
startActivityForResult(intent, -1);
return true;
}
case SEARCH:
doSearch();
return true;
}
return super.onContextItemSelected(item);
}
void doSearch() {
CharSequence title = null;
String query = "";
Intent i = new Intent();
i.setAction(MediaStore.INTENT_ACTION_MEDIA_SEARCH);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
title = "";
if (!mIsUnknownAlbum) {
query = mCurrentAlbumName;
i.putExtra(MediaStore.EXTRA_MEDIA_ALBUM, mCurrentAlbumName);
title = mCurrentAlbumName;
}
if(!mIsUnknownArtist) {
query = query + " " + mCurrentArtistNameForAlbum;
i.putExtra(MediaStore.EXTRA_MEDIA_ARTIST, mCurrentArtistNameForAlbum);
title = title + " " + mCurrentArtistNameForAlbum;
}
// Since we hide the 'search' menu item when both album and artist are
// unknown, the query and title strings will have at least one of those.
i.putExtra(MediaStore.EXTRA_MEDIA_FOCUS, MediaStore.Audio.Albums.ENTRY_CONTENT_TYPE);
title = getString(R.string.mediasearch, title);
i.putExtra(SearchManager.QUERY, query);
startActivity(Intent.createChooser(i, title));
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
switch (requestCode) {
case SCAN_DONE:
if (resultCode == RESULT_CANCELED) {
finish();
} else {
getAlbumCursor(mAdapter.getQueryHandler(), null);
}
break;
case NEW_PLAYLIST:
if (resultCode == RESULT_OK) {
Uri uri = intent.getData();
if (uri != null) {
long [] list = MusicUtils.getSongListForAlbum(this, Long.parseLong(mCurrentAlbumId));
MusicUtils.addToPlaylist(this, list, Long.parseLong(uri.getLastPathSegment()));
}
}
break;
}
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id)
{
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setDataAndType(Uri.EMPTY, "vnd.android.cursor.dir/track");
intent.putExtra("album", Long.valueOf(id).toString());
intent.putExtra("artist", mArtistId);
startActivity(intent);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
menu.add(0, PARTY_SHUFFLE, 0, R.string.party_shuffle); // icon will be set in onPrepareOptionsMenu()
menu.add(0, SHUFFLE_ALL, 0, R.string.shuffle_all).setIcon(R.drawable.ic_menu_shuffle);
return true;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
MusicUtils.setPartyShuffleMenuIcon(menu);
return super.onPrepareOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent intent;
Cursor cursor;
switch (item.getItemId()) {
case PARTY_SHUFFLE:
MusicUtils.togglePartyShuffle();
break;
case SHUFFLE_ALL:
cursor = MusicUtils.query(this, MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
new String [] { MediaStore.Audio.Media._ID},
MediaStore.Audio.Media.IS_MUSIC + "=1", null,
MediaStore.Audio.Media.DEFAULT_SORT_ORDER);
if (cursor != null) {
MusicUtils.shuffleAll(this, cursor);
cursor.close();
}
return true;
}
return super.onOptionsItemSelected(item);
}
private Cursor getAlbumCursor(AsyncQueryHandler async, String filter) {
StringBuilder where = new StringBuilder();
where.append(MediaStore.Audio.Albums.ALBUM + " != ''");
// Add in the filtering constraints
String [] keywords = null;
if (filter != null) {
String [] searchWords = filter.split(" ");
keywords = new String[searchWords.length];
Collator col = Collator.getInstance();
col.setStrength(Collator.PRIMARY);
for (int i = 0; i < searchWords.length; i++) {
keywords[i] = '%' + MediaStore.Audio.keyFor(searchWords[i]) + '%';
}
for (int i = 0; i < searchWords.length; i++) {
where.append(" AND ");
where.append(MediaStore.Audio.Media.ARTIST_KEY + "||");
where.append(MediaStore.Audio.Media.ALBUM_KEY + " LIKE ?");
}
}
String whereclause = where.toString();
String[] cols = new String[] {
MediaStore.Audio.Albums._ID,
MediaStore.Audio.Albums.ARTIST,
MediaStore.Audio.Albums.ALBUM,
MediaStore.Audio.Albums.ALBUM_ART
};
Cursor ret = null;
if (mArtistId != null) {
if (async != null) {
async.startQuery(0, null,
MediaStore.Audio.Artists.Albums.getContentUri("external",
Long.valueOf(mArtistId)),
cols, whereclause, keywords, MediaStore.Audio.Albums.DEFAULT_SORT_ORDER);
} else {
ret = MusicUtils.query(this,
MediaStore.Audio.Artists.Albums.getContentUri("external",
Long.valueOf(mArtistId)),
cols, whereclause, keywords, MediaStore.Audio.Albums.DEFAULT_SORT_ORDER);
}
} else {
if (async != null) {
async.startQuery(0, null,
MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI,
cols, whereclause, keywords, MediaStore.Audio.Albums.DEFAULT_SORT_ORDER);
} else {
ret = MusicUtils.query(this, MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI,
cols, whereclause, keywords, MediaStore.Audio.Albums.DEFAULT_SORT_ORDER);
}
}
return ret;
}
static class AlbumListAdapter extends SimpleCursorAdapter implements SectionIndexer {
private final Drawable mNowPlayingOverlay;
private final BitmapDrawable mDefaultAlbumIcon;
private int mAlbumIdx;
private int mArtistIdx;
private int mAlbumArtIndex;
private final Resources mResources;
private final StringBuilder mStringBuilder = new StringBuilder();
private final String mUnknownAlbum;
private final String mUnknownArtist;
private final String mAlbumSongSeparator;
private final Object[] mFormatArgs = new Object[1];
private AlphabetIndexer mIndexer;
private AlbumBrowserActivity mActivity;
private AsyncQueryHandler mQueryHandler;
private String mConstraint = null;
private boolean mConstraintIsValid = false;
static class ViewHolder {
TextView line1;
TextView line2;
ImageView play_indicator;
ImageView icon;
}
class QueryHandler extends AsyncQueryHandler {
QueryHandler(ContentResolver res) {
super(res);
}
@Override
protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
//Log.i("@@@", "query complete");
mActivity.init(cursor);
}
}
AlbumListAdapter(Context context, AlbumBrowserActivity currentactivity,
int layout, Cursor cursor, String[] from, int[] to) {
super(context, layout, cursor, from, to);
mActivity = currentactivity;
mQueryHandler = new QueryHandler(context.getContentResolver());
mUnknownAlbum = context.getString(R.string.unknown_album_name);
mUnknownArtist = context.getString(R.string.unknown_artist_name);
mAlbumSongSeparator = context.getString(R.string.albumsongseparator);
Resources r = context.getResources();
mNowPlayingOverlay = r.getDrawable(R.drawable.indicator_ic_mp_playing_list);
Bitmap b = BitmapFactory.decodeResource(r, R.drawable.albumart_mp_unknown_list);
mDefaultAlbumIcon = new BitmapDrawable(context.getResources(), b);
// no filter or dither, it's a lot faster and we can't tell the difference
mDefaultAlbumIcon.setFilterBitmap(false);
mDefaultAlbumIcon.setDither(false);
getColumnIndices(cursor);
mResources = context.getResources();
}
private void getColumnIndices(Cursor cursor) {
if (cursor != null) {
mAlbumIdx = cursor.getColumnIndexOrThrow(MediaStore.Audio.Albums.ALBUM);
mArtistIdx = cursor.getColumnIndexOrThrow(MediaStore.Audio.Albums.ARTIST);
mAlbumArtIndex = cursor.getColumnIndexOrThrow(MediaStore.Audio.Albums.ALBUM_ART);
if (mIndexer != null) {
mIndexer.setCursor(cursor);
} else {
mIndexer = new MusicAlphabetIndexer(cursor, mAlbumIdx, mResources.getString(
com.android.internal.R.string.fast_scroll_alphabet));
}
}
}
public void setActivity(AlbumBrowserActivity newactivity) {
mActivity = newactivity;
}
public AsyncQueryHandler getQueryHandler() {
return mQueryHandler;
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View v = super.newView(context, cursor, parent);
ViewHolder vh = new ViewHolder();
vh.line1 = (TextView) v.findViewById(R.id.line1);
vh.line2 = (TextView) v.findViewById(R.id.line2);
vh.play_indicator = (ImageView) v.findViewById(R.id.play_indicator);
vh.icon = (ImageView) v.findViewById(R.id.icon);
vh.icon.setBackgroundDrawable(mDefaultAlbumIcon);
vh.icon.setPadding(0, 0, 1, 0);
v.setTag(vh);
return v;
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
ViewHolder vh = (ViewHolder) view.getTag();
String name = cursor.getString(mAlbumIdx);
String displayname = name;
boolean unknown = name == null || name.equals(MediaFile.UNKNOWN_STRING);
if (unknown) {
displayname = mUnknownAlbum;
}
vh.line1.setText(displayname);
name = cursor.getString(mArtistIdx);
displayname = name;
if (name == null || name.equals(MediaFile.UNKNOWN_STRING)) {
displayname = mUnknownArtist;
}
vh.line2.setText(displayname);
ImageView iv = vh.icon;
// We don't actually need the path to the thumbnail file,
// we just use it to see if there is album art or not
String art = cursor.getString(mAlbumArtIndex);
long aid = cursor.getLong(0);
if (unknown || art == null || art.length() == 0) {
iv.setImageDrawable(null);
} else {
Drawable d = MusicUtils.getCachedArtwork(context, aid, mDefaultAlbumIcon);
iv.setImageDrawable(d);
}
long currentalbumid = MusicUtils.getCurrentAlbumId();
iv = vh.play_indicator;
if (currentalbumid == aid) {
iv.setImageDrawable(mNowPlayingOverlay);
} else {
iv.setImageDrawable(null);
}
}
@Override
public void changeCursor(Cursor cursor) {
if (mActivity.isFinishing() && cursor != null) {
cursor.close();
cursor = null;
}
if (cursor != mActivity.mAlbumCursor) {
mActivity.mAlbumCursor = cursor;
getColumnIndices(cursor);
super.changeCursor(cursor);
}
}
@Override
public Cursor runQueryOnBackgroundThread(CharSequence constraint) {
String s = constraint.toString();
if (mConstraintIsValid && (
(s == null && mConstraint == null) ||
(s != null && s.equals(mConstraint)))) {
return getCursor();
}
Cursor c = mActivity.getAlbumCursor(null, s);
mConstraint = s;
mConstraintIsValid = true;
return c;
}
public Object[] getSections() {
return mIndexer.getSections();
}
public int getPositionForSection(int section) {
return mIndexer.getPositionForSection(section);
}
public int getSectionForPosition(int position) {
return 0;
}
}
private Cursor mAlbumCursor;
private String mArtistId;
public void onServiceConnected(ComponentName name, IBinder service) {
MusicUtils.updateNowPlaying(this);
}
public void onServiceDisconnected(ComponentName name) {
finish();
}
}
diff --git a/src/com/android/music/ArtistAlbumBrowserActivity.java b/src/com/android/music/ArtistAlbumBrowserActivity.java
index ad94cb1..a696fb3 100644
--- a/src/com/android/music/ArtistAlbumBrowserActivity.java
+++ b/src/com/android/music/ArtistAlbumBrowserActivity.java
@@ -1,872 +1,875 @@
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR 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.music;
import com.android.music.QueryBrowserActivity.QueryListAdapter.QueryHandler;
import android.app.ExpandableListActivity;
import android.app.SearchManager;
import android.content.AsyncQueryHandler;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.CursorWrapper;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.media.MediaFile;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Parcel;
import android.os.Parcelable;
import android.provider.MediaStore;
import android.util.Log;
import android.util.SparseArray;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.SectionIndexer;
import android.widget.SimpleCursorTreeAdapter;
import android.widget.TextView;
import android.widget.ExpandableListView.ExpandableListContextMenuInfo;
import java.text.Collator;
public class ArtistAlbumBrowserActivity extends ExpandableListActivity
implements View.OnCreateContextMenuListener, MusicUtils.Defs, ServiceConnection
{
private String mCurrentArtistId;
private String mCurrentArtistName;
private String mCurrentAlbumId;
private String mCurrentAlbumName;
private String mCurrentArtistNameForAlbum;
boolean mIsUnknownArtist;
boolean mIsUnknownAlbum;
private ArtistAlbumListAdapter mAdapter;
private boolean mAdapterSent;
private final static int SEARCH = CHILD_MENU_BASE;
private static int mLastListPosCourse = -1;
private static int mLastListPosFine = -1;
public void onTabClick(View v) {
MusicUtils.processTabClick(this, v, R.id.artisttab);
}
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
if (icicle != null) {
mCurrentAlbumId = icicle.getString("selectedalbum");
mCurrentAlbumName = icicle.getString("selectedalbumname");
mCurrentArtistId = icicle.getString("selectedartist");
mCurrentArtistName = icicle.getString("selectedartistname");
}
MusicUtils.bindToService(this, this);
IntentFilter f = new IntentFilter();
f.addAction(Intent.ACTION_MEDIA_SCANNER_STARTED);
f.addAction(Intent.ACTION_MEDIA_SCANNER_FINISHED);
f.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
f.addDataScheme("file");
registerReceiver(mScanListener, f);
setContentView(R.layout.media_picker_activity_expanding);
MusicUtils.updateButtonBar(this, R.id.artisttab);
ExpandableListView lv = getExpandableListView();
lv.setOnCreateContextMenuListener(this);
lv.setTextFilterEnabled(true);
mAdapter = (ArtistAlbumListAdapter) getLastNonConfigurationInstance();
if (mAdapter == null) {
//Log.i("@@@", "starting query");
mAdapter = new ArtistAlbumListAdapter(
getApplication(),
this,
null, // cursor
R.layout.track_list_item_group,
new String[] {},
new int[] {},
R.layout.track_list_item_child,
new String[] {},
new int[] {});
setListAdapter(mAdapter);
setTitle(R.string.working_artists);
getArtistCursor(mAdapter.getQueryHandler(), null);
} else {
mAdapter.setActivity(this);
setListAdapter(mAdapter);
mArtistCursor = mAdapter.getCursor();
if (mArtistCursor != null) {
init(mArtistCursor);
} else {
getArtistCursor(mAdapter.getQueryHandler(), null);
}
}
}
@Override
public Object onRetainNonConfigurationInstance() {
mAdapterSent = true;
return mAdapter;
}
@Override
public void onSaveInstanceState(Bundle outcicle) {
// need to store the selected item so we don't lose it in case
// of an orientation switch. Otherwise we could lose it while
// in the middle of specifying a playlist to add the item to.
outcicle.putString("selectedalbum", mCurrentAlbumId);
outcicle.putString("selectedalbumname", mCurrentAlbumName);
outcicle.putString("selectedartist", mCurrentArtistId);
outcicle.putString("selectedartistname", mCurrentArtistName);
super.onSaveInstanceState(outcicle);
}
@Override
public void onDestroy() {
ExpandableListView lv = getExpandableListView();
if (lv != null) {
mLastListPosCourse = lv.getFirstVisiblePosition();
- mLastListPosFine = lv.getChildAt(0).getTop();
+ View cv = lv.getChildAt(0);
+ if (cv != null) {
+ mLastListPosFine = cv.getTop();
+ }
}
MusicUtils.unbindFromService(this);
// If we have an adapter and didn't send it off to another activity yet, we should
// close its cursor, which we do by assigning a null cursor to it. Doing this
// instead of closing the cursor directly keeps the framework from accessing
// the closed cursor later.
if (!mAdapterSent && mAdapter != null) {
mAdapter.changeCursor(null);
}
// Because we pass the adapter to the next activity, we need to make
// sure it doesn't keep a reference to this activity. We can do this
// by clearing its DatasetObservers, which setListAdapter(null) does.
setListAdapter(null);
mAdapter = null;
unregisterReceiver(mScanListener);
setListAdapter(null);
super.onDestroy();
}
@Override
public void onResume() {
super.onResume();
IntentFilter f = new IntentFilter();
f.addAction(MediaPlaybackService.META_CHANGED);
f.addAction(MediaPlaybackService.QUEUE_CHANGED);
registerReceiver(mTrackListListener, f);
mTrackListListener.onReceive(null, null);
MusicUtils.setSpinnerState(this);
}
private BroadcastReceiver mTrackListListener = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
getExpandableListView().invalidateViews();
MusicUtils.updateNowPlaying(ArtistAlbumBrowserActivity.this);
}
};
private BroadcastReceiver mScanListener = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
MusicUtils.setSpinnerState(ArtistAlbumBrowserActivity.this);
mReScanHandler.sendEmptyMessage(0);
if (intent.getAction().equals(Intent.ACTION_MEDIA_UNMOUNTED)) {
MusicUtils.clearAlbumArtCache();
}
}
};
private Handler mReScanHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (mAdapter != null) {
getArtistCursor(mAdapter.getQueryHandler(), null);
}
}
};
@Override
public void onPause() {
unregisterReceiver(mTrackListListener);
mReScanHandler.removeCallbacksAndMessages(null);
super.onPause();
}
public void init(Cursor c) {
if (mAdapter == null) {
return;
}
mAdapter.changeCursor(c); // also sets mArtistCursor
if (mArtistCursor == null) {
MusicUtils.displayDatabaseError(this);
closeContextMenu();
mReScanHandler.sendEmptyMessageDelayed(0, 1000);
return;
}
// restore previous position
if (mLastListPosCourse >= 0) {
ExpandableListView elv = getExpandableListView();
elv.setSelectionFromTop(mLastListPosCourse, mLastListPosFine);
mLastListPosCourse = -1;
}
MusicUtils.hideDatabaseError(this);
MusicUtils.updateButtonBar(this, R.id.artisttab);
setTitle();
}
private void setTitle() {
setTitle(R.string.artists_title);
}
@Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
mCurrentAlbumId = Long.valueOf(id).toString();
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setDataAndType(Uri.EMPTY, "vnd.android.cursor.dir/track");
intent.putExtra("album", mCurrentAlbumId);
Cursor c = (Cursor) getExpandableListAdapter().getChild(groupPosition, childPosition);
String album = c.getString(c.getColumnIndex(MediaStore.Audio.Albums.ALBUM));
if (album == null || album.equals(MediaFile.UNKNOWN_STRING)) {
// unknown album, so we should include the artist ID to limit the songs to songs only by that artist
mArtistCursor.moveToPosition(groupPosition);
mCurrentArtistId = mArtistCursor.getString(mArtistCursor.getColumnIndex(MediaStore.Audio.Artists._ID));
intent.putExtra("artist", mCurrentArtistId);
}
startActivity(intent);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
menu.add(0, PARTY_SHUFFLE, 0, R.string.party_shuffle); // icon will be set in onPrepareOptionsMenu()
menu.add(0, SHUFFLE_ALL, 0, R.string.shuffle_all).setIcon(R.drawable.ic_menu_shuffle);
return true;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
MusicUtils.setPartyShuffleMenuIcon(menu);
return super.onPrepareOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent intent;
Cursor cursor;
switch (item.getItemId()) {
case PARTY_SHUFFLE:
MusicUtils.togglePartyShuffle();
break;
case SHUFFLE_ALL:
cursor = MusicUtils.query(this, MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
new String [] { MediaStore.Audio.Media._ID},
MediaStore.Audio.Media.IS_MUSIC + "=1", null,
MediaStore.Audio.Media.DEFAULT_SORT_ORDER);
if (cursor != null) {
MusicUtils.shuffleAll(this, cursor);
cursor.close();
}
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo menuInfoIn) {
menu.add(0, PLAY_SELECTION, 0, R.string.play_selection);
SubMenu sub = menu.addSubMenu(0, ADD_TO_PLAYLIST, 0, R.string.add_to_playlist);
MusicUtils.makePlaylistMenu(this, sub);
menu.add(0, DELETE_ITEM, 0, R.string.delete_item);
ExpandableListContextMenuInfo mi = (ExpandableListContextMenuInfo) menuInfoIn;
int itemtype = ExpandableListView.getPackedPositionType(mi.packedPosition);
int gpos = ExpandableListView.getPackedPositionGroup(mi.packedPosition);
int cpos = ExpandableListView.getPackedPositionChild(mi.packedPosition);
if (itemtype == ExpandableListView.PACKED_POSITION_TYPE_GROUP) {
if (gpos == -1) {
// this shouldn't happen
Log.d("Artist/Album", "no group");
return;
}
gpos = gpos - getExpandableListView().getHeaderViewsCount();
mArtistCursor.moveToPosition(gpos);
mCurrentArtistId = mArtistCursor.getString(mArtistCursor.getColumnIndexOrThrow(MediaStore.Audio.Artists._ID));
mCurrentArtistName = mArtistCursor.getString(mArtistCursor.getColumnIndexOrThrow(MediaStore.Audio.Artists.ARTIST));
mCurrentAlbumId = null;
mIsUnknownArtist = mCurrentArtistName == null ||
mCurrentArtistName.equals(MediaFile.UNKNOWN_STRING);
mIsUnknownAlbum = true;
if (mIsUnknownArtist) {
menu.setHeaderTitle(getString(R.string.unknown_artist_name));
} else {
menu.setHeaderTitle(mCurrentArtistName);
menu.add(0, SEARCH, 0, R.string.search_title);
}
return;
} else if (itemtype == ExpandableListView.PACKED_POSITION_TYPE_CHILD) {
if (cpos == -1) {
// this shouldn't happen
Log.d("Artist/Album", "no child");
return;
}
Cursor c = (Cursor) getExpandableListAdapter().getChild(gpos, cpos);
c.moveToPosition(cpos);
mCurrentArtistId = null;
mCurrentAlbumId = Long.valueOf(mi.id).toString();
mCurrentAlbumName = c.getString(c.getColumnIndexOrThrow(MediaStore.Audio.Albums.ALBUM));
gpos = gpos - getExpandableListView().getHeaderViewsCount();
mArtistCursor.moveToPosition(gpos);
mCurrentArtistNameForAlbum = mArtistCursor.getString(
mArtistCursor.getColumnIndexOrThrow(MediaStore.Audio.Artists.ARTIST));
mIsUnknownArtist = mCurrentArtistNameForAlbum == null ||
mCurrentArtistNameForAlbum.equals(MediaFile.UNKNOWN_STRING);
mIsUnknownAlbum = mCurrentAlbumName == null ||
mCurrentAlbumName.equals(MediaFile.UNKNOWN_STRING);
if (mIsUnknownAlbum) {
menu.setHeaderTitle(getString(R.string.unknown_album_name));
} else {
menu.setHeaderTitle(mCurrentAlbumName);
}
if (!mIsUnknownAlbum || !mIsUnknownArtist) {
menu.add(0, SEARCH, 0, R.string.search_title);
}
}
}
@Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case PLAY_SELECTION: {
// play everything by the selected artist
long [] list =
mCurrentArtistId != null ?
MusicUtils.getSongListForArtist(this, Long.parseLong(mCurrentArtistId))
: MusicUtils.getSongListForAlbum(this, Long.parseLong(mCurrentAlbumId));
MusicUtils.playAll(this, list, 0);
return true;
}
case QUEUE: {
long [] list =
mCurrentArtistId != null ?
MusicUtils.getSongListForArtist(this, Long.parseLong(mCurrentArtistId))
: MusicUtils.getSongListForAlbum(this, Long.parseLong(mCurrentAlbumId));
MusicUtils.addToCurrentPlaylist(this, list);
return true;
}
case NEW_PLAYLIST: {
Intent intent = new Intent();
intent.setClass(this, CreatePlaylist.class);
startActivityForResult(intent, NEW_PLAYLIST);
return true;
}
case PLAYLIST_SELECTED: {
long [] list =
mCurrentArtistId != null ?
MusicUtils.getSongListForArtist(this, Long.parseLong(mCurrentArtistId))
: MusicUtils.getSongListForAlbum(this, Long.parseLong(mCurrentAlbumId));
long playlist = item.getIntent().getLongExtra("playlist", 0);
MusicUtils.addToPlaylist(this, list, playlist);
return true;
}
case DELETE_ITEM: {
long [] list;
String desc;
if (mCurrentArtistId != null) {
list = MusicUtils.getSongListForArtist(this, Long.parseLong(mCurrentArtistId));
String f = getString(R.string.delete_artist_desc);
desc = String.format(f, mCurrentArtistName);
} else {
list = MusicUtils.getSongListForAlbum(this, Long.parseLong(mCurrentAlbumId));
String f = getString(R.string.delete_album_desc);
desc = String.format(f, mCurrentAlbumName);
}
Bundle b = new Bundle();
b.putString("description", desc);
b.putLongArray("items", list);
Intent intent = new Intent();
intent.setClass(this, DeleteItems.class);
intent.putExtras(b);
startActivityForResult(intent, -1);
return true;
}
case SEARCH:
doSearch();
return true;
}
return super.onContextItemSelected(item);
}
void doSearch() {
CharSequence title = null;
String query = null;
Intent i = new Intent();
i.setAction(MediaStore.INTENT_ACTION_MEDIA_SEARCH);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
if (mCurrentArtistId != null) {
title = mCurrentArtistName;
query = mCurrentArtistName;
i.putExtra(MediaStore.EXTRA_MEDIA_ARTIST, mCurrentArtistName);
i.putExtra(MediaStore.EXTRA_MEDIA_FOCUS, MediaStore.Audio.Artists.ENTRY_CONTENT_TYPE);
} else {
if (mIsUnknownAlbum) {
title = query = mCurrentArtistNameForAlbum;
} else {
title = query = mCurrentAlbumName;
if (!mIsUnknownArtist) {
query = query + " " + mCurrentArtistNameForAlbum;
}
}
i.putExtra(MediaStore.EXTRA_MEDIA_ARTIST, mCurrentArtistNameForAlbum);
i.putExtra(MediaStore.EXTRA_MEDIA_ALBUM, mCurrentAlbumName);
i.putExtra(MediaStore.EXTRA_MEDIA_FOCUS, MediaStore.Audio.Albums.ENTRY_CONTENT_TYPE);
}
title = getString(R.string.mediasearch, title);
i.putExtra(SearchManager.QUERY, query);
startActivity(Intent.createChooser(i, title));
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
switch (requestCode) {
case SCAN_DONE:
if (resultCode == RESULT_CANCELED) {
finish();
} else {
getArtistCursor(mAdapter.getQueryHandler(), null);
}
break;
case NEW_PLAYLIST:
if (resultCode == RESULT_OK) {
Uri uri = intent.getData();
if (uri != null) {
long [] list = null;
if (mCurrentArtistId != null) {
list = MusicUtils.getSongListForArtist(this, Long.parseLong(mCurrentArtistId));
} else if (mCurrentAlbumId != null) {
list = MusicUtils.getSongListForAlbum(this, Long.parseLong(mCurrentAlbumId));
}
MusicUtils.addToPlaylist(this, list, Long.parseLong(uri.getLastPathSegment()));
}
}
break;
}
}
private Cursor getArtistCursor(AsyncQueryHandler async, String filter) {
StringBuilder where = new StringBuilder();
where.append(MediaStore.Audio.Artists.ARTIST + " != ''");
// Add in the filtering constraints
String [] keywords = null;
if (filter != null) {
String [] searchWords = filter.split(" ");
keywords = new String[searchWords.length];
Collator col = Collator.getInstance();
col.setStrength(Collator.PRIMARY);
for (int i = 0; i < searchWords.length; i++) {
keywords[i] = '%' + MediaStore.Audio.keyFor(searchWords[i]) + '%';
}
for (int i = 0; i < searchWords.length; i++) {
where.append(" AND ");
where.append(MediaStore.Audio.Media.ARTIST_KEY + " LIKE ?");
}
}
String whereclause = where.toString();
String[] cols = new String[] {
MediaStore.Audio.Artists._ID,
MediaStore.Audio.Artists.ARTIST,
MediaStore.Audio.Artists.NUMBER_OF_ALBUMS,
MediaStore.Audio.Artists.NUMBER_OF_TRACKS
};
Cursor ret = null;
if (async != null) {
async.startQuery(0, null, MediaStore.Audio.Artists.EXTERNAL_CONTENT_URI,
cols, whereclause , keywords, MediaStore.Audio.Artists.ARTIST_KEY);
} else {
ret = MusicUtils.query(this, MediaStore.Audio.Artists.EXTERNAL_CONTENT_URI,
cols, whereclause , keywords, MediaStore.Audio.Artists.ARTIST_KEY);
}
return ret;
}
static class ArtistAlbumListAdapter extends SimpleCursorTreeAdapter implements SectionIndexer {
private final Drawable mNowPlayingOverlay;
private final BitmapDrawable mDefaultAlbumIcon;
private int mGroupArtistIdIdx;
private int mGroupArtistIdx;
private int mGroupAlbumIdx;
private int mGroupSongIdx;
private final Context mContext;
private final Resources mResources;
private final String mAlbumSongSeparator;
private final String mUnknownAlbum;
private final String mUnknownArtist;
private final StringBuilder mBuffer = new StringBuilder();
private final Object[] mFormatArgs = new Object[1];
private final Object[] mFormatArgs3 = new Object[3];
private MusicAlphabetIndexer mIndexer;
private ArtistAlbumBrowserActivity mActivity;
private AsyncQueryHandler mQueryHandler;
private String mConstraint = null;
private boolean mConstraintIsValid = false;
static class ViewHolder {
TextView line1;
TextView line2;
ImageView play_indicator;
ImageView icon;
}
class QueryHandler extends AsyncQueryHandler {
QueryHandler(ContentResolver res) {
super(res);
}
@Override
protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
//Log.i("@@@", "query complete");
mActivity.init(cursor);
}
}
ArtistAlbumListAdapter(Context context, ArtistAlbumBrowserActivity currentactivity,
Cursor cursor, int glayout, String[] gfrom, int[] gto,
int clayout, String[] cfrom, int[] cto) {
super(context, cursor, glayout, gfrom, gto, clayout, cfrom, cto);
mActivity = currentactivity;
mQueryHandler = new QueryHandler(context.getContentResolver());
Resources r = context.getResources();
mNowPlayingOverlay = r.getDrawable(R.drawable.indicator_ic_mp_playing_list);
mDefaultAlbumIcon = (BitmapDrawable) r.getDrawable(R.drawable.albumart_mp_unknown_list);
// no filter or dither, it's a lot faster and we can't tell the difference
mDefaultAlbumIcon.setFilterBitmap(false);
mDefaultAlbumIcon.setDither(false);
mContext = context;
getColumnIndices(cursor);
mResources = context.getResources();
mAlbumSongSeparator = context.getString(R.string.albumsongseparator);
mUnknownAlbum = context.getString(R.string.unknown_album_name);
mUnknownArtist = context.getString(R.string.unknown_artist_name);
}
private void getColumnIndices(Cursor cursor) {
if (cursor != null) {
mGroupArtistIdIdx = cursor.getColumnIndexOrThrow(MediaStore.Audio.Artists._ID);
mGroupArtistIdx = cursor.getColumnIndexOrThrow(MediaStore.Audio.Artists.ARTIST);
mGroupAlbumIdx = cursor.getColumnIndexOrThrow(MediaStore.Audio.Artists.NUMBER_OF_ALBUMS);
mGroupSongIdx = cursor.getColumnIndexOrThrow(MediaStore.Audio.Artists.NUMBER_OF_TRACKS);
if (mIndexer != null) {
mIndexer.setCursor(cursor);
} else {
mIndexer = new MusicAlphabetIndexer(cursor, mGroupArtistIdx,
mResources.getString(com.android.internal.R.string.fast_scroll_alphabet));
}
}
}
public void setActivity(ArtistAlbumBrowserActivity newactivity) {
mActivity = newactivity;
}
public AsyncQueryHandler getQueryHandler() {
return mQueryHandler;
}
@Override
public View newGroupView(Context context, Cursor cursor, boolean isExpanded, ViewGroup parent) {
View v = super.newGroupView(context, cursor, isExpanded, parent);
ImageView iv = (ImageView) v.findViewById(R.id.icon);
ViewGroup.LayoutParams p = iv.getLayoutParams();
p.width = ViewGroup.LayoutParams.WRAP_CONTENT;
p.height = ViewGroup.LayoutParams.WRAP_CONTENT;
ViewHolder vh = new ViewHolder();
vh.line1 = (TextView) v.findViewById(R.id.line1);
vh.line2 = (TextView) v.findViewById(R.id.line2);
vh.play_indicator = (ImageView) v.findViewById(R.id.play_indicator);
vh.icon = (ImageView) v.findViewById(R.id.icon);
vh.icon.setPadding(0, 0, 1, 0);
v.setTag(vh);
return v;
}
@Override
public View newChildView(Context context, Cursor cursor, boolean isLastChild,
ViewGroup parent) {
View v = super.newChildView(context, cursor, isLastChild, parent);
ViewHolder vh = new ViewHolder();
vh.line1 = (TextView) v.findViewById(R.id.line1);
vh.line2 = (TextView) v.findViewById(R.id.line2);
vh.play_indicator = (ImageView) v.findViewById(R.id.play_indicator);
vh.icon = (ImageView) v.findViewById(R.id.icon);
vh.icon.setBackgroundDrawable(mDefaultAlbumIcon);
vh.icon.setPadding(0, 0, 1, 0);
v.setTag(vh);
return v;
}
@Override
public void bindGroupView(View view, Context context, Cursor cursor, boolean isexpanded) {
ViewHolder vh = (ViewHolder) view.getTag();
String artist = cursor.getString(mGroupArtistIdx);
String displayartist = artist;
boolean unknown = artist == null || artist.equals(MediaFile.UNKNOWN_STRING);
if (unknown) {
displayartist = mUnknownArtist;
}
vh.line1.setText(displayartist);
int numalbums = cursor.getInt(mGroupAlbumIdx);
int numsongs = cursor.getInt(mGroupSongIdx);
String songs_albums = MusicUtils.makeAlbumsLabel(context,
numalbums, numsongs, unknown);
vh.line2.setText(songs_albums);
long currentartistid = MusicUtils.getCurrentArtistId();
long artistid = cursor.getLong(mGroupArtistIdIdx);
if (currentartistid == artistid && !isexpanded) {
vh.play_indicator.setImageDrawable(mNowPlayingOverlay);
} else {
vh.play_indicator.setImageDrawable(null);
}
}
@Override
public void bindChildView(View view, Context context, Cursor cursor, boolean islast) {
ViewHolder vh = (ViewHolder) view.getTag();
String name = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Albums.ALBUM));
String displayname = name;
boolean unknown = name == null || name.equals(MediaFile.UNKNOWN_STRING);
if (unknown) {
displayname = mUnknownAlbum;
}
vh.line1.setText(displayname);
int numsongs = cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Audio.Albums.NUMBER_OF_SONGS));
int numartistsongs = cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Audio.Albums.NUMBER_OF_SONGS_FOR_ARTIST));
final StringBuilder builder = mBuffer;
builder.delete(0, builder.length());
if (unknown) {
numsongs = numartistsongs;
}
if (numsongs == 1) {
builder.append(context.getString(R.string.onesong));
} else {
if (numsongs == numartistsongs) {
final Object[] args = mFormatArgs;
args[0] = numsongs;
builder.append(mResources.getQuantityString(R.plurals.Nsongs, numsongs, args));
} else {
final Object[] args = mFormatArgs3;
args[0] = numsongs;
args[1] = numartistsongs;
args[2] = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Artists.ARTIST));
builder.append(mResources.getQuantityString(R.plurals.Nsongscomp, numsongs, args));
}
}
vh.line2.setText(builder.toString());
ImageView iv = vh.icon;
// We don't actually need the path to the thumbnail file,
// we just use it to see if there is album art or not
String art = cursor.getString(cursor.getColumnIndexOrThrow(
MediaStore.Audio.Albums.ALBUM_ART));
if (unknown || art == null || art.length() == 0) {
iv.setBackgroundDrawable(mDefaultAlbumIcon);
iv.setImageDrawable(null);
} else {
long artIndex = cursor.getLong(0);
Drawable d = MusicUtils.getCachedArtwork(context, artIndex, mDefaultAlbumIcon);
iv.setImageDrawable(d);
}
long currentalbumid = MusicUtils.getCurrentAlbumId();
long aid = cursor.getLong(0);
iv = vh.play_indicator;
if (currentalbumid == aid) {
iv.setImageDrawable(mNowPlayingOverlay);
} else {
iv.setImageDrawable(null);
}
}
@Override
protected Cursor getChildrenCursor(Cursor groupCursor) {
long id = groupCursor.getLong(groupCursor.getColumnIndexOrThrow(MediaStore.Audio.Artists._ID));
String[] cols = new String[] {
MediaStore.Audio.Albums._ID,
MediaStore.Audio.Albums.ALBUM,
MediaStore.Audio.Albums.NUMBER_OF_SONGS,
MediaStore.Audio.Albums.NUMBER_OF_SONGS_FOR_ARTIST,
MediaStore.Audio.Albums.ALBUM_ART
};
Cursor c = MusicUtils.query(mActivity,
MediaStore.Audio.Artists.Albums.getContentUri("external", id),
cols, null, null, MediaStore.Audio.Albums.DEFAULT_SORT_ORDER);
class MyCursorWrapper extends CursorWrapper {
String mArtistName;
int mMagicColumnIdx;
MyCursorWrapper(Cursor c, String artist) {
super(c);
mArtistName = artist;
if (mArtistName == null || mArtistName.equals(MediaFile.UNKNOWN_STRING)) {
mArtistName = mUnknownArtist;
}
mMagicColumnIdx = c.getColumnCount();
}
@Override
public String getString(int columnIndex) {
if (columnIndex != mMagicColumnIdx) {
return super.getString(columnIndex);
}
return mArtistName;
}
@Override
public int getColumnIndexOrThrow(String name) {
if (MediaStore.Audio.Albums.ARTIST.equals(name)) {
return mMagicColumnIdx;
}
return super.getColumnIndexOrThrow(name);
}
@Override
public String getColumnName(int idx) {
if (idx != mMagicColumnIdx) {
return super.getColumnName(idx);
}
return MediaStore.Audio.Albums.ARTIST;
}
@Override
public int getColumnCount() {
return super.getColumnCount() + 1;
}
}
return new MyCursorWrapper(c, groupCursor.getString(mGroupArtistIdx));
}
@Override
public void changeCursor(Cursor cursor) {
if (mActivity.isFinishing() && cursor != null) {
cursor.close();
cursor = null;
}
if (cursor != mActivity.mArtistCursor) {
mActivity.mArtistCursor = cursor;
getColumnIndices(cursor);
super.changeCursor(cursor);
}
}
@Override
public Cursor runQueryOnBackgroundThread(CharSequence constraint) {
String s = constraint.toString();
if (mConstraintIsValid && (
(s == null && mConstraint == null) ||
(s != null && s.equals(mConstraint)))) {
return getCursor();
}
Cursor c = mActivity.getArtistCursor(null, s);
mConstraint = s;
mConstraintIsValid = true;
return c;
}
public Object[] getSections() {
return mIndexer.getSections();
}
public int getPositionForSection(int sectionIndex) {
return mIndexer.getPositionForSection(sectionIndex);
}
public int getSectionForPosition(int position) {
return 0;
}
}
private Cursor mArtistCursor;
public void onServiceConnected(ComponentName name, IBinder service) {
MusicUtils.updateNowPlaying(this);
}
public void onServiceDisconnected(ComponentName name) {
finish();
}
}
diff --git a/src/com/android/music/PlaylistBrowserActivity.java b/src/com/android/music/PlaylistBrowserActivity.java
index cd8b58e..6e57c61 100644
--- a/src/com/android/music/PlaylistBrowserActivity.java
+++ b/src/com/android/music/PlaylistBrowserActivity.java
@@ -1,634 +1,637 @@
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR 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.music;
import java.text.Collator;
import java.util.ArrayList;
import android.app.ListActivity;
import android.content.AsyncQueryHandler;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import com.android.internal.database.ArrayListCursor;
import android.database.Cursor;
import android.database.MergeCursor;
import android.database.sqlite.SQLiteException;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.AdapterContextMenuInfo;
public class PlaylistBrowserActivity extends ListActivity
implements View.OnCreateContextMenuListener, MusicUtils.Defs
{
private static final String TAG = "PlaylistBrowserActivity";
private static final int DELETE_PLAYLIST = CHILD_MENU_BASE + 1;
private static final int EDIT_PLAYLIST = CHILD_MENU_BASE + 2;
private static final int RENAME_PLAYLIST = CHILD_MENU_BASE + 3;
private static final int CHANGE_WEEKS = CHILD_MENU_BASE + 4;
private static final long RECENTLY_ADDED_PLAYLIST = -1;
private static final long ALL_SONGS_PLAYLIST = -2;
private static final long PODCASTS_PLAYLIST = -3;
private PlaylistListAdapter mAdapter;
boolean mAdapterSent;
private static int mLastListPosCourse = -1;
private static int mLastListPosFine = -1;
private boolean mCreateShortcut;
public PlaylistBrowserActivity()
{
}
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle icicle)
{
super.onCreate(icicle);
final Intent intent = getIntent();
final String action = intent.getAction();
if (Intent.ACTION_CREATE_SHORTCUT.equals(action)) {
mCreateShortcut = true;
}
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
MusicUtils.bindToService(this, new ServiceConnection() {
public void onServiceConnected(ComponentName classname, IBinder obj) {
if (Intent.ACTION_VIEW.equals(action)) {
long id = Long.parseLong(intent.getExtras().getString("playlist"));
if (id == RECENTLY_ADDED_PLAYLIST) {
playRecentlyAdded();
} else if (id == PODCASTS_PLAYLIST) {
playPodcasts();
} else if (id == ALL_SONGS_PLAYLIST) {
long [] list = MusicUtils.getAllSongs(PlaylistBrowserActivity.this);
if (list != null) {
MusicUtils.playAll(PlaylistBrowserActivity.this, list, 0);
}
} else {
MusicUtils.playPlaylist(PlaylistBrowserActivity.this, id);
}
finish();
return;
}
MusicUtils.updateNowPlaying(PlaylistBrowserActivity.this);
}
public void onServiceDisconnected(ComponentName classname) {
}
});
IntentFilter f = new IntentFilter();
f.addAction(Intent.ACTION_MEDIA_SCANNER_STARTED);
f.addAction(Intent.ACTION_MEDIA_SCANNER_FINISHED);
f.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
f.addDataScheme("file");
registerReceiver(mScanListener, f);
setContentView(R.layout.media_picker_activity);
MusicUtils.updateButtonBar(this, R.id.playlisttab);
ListView lv = getListView();
lv.setOnCreateContextMenuListener(this);
lv.setTextFilterEnabled(true);
mAdapter = (PlaylistListAdapter) getLastNonConfigurationInstance();
if (mAdapter == null) {
//Log.i("@@@", "starting query");
mAdapter = new PlaylistListAdapter(
getApplication(),
this,
R.layout.track_list_item,
mPlaylistCursor,
new String[] { MediaStore.Audio.Playlists.NAME},
new int[] { android.R.id.text1 });
setListAdapter(mAdapter);
setTitle(R.string.working_playlists);
getPlaylistCursor(mAdapter.getQueryHandler(), null);
} else {
mAdapter.setActivity(this);
setListAdapter(mAdapter);
mPlaylistCursor = mAdapter.getCursor();
// If mPlaylistCursor is null, this can be because it doesn't have
// a cursor yet (because the initial query that sets its cursor
// is still in progress), or because the query failed.
// In order to not flash the error dialog at the user for the
// first case, simply retry the query when the cursor is null.
// Worst case, we end up doing the same query twice.
if (mPlaylistCursor != null) {
init(mPlaylistCursor);
} else {
setTitle(R.string.working_playlists);
getPlaylistCursor(mAdapter.getQueryHandler(), null);
}
}
}
@Override
public Object onRetainNonConfigurationInstance() {
PlaylistListAdapter a = mAdapter;
mAdapterSent = true;
return a;
}
@Override
public void onDestroy() {
ListView lv = getListView();
if (lv != null) {
mLastListPosCourse = lv.getFirstVisiblePosition();
- mLastListPosFine = lv.getChildAt(0).getTop();
+ View cv = lv.getChildAt(0);
+ if (cv != null) {
+ mLastListPosFine = cv.getTop();
+ }
}
MusicUtils.unbindFromService(this);
// If we have an adapter and didn't send it off to another activity yet, we should
// close its cursor, which we do by assigning a null cursor to it. Doing this
// instead of closing the cursor directly keeps the framework from accessing
// the closed cursor later.
if (!mAdapterSent && mAdapter != null) {
mAdapter.changeCursor(null);
}
// Because we pass the adapter to the next activity, we need to make
// sure it doesn't keep a reference to this activity. We can do this
// by clearing its DatasetObservers, which setListAdapter(null) does.
setListAdapter(null);
mAdapter = null;
unregisterReceiver(mScanListener);
super.onDestroy();
}
@Override
public void onResume() {
super.onResume();
MusicUtils.setSpinnerState(this);
MusicUtils.updateNowPlaying(PlaylistBrowserActivity.this);
}
@Override
public void onPause() {
mReScanHandler.removeCallbacksAndMessages(null);
super.onPause();
}
private BroadcastReceiver mScanListener = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
MusicUtils.setSpinnerState(PlaylistBrowserActivity.this);
mReScanHandler.sendEmptyMessage(0);
}
};
private Handler mReScanHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (mAdapter != null) {
getPlaylistCursor(mAdapter.getQueryHandler(), null);
}
}
};
public void init(Cursor cursor) {
if (mAdapter == null) {
return;
}
mAdapter.changeCursor(cursor);
if (mPlaylistCursor == null) {
MusicUtils.displayDatabaseError(this);
closeContextMenu();
mReScanHandler.sendEmptyMessageDelayed(0, 1000);
return;
}
// restore previous position
if (mLastListPosCourse >= 0) {
getListView().setSelectionFromTop(mLastListPosCourse, mLastListPosFine);
mLastListPosCourse = -1;
}
MusicUtils.hideDatabaseError(this);
MusicUtils.updateButtonBar(this, R.id.playlisttab);
setTitle();
}
private void setTitle() {
setTitle(R.string.playlists_title);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mCreateShortcut) {
menu.add(0, PARTY_SHUFFLE, 0, R.string.party_shuffle); // icon will be set in onPrepareOptionsMenu()
}
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
MusicUtils.setPartyShuffleMenuIcon(menu);
return super.onPrepareOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent intent;
switch (item.getItemId()) {
case PARTY_SHUFFLE:
MusicUtils.togglePartyShuffle();
break;
}
return super.onOptionsItemSelected(item);
}
public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo menuInfoIn) {
if (mCreateShortcut) {
return;
}
AdapterContextMenuInfo mi = (AdapterContextMenuInfo) menuInfoIn;
menu.add(0, PLAY_SELECTION, 0, R.string.play_selection);
if (mi.id >= 0 /*|| mi.id == PODCASTS_PLAYLIST*/) {
menu.add(0, DELETE_PLAYLIST, 0, R.string.delete_playlist_menu);
}
if (mi.id == RECENTLY_ADDED_PLAYLIST) {
menu.add(0, EDIT_PLAYLIST, 0, R.string.edit_playlist_menu);
}
if (mi.id >= 0) {
menu.add(0, RENAME_PLAYLIST, 0, R.string.rename_playlist_menu);
}
mPlaylistCursor.moveToPosition(mi.position);
menu.setHeaderTitle(mPlaylistCursor.getString(mPlaylistCursor.getColumnIndexOrThrow(
MediaStore.Audio.Playlists.NAME)));
}
@Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo mi = (AdapterContextMenuInfo) item.getMenuInfo();
switch (item.getItemId()) {
case PLAY_SELECTION:
if (mi.id == RECENTLY_ADDED_PLAYLIST) {
playRecentlyAdded();
} else if (mi.id == PODCASTS_PLAYLIST) {
playPodcasts();
} else {
MusicUtils.playPlaylist(this, mi.id);
}
break;
case DELETE_PLAYLIST:
Uri uri = ContentUris.withAppendedId(
MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI, mi.id);
getContentResolver().delete(uri, null, null);
Toast.makeText(this, R.string.playlist_deleted_message, Toast.LENGTH_SHORT).show();
if (mPlaylistCursor.getCount() == 0) {
setTitle(R.string.no_playlists_title);
}
break;
case EDIT_PLAYLIST:
if (mi.id == RECENTLY_ADDED_PLAYLIST) {
Intent intent = new Intent();
intent.setClass(this, WeekSelector.class);
startActivityForResult(intent, CHANGE_WEEKS);
return true;
} else {
Log.e(TAG, "should not be here");
}
break;
case RENAME_PLAYLIST:
Intent intent = new Intent();
intent.setClass(this, RenamePlaylist.class);
intent.putExtra("rename", mi.id);
startActivityForResult(intent, RENAME_PLAYLIST);
break;
}
return true;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
switch (requestCode) {
case SCAN_DONE:
if (resultCode == RESULT_CANCELED) {
finish();
} else if (mAdapter != null) {
getPlaylistCursor(mAdapter.getQueryHandler(), null);
}
break;
}
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id)
{
if (mCreateShortcut) {
final Intent shortcut = new Intent();
shortcut.setAction(Intent.ACTION_VIEW);
shortcut.setDataAndType(Uri.EMPTY, "vnd.android.cursor.dir/playlist");
shortcut.putExtra("playlist", String.valueOf(id));
final Intent intent = new Intent();
intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcut);
intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, ((TextView) v.findViewById(R.id.line1)).getText());
intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, Intent.ShortcutIconResource.fromContext(
this, R.drawable.ic_launcher_shortcut_music_playlist));
setResult(RESULT_OK, intent);
finish();
return;
}
if (id == RECENTLY_ADDED_PLAYLIST) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setDataAndType(Uri.EMPTY, "vnd.android.cursor.dir/track");
intent.putExtra("playlist", "recentlyadded");
startActivity(intent);
} else if (id == PODCASTS_PLAYLIST) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setDataAndType(Uri.EMPTY, "vnd.android.cursor.dir/track");
intent.putExtra("playlist", "podcasts");
startActivity(intent);
} else {
Intent intent = new Intent(Intent.ACTION_EDIT);
intent.setDataAndType(Uri.EMPTY, "vnd.android.cursor.dir/track");
intent.putExtra("playlist", Long.valueOf(id).toString());
startActivity(intent);
}
}
private void playRecentlyAdded() {
// do a query for all songs added in the last X weeks
int X = MusicUtils.getIntPref(this, "numweeks", 2) * (3600 * 24 * 7);
final String[] ccols = new String[] { MediaStore.Audio.Media._ID};
String where = MediaStore.MediaColumns.DATE_ADDED + ">" + (System.currentTimeMillis() / 1000 - X);
Cursor cursor = MusicUtils.query(this, MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
ccols, where, null, MediaStore.Audio.Media.DEFAULT_SORT_ORDER);
if (cursor == null) {
// Todo: show a message
return;
}
try {
int len = cursor.getCount();
long [] list = new long[len];
for (int i = 0; i < len; i++) {
cursor.moveToNext();
list[i] = cursor.getLong(0);
}
MusicUtils.playAll(this, list, 0);
} catch (SQLiteException ex) {
} finally {
cursor.close();
}
}
private void playPodcasts() {
// do a query for all files that are podcasts
final String[] ccols = new String[] { MediaStore.Audio.Media._ID};
Cursor cursor = MusicUtils.query(this, MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
ccols, MediaStore.Audio.Media.IS_PODCAST + "=1",
null, MediaStore.Audio.Media.DEFAULT_SORT_ORDER);
if (cursor == null) {
// Todo: show a message
return;
}
try {
int len = cursor.getCount();
long [] list = new long[len];
for (int i = 0; i < len; i++) {
cursor.moveToNext();
list[i] = cursor.getLong(0);
}
MusicUtils.playAll(this, list, 0);
} catch (SQLiteException ex) {
} finally {
cursor.close();
}
}
String[] mCols = new String[] {
MediaStore.Audio.Playlists._ID,
MediaStore.Audio.Playlists.NAME
};
private Cursor getPlaylistCursor(AsyncQueryHandler async, String filterstring) {
StringBuilder where = new StringBuilder();
where.append(MediaStore.Audio.Playlists.NAME + " != ''");
// Add in the filtering constraints
String [] keywords = null;
if (filterstring != null) {
String [] searchWords = filterstring.split(" ");
keywords = new String[searchWords.length];
Collator col = Collator.getInstance();
col.setStrength(Collator.PRIMARY);
for (int i = 0; i < searchWords.length; i++) {
keywords[i] = '%' + searchWords[i] + '%';
}
for (int i = 0; i < searchWords.length; i++) {
where.append(" AND ");
where.append(MediaStore.Audio.Playlists.NAME + " LIKE ?");
}
}
String whereclause = where.toString();
if (async != null) {
async.startQuery(0, null, MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI,
mCols, whereclause, keywords, MediaStore.Audio.Playlists.NAME);
return null;
}
Cursor c = null;
c = MusicUtils.query(this, MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI,
mCols, whereclause, keywords, MediaStore.Audio.Playlists.NAME);
return mergedCursor(c);
}
private Cursor mergedCursor(Cursor c) {
if (c == null) {
return null;
}
if (c instanceof MergeCursor) {
// this shouldn't happen, but fail gracefully
Log.d("PlaylistBrowserActivity", "Already wrapped");
return c;
}
ArrayList<ArrayList> autoplaylists = new ArrayList<ArrayList>();
if (mCreateShortcut) {
ArrayList<Object> all = new ArrayList<Object>(2);
all.add(ALL_SONGS_PLAYLIST);
all.add(getString(R.string.play_all));
autoplaylists.add(all);
}
ArrayList<Object> recent = new ArrayList<Object>(2);
recent.add(RECENTLY_ADDED_PLAYLIST);
recent.add(getString(R.string.recentlyadded));
autoplaylists.add(recent);
// check if there are any podcasts
Cursor counter = MusicUtils.query(this, MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
new String[] {"count(*)"}, "is_podcast=1", null, null);
if (counter != null) {
counter.moveToFirst();
int numpodcasts = counter.getInt(0);
counter.close();
if (numpodcasts > 0) {
ArrayList<Object> podcasts = new ArrayList<Object>(2);
podcasts.add(PODCASTS_PLAYLIST);
podcasts.add(getString(R.string.podcasts_listitem));
autoplaylists.add(podcasts);
}
}
ArrayListCursor autoplaylistscursor = new ArrayListCursor(mCols, autoplaylists);
Cursor cc = new MergeCursor(new Cursor [] {autoplaylistscursor, c});
return cc;
}
static class PlaylistListAdapter extends SimpleCursorAdapter {
int mTitleIdx;
int mIdIdx;
private PlaylistBrowserActivity mActivity = null;
private AsyncQueryHandler mQueryHandler;
private String mConstraint = null;
private boolean mConstraintIsValid = false;
class QueryHandler extends AsyncQueryHandler {
QueryHandler(ContentResolver res) {
super(res);
}
@Override
protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
//Log.i("@@@", "query complete: " + cursor.getCount() + " " + mActivity);
if (cursor != null) {
cursor = mActivity.mergedCursor(cursor);
}
mActivity.init(cursor);
}
}
PlaylistListAdapter(Context context, PlaylistBrowserActivity currentactivity,
int layout, Cursor cursor, String[] from, int[] to) {
super(context, layout, cursor, from, to);
mActivity = currentactivity;
getColumnIndices(cursor);
mQueryHandler = new QueryHandler(context.getContentResolver());
}
private void getColumnIndices(Cursor cursor) {
if (cursor != null) {
mTitleIdx = cursor.getColumnIndexOrThrow(MediaStore.Audio.Playlists.NAME);
mIdIdx = cursor.getColumnIndexOrThrow(MediaStore.Audio.Playlists._ID);
}
}
public void setActivity(PlaylistBrowserActivity newactivity) {
mActivity = newactivity;
}
public AsyncQueryHandler getQueryHandler() {
return mQueryHandler;
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
TextView tv = (TextView) view.findViewById(R.id.line1);
String name = cursor.getString(mTitleIdx);
tv.setText(name);
long id = cursor.getLong(mIdIdx);
ImageView iv = (ImageView) view.findViewById(R.id.icon);
if (id == RECENTLY_ADDED_PLAYLIST) {
iv.setImageResource(R.drawable.ic_mp_playlist_recently_added_list);
} else {
iv.setImageResource(R.drawable.ic_mp_playlist_list);
}
ViewGroup.LayoutParams p = iv.getLayoutParams();
p.width = ViewGroup.LayoutParams.WRAP_CONTENT;
p.height = ViewGroup.LayoutParams.WRAP_CONTENT;
iv = (ImageView) view.findViewById(R.id.play_indicator);
iv.setVisibility(View.GONE);
view.findViewById(R.id.line2).setVisibility(View.GONE);
}
@Override
public void changeCursor(Cursor cursor) {
if (mActivity.isFinishing() && cursor != null) {
cursor.close();
cursor = null;
}
if (cursor != mActivity.mPlaylistCursor) {
mActivity.mPlaylistCursor = cursor;
super.changeCursor(cursor);
getColumnIndices(cursor);
}
}
@Override
public Cursor runQueryOnBackgroundThread(CharSequence constraint) {
String s = constraint.toString();
if (mConstraintIsValid && (
(s == null && mConstraint == null) ||
(s != null && s.equals(mConstraint)))) {
return getCursor();
}
Cursor c = mActivity.getPlaylistCursor(null, s);
mConstraint = s;
mConstraintIsValid = true;
return c;
}
}
private Cursor mPlaylistCursor;
}
diff --git a/src/com/android/music/TrackBrowserActivity.java b/src/com/android/music/TrackBrowserActivity.java
index 903f2e7..8065356 100644
--- a/src/com/android/music/TrackBrowserActivity.java
+++ b/src/com/android/music/TrackBrowserActivity.java
@@ -1,1522 +1,1525 @@
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR 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.music;
import android.app.ListActivity;
import android.app.SearchManager;
import android.content.AsyncQueryHandler;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.database.AbstractCursor;
import android.database.CharArrayBuffer;
import android.database.Cursor;
import android.media.AudioManager;
import android.media.MediaFile;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.provider.MediaStore;
import android.provider.MediaStore.Audio.Playlists;
import android.util.Log;
import android.view.ContextMenu;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.AlphabetIndexer;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SectionIndexer;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import java.text.Collator;
import java.util.Arrays;
public class TrackBrowserActivity extends ListActivity
implements View.OnCreateContextMenuListener, MusicUtils.Defs, ServiceConnection
{
private static final int Q_SELECTED = CHILD_MENU_BASE;
private static final int Q_ALL = CHILD_MENU_BASE + 1;
private static final int SAVE_AS_PLAYLIST = CHILD_MENU_BASE + 2;
private static final int PLAY_ALL = CHILD_MENU_BASE + 3;
private static final int CLEAR_PLAYLIST = CHILD_MENU_BASE + 4;
private static final int REMOVE = CHILD_MENU_BASE + 5;
private static final int SEARCH = CHILD_MENU_BASE + 6;
private static final String LOGTAG = "TrackBrowser";
private String[] mCursorCols;
private String[] mPlaylistMemberCols;
private boolean mDeletedOneRow = false;
private boolean mEditMode = false;
private String mCurrentTrackName;
private String mCurrentAlbumName;
private String mCurrentArtistNameForAlbum;
private ListView mTrackList;
private Cursor mTrackCursor;
private TrackListAdapter mAdapter;
private boolean mAdapterSent = false;
private String mAlbumId;
private String mArtistId;
private String mPlaylist;
private String mGenre;
private String mSortOrder;
private int mSelectedPosition;
private long mSelectedId;
private static int mLastListPosCourse = -1;
private static int mLastListPosFine = -1;
public TrackBrowserActivity()
{
}
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle icicle)
{
super.onCreate(icicle);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
Intent intent = getIntent();
if (intent != null) {
if (intent.getBooleanExtra("withtabs", false)) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
}
}
setVolumeControlStream(AudioManager.STREAM_MUSIC);
if (icicle != null) {
mSelectedId = icicle.getLong("selectedtrack");
mAlbumId = icicle.getString("album");
mArtistId = icicle.getString("artist");
mPlaylist = icicle.getString("playlist");
mGenre = icicle.getString("genre");
mEditMode = icicle.getBoolean("editmode", false);
} else {
mAlbumId = intent.getStringExtra("album");
// If we have an album, show everything on the album, not just stuff
// by a particular artist.
mArtistId = intent.getStringExtra("artist");
mPlaylist = intent.getStringExtra("playlist");
mGenre = intent.getStringExtra("genre");
mEditMode = intent.getAction().equals(Intent.ACTION_EDIT);
}
mCursorCols = new String[] {
MediaStore.Audio.Media._ID,
MediaStore.Audio.Media.TITLE,
MediaStore.Audio.Media.TITLE_KEY,
MediaStore.Audio.Media.DATA,
MediaStore.Audio.Media.ALBUM,
MediaStore.Audio.Media.ARTIST,
MediaStore.Audio.Media.ARTIST_ID,
MediaStore.Audio.Media.DURATION
};
mPlaylistMemberCols = new String[] {
MediaStore.Audio.Playlists.Members._ID,
MediaStore.Audio.Media.TITLE,
MediaStore.Audio.Media.TITLE_KEY,
MediaStore.Audio.Media.DATA,
MediaStore.Audio.Media.ALBUM,
MediaStore.Audio.Media.ARTIST,
MediaStore.Audio.Media.ARTIST_ID,
MediaStore.Audio.Media.DURATION,
MediaStore.Audio.Playlists.Members.PLAY_ORDER,
MediaStore.Audio.Playlists.Members.AUDIO_ID,
MediaStore.Audio.Media.IS_MUSIC
};
setContentView(R.layout.media_picker_activity);
MusicUtils.updateButtonBar(this, R.id.songtab);
mTrackList = getListView();
mTrackList.setOnCreateContextMenuListener(this);
if (mEditMode) {
((TouchInterceptor) mTrackList).setDropListener(mDropListener);
((TouchInterceptor) mTrackList).setRemoveListener(mRemoveListener);
mTrackList.setCacheColorHint(0);
} else {
mTrackList.setTextFilterEnabled(true);
}
mAdapter = (TrackListAdapter) getLastNonConfigurationInstance();
if (mAdapter != null) {
mAdapter.setActivity(this);
setListAdapter(mAdapter);
}
MusicUtils.bindToService(this, this);
}
public void onServiceConnected(ComponentName name, IBinder service)
{
IntentFilter f = new IntentFilter();
f.addAction(Intent.ACTION_MEDIA_SCANNER_STARTED);
f.addAction(Intent.ACTION_MEDIA_SCANNER_FINISHED);
f.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
f.addDataScheme("file");
registerReceiver(mScanListener, f);
if (mAdapter == null) {
//Log.i("@@@", "starting query");
mAdapter = new TrackListAdapter(
getApplication(), // need to use application context to avoid leaks
this,
mEditMode ? R.layout.edit_track_list_item : R.layout.track_list_item,
null, // cursor
new String[] {},
new int[] {},
"nowplaying".equals(mPlaylist),
mPlaylist != null &&
!(mPlaylist.equals("podcasts") || mPlaylist.equals("recentlyadded")));
setListAdapter(mAdapter);
setTitle(R.string.working_songs);
getTrackCursor(mAdapter.getQueryHandler(), null, true);
} else {
mTrackCursor = mAdapter.getCursor();
// If mTrackCursor is null, this can be because it doesn't have
// a cursor yet (because the initial query that sets its cursor
// is still in progress), or because the query failed.
// In order to not flash the error dialog at the user for the
// first case, simply retry the query when the cursor is null.
// Worst case, we end up doing the same query twice.
if (mTrackCursor != null) {
init(mTrackCursor, false);
} else {
setTitle(R.string.working_songs);
getTrackCursor(mAdapter.getQueryHandler(), null, true);
}
}
if (!mEditMode) {
MusicUtils.updateNowPlaying(this);
}
}
public void onServiceDisconnected(ComponentName name) {
// we can't really function without the service, so don't
finish();
}
@Override
public Object onRetainNonConfigurationInstance() {
TrackListAdapter a = mAdapter;
mAdapterSent = true;
return a;
}
@Override
public void onDestroy() {
ListView lv = getListView();
if (lv != null) {
mLastListPosCourse = lv.getFirstVisiblePosition();
- mLastListPosFine = lv.getChildAt(0).getTop();
+ View cv = lv.getChildAt(0);
+ if (cv != null) {
+ mLastListPosFine = cv.getTop();
+ }
}
MusicUtils.unbindFromService(this);
try {
if ("nowplaying".equals(mPlaylist)) {
unregisterReceiverSafe(mNowPlayingListener);
} else {
unregisterReceiverSafe(mTrackListListener);
}
} catch (IllegalArgumentException ex) {
// we end up here in case we never registered the listeners
}
// If we have an adapter and didn't send it off to another activity yet, we should
// close its cursor, which we do by assigning a null cursor to it. Doing this
// instead of closing the cursor directly keeps the framework from accessing
// the closed cursor later.
if (!mAdapterSent && mAdapter != null) {
mAdapter.changeCursor(null);
}
// Because we pass the adapter to the next activity, we need to make
// sure it doesn't keep a reference to this activity. We can do this
// by clearing its DatasetObservers, which setListAdapter(null) does.
setListAdapter(null);
mAdapter = null;
unregisterReceiverSafe(mScanListener);
super.onDestroy();
}
/**
* Unregister a receiver, but eat the exception that is thrown if the
* receiver was never registered to begin with. This is a little easier
* than keeping track of whether the receivers have actually been
* registered by the time onDestroy() is called.
*/
private void unregisterReceiverSafe(BroadcastReceiver receiver) {
try {
unregisterReceiver(receiver);
} catch (IllegalArgumentException e) {
// ignore
}
}
@Override
public void onResume() {
super.onResume();
if (mTrackCursor != null) {
getListView().invalidateViews();
}
MusicUtils.setSpinnerState(this);
}
@Override
public void onPause() {
mReScanHandler.removeCallbacksAndMessages(null);
super.onPause();
}
/*
* This listener gets called when the media scanner starts up or finishes, and
* when the sd card is unmounted.
*/
private BroadcastReceiver mScanListener = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (Intent.ACTION_MEDIA_SCANNER_STARTED.equals(action) ||
Intent.ACTION_MEDIA_SCANNER_FINISHED.equals(action)) {
MusicUtils.setSpinnerState(TrackBrowserActivity.this);
}
mReScanHandler.sendEmptyMessage(0);
}
};
private Handler mReScanHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (mAdapter != null) {
getTrackCursor(mAdapter.getQueryHandler(), null, true);
}
// if the query results in a null cursor, onQueryComplete() will
// call init(), which will post a delayed message to this handler
// in order to try again.
}
};
public void onSaveInstanceState(Bundle outcicle) {
// need to store the selected item so we don't lose it in case
// of an orientation switch. Otherwise we could lose it while
// in the middle of specifying a playlist to add the item to.
outcicle.putLong("selectedtrack", mSelectedId);
outcicle.putString("artist", mArtistId);
outcicle.putString("album", mAlbumId);
outcicle.putString("playlist", mPlaylist);
outcicle.putString("genre", mGenre);
outcicle.putBoolean("editmode", mEditMode);
super.onSaveInstanceState(outcicle);
}
public void init(Cursor newCursor, boolean isLimited) {
if (mAdapter == null) {
return;
}
mAdapter.changeCursor(newCursor); // also sets mTrackCursor
if (mTrackCursor == null) {
MusicUtils.displayDatabaseError(this);
closeContextMenu();
mReScanHandler.sendEmptyMessageDelayed(0, 1000);
return;
}
// Restore previous position
if (mLastListPosCourse >= 0) {
ListView lv = getListView();
// this hack is needed because otherwise the position doesn't change
// for the 2nd (non-limited) cursor
lv.setAdapter(lv.getAdapter());
lv.setSelectionFromTop(mLastListPosCourse, mLastListPosFine);
if (!isLimited) {
mLastListPosCourse = -1;
}
}
MusicUtils.hideDatabaseError(this);
MusicUtils.updateButtonBar(this, R.id.songtab);
setTitle();
// When showing the queue, position the selection on the currently playing track
// Otherwise, position the selection on the first matching artist, if any
IntentFilter f = new IntentFilter();
f.addAction(MediaPlaybackService.META_CHANGED);
f.addAction(MediaPlaybackService.QUEUE_CHANGED);
if ("nowplaying".equals(mPlaylist)) {
try {
int cur = MusicUtils.sService.getQueuePosition();
setSelection(cur);
registerReceiver(mNowPlayingListener, new IntentFilter(f));
mNowPlayingListener.onReceive(this, new Intent(MediaPlaybackService.META_CHANGED));
} catch (RemoteException ex) {
}
} else {
String key = getIntent().getStringExtra("artist");
if (key != null) {
int keyidx = mTrackCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST_ID);
mTrackCursor.moveToFirst();
while (! mTrackCursor.isAfterLast()) {
String artist = mTrackCursor.getString(keyidx);
if (artist.equals(key)) {
setSelection(mTrackCursor.getPosition());
break;
}
mTrackCursor.moveToNext();
}
}
registerReceiver(mTrackListListener, new IntentFilter(f));
mTrackListListener.onReceive(this, new Intent(MediaPlaybackService.META_CHANGED));
}
}
private void setTitle() {
CharSequence fancyName = null;
if (mAlbumId != null) {
int numresults = mTrackCursor != null ? mTrackCursor.getCount() : 0;
if (numresults > 0) {
mTrackCursor.moveToFirst();
int idx = mTrackCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM);
fancyName = mTrackCursor.getString(idx);
// For compilation albums show only the album title,
// but for regular albums show "artist - album".
// To determine whether something is a compilation
// album, do a query for the artist + album of the
// first item, and see if it returns the same number
// of results as the album query.
String where = MediaStore.Audio.Media.ALBUM_ID + "='" + mAlbumId +
"' AND " + MediaStore.Audio.Media.ARTIST_ID + "=" +
mTrackCursor.getLong(mTrackCursor.getColumnIndexOrThrow(
MediaStore.Audio.Media.ARTIST_ID));
Cursor cursor = MusicUtils.query(this, MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
new String[] {MediaStore.Audio.Media.ALBUM}, where, null, null);
if (cursor != null) {
if (cursor.getCount() != numresults) {
// compilation album
fancyName = mTrackCursor.getString(idx);
}
cursor.deactivate();
}
if (fancyName == null || fancyName.equals(MediaFile.UNKNOWN_STRING)) {
fancyName = getString(R.string.unknown_album_name);
}
}
} else if (mPlaylist != null) {
if (mPlaylist.equals("nowplaying")) {
if (MusicUtils.getCurrentShuffleMode() == MediaPlaybackService.SHUFFLE_AUTO) {
fancyName = getText(R.string.partyshuffle_title);
} else {
fancyName = getText(R.string.nowplaying_title);
}
} else if (mPlaylist.equals("podcasts")){
fancyName = getText(R.string.podcasts_title);
} else if (mPlaylist.equals("recentlyadded")){
fancyName = getText(R.string.recentlyadded_title);
} else {
String [] cols = new String [] {
MediaStore.Audio.Playlists.NAME
};
Cursor cursor = MusicUtils.query(this,
ContentUris.withAppendedId(Playlists.EXTERNAL_CONTENT_URI, Long.valueOf(mPlaylist)),
cols, null, null, null);
if (cursor != null) {
if (cursor.getCount() != 0) {
cursor.moveToFirst();
fancyName = cursor.getString(0);
}
cursor.deactivate();
}
}
} else if (mGenre != null) {
String [] cols = new String [] {
MediaStore.Audio.Genres.NAME
};
Cursor cursor = MusicUtils.query(this,
ContentUris.withAppendedId(MediaStore.Audio.Genres.EXTERNAL_CONTENT_URI, Long.valueOf(mGenre)),
cols, null, null, null);
if (cursor != null) {
if (cursor.getCount() != 0) {
cursor.moveToFirst();
fancyName = cursor.getString(0);
}
cursor.deactivate();
}
}
if (fancyName != null) {
setTitle(fancyName);
} else {
setTitle(R.string.tracks_title);
}
}
private TouchInterceptor.DropListener mDropListener =
new TouchInterceptor.DropListener() {
public void drop(int from, int to) {
if (mTrackCursor instanceof NowPlayingCursor) {
// update the currently playing list
NowPlayingCursor c = (NowPlayingCursor) mTrackCursor;
c.moveItem(from, to);
((TrackListAdapter)getListAdapter()).notifyDataSetChanged();
getListView().invalidateViews();
mDeletedOneRow = true;
} else {
// update a saved playlist
MediaStore.Audio.Playlists.Members.moveItem(getContentResolver(),
Long.valueOf(mPlaylist), from, to);
}
}
};
private TouchInterceptor.RemoveListener mRemoveListener =
new TouchInterceptor.RemoveListener() {
public void remove(int which) {
removePlaylistItem(which);
}
};
private void removePlaylistItem(int which) {
View v = mTrackList.getChildAt(which - mTrackList.getFirstVisiblePosition());
if (v == null) {
Log.d(LOGTAG, "No view when removing playlist item " + which);
return;
}
try {
if (MusicUtils.sService != null
&& which != MusicUtils.sService.getQueuePosition()) {
mDeletedOneRow = true;
}
} catch (RemoteException e) {
// Service died, so nothing playing.
mDeletedOneRow = true;
}
v.setVisibility(View.GONE);
mTrackList.invalidateViews();
if (mTrackCursor instanceof NowPlayingCursor) {
((NowPlayingCursor)mTrackCursor).removeItem(which);
} else {
int colidx = mTrackCursor.getColumnIndexOrThrow(
MediaStore.Audio.Playlists.Members._ID);
mTrackCursor.moveToPosition(which);
long id = mTrackCursor.getLong(colidx);
Uri uri = MediaStore.Audio.Playlists.Members.getContentUri("external",
Long.valueOf(mPlaylist));
getContentResolver().delete(
ContentUris.withAppendedId(uri, id), null, null);
}
v.setVisibility(View.VISIBLE);
mTrackList.invalidateViews();
}
private BroadcastReceiver mTrackListListener = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
getListView().invalidateViews();
if (!mEditMode) {
MusicUtils.updateNowPlaying(TrackBrowserActivity.this);
}
}
};
private BroadcastReceiver mNowPlayingListener = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(MediaPlaybackService.META_CHANGED)) {
getListView().invalidateViews();
} else if (intent.getAction().equals(MediaPlaybackService.QUEUE_CHANGED)) {
if (mDeletedOneRow) {
// This is the notification for a single row that was
// deleted previously, which is already reflected in
// the UI.
mDeletedOneRow = false;
return;
}
Cursor c = new NowPlayingCursor(MusicUtils.sService, mCursorCols);
if (c.getCount() == 0) {
finish();
return;
}
mAdapter.changeCursor(c);
}
}
};
// Cursor should be positioned on the entry to be checked
// Returns false if the entry matches the naming pattern used for recordings,
// or if it is marked as not music in the database.
private boolean isMusic(Cursor c) {
int titleidx = c.getColumnIndex(MediaStore.Audio.Media.TITLE);
int albumidx = c.getColumnIndex(MediaStore.Audio.Media.ALBUM);
int artistidx = c.getColumnIndex(MediaStore.Audio.Media.ARTIST);
String title = c.getString(titleidx);
String album = c.getString(albumidx);
String artist = c.getString(artistidx);
if (MediaFile.UNKNOWN_STRING.equals(album) &&
MediaFile.UNKNOWN_STRING.equals(artist) &&
title != null &&
title.startsWith("recording")) {
// not music
return false;
}
int ismusic_idx = c.getColumnIndex(MediaStore.Audio.Media.IS_MUSIC);
boolean ismusic = true;
if (ismusic_idx >= 0) {
ismusic = mTrackCursor.getInt(ismusic_idx) != 0;
}
return ismusic;
}
@Override
public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo menuInfoIn) {
menu.add(0, PLAY_SELECTION, 0, R.string.play_selection);
SubMenu sub = menu.addSubMenu(0, ADD_TO_PLAYLIST, 0, R.string.add_to_playlist);
MusicUtils.makePlaylistMenu(this, sub);
if (mEditMode) {
menu.add(0, REMOVE, 0, R.string.remove_from_playlist);
}
menu.add(0, USE_AS_RINGTONE, 0, R.string.ringtone_menu);
menu.add(0, DELETE_ITEM, 0, R.string.delete_item);
AdapterContextMenuInfo mi = (AdapterContextMenuInfo) menuInfoIn;
mSelectedPosition = mi.position;
mTrackCursor.moveToPosition(mSelectedPosition);
try {
int id_idx = mTrackCursor.getColumnIndexOrThrow(
MediaStore.Audio.Playlists.Members.AUDIO_ID);
mSelectedId = mTrackCursor.getLong(id_idx);
} catch (IllegalArgumentException ex) {
mSelectedId = mi.id;
}
// only add the 'search' menu if the selected item is music
if (isMusic(mTrackCursor)) {
menu.add(0, SEARCH, 0, R.string.search_title);
}
mCurrentAlbumName = mTrackCursor.getString(mTrackCursor.getColumnIndexOrThrow(
MediaStore.Audio.Media.ALBUM));
mCurrentArtistNameForAlbum = mTrackCursor.getString(mTrackCursor.getColumnIndexOrThrow(
MediaStore.Audio.Media.ARTIST));
mCurrentTrackName = mTrackCursor.getString(mTrackCursor.getColumnIndexOrThrow(
MediaStore.Audio.Media.TITLE));
menu.setHeaderTitle(mCurrentTrackName);
}
@Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case PLAY_SELECTION: {
// play the track
int position = mSelectedPosition;
MusicUtils.playAll(this, mTrackCursor, position);
return true;
}
case QUEUE: {
long [] list = new long[] { mSelectedId };
MusicUtils.addToCurrentPlaylist(this, list);
return true;
}
case NEW_PLAYLIST: {
Intent intent = new Intent();
intent.setClass(this, CreatePlaylist.class);
startActivityForResult(intent, NEW_PLAYLIST);
return true;
}
case PLAYLIST_SELECTED: {
long [] list = new long[] { mSelectedId };
long playlist = item.getIntent().getLongExtra("playlist", 0);
MusicUtils.addToPlaylist(this, list, playlist);
return true;
}
case USE_AS_RINGTONE:
// Set the system setting to make this the current ringtone
MusicUtils.setRingtone(this, mSelectedId);
return true;
case DELETE_ITEM: {
long [] list = new long[1];
list[0] = (int) mSelectedId;
Bundle b = new Bundle();
String f = getString(R.string.delete_song_desc);
String desc = String.format(f, mCurrentTrackName);
b.putString("description", desc);
b.putLongArray("items", list);
Intent intent = new Intent();
intent.setClass(this, DeleteItems.class);
intent.putExtras(b);
startActivityForResult(intent, -1);
return true;
}
case REMOVE:
removePlaylistItem(mSelectedPosition);
return true;
case SEARCH:
doSearch();
return true;
}
return super.onContextItemSelected(item);
}
void doSearch() {
CharSequence title = null;
String query = null;
Intent i = new Intent();
i.setAction(MediaStore.INTENT_ACTION_MEDIA_SEARCH);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
title = mCurrentTrackName;
if (MediaFile.UNKNOWN_STRING.equals(mCurrentArtistNameForAlbum)) {
query = mCurrentTrackName;
} else {
query = mCurrentArtistNameForAlbum + " " + mCurrentTrackName;
i.putExtra(MediaStore.EXTRA_MEDIA_ARTIST, mCurrentArtistNameForAlbum);
}
if (MediaFile.UNKNOWN_STRING.equals(mCurrentAlbumName)) {
i.putExtra(MediaStore.EXTRA_MEDIA_ALBUM, mCurrentAlbumName);
}
i.putExtra(MediaStore.EXTRA_MEDIA_FOCUS, "audio/*");
title = getString(R.string.mediasearch, title);
i.putExtra(SearchManager.QUERY, query);
startActivity(Intent.createChooser(i, title));
}
// In order to use alt-up/down as a shortcut for moving the selected item
// in the list, we need to override dispatchKeyEvent, not onKeyDown.
// (onKeyDown never sees these events, since they are handled by the list)
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
if (mPlaylist != null && event.getMetaState() != 0 &&
event.getAction() == KeyEvent.ACTION_DOWN) {
switch (event.getKeyCode()) {
case KeyEvent.KEYCODE_DPAD_UP:
moveItem(true);
return true;
case KeyEvent.KEYCODE_DPAD_DOWN:
moveItem(false);
return true;
case KeyEvent.KEYCODE_DEL:
removeItem();
return true;
}
}
return super.dispatchKeyEvent(event);
}
private void removeItem() {
int curcount = mTrackCursor.getCount();
int curpos = mTrackList.getSelectedItemPosition();
if (curcount == 0 || curpos < 0) {
return;
}
if ("nowplaying".equals(mPlaylist)) {
// remove track from queue
// Work around bug 902971. To get quick visual feedback
// of the deletion of the item, hide the selected view.
try {
if (curpos != MusicUtils.sService.getQueuePosition()) {
mDeletedOneRow = true;
}
} catch (RemoteException ex) {
}
View v = mTrackList.getSelectedView();
v.setVisibility(View.GONE);
mTrackList.invalidateViews();
((NowPlayingCursor)mTrackCursor).removeItem(curpos);
v.setVisibility(View.VISIBLE);
mTrackList.invalidateViews();
} else {
// remove track from playlist
int colidx = mTrackCursor.getColumnIndexOrThrow(
MediaStore.Audio.Playlists.Members._ID);
mTrackCursor.moveToPosition(curpos);
long id = mTrackCursor.getLong(colidx);
Uri uri = MediaStore.Audio.Playlists.Members.getContentUri("external",
Long.valueOf(mPlaylist));
getContentResolver().delete(
ContentUris.withAppendedId(uri, id), null, null);
curcount--;
if (curcount == 0) {
finish();
} else {
mTrackList.setSelection(curpos < curcount ? curpos : curcount);
}
}
}
private void moveItem(boolean up) {
int curcount = mTrackCursor.getCount();
int curpos = mTrackList.getSelectedItemPosition();
if ( (up && curpos < 1) || (!up && curpos >= curcount - 1)) {
return;
}
if (mTrackCursor instanceof NowPlayingCursor) {
NowPlayingCursor c = (NowPlayingCursor) mTrackCursor;
c.moveItem(curpos, up ? curpos - 1 : curpos + 1);
((TrackListAdapter)getListAdapter()).notifyDataSetChanged();
getListView().invalidateViews();
mDeletedOneRow = true;
if (up) {
mTrackList.setSelection(curpos - 1);
} else {
mTrackList.setSelection(curpos + 1);
}
} else {
int colidx = mTrackCursor.getColumnIndexOrThrow(
MediaStore.Audio.Playlists.Members.PLAY_ORDER);
mTrackCursor.moveToPosition(curpos);
int currentplayidx = mTrackCursor.getInt(colidx);
Uri baseUri = MediaStore.Audio.Playlists.Members.getContentUri("external",
Long.valueOf(mPlaylist));
ContentValues values = new ContentValues();
String where = MediaStore.Audio.Playlists.Members._ID + "=?";
String [] wherearg = new String[1];
ContentResolver res = getContentResolver();
if (up) {
values.put(MediaStore.Audio.Playlists.Members.PLAY_ORDER, currentplayidx - 1);
wherearg[0] = mTrackCursor.getString(0);
res.update(baseUri, values, where, wherearg);
mTrackCursor.moveToPrevious();
} else {
values.put(MediaStore.Audio.Playlists.Members.PLAY_ORDER, currentplayidx + 1);
wherearg[0] = mTrackCursor.getString(0);
res.update(baseUri, values, where, wherearg);
mTrackCursor.moveToNext();
}
values.put(MediaStore.Audio.Playlists.Members.PLAY_ORDER, currentplayidx);
wherearg[0] = mTrackCursor.getString(0);
res.update(baseUri, values, where, wherearg);
}
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id)
{
if (mTrackCursor.getCount() == 0) {
return;
}
// When selecting a track from the queue, just jump there instead of
// reloading the queue. This is both faster, and prevents accidentally
// dropping out of party shuffle.
if (mTrackCursor instanceof NowPlayingCursor) {
if (MusicUtils.sService != null) {
try {
MusicUtils.sService.setQueuePosition(position);
return;
} catch (RemoteException ex) {
}
}
}
MusicUtils.playAll(this, mTrackCursor, position);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
/* This activity is used for a number of different browsing modes, and the menu can
* be different for each of them:
* - all tracks, optionally restricted to an album, artist or playlist
* - the list of currently playing songs
*/
super.onCreateOptionsMenu(menu);
if (mPlaylist == null) {
menu.add(0, PLAY_ALL, 0, R.string.play_all).setIcon(com.android.internal.R.drawable.ic_menu_play_clip);
}
menu.add(0, PARTY_SHUFFLE, 0, R.string.party_shuffle); // icon will be set in onPrepareOptionsMenu()
menu.add(0, SHUFFLE_ALL, 0, R.string.shuffle_all).setIcon(R.drawable.ic_menu_shuffle);
if (mPlaylist != null) {
menu.add(0, SAVE_AS_PLAYLIST, 0, R.string.save_as_playlist).setIcon(android.R.drawable.ic_menu_save);
if (mPlaylist.equals("nowplaying")) {
menu.add(0, CLEAR_PLAYLIST, 0, R.string.clear_playlist).setIcon(com.android.internal.R.drawable.ic_menu_clear_playlist);
}
}
return true;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
MusicUtils.setPartyShuffleMenuIcon(menu);
return super.onPrepareOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent intent;
Cursor cursor;
switch (item.getItemId()) {
case PLAY_ALL: {
MusicUtils.playAll(this, mTrackCursor);
return true;
}
case PARTY_SHUFFLE:
MusicUtils.togglePartyShuffle();
break;
case SHUFFLE_ALL:
// Should 'shuffle all' shuffle ALL, or only the tracks shown?
cursor = MusicUtils.query(this, MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
new String [] { MediaStore.Audio.Media._ID},
MediaStore.Audio.Media.IS_MUSIC + "=1", null,
MediaStore.Audio.Media.DEFAULT_SORT_ORDER);
if (cursor != null) {
MusicUtils.shuffleAll(this, cursor);
cursor.close();
}
return true;
case SAVE_AS_PLAYLIST:
intent = new Intent();
intent.setClass(this, CreatePlaylist.class);
startActivityForResult(intent, SAVE_AS_PLAYLIST);
return true;
case CLEAR_PLAYLIST:
// We only clear the current playlist
MusicUtils.clearQueue();
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
switch (requestCode) {
case SCAN_DONE:
if (resultCode == RESULT_CANCELED) {
finish();
} else {
getTrackCursor(mAdapter.getQueryHandler(), null, true);
}
break;
case NEW_PLAYLIST:
if (resultCode == RESULT_OK) {
Uri uri = intent.getData();
if (uri != null) {
long [] list = new long[] { mSelectedId };
MusicUtils.addToPlaylist(this, list, Integer.valueOf(uri.getLastPathSegment()));
}
}
break;
case SAVE_AS_PLAYLIST:
if (resultCode == RESULT_OK) {
Uri uri = intent.getData();
if (uri != null) {
long [] list = MusicUtils.getSongListForCursor(mTrackCursor);
int plid = Integer.parseInt(uri.getLastPathSegment());
MusicUtils.addToPlaylist(this, list, plid);
}
}
break;
}
}
private Cursor getTrackCursor(TrackListAdapter.TrackQueryHandler queryhandler, String filter,
boolean async) {
if (queryhandler == null) {
throw new IllegalArgumentException();
}
Cursor ret = null;
mSortOrder = MediaStore.Audio.Media.TITLE_KEY;
StringBuilder where = new StringBuilder();
where.append(MediaStore.Audio.Media.TITLE + " != ''");
// Add in the filtering constraints
String [] keywords = null;
if (filter != null) {
String [] searchWords = filter.split(" ");
keywords = new String[searchWords.length];
Collator col = Collator.getInstance();
col.setStrength(Collator.PRIMARY);
for (int i = 0; i < searchWords.length; i++) {
keywords[i] = '%' + MediaStore.Audio.keyFor(searchWords[i]) + '%';
}
for (int i = 0; i < searchWords.length; i++) {
where.append(" AND ");
where.append(MediaStore.Audio.Media.ARTIST_KEY + "||");
where.append(MediaStore.Audio.Media.TITLE_KEY + " LIKE ?");
}
}
if (mGenre != null) {
mSortOrder = MediaStore.Audio.Genres.Members.DEFAULT_SORT_ORDER;
ret = queryhandler.doQuery(MediaStore.Audio.Genres.Members.getContentUri("external",
Integer.valueOf(mGenre)),
mCursorCols, where.toString(), keywords, mSortOrder, async);
} else if (mPlaylist != null) {
if (mPlaylist.equals("nowplaying")) {
if (MusicUtils.sService != null) {
ret = new NowPlayingCursor(MusicUtils.sService, mCursorCols);
if (ret.getCount() == 0) {
finish();
}
} else {
// Nothing is playing.
}
} else if (mPlaylist.equals("podcasts")) {
where.append(" AND " + MediaStore.Audio.Media.IS_PODCAST + "=1");
ret = queryhandler.doQuery(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
mCursorCols, where.toString(), keywords,
MediaStore.Audio.Media.DEFAULT_SORT_ORDER, async);
} else if (mPlaylist.equals("recentlyadded")) {
// do a query for all songs added in the last X weeks
int X = MusicUtils.getIntPref(this, "numweeks", 2) * (3600 * 24 * 7);
where.append(" AND " + MediaStore.MediaColumns.DATE_ADDED + ">");
where.append(System.currentTimeMillis() / 1000 - X);
ret = queryhandler.doQuery(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
mCursorCols, where.toString(), keywords,
MediaStore.Audio.Media.DEFAULT_SORT_ORDER, async);
} else {
mSortOrder = MediaStore.Audio.Playlists.Members.DEFAULT_SORT_ORDER;
ret = queryhandler.doQuery(MediaStore.Audio.Playlists.Members.getContentUri("external",
Long.valueOf(mPlaylist)), mPlaylistMemberCols,
where.toString(), keywords, mSortOrder, async);
}
} else {
if (mAlbumId != null) {
where.append(" AND " + MediaStore.Audio.Media.ALBUM_ID + "=" + mAlbumId);
mSortOrder = MediaStore.Audio.Media.TRACK + ", " + mSortOrder;
}
if (mArtistId != null) {
where.append(" AND " + MediaStore.Audio.Media.ARTIST_ID + "=" + mArtistId);
}
where.append(" AND " + MediaStore.Audio.Media.IS_MUSIC + "=1");
ret = queryhandler.doQuery(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
mCursorCols, where.toString() , keywords, mSortOrder, async);
}
// This special case is for the "nowplaying" cursor, which cannot be handled
// asynchronously using AsyncQueryHandler, so we do some extra initialization here.
if (ret != null && async) {
init(ret, false);
setTitle();
}
return ret;
}
private class NowPlayingCursor extends AbstractCursor
{
public NowPlayingCursor(IMediaPlaybackService service, String [] cols)
{
mCols = cols;
mService = service;
makeNowPlayingCursor();
}
private void makeNowPlayingCursor() {
mCurrentPlaylistCursor = null;
try {
mNowPlaying = mService.getQueue();
} catch (RemoteException ex) {
mNowPlaying = new long[0];
}
mSize = mNowPlaying.length;
if (mSize == 0) {
return;
}
StringBuilder where = new StringBuilder();
where.append(MediaStore.Audio.Media._ID + " IN (");
for (int i = 0; i < mSize; i++) {
where.append(mNowPlaying[i]);
if (i < mSize - 1) {
where.append(",");
}
}
where.append(")");
mCurrentPlaylistCursor = MusicUtils.query(TrackBrowserActivity.this,
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
mCols, where.toString(), null, MediaStore.Audio.Media._ID);
if (mCurrentPlaylistCursor == null) {
mSize = 0;
return;
}
int size = mCurrentPlaylistCursor.getCount();
mCursorIdxs = new long[size];
mCurrentPlaylistCursor.moveToFirst();
int colidx = mCurrentPlaylistCursor.getColumnIndexOrThrow(MediaStore.Audio.Media._ID);
for (int i = 0; i < size; i++) {
mCursorIdxs[i] = mCurrentPlaylistCursor.getLong(colidx);
mCurrentPlaylistCursor.moveToNext();
}
mCurrentPlaylistCursor.moveToFirst();
mCurPos = -1;
// At this point we can verify the 'now playing' list we got
// earlier to make sure that all the items in there still exist
// in the database, and remove those that aren't. This way we
// don't get any blank items in the list.
try {
int removed = 0;
for (int i = mNowPlaying.length - 1; i >= 0; i--) {
long trackid = mNowPlaying[i];
int crsridx = Arrays.binarySearch(mCursorIdxs, trackid);
if (crsridx < 0) {
//Log.i("@@@@@", "item no longer exists in db: " + trackid);
removed += mService.removeTrack(trackid);
}
}
if (removed > 0) {
mNowPlaying = mService.getQueue();
mSize = mNowPlaying.length;
if (mSize == 0) {
mCursorIdxs = null;
return;
}
}
} catch (RemoteException ex) {
mNowPlaying = new long[0];
}
}
@Override
public int getCount()
{
return mSize;
}
@Override
public boolean onMove(int oldPosition, int newPosition)
{
if (oldPosition == newPosition)
return true;
if (mNowPlaying == null || mCursorIdxs == null) {
return false;
}
// The cursor doesn't have any duplicates in it, and is not ordered
// in queue-order, so we need to figure out where in the cursor we
// should be.
long newid = mNowPlaying[newPosition];
int crsridx = Arrays.binarySearch(mCursorIdxs, newid);
mCurrentPlaylistCursor.moveToPosition(crsridx);
mCurPos = newPosition;
return true;
}
public boolean removeItem(int which)
{
try {
if (mService.removeTracks(which, which) == 0) {
return false; // delete failed
}
int i = (int) which;
mSize--;
while (i < mSize) {
mNowPlaying[i] = mNowPlaying[i+1];
i++;
}
onMove(-1, (int) mCurPos);
} catch (RemoteException ex) {
}
return true;
}
public void moveItem(int from, int to) {
try {
mService.moveQueueItem(from, to);
mNowPlaying = mService.getQueue();
onMove(-1, mCurPos); // update the underlying cursor
} catch (RemoteException ex) {
}
}
private void dump() {
String where = "(";
for (int i = 0; i < mSize; i++) {
where += mNowPlaying[i];
if (i < mSize - 1) {
where += ",";
}
}
where += ")";
Log.i("NowPlayingCursor: ", where);
}
@Override
public String getString(int column)
{
try {
return mCurrentPlaylistCursor.getString(column);
} catch (Exception ex) {
onChange(true);
return "";
}
}
@Override
public short getShort(int column)
{
return mCurrentPlaylistCursor.getShort(column);
}
@Override
public int getInt(int column)
{
try {
return mCurrentPlaylistCursor.getInt(column);
} catch (Exception ex) {
onChange(true);
return 0;
}
}
@Override
public long getLong(int column)
{
try {
return mCurrentPlaylistCursor.getLong(column);
} catch (Exception ex) {
onChange(true);
return 0;
}
}
@Override
public float getFloat(int column)
{
return mCurrentPlaylistCursor.getFloat(column);
}
@Override
public double getDouble(int column)
{
return mCurrentPlaylistCursor.getDouble(column);
}
@Override
public boolean isNull(int column)
{
return mCurrentPlaylistCursor.isNull(column);
}
@Override
public String[] getColumnNames()
{
return mCols;
}
@Override
public void deactivate()
{
if (mCurrentPlaylistCursor != null)
mCurrentPlaylistCursor.deactivate();
}
@Override
public boolean requery()
{
makeNowPlayingCursor();
return true;
}
private String [] mCols;
private Cursor mCurrentPlaylistCursor; // updated in onMove
private int mSize; // size of the queue
private long[] mNowPlaying;
private long[] mCursorIdxs;
private int mCurPos;
private IMediaPlaybackService mService;
}
static class TrackListAdapter extends SimpleCursorAdapter implements SectionIndexer {
boolean mIsNowPlaying;
boolean mDisableNowPlayingIndicator;
int mTitleIdx;
int mArtistIdx;
int mDurationIdx;
int mAudioIdIdx;
private final StringBuilder mBuilder = new StringBuilder();
private final String mUnknownArtist;
private final String mUnknownAlbum;
private AlphabetIndexer mIndexer;
private TrackBrowserActivity mActivity = null;
private TrackQueryHandler mQueryHandler;
private String mConstraint = null;
private boolean mConstraintIsValid = false;
static class ViewHolder {
TextView line1;
TextView line2;
TextView duration;
ImageView play_indicator;
CharArrayBuffer buffer1;
char [] buffer2;
}
class TrackQueryHandler extends AsyncQueryHandler {
class QueryArgs {
public Uri uri;
public String [] projection;
public String selection;
public String [] selectionArgs;
public String orderBy;
}
TrackQueryHandler(ContentResolver res) {
super(res);
}
public Cursor doQuery(Uri uri, String[] projection,
String selection, String[] selectionArgs,
String orderBy, boolean async) {
if (async) {
// Get 100 results first, which is enough to allow the user to start scrolling,
// while still being very fast.
Uri limituri = uri.buildUpon().appendQueryParameter("limit", "100").build();
QueryArgs args = new QueryArgs();
args.uri = uri;
args.projection = projection;
args.selection = selection;
args.selectionArgs = selectionArgs;
args.orderBy = orderBy;
startQuery(0, args, limituri, projection, selection, selectionArgs, orderBy);
return null;
}
return MusicUtils.query(mActivity,
uri, projection, selection, selectionArgs, orderBy);
}
@Override
protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
//Log.i("@@@", "query complete: " + cursor.getCount() + " " + mActivity);
mActivity.init(cursor, cookie != null);
if (token == 0 && cookie != null && cursor != null && cursor.getCount() >= 100) {
QueryArgs args = (QueryArgs) cookie;
startQuery(1, null, args.uri, args.projection, args.selection,
args.selectionArgs, args.orderBy);
}
}
}
TrackListAdapter(Context context, TrackBrowserActivity currentactivity,
int layout, Cursor cursor, String[] from, int[] to,
boolean isnowplaying, boolean disablenowplayingindicator) {
super(context, layout, cursor, from, to);
mActivity = currentactivity;
getColumnIndices(cursor);
mIsNowPlaying = isnowplaying;
mDisableNowPlayingIndicator = disablenowplayingindicator;
mUnknownArtist = context.getString(R.string.unknown_artist_name);
mUnknownAlbum = context.getString(R.string.unknown_album_name);
mQueryHandler = new TrackQueryHandler(context.getContentResolver());
}
public void setActivity(TrackBrowserActivity newactivity) {
mActivity = newactivity;
}
public TrackQueryHandler getQueryHandler() {
return mQueryHandler;
}
private void getColumnIndices(Cursor cursor) {
if (cursor != null) {
mTitleIdx = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE);
mArtistIdx = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST);
mDurationIdx = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DURATION);
try {
mAudioIdIdx = cursor.getColumnIndexOrThrow(
MediaStore.Audio.Playlists.Members.AUDIO_ID);
} catch (IllegalArgumentException ex) {
mAudioIdIdx = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media._ID);
}
if (mIndexer != null) {
mIndexer.setCursor(cursor);
} else if (!mActivity.mEditMode) {
String alpha = mActivity.getString(
com.android.internal.R.string.fast_scroll_alphabet);
mIndexer = new MusicAlphabetIndexer(cursor, mTitleIdx, alpha);
}
}
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View v = super.newView(context, cursor, parent);
ImageView iv = (ImageView) v.findViewById(R.id.icon);
if (mActivity.mEditMode) {
iv.setVisibility(View.VISIBLE);
iv.setImageResource(R.drawable.ic_mp_move);
} else {
iv.setVisibility(View.GONE);
}
ViewHolder vh = new ViewHolder();
vh.line1 = (TextView) v.findViewById(R.id.line1);
vh.line2 = (TextView) v.findViewById(R.id.line2);
vh.duration = (TextView) v.findViewById(R.id.duration);
vh.play_indicator = (ImageView) v.findViewById(R.id.play_indicator);
vh.buffer1 = new CharArrayBuffer(100);
vh.buffer2 = new char[200];
v.setTag(vh);
return v;
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
ViewHolder vh = (ViewHolder) view.getTag();
cursor.copyStringToBuffer(mTitleIdx, vh.buffer1);
vh.line1.setText(vh.buffer1.data, 0, vh.buffer1.sizeCopied);
int secs = cursor.getInt(mDurationIdx) / 1000;
if (secs == 0) {
vh.duration.setText("");
} else {
vh.duration.setText(MusicUtils.makeTimeString(context, secs));
}
final StringBuilder builder = mBuilder;
builder.delete(0, builder.length());
String name = cursor.getString(mArtistIdx);
if (name == null || name.equals(MediaFile.UNKNOWN_STRING)) {
builder.append(mUnknownArtist);
} else {
builder.append(name);
}
int len = builder.length();
if (vh.buffer2.length < len) {
vh.buffer2 = new char[len];
}
builder.getChars(0, len, vh.buffer2, 0);
vh.line2.setText(vh.buffer2, 0, len);
ImageView iv = vh.play_indicator;
long id = -1;
if (MusicUtils.sService != null) {
// TODO: IPC call on each bind??
try {
if (mIsNowPlaying) {
id = MusicUtils.sService.getQueuePosition();
} else {
id = MusicUtils.sService.getAudioId();
}
} catch (RemoteException ex) {
}
}
// Determining whether and where to show the "now playing indicator
// is tricky, because we don't actually keep track of where the songs
// in the current playlist came from after they've started playing.
//
// If the "current playlists" is shown, then we can simply match by position,
// otherwise, we need to match by id. Match-by-id gets a little weird if
// a song appears in a playlist more than once, and you're in edit-playlist
// mode. In that case, both items will have the "now playing" indicator.
// For this reason, we don't show the play indicator at all when in edit
// playlist mode (except when you're viewing the "current playlist",
// which is not really a playlist)
if ( (mIsNowPlaying && cursor.getPosition() == id) ||
(!mIsNowPlaying && !mDisableNowPlayingIndicator && cursor.getLong(mAudioIdIdx) == id)) {
iv.setImageResource(R.drawable.indicator_ic_mp_playing_list);
iv.setVisibility(View.VISIBLE);
} else {
iv.setVisibility(View.GONE);
}
}
@Override
public void changeCursor(Cursor cursor) {
if (mActivity.isFinishing() && cursor != null) {
cursor.close();
cursor = null;
}
if (cursor != mActivity.mTrackCursor) {
mActivity.mTrackCursor = cursor;
super.changeCursor(cursor);
getColumnIndices(cursor);
}
}
@Override
public Cursor runQueryOnBackgroundThread(CharSequence constraint) {
String s = constraint.toString();
if (mConstraintIsValid && (
(s == null && mConstraint == null) ||
(s != null && s.equals(mConstraint)))) {
return getCursor();
}
Cursor c = mActivity.getTrackCursor(mQueryHandler, s, false);
mConstraint = s;
mConstraintIsValid = true;
return c;
}
// SectionIndexer methods
public Object[] getSections() {
if (mIndexer != null) {
return mIndexer.getSections();
} else {
return null;
}
}
public int getPositionForSection(int section) {
int pos = mIndexer.getPositionForSection(section);
return pos;
}
public int getSectionForPosition(int position) {
return 0;
}
}
}
| false | false | null | null |
diff --git a/src/core/model/src/main/java/it/geosolutions/geobatch/catalog/impl/BaseIdentifiable.java b/src/core/model/src/main/java/it/geosolutions/geobatch/catalog/impl/BaseIdentifiable.java
index fda53a2c..58e9b0e2 100644
--- a/src/core/model/src/main/java/it/geosolutions/geobatch/catalog/impl/BaseIdentifiable.java
+++ b/src/core/model/src/main/java/it/geosolutions/geobatch/catalog/impl/BaseIdentifiable.java
@@ -1,74 +1,71 @@
/*
* GeoBatch - Open Source geospatial batch processing system
* http://geobatch.codehaus.org/
* Copyright (C) 2007-2012 GeoSolutions S.A.S.
* http://www.geo-solutions.it
*
* GPLv3 + Classpath exception
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package it.geosolutions.geobatch.catalog.impl;
-import java.util.UUID;
-
import it.geosolutions.geobatch.catalog.Identifiable;
public abstract class BaseIdentifiable implements Identifiable, Cloneable {
private String id;
/**
* A constructor which do not initialize the resource id
* @deprecated use the complete constructor
*/
protected BaseIdentifiable() {
}
/**
* Constructor forcing initialization of: id ,name and description of this resource
* @param id
*/
public BaseIdentifiable(String id) {
this.id = id;
}
/**
* @return
*/
public String getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(String id) {
this.id = id;
}
public BaseIdentifiable clone() {
try {
BaseIdentifiable bi = (BaseIdentifiable) super.clone();
- bi.id = UUID.randomUUID().toString(); // check me: does this respect the clone contract?
return bi;
} catch (CloneNotSupportedException e) {
// this shouldn't happen, since we are Cloneable
throw new InternalError();
}
}
}
\ No newline at end of file
diff --git a/src/file-catalog/src/main/java/it/geosolutions/geobatch/flow/event/consumer/file/FileBasedEventConsumer.java b/src/file-catalog/src/main/java/it/geosolutions/geobatch/flow/event/consumer/file/FileBasedEventConsumer.java
index b3089f02..7410bd3b 100644
--- a/src/file-catalog/src/main/java/it/geosolutions/geobatch/flow/event/consumer/file/FileBasedEventConsumer.java
+++ b/src/file-catalog/src/main/java/it/geosolutions/geobatch/flow/event/consumer/file/FileBasedEventConsumer.java
@@ -1,685 +1,685 @@
/*
* GeoBatch - Open Source geospatial batch processing system
* http://geobatch.codehaus.org/
* Copyright (C) 2007-2012 GeoSolutions S.A.S.
* http://www.geo-solutions.it
*
* GPLv3 + Classpath exception
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package it.geosolutions.geobatch.flow.event.consumer.file;
import it.geosolutions.filesystemmonitor.monitor.FileSystemEvent;
import it.geosolutions.geobatch.catalog.Catalog;
import it.geosolutions.geobatch.configuration.event.action.ActionConfiguration;
import it.geosolutions.geobatch.configuration.event.consumer.file.FileBasedEventConsumerConfiguration;
import it.geosolutions.geobatch.configuration.event.listener.ProgressListenerConfiguration;
import it.geosolutions.geobatch.configuration.event.listener.ProgressListenerService;
import it.geosolutions.geobatch.flow.event.IProgressListener;
import it.geosolutions.geobatch.flow.event.ProgressListener;
import it.geosolutions.geobatch.flow.event.ProgressListenerForwarder;
import it.geosolutions.geobatch.flow.event.action.Action;
import it.geosolutions.geobatch.flow.event.action.ActionException;
import it.geosolutions.geobatch.flow.event.action.ActionService;
import it.geosolutions.geobatch.flow.event.action.BaseAction;
import it.geosolutions.geobatch.flow.event.consumer.BaseEventConsumer;
import it.geosolutions.geobatch.flow.event.consumer.EventConsumerStatus;
import it.geosolutions.geobatch.flow.event.listeners.cumulator.CumulatingProgressListener;
import it.geosolutions.geobatch.global.CatalogHolder;
import it.geosolutions.tools.io.file.IOUtils;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.TimeZone;
import java.util.UUID;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Simone Giannecchini, GeoSolutions S.A.S.
* @author Emanuele Tajariol, GeoSolutions S.A.S.
* @author (r2)Carlo Cancellieri - [email protected]
*
*/
public class FileBasedEventConsumer
extends BaseEventConsumer<FileSystemEvent, FileBasedEventConsumerConfiguration> {
/**
* Default logger
*/
private static final Logger LOGGER = LoggerFactory.getLogger(FileBasedEventConsumer.class);
/**
* The number of expected mandatory files before the flow can be started.
* Should be set by configuration, and decremented each time a mandatory
* file is consumed.
*/
private long numInputFiles = 0;
/**
* Temporary dir for this flow instance.<br>
* It represents the parent dir of the {@link #flowInstanceTempDir}<br>
*/
private File flowBaseTempDir;
private File flowConfigDir;
/**
* Temporary folder for a given flow instance.
* It's created using
* {@link FileBasedEventConsumer#createFlowInstanceTempDir(File)}
*/
private File flowInstanceTempDir;
// private File runtimeDir;
private FileBasedEventConsumerConfiguration configuration;
private volatile boolean canceled;
/**
* do not remove runtimeDir when consumer is disposed
*/
private boolean keepRuntimeDir = false;
/**
* PUBLIC CONSTRUCTORS: Initialize the consumer using the passed
* configuration.<br>
* Note that the id is initialized using UUID.randomUUID()<br>
* It also try to create a {@link FileBasedEventConsumer#runtimeDir} into
* the {@link FileBasedEventConsumer#workingDir}
*
* @param configuration
* @throws InterruptedException
* @throws IOException
*/
public FileBasedEventConsumer(FileBasedEventConsumerConfiguration configuration, File flowConfigDir, File flowBaseTempDir)
throws InterruptedException, IOException {
super(UUID.randomUUID().toString());
this.flowConfigDir = flowConfigDir;
this.flowInstanceTempDir = createFlowInstanceTempDir(flowBaseTempDir);
if(LOGGER.isDebugEnabled())
LOGGER.debug("Prepared flowInstanceTempDir " + flowInstanceTempDir);
initialize(configuration);
}
/**
* Called by ctor
*/
private static File createFlowInstanceTempDir(File flowBaseTempDir) {
// current directory inside the flow temp dir, specifically created for this execution/thread.
// Creation is eager
final File instanceTempDir = new File(flowBaseTempDir, UniqueTimeStampProvider.getTimeStamp());
instanceTempDir.mkdirs();
return instanceTempDir;
}
/**
*
* FileBasedEventConsumer initialization.
*
* @param configuration
* @param workingDir
* @throws InterruptedException
* @throws IllegalArgumentException
* @throws IOException
*/
private void initialize(FileBasedEventConsumerConfiguration configuration)
throws InterruptedException, IllegalArgumentException, IOException {
this.configuration = configuration;
this.keepRuntimeDir = configuration.isKeepRuntimeDir();
this.canceled = false;
// ////////////////////////////////////////////////////////////////////
// LISTENER
// ////////////////////////////////////////////////////////////////////
for (ProgressListenerConfiguration plConfig : configuration.getListenerConfigurations()) {
final String serviceID = plConfig.getServiceID();
final ProgressListenerService progressListenerService =
CatalogHolder.getCatalog().getResource(serviceID, ProgressListenerService.class);
if (progressListenerService != null) {
ProgressListener progressListener = progressListenerService.createProgressListener(plConfig, this);
getListenerForwarder().addListener(progressListener);
} else {
throw new IllegalArgumentException("Could not find '" + serviceID
+ "' listener, declared in " + configuration.getId()
+ " configuration");
}
}
// ////////////////////////////////////////////////////////////////////
// ACTIONS
// ////////////////////////////////////////////////////////////////////
final List<BaseAction<FileSystemEvent>> loadedActions = new ArrayList<BaseAction<FileSystemEvent>>();
final Catalog catalog = CatalogHolder.getCatalog();
for (ActionConfiguration actionConfig : configuration.getActions()) {
final String actionServiceID = actionConfig.getServiceID();
if(LOGGER.isDebugEnabled())
LOGGER.debug("Loading actionService " + actionServiceID
+ " from " + actionConfig.getClass().getSimpleName()
+ " " + actionConfig.getId()+":"+actionConfig.getName());
final ActionService<FileSystemEvent, ActionConfiguration> actionService = catalog.getResource(actionServiceID, ActionService.class);
if (actionService != null) {
Action<FileSystemEvent> action = null;
if (actionService.canCreateAction(actionConfig)) {
action = actionService.createAction(actionConfig);
if (action == null) {
throw new IllegalArgumentException("Action could not be instantiated for config "
+ actionConfig);
}
} else {
throw new IllegalArgumentException("Cannot create the action using the service "
+ actionServiceID + " check the configuration.");
}
// add default status listener (Used by the GUI to track action
// stat)
// TODO
// attach listeners to actions
for (ProgressListenerConfiguration plConfig : actionConfig.getListenerConfigurations()) {
final String listenerServiceID = plConfig.getServiceID();
final ProgressListenerService progressListenerService = CatalogHolder.getCatalog()
.getResource(listenerServiceID, ProgressListenerService.class);
if (progressListenerService != null) {
ProgressListener progressListener = progressListenerService
.createProgressListener(plConfig, action);
action.addListener(progressListener);
} else {
throw new IllegalArgumentException("Could not find '" + listenerServiceID
+ "' listener," + " declared in "
+ actionConfig.getId() + " action configuration,"
+ " in " + configuration.getId() + " consumer");
}
}
loadedActions.add((BaseAction<FileSystemEvent>)action);
} else {
throw new IllegalArgumentException("ActionService not found '" + actionServiceID
+ "' for ActionConfig '" + actionConfig.getName() + "'");
}
}
super.addActions(loadedActions);
if (loadedActions.isEmpty()) {
if (LOGGER.isInfoEnabled()) {
LOGGER.info(getClass().getSimpleName() + " initialized with " + loadedActions.size()
+ " actions");
}
}
}
/***************************************************************************
* Main Thread cycle.
*
* <LI>Create needed dirs</LI> <LI>Optionally backup files</LI> <LI>Move
* files into a job-specific working dir</LI> <LI>Run the actions</LI>
*/
public Queue<FileSystemEvent> call() throws Exception {
this.canceled = false;
boolean jobResultSuccessful = false;
Throwable exceptionOccurred = null;
getListenerForwarder().setTask("Configuring");
getListenerForwarder().started();
try {
// create live working dir
getListenerForwarder().progressing(10, "Managing events");
//
// Management of current working directory
//
// if we work on the input directory, we do not move around
// anything, unless we want to
// perform a backup
if (configuration.isPerformBackup() || !configuration.isPreserveInput()) {
if ( ! flowInstanceTempDir.exists() && ! flowInstanceTempDir.mkdirs()) {
throw new IllegalStateException("Could not create consumer backup directory!");
}
}
// set the consumer running context
// don't know how this running context will be used in a FileBased* hiererchy, anyway let's force the use of proper methods.
setRunningContext("DONT_USE_AS_FILEPATH_" + flowInstanceTempDir.getAbsolutePath());
// create backup dir. Creation is deferred until first usage
getListenerForwarder().progressing(20, "Creating backup dir");
final File backupDirectory = new File(flowInstanceTempDir, "backup");
if (configuration.isPerformBackup()) {
if (!backupDirectory.exists() && !backupDirectory.mkdirs()) {
throw new IllegalStateException("Could not create consumer backup directory!");
}
}
//
// Cycling on all the input events
//
Queue<FileSystemEvent> fileEventList = new LinkedList<FileSystemEvent>();
int numProcessedFiles = 0;
for (FileSystemEvent event : this.eventsQueue) {
if (LOGGER.isInfoEnabled()) {
LOGGER.info("[" + Thread.currentThread().getName()
+ "]: new element retrieved from the MailBox.");
}
// get info for the input file event
final File sourceDataFile = event.getSource();
final String fileBareName;
if ((sourceDataFile != null) && sourceDataFile.exists()) {
fileBareName = FilenameUtils.getName(sourceDataFile.toString());
getListenerForwarder()
.progressing(30 + (10f / this.eventsQueue.size() * numProcessedFiles++),
"Preprocessing event " + fileBareName);
//
// copy input file/dir to current working directory
//
if (IOUtils.acquireLock(this, sourceDataFile)) {
//
// Backing up inputs?
//
if (this.configuration.isPerformBackup()) {
// Backing up files and delete sources.
getListenerForwarder()
.progressing(30 + (10f / this.eventsQueue.size() * numProcessedFiles++),
"Creating backup files");
// In case we do not work on the input as is, we
// move it to our
// current working directory
final File destDataFile = new File(backupDirectory, fileBareName);
if (sourceDataFile.isDirectory()) {
FileUtils.copyDirectory(sourceDataFile, destDataFile);
} else {
FileUtils.copyFile(sourceDataFile, destDataFile);
}
}
//
// Working on input events directly without moving to
// working dir?
//
if (!configuration.isPreserveInput()) {
// In case we do not work on the input as is, we
// move it to our current working directory
final File destDataFile = new File(flowInstanceTempDir, fileBareName);
if (sourceDataFile.isDirectory()) {
FileUtils.moveDirectory(sourceDataFile, destDataFile);
} else {
FileUtils.moveFile(sourceDataFile, destDataFile);
}
// adjust event sources since we moved the files
// locally
fileEventList.offer(new FileSystemEvent(destDataFile, event.getEventType()));
} else {
// we are going to work directly on the input files
fileEventList.offer(event);
}
if (LOGGER.isInfoEnabled()) {
LOGGER.info("[" + Thread.currentThread().getName() + "]: accepted file "
+ sourceDataFile);
}
} else {
if (LOGGER.isErrorEnabled()) {
LOGGER.error(new StringBuilder("[").append(Thread.currentThread().getName())
.append("]: could not lock file ").append(sourceDataFile).toString());
}
/*
* TODO: lock not acquired: what else?
*/
}
} // event.getSource()!=null && sourceDataFile.exists()
else {
/*
* event.getSource()==null || !sourceDataFile.exists() this
* could be an empty file representing a POLLING event
*/
fileEventList.offer(event);
}
}
// //
// TODO if no further processing is necessary or can be
// done due to some error, set eventConsumerStatus to Finished or
// Failure. (etj: ???)
// //
if (LOGGER.isInfoEnabled()) {
LOGGER.info("[" + Thread.currentThread().getName() + "]: new element processed.");
}
// // Finally, run the Actions on the files
getListenerForwarder().progressing(50, "Running actions");
try {
// apply actions into the actual context (currentRunDirectory)
fileEventList = this.applyActions(fileEventList);
this.setStatus(EventConsumerStatus.COMPLETED);
jobResultSuccessful = true;
} catch (ActionException ae) {
this.setStatus(EventConsumerStatus.FAILED);
throw ae;
}
return fileEventList;
} catch (ActionException e) {
String msg = "[" + Thread.currentThread().getName() + "] Error during "
+ e.getType().getSimpleName() + " execution: " + e.getLocalizedMessage();
if (LOGGER.isDebugEnabled()) {
LOGGER.error(msg, e);
} else {
LOGGER.error(msg);
}
this.setStatus(EventConsumerStatus.FAILED);
exceptionOccurred = e;
} catch (IOException e) {
if (LOGGER.isErrorEnabled()) {
LOGGER.error("[" + Thread.currentThread().getName()
+ "] could not move file " + " due to the following IO error: "
+ e.getLocalizedMessage(), e);
}
this.setStatus(EventConsumerStatus.FAILED);
exceptionOccurred = e;
} catch (InterruptedException e) {
if (LOGGER.isErrorEnabled()) {
LOGGER.error("[" + Thread.currentThread().getName()
+ "] could not move file " + " due to an InterruptedException: "
+ e.getLocalizedMessage(), e);
}
this.setStatus(EventConsumerStatus.FAILED);
exceptionOccurred = e;
} catch (RuntimeException e) {
exceptionOccurred = e;
throw e;
} finally {
getListenerForwarder().progressing(100, "Running actions");
if (LOGGER.isInfoEnabled()) {
LOGGER.info(Thread.currentThread().getName() + " DONE!");
}
// this.dispose();
if (jobResultSuccessful && (exceptionOccurred == null)) {
getListenerForwarder().completed();
} else {
getListenerForwarder().failed(exceptionOccurred);
}
}
return null;
}
/**
* @param configuration
*/
public void setConfiguration(FileBasedEventConsumerConfiguration configuration) {
this.configuration = configuration;
}
/**
* @return
*/
public FileBasedEventConsumerConfiguration getConfiguration() {
return configuration;
}
/*
* (non-Javadoc)
*
* @see it.geosolutions.geobatch.manager.Manager#dispose()
*/
public void dispose() {
if (LOGGER.isInfoEnabled()) {
LOGGER.info(Thread.currentThread().getName() + " DISPOSING!");
}
clear();
super.dispose();
this.numInputFiles = 0;
this.configuration = null;
}
/**
* remove all Cumulating progress listener from the Consumer and containing
* action(s) remove all the actions from the action list remove
* contextRunningDir
*/
private void clear() {
// Progress Logging...
// remove all Cumulating progress listener from the Consumer and
// containing action(s)
final ProgressListenerForwarder lf = this.getListenerForwarder();
final Collection<? extends IProgressListener> listeners = lf.getListeners();
if (listeners != null) {
for (IProgressListener listener : listeners) {
if (listener instanceof CumulatingProgressListener) {
((CumulatingProgressListener)listener).clearMessages();
}
}
}
// Current Action Status...
// remove all the actions from the action list
if (actions != null) {
for (Action action : this.actions) {
if (action instanceof BaseAction<?>) {
final BaseAction<?> baseAction = (BaseAction)action;
// try the most interesting information holder
Collection<IProgressListener> coll = baseAction
.getListeners(CumulatingProgressListener.class);
for (IProgressListener cpl : coll) {
if (cpl != null && cpl instanceof CumulatingProgressListener) {
((CumulatingProgressListener)cpl).clearMessages();
}
}
}
}
this.actions.clear();
}
// remove contextRunningDir
if (!keepRuntimeDir) {
// removing running context directory
try {
FileUtils.deleteDirectory(getFlowInstanceTempDir());
} catch (IOException e) {
if (LOGGER.isWarnEnabled()) {
LOGGER.warn("Problem trying to remove the running context directory: "
+ getFlowInstanceTempDir() + ".\n " + e.getLocalizedMessage());
}
}
}
}
@Override
public boolean consume(FileSystemEvent event) {
if ((getStatus() != EventConsumerStatus.IDLE) && (getStatus() != EventConsumerStatus.WAITING)) {
return false;
}
if (super.consume(event)) {
// start execution
if (numInputFiles == 0) {
setStatus(EventConsumerStatus.EXECUTING);
}
// move to waiting
if (getStatus() == EventConsumerStatus.IDLE) {
setStatus(EventConsumerStatus.WAITING);
}
return true;
} else {
if (LOGGER.isErrorEnabled()) {
LOGGER.error("Action execution is rejected. Probably execution queue is full.");
}
setStatus(EventConsumerStatus.CANCELED);
return false;
}
}
public void cancel() {
this.canceled = true;
}
/**
* @return
*/
public boolean isCanceled() {
return canceled;
}
@Override
protected void setStatus(EventConsumerStatus eventConsumerStatus) {
super.setStatus(eventConsumerStatus);
// // are we executing? If yes, let's trigger a thread!
// if (eventConsumerStatus == EventConsumerStatus.EXECUTING)
// getCatalog().getExecutor().execute(this);
}
/**
* Create a temp dir for an action in a flow.<br/>
*/
@Override
protected void setupAction(BaseAction action, int step) throws IllegalStateException {
// random id
action.setId(UUID.randomUUID().toString());
// tempDir
String actionTempDirName = step + "_" + action.getName();
File actionTempDir = new File(flowInstanceTempDir, actionTempDirName);
if (!actionTempDir.mkdirs()) {
throw new IllegalStateException("Unable to create the action temporary dir: " + actionTempDir);
}
action.setTempDir(actionTempDir);
File actionConfigDir = initConfigDir(action.getConfiguration(), flowConfigDir);
action.setConfigDir(actionConfigDir);
}
private File initConfigDir(ActionConfiguration actionCfg, File flowConfigDir) {
File ret = null;
File ovr = actionCfg.getOverrideConfigDir();
if( ovr != null) {
if( ! ovr.isAbsolute())
ret = new File(flowConfigDir, ovr.getPath());
else
- ret = ovr;
+ ret = ovr;
} else
ret = new File(flowConfigDir, actionCfg.getId());
if(LOGGER.isDebugEnabled())
LOGGER.debug("Action config dir set to " + ret);
return ret;
}
@Override
public String toString() {
return getClass().getSimpleName() + "[" + " status:" + getStatus() + " actions:" + actions.size()
+ " tempDir:" + getFlowInstanceTempDir() + " events:" + eventsQueue.size()
+ (isPaused() ? " PAUSED" : "")
+ (eventsQueue.isEmpty() ? "" : (" first event:" + eventsQueue.peek().getSource().getName()))
+ "]";
}
/**
* Temporary folder used in the flow instance.
*/
public final File getFlowInstanceTempDir() {
return flowInstanceTempDir;
}
/**
* @return the keepRuntimeDir
*/
public final boolean isKeepRuntimeDir() {
return keepRuntimeDir;
}
/**
* @param keepRuntimeDir if true the runtime dir is not removed
*/
public final void setKeepRuntimeDir(boolean keepRuntimeDir) {
this.keepRuntimeDir = keepRuntimeDir;
}
/**
* Used to create a unique timestamp useful for creating unique temp dir names.
*/
static class UniqueTimeStampProvider {
// Dateformat for creating flow instance temp dirs.
final static SimpleDateFormat DATEFORMATTER = new SimpleDateFormat("yyyyMMdd'-'HHmmss-SSS");
static{
TimeZone TZ_UTC = TimeZone.getTimeZone("UTC");
DATEFORMATTER.setTimeZone(TZ_UTC);
}
static long lastDate = new Date().getTime(); // arbitrary init
synchronized static public String getTimeStamp() {
Date now;
do {
now = new Date();
} while (lastDate == now.getTime());
lastDate = now.getTime();
final String timeStamp = DATEFORMATTER.format(now);
return timeStamp;
}
}
}
| false | false | null | null |
diff --git a/src/test/java/bad/robot/http/listener/LoggingHttpClientTest.java b/src/test/java/bad/robot/http/listener/LoggingHttpClientTest.java
index c1d1096..1884d7a 100644
--- a/src/test/java/bad/robot/http/listener/LoggingHttpClientTest.java
+++ b/src/test/java/bad/robot/http/listener/LoggingHttpClientTest.java
@@ -1,136 +1,127 @@
/*
* Copyright (c) 2011-2012, bad robot (london) ltd
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package bad.robot.http.listener;
import bad.robot.http.FormUrlEncodedMessage;
import bad.robot.http.HttpClient;
import bad.robot.http.Log4J;
import bad.robot.http.UnencodedStringMessage;
-import com.google.code.tempusfugit.FactoryException;
-import com.google.code.tempusfugit.temporal.Clock;
import org.apache.log4j.Logger;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.jmock.integration.junit4.JMock;
import org.junit.After;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.net.MalformedURLException;
-import java.util.Date;
import static bad.robot.http.Any.anyUrl;
import static bad.robot.http.FormParameters.params;
import static bad.robot.http.SimpleHeader.header;
import static bad.robot.http.SimpleHeaders.headers;
import static org.apache.log4j.Level.INFO;
import static org.hamcrest.Matchers.containsString;
@RunWith(JMock.class)
public class LoggingHttpClientTest {
public static final String lineSeparator = System.getProperty("line.separator");
private final Mockery context = new Mockery();
- private final Clock mock = new Clock() {
- @Override
- public Date create() throws FactoryException {
- return new Date();
- }
- };
private final Logger logger = Logger.getLogger(this.getClass());
private final Log4J log4J = Log4J.appendTo(logger, INFO);
private final HttpClient client = context.mock(HttpClient.class);
private final LoggingHttpClient http = new LoggingHttpClient(client, logger);
@Test
public void shouldLogGet() throws MalformedURLException {
expectingHttpClientCall();
http.get(anyUrl());
- log4J.assertThat(containsString("GET http://baddotrobot.com HTTP/1.1"));
+ log4J.assertThat(containsString("GET http://not.real.url HTTP/1.1"));
}
@Test
public void shouldLogGetWithHeaders() throws MalformedURLException {
expectingHttpClientCall();
http.get(anyUrl(), headers(header("Accept", "text/plain"), header("Host", "127.0.0.1")));
- log4J.assertThat(containsString("GET http://baddotrobot.com HTTP/1.1" + lineSeparator + "Accept: text/plain" + lineSeparator + "Host: 127.0.0.1"));
+ log4J.assertThat(containsString("GET http://not.real.url HTTP/1.1" + lineSeparator + "Accept: text/plain" + lineSeparator + "Host: 127.0.0.1"));
}
@Test
public void shouldLogPostFormUrlEncoded() throws MalformedURLException {
expectingHttpClientCall();
http.post(anyUrl(), new FormUrlEncodedMessage(
params(
"first name", "bob la rock",
"age", "28"
),
headers(
header("Accept", "text/plain"),
header("Host", "127.0.0.1"))
));
- log4J.assertThat(containsString("POST http://baddotrobot.com HTTP/1.1" + lineSeparator));
+ log4J.assertThat(containsString("POST http://not.real.url HTTP/1.1" + lineSeparator));
log4J.assertThat(containsString("Accept: text/plain"));
log4J.assertThat(containsString("Host: 127.0.0.1"));
log4J.assertThat(containsString("Content-Type: application/x-www-form-urlencoded"));
log4J.assertThat(containsString("Content-Length: " + "first+name=bob+la+rock&age=28".getBytes().length));
log4J.assertThat(containsString("first+name=bob+la+rock&age=28"));
}
@Test
public void shouldLogPostUnencoded() throws MalformedURLException {
expectingHttpClientCall();
http.post(anyUrl(), new UnencodedStringMessage("cheese sandwich", headers(header("Accept", "text/plain"), header("Host", "127.0.0.1"))));
- log4J.assertThat(containsString("POST http://baddotrobot.com HTTP/1.1"));
+ log4J.assertThat(containsString("POST http://not.real.url HTTP/1.1"));
log4J.assertThat(containsString("Accept: text/plain"));
log4J.assertThat(containsString("Host: 127.0.0.1"));
log4J.assertThat(containsString("cheese sandwich"));
}
@Test
public void shouldLogPut() throws MalformedURLException {
expectingHttpClientCall();
http.put(anyUrl(), new UnencodedStringMessage("cheese sandwich", headers(header("Accept", "text/plain"), header("Host", "127.0.0.1"))));
- log4J.assertThat(containsString("PUT http://baddotrobot.com HTTP/1.1"));
+ log4J.assertThat(containsString("PUT http://not.real.url HTTP/1.1"));
log4J.assertThat(containsString("Accept: text/plain"));
log4J.assertThat(containsString("Host: 127.0.0.1"));
log4J.assertThat(containsString("cheese sandwich"));
}
@Test
public void shouldLogDelete() throws MalformedURLException {
expectingHttpClientCall();
http.delete(anyUrl());
- log4J.assertThat(containsString("DELETE http://baddotrobot.com HTTP/1.1"));
+ log4J.assertThat(containsString("DELETE http://not.real.url HTTP/1.1"));
}
private void expectingHttpClientCall() {
context.checking(new Expectations() {{
oneOf(client);
}});
}
@After
public void cleanupLog4J() {
log4J.clean();
}
}
diff --git a/src/test/java/bad/robot/http/listener/TimedHttpClientTest.java b/src/test/java/bad/robot/http/listener/TimedHttpClientTest.java
index 023aebc..16a1c5c 100644
--- a/src/test/java/bad/robot/http/listener/TimedHttpClientTest.java
+++ b/src/test/java/bad/robot/http/listener/TimedHttpClientTest.java
@@ -1,105 +1,105 @@
/*
* Copyright (c) 2011-2012, bad robot (london) ltd
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package bad.robot.http.listener;
import bad.robot.http.DefaultHttpResponse;
import bad.robot.http.HttpClient;
import bad.robot.http.Log4J;
import com.google.code.tempusfugit.FactoryException;
import com.google.code.tempusfugit.temporal.Clock;
import org.apache.log4j.Logger;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.jmock.integration.junit4.JMock;
import org.junit.After;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Date;
import static bad.robot.http.Any.anyUrl;
import static bad.robot.http.SimpleHeaders.noHeaders;
import static bad.robot.http.listener.TimedHttpClient.timedHttpClient;
import static com.google.code.tempusfugit.temporal.Duration.millis;
import static org.apache.log4j.Level.INFO;
import static org.hamcrest.Matchers.containsString;
@RunWith(JMock.class)
public class TimedHttpClientTest {
private final Mockery context = new Mockery();
private final Class<? extends TimedHttpClientTest> logger = this.getClass();
private final Clock clock = context.mock(Clock.class);
private final HttpClient delegate = context.mock(HttpClient.class);
private final Log4J log4J = Log4J.appendTo(Logger.getLogger(logger), INFO);
@Test
public void shouldDelegate() throws MalformedURLException {
final URL url = anyUrl();
context.checking(new Expectations() {{
oneOf(delegate).get(url);
}});
timedHttpClient(delegate, new FixedClock(), logger).get(url);
}
@Test
public void shouldTimeRequest() throws IOException {
context.checking(new Expectations() {{
allowing(delegate).get(with(any(URL.class)));
oneOf(clock).create(); will(returnValue(new Date(0)));
oneOf(clock).create(); will(returnValue(new Date(millis(100).inMillis())));
}});
timedHttpClient(delegate, clock, logger).get(anyUrl());
log4J.assertThat(containsString("100 MILLISECONDS"));
}
@Test
public void shouldLogDetails() throws MalformedURLException {
context.checking(new Expectations() {{
allowing(delegate).get(with(any(URL.class))); will(returnValue(new DefaultHttpResponse(200, "OK", "nothing", noHeaders())));
}});
timedHttpClient(delegate, new FixedClock(), logger).get(anyUrl());
- log4J.assertThat(containsString("GET http://not.real.url 200 (OK), took Duration 0 MILLISECONDS"));
+ log4J.assertThat(containsString("GET http://not.real.url was 200 (OK), took Duration 0 MILLISECONDS"));
}
@Test (expected = IllegalArgumentException.class)
public void shouldNotAllowVagueLoggerClass() throws IOException {
timedHttpClient(delegate, clock, Object.class).get(anyUrl());
}
@After
public void cleanupLog4J() {
log4J.clean();
}
private static class FixedClock implements Clock {
@Override
public Date create() throws FactoryException {
return new Date(0);
}
}
}
| false | false | null | null |
diff --git a/src/de/aidger/model/AbstractModel.java b/src/de/aidger/model/AbstractModel.java
index 9b364815..06982cb6 100644
--- a/src/de/aidger/model/AbstractModel.java
+++ b/src/de/aidger/model/AbstractModel.java
@@ -1,434 +1,435 @@
package de.aidger.model;
import static de.aidger.utils.Translation._;
import java.lang.reflect.InvocationTargetException;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Observable;
import java.util.Vector;
import de.aidger.model.validators.DateRangeValidator;
import de.aidger.model.validators.EmailValidator;
import de.aidger.model.validators.InclusionValidator;
import de.aidger.model.validators.PresenceValidator;
import de.aidger.model.validators.Validator;
import de.aidger.utils.Logger;
import de.unistuttgart.iste.se.adohive.controller.AdoHiveController;
import de.unistuttgart.iste.se.adohive.controller.IAdoHiveManager;
import de.unistuttgart.iste.se.adohive.exceptions.AdoHiveException;
import de.unistuttgart.iste.se.adohive.model.IAdoHiveModel;
/**
* AbstractModel contains all important database related functions which all
* models need to contain. This includes getting instances of models and saving
* or removing them.
*
* @author Philipp Gildein
*/
public abstract class AbstractModel<T> extends Observable implements
IAdoHiveModel<T> {
/**
* The unique id of the model in the database.
*/
protected int id = 0;
/**
* Determines if the model has been saved in the db yet.
*/
protected boolean isNew = true;
/**
* Should the model first be removed before saveing. Needed for example for
* HourlyWage which has several Primary Keys and needs to be removed when
* edited.
*/
protected boolean removeOnUpdate = false;
/**
* Used to cache the AdoHiveManagers after getting them the first time.
*/
protected static Map<String, IAdoHiveManager> managers =
new HashMap<String, IAdoHiveManager>();
/**
* Array containing all validators for that specific model.
*/
protected List<Validator> validators = new Vector<Validator>();
/**
* Array containing errors if a validator fails.
*/
protected List<String> errors = new Vector<String>();
/**
* Map of errors for specific fields.
*/
protected Map<String, List<String>> fieldErrors = new HashMap<String, List<String>>();
/**
* Cloneable function inherited from IAdoHiveModel.
*
* @return Clone of the model
*/
@Override
abstract public T clone();
/**
* Get all models from the database.
*
* @return An array containing all found models or null
*/
@SuppressWarnings("unchecked")
public List getAll() throws AdoHiveException {
return getManager().getAll();
}
/**
* Get a specific model by specifying its unique id.
*
* @param id
* The unique id of the model
* @return The model if one was found or null
*/
@SuppressWarnings("unchecked")
public T getById(int id) throws AdoHiveException {
return (T) getManager().getById(id);
}
/**
* Get a specific model by specifying a set of keys.
*
* @param o
* The set of keys specific to this model
* @return The model if one was found or null
*/
@SuppressWarnings("unchecked")
public T getByKeys(Object... o) throws AdoHiveException {
return (T) getManager().getByKeys(o);
}
/**
* Get the number of models in the database.
*
* @return The number of models
* @throws AdoHiveException
*/
public int size() throws AdoHiveException {
return getManager().size();
}
/**
* Returns true if no model has been saved into the database.
*
* @return True if no model is in the database
* @throws AdoHiveException
*/
public boolean isEmpty() throws AdoHiveException {
return getManager().isEmpty();
}
/**
* Checks if the current instance exists in the database.
*
* @return True if the instance exists
* @throws AdoHiveException
*/
public boolean isInDatabase() throws AdoHiveException {
return getManager().contains(this);
}
/**
* Deletes everything from the associated table.
*
* @throws AdoHiveException
*/
public void clearTable() throws AdoHiveException {
getManager().clear();
id = 0; // Reset
}
// TODO: Add get(index) method?
/**
* Save the current model to the database.
*
* @return True if validation succeeds
* @throws AdoHiveException
*/
@SuppressWarnings("unchecked")
public boolean save() throws AdoHiveException {
if (!doValidate()) {
return false;
} else if (!errors.isEmpty()) {
Logger.debug(_("The model was not saved because the error list is not empty."));
return false;
}
/* Add or update model */
IAdoHiveManager mgr = getManager();
if (isNew) {
mgr.add(this);
isNew = false;
} else if (removeOnUpdate) {
remove();
mgr.add(this);
+ setNew(false);
} else {
mgr.update(this);
}
setChanged();
notifyObservers();
return true;
}
/**
* Remove the current model from the database.
*
* @throws AdoHiveException
*/
@SuppressWarnings("unchecked")
public void remove() throws AdoHiveException {
if (!isNew) {
getManager().remove(this);
clearChanged();
notifyObservers();
setNew(true);
}
}
/**
* Get a list of all errors.
*
* @return A list of errors
*/
public List<String> getErrors() {
return errors;
}
/**
* Get a list of errors for a specific field.
*
* @param field
* The field to get the errors for
* @return A list of errors
*/
public List<String> getErrorsFor(String field) {
return fieldErrors.get(field);
}
/**
* Add an error to the list,
*
* @param error
* The error to add
*/
public void addError(String error) {
errors.add(error);
}
/**
* Add an error for a specific field to the list.
*
* @param field
* The field on which the error occured
* @param error
* The error to add
*/
public void addError(String field, String error) {
error = field + " " + error;
errors.add(error);
if (fieldErrors.containsKey(field)) {
fieldErrors.get(field).add(error);
} else {
List<String> list = new Vector<String>();
list.add(error);
fieldErrors.put(field, list);
}
}
/**
* Clear the error lists.
*/
public void resetErrors() {
errors.clear();
fieldErrors.clear();
}
/**
* Add a validator to the model.
*
* @param valid
* The validator to add
*/
public void addValidator(Validator valid) {
validators.add(valid);
}
/**
* Add a presence validator to the model.
*
* @param members
* The name of the member variables to validate
*/
public void validatePresenceOf(String[] members) {
validators.add(new PresenceValidator(this, members));
}
/**
* Add an email validator to the model.
*
* @param member
* The name of the member variable to validate
*/
public void validateEmailAddress(String member) {
validators.add(new EmailValidator(this, new String[] { member }));
}
/**
* Add an date range validator to the model.
*
* @param from
* The starting date
* @param to
* The end date
*/
public void validateDateRange(String from, String to) {
validators.add(new DateRangeValidator(this, from, to));
}
/**
* Add an inclusion validator to the model.
*
* @param members
* The name of the member variables to validate
* @param inc
* The list to check for inclusion
*/
public void validateInclusionOf(String[] members, String[] inc) {
validators.add(new InclusionValidator(this, members, inc));
}
/**
* Returns the unique id of the activity.
*
* @return The unique id of the activity
*/
@Override
public int getId() {
return id;
}
/**
* Set the unique id of the assistant.
*
* <b>!!! THIS IS FOR INTERNAL ADOHIVE USAGE ONLY !!!</b>
*
* @param id
* The unique id of the assistant
*/
@Override
public void setId(int id) {
this.id = id;
}
/**
* Set if the model is new and should be added to the database.
*
* @param isnew
* Is the model new?
*/
public void setNew(boolean isnew) {
isNew = isnew;
if (isNew) {
setId(0);
}
}
/**
* Returns a string containing all informations stored in the model.
*
* @return A string containing informations on the model
*/
@Override
public String toString() {
String ret = getClass().getSimpleName() + " [" + "ID: " + getId()
+ ", ";
try {
for (java.lang.reflect.Method m : getClass().getDeclaredMethods()) {
if (m.getName().startsWith("get")
&& m.getParameterTypes().length == 0) {
ret += m.getName().substring(3) + ": ";
ret += m.invoke(this, new Object[0]) + ", ";
}
}
if (ret.endsWith(", ")) {
ret = ret.substring(0, ret.length() - 2);
}
} catch (InvocationTargetException ex) {
System.err.println(ex.getMessage());
} catch (IllegalArgumentException ex) {
System.err.println(ex.getMessage());
} catch (IllegalAccessException ex) {
System.err.println(ex.getMessage());
}
return ret + "]";
}
/**
* Extract the name of the class and return the correct manager.
*
* @return The name of the model class
*/
@SuppressWarnings("unchecked")
protected IAdoHiveManager getManager() {
String classname = getClass().getSimpleName();
if (!managers.containsKey(classname) ||
managers.get(classname) == null) {
/* Try to get the correct manager from the AdoHiveController */
try {
java.lang.reflect.Method m = AdoHiveController.class
.getMethod("get" + classname + "Manager");
managers.put(classname, (IAdoHiveManager) m.invoke(
AdoHiveController.getInstance(), new Object[0]));
} catch (Exception ex) {
Logger.error(MessageFormat.format(
_("Could not get manager for class \"{0}\". Error: {1}"),
new Object[] { classname, ex.getMessage() }));
}
}
return managers.get(classname);
}
/**
* Validate the input using the validators and a custom validate function.
*
* @return True if everything validates
*/
protected boolean doValidate() {
/* Try to validate before adding/updating */
boolean ret = true;
for (Validator v : validators) {
if (!v.validate()) {
ret = false;
}
}
/* Check if the model got a validate() function */
try {
java.lang.reflect.Method m = getClass().getDeclaredMethod(
"validate");
if (!(Boolean) m.invoke(this, new Object[0])) {
ret = false;
}
} catch (Exception ex) {
}
return ret;
}
}
| true | true | public boolean save() throws AdoHiveException {
if (!doValidate()) {
return false;
} else if (!errors.isEmpty()) {
Logger.debug(_("The model was not saved because the error list is not empty."));
return false;
}
/* Add or update model */
IAdoHiveManager mgr = getManager();
if (isNew) {
mgr.add(this);
isNew = false;
} else if (removeOnUpdate) {
remove();
mgr.add(this);
} else {
mgr.update(this);
}
setChanged();
notifyObservers();
return true;
}
| public boolean save() throws AdoHiveException {
if (!doValidate()) {
return false;
} else if (!errors.isEmpty()) {
Logger.debug(_("The model was not saved because the error list is not empty."));
return false;
}
/* Add or update model */
IAdoHiveManager mgr = getManager();
if (isNew) {
mgr.add(this);
isNew = false;
} else if (removeOnUpdate) {
remove();
mgr.add(this);
setNew(false);
} else {
mgr.update(this);
}
setChanged();
notifyObservers();
return true;
}
|
diff --git a/src/com/twobuntu/twobuntu/ArticleDetailFragment.java b/src/com/twobuntu/twobuntu/ArticleDetailFragment.java
index 80523a5..3e7b2c3 100644
--- a/src/com/twobuntu/twobuntu/ArticleDetailFragment.java
+++ b/src/com/twobuntu/twobuntu/ArticleDetailFragment.java
@@ -1,119 +1,121 @@
package com.twobuntu.twobuntu;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.annotation.SuppressLint;
import android.app.Fragment;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
+import android.webkit.WebSettings;
import android.webkit.WebView;
-import com.twobuntu.db.ArticleProvider;
import com.twobuntu.db.Article;
+import com.twobuntu.db.ArticleProvider;
// Displays details about the particular article.
public class ArticleDetailFragment extends Fragment {
// This is the ID of the article being displayed.
public static final String ARG_ARTICLE_ID = "article_id";
// This holds the ID and URL of the current article.
private long mID;
private String mURL;
// Columns to retrieve for the article.
private static final String[] mColumns = new String[] {
Article.COLUMN_TITLE,
Article.COLUMN_AUTHOR_EMAIL_HASH,
Article.COLUMN_CREATION_DATE,
Article.COLUMN_AUTHOR_NAME,
Article.COLUMN_BODY,
Article.COLUMN_URL
};
// Generates the HTML for the entire page given the title and body to display.
@SuppressLint("SimpleDateFormat")
private String generateHTML(String title, String email_hash, long creation_date, String author, String body) {
- String date = new SimpleDateFormat("MMMM dd, yyyy").format(new Date(creation_date * 1000));
+ String date = new SimpleDateFormat("MMMM d, yyyy").format(new Date(creation_date * 1000));
return "<html>" +
"<head>" +
" <link rel='stylesheet' href='css/style.css'>" +
"</head>" +
"<body>" +
"<header>" +
"<div>" +
"<img src='http://gravatar.com/avatar/" + email_hash + "?s=64&d=identicon'>" +
"<h2>" + title + "</h2>" +
"</div>" +
"<table><tr><td>by " + author + "</td>" +
"<td>" + date + "</td></tr></table>" +
"</header>" +
body +
"</body>" +
"</html>";
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Indicate that this fragment has a context menu and should not be recreated on a config change.
setHasOptionsMenu(true);
setRetainInstance(true);
// Attempt to load the specified article.
View rootView = inflater.inflate(R.layout.fragment_article_detail, container, false);
if(getArguments().containsKey(ARG_ARTICLE_ID)) {
Uri uri = Uri.withAppendedPath(ArticleProvider.CONTENT_LOOKUP_URI,
String.valueOf(getArguments().getLong(ARG_ARTICLE_ID)));
Cursor cursor = getActivity().getContentResolver().query(uri, mColumns, null, null, null);
cursor.moveToFirst();
// Set the title and body.
WebView webView = (WebView)rootView.findViewById(R.id.article_content);
+ webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
webView.loadDataWithBaseURL("file:///android_asset/", generateHTML(cursor.getString(0),
cursor.getString(1), cursor.getLong(2), cursor.getString(3), cursor.getString(4)),
"text/html", "utf-8", null);
// ...and remember the ID + URL.
mID = getArguments().getLong(ARG_ARTICLE_ID);
mURL = cursor.getString(3);
}
return rootView;
}
// Add the "toolbar" buttons to the action bar.
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.activity_article_detail, menu);
}
// Process an item from the action bar.
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.menu_comments:
{
Intent intent = new Intent(getActivity(), ArticleCommentsActivity.class);
intent.putExtra(ArticleCommentsFragment.ARG_ARTICLE_ID, mID);
startActivity(intent);
return true;
}
case R.id.menu_share:
{
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(android.content.Intent.EXTRA_TEXT, mURL);
getActivity().startActivity(Intent.createChooser(intent,
getActivity().getResources().getText(R.string.intent_share_article)));
return true;
}
default:
return false;
}
}
}
| false | false | null | null |
diff --git a/pact/pact-examples/src/main/java/eu/stratosphere/pact/example/wordcount/WordCount.java b/pact/pact-examples/src/main/java/eu/stratosphere/pact/example/wordcount/WordCount.java
index cc0057f6a..c181a0cc7 100644
--- a/pact/pact-examples/src/main/java/eu/stratosphere/pact/example/wordcount/WordCount.java
+++ b/pact/pact-examples/src/main/java/eu/stratosphere/pact/example/wordcount/WordCount.java
@@ -1,190 +1,186 @@
/***********************************************************************************************************************
*
* Copyright (C) 2010 by the Stratosphere project (http://stratosphere.eu)
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
**********************************************************************************************************************/
package eu.stratosphere.pact.example.wordcount;
import java.io.IOException;
import java.util.Iterator;
import eu.stratosphere.pact.common.contract.FileDataSink;
import eu.stratosphere.pact.common.contract.FileDataSource;
import eu.stratosphere.pact.common.contract.MapContract;
import eu.stratosphere.pact.common.contract.ReduceContract;
import eu.stratosphere.pact.common.io.DelimitedInputFormat;
import eu.stratosphere.pact.common.io.FileOutputFormat;
import eu.stratosphere.pact.common.plan.Plan;
import eu.stratosphere.pact.common.plan.PlanAssembler;
import eu.stratosphere.pact.common.plan.PlanAssemblerDescription;
import eu.stratosphere.pact.common.stubs.Collector;
import eu.stratosphere.pact.common.stubs.MapStub;
import eu.stratosphere.pact.common.stubs.ReduceStub;
import eu.stratosphere.pact.common.type.PactRecord;
import eu.stratosphere.pact.common.type.base.PactInteger;
import eu.stratosphere.pact.common.type.base.PactString;
/**
* Implements a word count which takes the input file and counts the number of
* the occurrences of each word in the file.
*
* @author Larysa, Moritz Kaufmann, Stephan Ewen
*/
public class WordCount implements PlanAssembler, PlanAssemblerDescription
{
/**
* Converts a input line, assuming to contain a string, into a record that has a single field,
* which is a {@link PactString}, containing that line.
*/
public static class LineInFormat extends DelimitedInputFormat
{
private final PactString string = new PactString();
@Override
public boolean readRecord(PactRecord record, byte[] line, int numBytes)
{
this.string.setValueAscii(line, 0, numBytes);
record.setField(0, this.string);
return true;
}
}
/**
* Writes a (String,Integer)-KeyValuePair to a string. The output format is:
* "<key>|;<value>\n"
*/
public static class WordCountOutFormat extends FileOutputFormat
{
private final StringBuilder buffer = new StringBuilder();
@Override
public void writeRecord(PactRecord record) throws IOException {
this.buffer.setLength(0);
this.buffer.append(record.getField(0, PactString.class).toString());
this.buffer.append(' ');
this.buffer.append(record.getField(1, PactInteger.class).getValue());
this.buffer.append('\n');
byte[] bytes = this.buffer.toString().getBytes();
this.stream.write(bytes);
}
}
/**
* Converts a (String,Integer)-KeyValuePair into multiple KeyValuePairs. The
* key string is tokenized by spaces. For each token a new
* (String,Integer)-KeyValuePair is emitted where the Token is the key and
* an Integer(1) is the value.
*/
public static class TokenizeLine extends MapStub
{
private final PactRecord outputRecord = new PactRecord();
private final PactString string = new PactString();
private final PactInteger integer = new PactInteger(1);
private final AsciiUtils.WhitespaceTokenizer tokenizer =
new AsciiUtils.WhitespaceTokenizer();
@Override
public void map(PactRecord record, Collector collector)
{
// get the first field (as type PactString) from the record
PactString str = record.getField(0, PactString.class);
// normalize the line
AsciiUtils.replaceNonWordChars(str, ' ');
AsciiUtils.toLowerCase(str);
// tokenize the line
this.tokenizer.setStringToTokenize(str);
while (tokenizer.next(this.string))
{
// we emit a (word, 1) pair
this.outputRecord.setField(0, this.string);
this.outputRecord.setField(1, this.integer);
collector.collect(this.outputRecord);
}
}
}
/**
* Counts the number of values for a given key. Hence, the number of
* occurrences of a given token (word) is computed and emitted. The key is
* not modified, hence a SameKey OutputContract is attached to this class.
*/
// @Combinable
public static class CountWords extends ReduceStub
{
private final PactInteger theInteger = new PactInteger();
@Override
public void reduce(Iterator<PactRecord> records, Collector out) throws Exception
{
PactRecord element = null;
int sum = 0;
while (records.hasNext()) {
element = records.next();
element.getField(1, this.theInteger);
// we could have equivalently used PactInteger i = record.getField(1, PactInteger.class);
sum += this.theInteger.getValue();
}
this.theInteger.setValue(sum);
element.setField(1, this.theInteger);
out.collect(element);
}
@Override
public void combine(Iterator<PactRecord> records, Collector out) throws Exception
{
this.reduce(records, out);
}
}
/**
* {@inheritDoc}
*/
@Override
public Plan getPlan(String... args)
{
// parse job parameters
int noSubTasks = (args.length > 0 ? Integer.parseInt(args[0]) : 1);
String dataInput = (args.length > 1 ? args[1] : "");
String output = (args.length > 2 ? args[2] : "");
FileDataSource source = new FileDataSource(LineInFormat.class, dataInput, "Input Lines");
- source.setDegreeOfParallelism(noSubTasks);
MapContract mapper = new MapContract(TokenizeLine.class, source, "Tokenize Lines");
- mapper.setDegreeOfParallelism(noSubTasks);
ReduceContract reducer = new ReduceContract(CountWords.class, 0, PactString.class, mapper, "Count Words");
- reducer.setDegreeOfParallelism(noSubTasks);
FileDataSink out = new FileDataSink(WordCountOutFormat.class, output, reducer, "Output");
- out.setDegreeOfParallelism(noSubTasks);
Plan plan = new Plan(out, "WordCount Example");
-// plan.setDefaultParallelism(noSubTasks);
+ plan.setDefaultParallelism(noSubTasks);
return plan;
}
/**
* {@inheritDoc}
*/
@Override
public String getDescription() {
return "Parameters: [noSubStasks] [input] [output]";
}
}
diff --git a/pact/pact-tests/src/test/java/eu/stratosphere/pact/test/util/TestBase.java b/pact/pact-tests/src/test/java/eu/stratosphere/pact/test/util/TestBase.java
index be54ec255..03ac6b520 100644
--- a/pact/pact-tests/src/test/java/eu/stratosphere/pact/test/util/TestBase.java
+++ b/pact/pact-tests/src/test/java/eu/stratosphere/pact/test/util/TestBase.java
@@ -1,315 +1,315 @@
/***********************************************************************************************************************
*
* Copyright (C) 2010 by the Stratosphere project (http://stratosphere.eu)
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
**********************************************************************************************************************/
package eu.stratosphere.pact.test.util;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
import java.util.PriorityQueue;
import java.util.Properties;
import java.util.StringTokenizer;
import junit.framework.Assert;
import junit.framework.TestCase;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.fs.FileSystem;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import eu.stratosphere.nephele.configuration.Configuration;
import eu.stratosphere.nephele.jobgraph.JobGraph;
import eu.stratosphere.pact.test.util.filesystem.FilesystemProvider;
import eu.stratosphere.pact.test.util.minicluster.ClusterProvider;
import eu.stratosphere.pact.test.util.minicluster.ClusterProviderPool;
/**
* @author Erik Nijkamp
* @author Fabian Hueske
*/
public abstract class TestBase extends TestCase {
private static final int MINIMUM_HEAP_SIZE_MB = 192;
private static final Log LOG = LogFactory.getLog(TestBase.class);
protected static ClusterProvider cluster;
protected final Configuration config;
protected final String clusterConfig;
public TestBase(Configuration config, String clusterConfig) {
this.clusterConfig = clusterConfig;
this.config = config;
verifyJvmOptions();
}
public TestBase(Configuration testConfig) {
this(testConfig, Constants.DEFAULT_TEST_CONFIG);
}
private void verifyJvmOptions() {
long heap = Runtime.getRuntime().maxMemory() >> 20;
Assert.assertTrue("Insufficient java heap space " + heap + "mb - set JVM option: -Xmx" + MINIMUM_HEAP_SIZE_MB
+ "m", heap > MINIMUM_HEAP_SIZE_MB - 50);
Assert.assertTrue("IPv4 stack required - set JVM option: -Djava.net.preferIPv4Stack=true", "true".equals(System
.getProperty("java.net.preferIPv4Stack")));
}
@Before
public void startCluster() throws Exception {
LOG.info("######################### start - cluster config : " + clusterConfig + " #########################");
cluster = ClusterProviderPool.getInstance(clusterConfig);
}
@After
public void stopCluster() throws Exception {
LOG.info("######################### stop - cluster config : " + clusterConfig + " #########################");
cluster.stopCluster();
ClusterProviderPool.removeInstance(clusterConfig);
FileSystem.closeAll();
System.gc();
}
@Test
public void testJob() throws Exception {
// pre-submit
preSubmit();
// submit job
JobGraph jobGraph = null;
try {
jobGraph = getJobGraph();
} catch(Exception e) {
LOG.error(e);
Assert.fail("Failed to obtain JobGraph!");
}
try {
cluster.submitJobAndWait(jobGraph, getJarFilePath());
} catch(Exception e) {
LOG.error(e);
Assert.fail("Job execution failed!");
}
// post-submit
postSubmit();
}
/**
* Returns the FilesystemProvider of the cluster setup
*
* @see eu.stratosphere.pact.test.util.filesystem.FilesystemProvider
*
* @return The FilesystemProvider of the cluster setup
*/
public FilesystemProvider getFilesystemProvider() {
return cluster.getFilesystemProvider();
}
/**
* Helper method to ease the pain to construct valid JUnit test parameter
* lists
*
* @param tConfigs
* list of PACT test configurations
* @return list of JUnit test configurations
* @throws IOException
* @throws FileNotFoundException
*/
protected static Collection<Object[]> toParameterList(Class<? extends TestBase> parent,
List<Configuration> testConfigs) throws FileNotFoundException, IOException {
String testClassName = parent.getName();
File configDir = new File(Constants.TEST_CONFIGS);
List<String> clusterConfigs = new ArrayList<String>();
if (configDir.isDirectory()) {
for (File configFile : configDir.listFiles()) {
Properties p = new Properties();
p.load(new FileInputStream(configFile));
for (String key : p.stringPropertyNames()) {
if (key.endsWith(testClassName)) {
for (String config : p.getProperty(key).split(",")) {
clusterConfigs.add(config);
}
}
}
}
}
if (clusterConfigs.isEmpty()) {
LOG.warn("No test config defined for test-class '" + testClassName + "'. Using default config: '"+Constants.DEFAULT_TEST_CONFIG+"'.");
clusterConfigs.add(Constants.DEFAULT_TEST_CONFIG);
}
LinkedList<Object[]> configs = new LinkedList<Object[]>();
for (String clusterConfig : clusterConfigs) {
for (Configuration testConfig : testConfigs) {
Object[] c = { clusterConfig, testConfig };
configs.add(c);
}
}
return configs;
}
protected static Collection<Object[]> toParameterList(List<Configuration> testConfigs) {
LinkedList<Object[]> configs = new LinkedList<Object[]>();
for (Configuration testConfig : testConfigs) {
Object[] c = { testConfig };
configs.add(c);
}
return configs;
}
/**
* Compares the expectedResultString and the file(s) in the HDFS linewise.
* Both results (expected and computed) are held in memory. Hence, this
* method should not be used to compare large results.
*
* @param expectedResult
* @param hdfsPath
*/
protected void compareResultsByLinesInMemory(String expectedResultStr, String resultPath) throws Exception {
Comparator<String> defaultStrComp = new Comparator<String>() {
@Override
public int compare(String arg0, String arg1) {
return arg0.compareTo(arg1);
}
};
this.compareResultsByLinesInMemory(expectedResultStr, resultPath, defaultStrComp);
}
/**
* Compares the expectedResultString and the file(s) in the HDFS linewise.
* Both results (expected and computed) are held in memory. Hence, this
* method should not be used to compare large results.
*
* The line comparator is used to compare lines from the expected and result set.
*
* @param expectedResult
* @param hdfsPath
* @param comp Line comparator
*/
protected void compareResultsByLinesInMemory(String expectedResultStr, String resultPath, Comparator<String> comp) throws Exception {
ArrayList<String> resultFiles = new ArrayList<String>();
// Determine all result files
if (getFilesystemProvider().isDir(resultPath)) {
for (String file : getFilesystemProvider().listFiles(resultPath)) {
if (!getFilesystemProvider().isDir(file)) {
resultFiles.add(resultPath+"/"+file);
}
}
} else {
resultFiles.add(resultPath);
}
// collect lines of all result files
PriorityQueue<String> computedResult = new PriorityQueue<String>();
for (String resultFile : resultFiles) {
// read each result file
InputStream is = getFilesystemProvider().getInputStream(resultFile);
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line = reader.readLine();
// collect lines
while (line != null) {
computedResult.add(line);
line = reader.readLine();
}
reader.close();
}
PriorityQueue<String> expectedResult = new PriorityQueue<String>();
StringTokenizer st = new StringTokenizer(expectedResultStr, "\n");
while (st.hasMoreElements()) {
expectedResult.add(st.nextToken());
}
// log expected and computed results
if (LOG.isDebugEnabled()) {
- LOG.info("Expected: " + expectedResult);
- LOG.info("Computed: " + computedResult);
+ LOG.debug("Expected: " + expectedResult);
+ LOG.debug("Computed: " + computedResult);
}
Assert.assertEquals("Computed and expected results have different size", expectedResult.size(), computedResult.size());
while (!expectedResult.isEmpty()) {
String expectedLine = expectedResult.poll();
String computedLine = computedResult.poll();
if (LOG.isDebugEnabled())
- LOG.info("expLine: <" + expectedLine + ">\t\t: compLine: <" + computedLine + ">");
+ LOG.debug("expLine: <" + expectedLine + ">\t\t: compLine: <" + computedLine + ">");
- Assert.assertTrue("Computed and expected lines differ", comp.compare(expectedLine, computedLine) != 0);
+ Assert.assertEquals("Computed and expected lines differ", expectedLine, computedLine);
}
}
/**
* Returns the job which that has to be executed.
*
* @return
* @throws Exception
*/
abstract protected JobGraph getJobGraph() throws Exception;
/**
* Performs general-purpose pre-job submit logic, i.e. load job input into
* hdfs.
*
* @return
* @throws Exception
*/
abstract protected void preSubmit() throws Exception;
/**
* Performs general-purpose post-job submit logic, i.e. check
*
* @return
* @throws Exception
*/
abstract protected void postSubmit() throws Exception;
/**
* Returns the path to a JAR-file that contains all classes necessary to run
* the test This is only important if distributed tests are run!
*
* @return Path to a JAR-file that contains all classes that are necessary
* to run the test
*/
protected String getJarFilePath() {
return null;
}
}
| false | false | null | null |
diff --git a/robocode/robocode/packager/RobotPackager.java b/robocode/robocode/packager/RobotPackager.java
index 749e8e938..e8aadea7b 100644
--- a/robocode/robocode/packager/RobotPackager.java
+++ b/robocode/robocode/packager/RobotPackager.java
@@ -1,590 +1,590 @@
/*******************************************************************************
* Copyright (c) 2001-2006 Mathew A. Nelson and Robocode contributors
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.robocode.net/license/CPLv1.0.html
*
* Contributors:
* Mathew A. Nelson
* - Initial API and implementation
* Matthew Reeder
* - Minor changes for UI keyboard accessibility
* Flemming N. Larsen
* - Renamed 'enum' variables to allow compiling with Java 1.5
* - Replaced FileSpecificationVector with plain Vector
* - Code cleanup
*******************************************************************************/
package robocode.packager;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.util.jar.*;
import java.io.*;
import java.net.*;
import robocode.peer.robot.RobotClassManager;
import robocode.repository.*;
import robocode.dialog.*;
import robocode.util.NoDuplicateJarOutputStream;
import robocode.manager.*;
import robocode.util.Utils;
/**
* @author Mathew A. Nelson (original)
* @author Matthew Reeder, Flemming N. Larsen (current)
*/
@SuppressWarnings("serial")
public class RobotPackager extends JDialog implements WizardListener {
private int minRobots = 1;
private int maxRobots = 1; // 250;
private JPanel robotPackagerContentPane;
private WizardCardPanel wizardPanel;
private WizardController buttonsPanel;
private FilenamePanel filenamePanel;
private ConfirmPanel confirmPanel;
private RobotSelectionPanel robotSelectionPanel;
private PackagerOptionsPanel packagerOptionsPanel;
public byte buf[] = new byte[4096];
private StringWriter output;
private RobotRepositoryManager robotManager;
private EventHandler eventHandler = new EventHandler();
private class EventHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("Refresh")) {
getRobotSelectionPanel().refreshRobotList();
}
}
}
/**
* Packager constructor comment.
*/
public RobotPackager(RobotRepositoryManager robotManager, boolean isTeamPackager) {
super(robotManager.getManager().getWindowManager().getRobocodeFrame());
this.robotManager = robotManager;
initialize();
}
public void cancelButtonActionPerformed() {
AWTEvent evt = new WindowEvent(this, WindowEvent.WINDOW_CLOSING);
this.dispatchEvent(evt);
}
public void copy(FileInputStream in, NoDuplicateJarOutputStream out) throws IOException {
while (in.available() > 0) {
int count = in.read(buf, 0, 4096);
out.write(buf, 0, count);
}
}
public void finishButtonActionPerformed() {
String resultsString;
int rc = packageRobots();
ConsoleDialog d;
d = new ConsoleDialog(robotManager.getManager().getWindowManager().getRobocodeFrame(), "Packaging results",
false);
if (rc == 0) {
resultsString = "Robots Packaged Successfully.\n" + output.toString();
} else if (rc == 4) {
resultsString = "Robots Packaged, but with warnings.\n" + output.toString();
} else if (rc == 8) {
resultsString = "Robots Packaging failed.\n" + output.toString();
} else {
resultsString = "FATAL: Unknown return code " + rc + " from packager.\n" + output.toString();
}
d.setText(resultsString);
d.pack();
d.pack();
Utils.packCenterShow(this, d);
if (rc < 8) {
this.dispose();
}
}
/**
* Return the buttonsPanel
*
* @return javax.swing.JButton
*/
private WizardController getButtonsPanel() {
if (buttonsPanel == null) {
buttonsPanel = getWizardPanel().getWizardController();
}
return buttonsPanel;
}
- public Enumeration getClasses(RobotClassManager robotClassManager) throws ClassNotFoundException {
+ public Enumeration<String> getClasses(RobotClassManager robotClassManager) throws ClassNotFoundException {
robotClassManager.getRobotClassLoader().loadRobotClass(robotClassManager.getFullClassName(), true);
return robotClassManager.getReferencedClasses();
}
/**
* Return the buttonsPanel
*
* @return javax.swing.JButton
*/
private ConfirmPanel getConfirmPanel() {
if (confirmPanel == null) {
confirmPanel = new ConfirmPanel(this);
}
return confirmPanel;
}
/**
* Return the optionsPanel
*
* @return robocode.packager.PackagerOptionsPanel
*/
protected FilenamePanel getFilenamePanel() {
if (filenamePanel == null) {
filenamePanel = new FilenamePanel(this);
}
return filenamePanel;
}
/**
* Return the optionsPanel
*
* @return robocode.packager.PackagerOptionsPanel
*/
protected PackagerOptionsPanel getPackagerOptionsPanel() {
if (packagerOptionsPanel == null) {
packagerOptionsPanel = new PackagerOptionsPanel(this);
}
return packagerOptionsPanel;
}
/**
* Return the newBattleDialogContentPane
*
* @return javax.swing.JPanel
*/
private javax.swing.JPanel getRobotPackagerContentPane() {
if (robotPackagerContentPane == null) {
robotPackagerContentPane = new javax.swing.JPanel();
robotPackagerContentPane.setLayout(new BorderLayout());
robotPackagerContentPane.add(getButtonsPanel(), BorderLayout.SOUTH);
robotPackagerContentPane.add(getWizardPanel(), BorderLayout.CENTER);
getWizardPanel().getWizardController().setFinishButtonTextAndMnemonic("Package!", 'P', 0);
robotPackagerContentPane.registerKeyboardAction(eventHandler, "Refresh",
KeyStroke.getKeyStroke(KeyEvent.VK_F5, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
robotPackagerContentPane.registerKeyboardAction(eventHandler, "Refresh",
KeyStroke.getKeyStroke(KeyEvent.VK_F5, 0), JComponent.WHEN_FOCUSED);
}
return robotPackagerContentPane;
}
/**
* Return the Page property value.
*
* @return javax.swing.JPanel
*/
public RobotSelectionPanel getRobotSelectionPanel() {
if (robotSelectionPanel == null) {
robotSelectionPanel = new RobotSelectionPanel(robotManager, minRobots, maxRobots, false,
"Select the robot or team you would like to package.", /* true */false, false, false/* true */, true,
false, true, null);
}
return robotSelectionPanel;
}
/**
* Return the tabbedPane.
*
* @return javax.swing.JTabbedPane
*/
private WizardCardPanel getWizardPanel() {
if (wizardPanel == null) {
wizardPanel = new WizardCardPanel(this);
wizardPanel.add(getRobotSelectionPanel(), "Select robot");
wizardPanel.add(getPackagerOptionsPanel(), "Select options");
wizardPanel.add(getFilenamePanel(), "Select filename");
wizardPanel.add(getConfirmPanel(), "Confirm");
}
return wizardPanel;
}
private void initialize() {
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("Robot Packager");
setContentPane(getRobotPackagerContentPane());
}
private int packageRobots() {
robotManager.clearRobotList();
int rv = 0;
output = new StringWriter();
PrintWriter out = new PrintWriter(output);
out.println("Robot Packager");
Vector<FileSpecification> robotSpecificationsVector = robotManager.getRobotRepository().getRobotSpecificationsVector(
false, false, false, false, false, false);
String jarFilename = getFilenamePanel().getFilenameField().getText();
File f = new File(jarFilename);
if (f.exists()) {
int ok = JOptionPane.showConfirmDialog(this,
jarFilename + " already exists. Are you sure you want to replace it?", "Warning",
JOptionPane.YES_NO_CANCEL_OPTION);
if (ok == JOptionPane.NO_OPTION) {
out.println("Cancelled by user.");
return -1;
}
if (ok == JOptionPane.CANCEL_OPTION) {
out.println("Cancelled by user.");
return -1;
}
out.println("Overwriting " + jarFilename);
}
Vector<FileSpecification> selectedRobots = getRobotSelectionPanel().getSelectedRobots();
// Create the jar file
Manifest manifest = new Manifest();
manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
String robots = "";
for (int i = 0; i < selectedRobots.size(); i++) {
robots += ((FileSpecification) selectedRobots.elementAt(i)).getFullClassName();
if (i < selectedRobots.size() - 1) {
robots += ",";
}
}
manifest.getMainAttributes().put(new Attributes.Name("robots"), robots);
NoDuplicateJarOutputStream jarout;
try {
out.println("Creating Jar file: " + f.getName());
jarout = new NoDuplicateJarOutputStream(new FileOutputStream(f));
jarout.setComment(robotManager.getManager().getVersionManager().getVersion() + " - Robocode version");
} catch (Exception e) {
out.println(e);
return 8;
}
for (int i = 0; i < selectedRobots.size(); i++) {
FileSpecification fileSpecification = (FileSpecification) selectedRobots.elementAt(i);
if (fileSpecification instanceof RobotSpecification) {
RobotSpecification robotSpecification = (RobotSpecification) fileSpecification;
if (robotSpecification.isDevelopmentVersion()) {
robotSpecification.setRobotDescription(getPackagerOptionsPanel().getDescriptionArea().getText());
robotSpecification.setRobotJavaSourceIncluded(
getPackagerOptionsPanel().getIncludeSource().isSelected());
robotSpecification.setRobotAuthorName(getPackagerOptionsPanel().getAuthorField().getText());
URL u = null;
String w = getPackagerOptionsPanel().getWebpageField().getText();
if (w.equals("")) {
u = null;
} else {
try {
u = new URL(w);
} catch (MalformedURLException e) {
try {
u = new URL("http://" + w);
getPackagerOptionsPanel().getWebpageField().setText(u.toString());
} catch (MalformedURLException e2) {
u = null;
}
}
}
robotSpecification.setRobotWebpage(u);
robotSpecification.setRobocodeVersion(robotManager.getManager().getVersionManager().getVersion());
try {
robotSpecification.store(new FileOutputStream(new File(robotSpecification.getThisFileName())),
"Robot Properties");
} catch (IOException e) {
rv = 4;
out.println("Unable to save properties: " + e);
out.println("Attempting to continue...");
}
// Create clone with version for jar
robotSpecification = (RobotSpecification) robotSpecification.clone();
robotSpecification.setRobotVersion(getPackagerOptionsPanel().getVersionField().getText());
addRobotSpecification(out, jarout, robotSpecification);
} else {
out.println("You Cannot package a packaged robot!");
}
} else if (fileSpecification instanceof TeamSpecification) {
TeamSpecification teamSpecification = (TeamSpecification) fileSpecification;
URL u = null;
String w = getPackagerOptionsPanel().getWebpageField().getText();
if (w.equals("")) {
u = null;
} else {
try {
u = new URL(w);
} catch (MalformedURLException e) {
try {
u = new URL("http://" + w);
getPackagerOptionsPanel().getWebpageField().setText(u.toString());
} catch (MalformedURLException e2) {
u = null;
}
}
}
teamSpecification.setTeamWebpage(u);
teamSpecification.setTeamDescription(getPackagerOptionsPanel().getDescriptionArea().getText());
teamSpecification.setTeamAuthorName(getPackagerOptionsPanel().getAuthorField().getText());
teamSpecification.setRobocodeVersion(robotManager.getManager().getVersionManager().getVersion());
try {
teamSpecification.store(new FileOutputStream(new File(teamSpecification.getThisFileName())),
"Team Properties");
} catch (IOException e) {
rv = 4;
out.println("Unable to save .team file: " + e);
out.println("Attempting to continue...");
}
teamSpecification = (TeamSpecification) teamSpecification.clone();
teamSpecification.setTeamVersion(getPackagerOptionsPanel().getVersionField().getText());
StringTokenizer teamTokenizer;
String bot;
FileSpecification currentFileSpecification;
teamTokenizer = new StringTokenizer(teamSpecification.getMembers(), ",");
String newMembers = "";
while (teamTokenizer.hasMoreTokens()) {
if (!(newMembers.equals(""))) {
newMembers += ",";
}
bot = teamTokenizer.nextToken();
for (int j = 0; j < robotSpecificationsVector.size(); j++) {
currentFileSpecification = (FileSpecification) robotSpecificationsVector.elementAt(j);
// Teams cannot include teams
if (currentFileSpecification instanceof TeamSpecification) {
continue;
}
if (currentFileSpecification.getNameManager().getUniqueFullClassNameWithVersion().equals(bot)) {
// Found team member
RobotSpecification current = (RobotSpecification) currentFileSpecification;
// Skip nonversioned packaged
if (!current.isDevelopmentVersion()
&& (current.getVersion() == null || current.getVersion().equals(""))) {
continue;
}
if (current.isDevelopmentVersion()
&& (current.getVersion() == null || current.getVersion().equals(""))) {
current = (RobotSpecification) current.clone();
current.setRobotVersion(
"[" + getPackagerOptionsPanel().getVersionField().getText() + "]");
}
// Package this member
newMembers += addRobotSpecification(out, jarout, current);
break;
}
}
}
teamSpecification.setMembers(newMembers);
try {
try {
JarEntry entry = new JarEntry(teamSpecification.getFullClassName().replace('.', '/') + ".team");
jarout.putNextEntry(entry);
teamSpecification.store(jarout, "Robocode Robot Team");
jarout.closeEntry();
out.println("Added: " + entry);
} catch (java.util.zip.ZipException e) {
if (e.getMessage().indexOf("duplicate entry") < 0) {
throw e;
}
// ignore duplicate entry, fine, it's already there.
}
} catch (Throwable e) {
rv = 8;
out.println(e);
}
}
}
try {
jarout.close();
} catch (IOException e) {
out.println(e);
return 8;
}
robotManager.clearRobotList();
out.println("Packaging complete.");
return rv;
}
public String addRobotSpecification(PrintWriter out, NoDuplicateJarOutputStream jarout,
RobotSpecification robotSpecification) {
int rv = 0;
if (!robotSpecification.isDevelopmentVersion()) {
try {
File inputJar = robotSpecification.getJarFile();
try {
JarEntry entry = new JarEntry(inputJar.getName());
jarout.putNextEntry(entry);
FileInputStream input = new FileInputStream(inputJar);
copy(input, jarout);
jarout.closeEntry();
out.println("Added: " + entry);
} catch (java.util.zip.ZipException e) {
if (e.getMessage().indexOf("duplicate entry") < 0) {
throw e;
}
// ignore duplicate entry, fine, it's already there.
}
} catch (Throwable e) {
rv = 8;
Utils.log(e);
out.println(e);
}
} else {
addToJar(out, jarout, robotSpecification);
}
String name = robotSpecification.getName() + " " + robotSpecification.getVersion();
if (rv != 0) {
return null;
}
return name;
}
public int addToJar(PrintWriter out, NoDuplicateJarOutputStream jarout, RobotSpecification robotSpecification) {
int rv = 0;
RobotClassManager classManager = new RobotClassManager((RobotSpecification) robotSpecification);
try {
- Enumeration classes = getClasses(classManager);
+ Enumeration<String> classes = getClasses(classManager);
String rootDirectory = classManager.getRobotClassLoader().getRootDirectory();
// Save props:
try {
JarEntry entry = new JarEntry(classManager.getFullClassName().replace('.', '/') + ".properties");
jarout.putNextEntry(entry);
robotSpecification.store(jarout, "Robot Properties");
jarout.closeEntry();
out.println("Added: " + entry);
} catch (java.util.zip.ZipException e) {
if (e.getMessage().indexOf("duplicate entry") < 0) {
throw e;
}
// ignore duplicate entry, fine, it's already there.
}
File html = new File(rootDirectory, classManager.getFullClassName().replace('.', '/') + ".html");
if (html.exists()) {
try {
JarEntry entry = new JarEntry(classManager.getFullClassName().replace('.', '/') + ".html");
jarout.putNextEntry(entry);
FileInputStream input = new FileInputStream(html);
copy(input, jarout);
jarout.closeEntry();
out.println("Added: " + entry);
} catch (java.util.zip.ZipException e) {
if (e.getMessage().indexOf("duplicate entry") < 0) {
throw e;
}
// ignore duplicate entry, fine, it's already there.
}
}
while (classes.hasMoreElements()) {
String className = (String) classes.nextElement();
// Add source file if selected (not inner classes of course)
if (getPackagerOptionsPanel().getIncludeSource().isSelected()) {
if (className.indexOf("$") < 0) {
File javaFile = new File(rootDirectory, className.replace('.', File.separatorChar) + ".java");
if (javaFile.exists()) {
try {
JarEntry entry = new JarEntry(className.replace('.', '/') + ".java");
jarout.putNextEntry(entry);
FileInputStream input = new FileInputStream(javaFile);
copy(input, jarout);
jarout.closeEntry();
out.println("Added: " + entry);
} catch (java.util.zip.ZipException e) {
if (e.getMessage().indexOf("duplicate entry") < 0) {
throw e;
}
// ignore duplicate entry, fine, it's already there.
}
} else {
out.println(className.replace('.', '/') + ".java does not exist.");
}
}
}
// Add class file
try {
JarEntry entry = new JarEntry(className.replace('.', '/') + ".class");
jarout.putNextEntry(entry);
FileInputStream input = new FileInputStream(
new File(rootDirectory, className.replace('.', File.separatorChar) + ".class"));
copy(input, jarout);
jarout.closeEntry();
out.println("Added: " + entry);
} catch (java.util.zip.ZipException e) {
if (e.getMessage().indexOf("duplicate entry") < 0) {
throw e;
}
// ignore duplicate entry, fine, it's already there.
}
}
File dataDirectory = new File(rootDirectory, classManager.getFullClassName().replace('.', '/') + ".data");
if (dataDirectory.exists()) {
File files[] = dataDirectory.listFiles();
for (int j = 0; j < files.length; j++) {
try {
JarEntry entry = new JarEntry(
classManager.getFullClassName().replace('.', '/') + ".data/" + files[j].getName());
jarout.putNextEntry(entry);
FileInputStream input = new FileInputStream(files[j]);
copy(input, jarout);
jarout.closeEntry();
out.println("Added: " + entry);
} catch (java.util.zip.ZipException e) {
if (e.getMessage().indexOf("duplicate entry") < 0) {
throw e;
}
// ignore duplicate entry, fine, it's already there.
}
}
}
} catch (Throwable e) {
rv = 8;
out.println(e);
}
return rv;
}
}
| false | false | null | null |
diff --git a/api/src/main/java/org/openmrs/module/appointmentscheduling/api/impl/AppointmentServiceImpl.java b/api/src/main/java/org/openmrs/module/appointmentscheduling/api/impl/AppointmentServiceImpl.java
index 8085b2c..369c403 100644
--- a/api/src/main/java/org/openmrs/module/appointmentscheduling/api/impl/AppointmentServiceImpl.java
+++ b/api/src/main/java/org/openmrs/module/appointmentscheduling/api/impl/AppointmentServiceImpl.java
@@ -1,833 +1,835 @@
/**
* The contents of this file are subject to the OpenMRS Public License
* Version 1.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://license.openmrs.org
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations
* under the License.
*
* Copyright (C) OpenMRS, LLC. All Rights Reserved.
*/
package org.openmrs.module.appointmentscheduling.api.impl;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.openmrs.module.appointmentscheduling.StudentT;
import org.apache.commons.chain.web.MapEntry;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openmrs.Location;
import org.openmrs.Patient;
import org.openmrs.PatientIdentifier;
import org.openmrs.Provider;
import org.openmrs.Visit;
import org.openmrs.api.APIException;
import org.openmrs.api.context.Context;
import org.openmrs.api.impl.BaseOpenmrsService;
import org.openmrs.module.appointmentscheduling.Appointment;
import org.openmrs.module.appointmentscheduling.Appointment.AppointmentStatus;
import org.openmrs.module.appointmentscheduling.AppointmentBlock;
import org.openmrs.module.appointmentscheduling.AppointmentStatusHistory;
import org.openmrs.module.appointmentscheduling.AppointmentType;
import org.openmrs.module.appointmentscheduling.TimeSlot;
import org.openmrs.module.appointmentscheduling.api.AppointmentService;
import org.openmrs.module.appointmentscheduling.api.db.AppointmentBlockDAO;
import org.openmrs.module.appointmentscheduling.api.db.AppointmentDAO;
import org.openmrs.module.appointmentscheduling.api.db.AppointmentStatusHistoryDAO;
import org.openmrs.module.appointmentscheduling.api.db.AppointmentTypeDAO;
import org.openmrs.module.appointmentscheduling.api.db.TimeSlotDAO;
import org.openmrs.validator.ValidateUtil;
import org.springframework.transaction.annotation.Transactional;
/**
* It is a default implementation of {@link AppointmentService}.
*/
public class AppointmentServiceImpl extends BaseOpenmrsService implements AppointmentService {
protected final Log log = LogFactory.getLog(this.getClass());
private AppointmentTypeDAO appointmentTypeDAO;
private AppointmentBlockDAO appointmentBlockDAO;
private AppointmentDAO appointmentDAO;
private TimeSlotDAO timeSlotDAO;
private AppointmentStatusHistoryDAO appointmentStatusHistoryDAO;
/**
* @param dao the appointment type dao to set
*/
public void setAppointmentTypeDAO(AppointmentTypeDAO appointmentTypeDAO) {
this.appointmentTypeDAO = appointmentTypeDAO;
}
/**
* @return the appointment type dao
*/
public AppointmentTypeDAO getAppointmentTypeDAO() {
return appointmentTypeDAO;
}
/**
* @see org.openmrs.module.appointmentscheduling.api.AppointmentService#getAllAppointmentTypes()
*/
@Transactional(readOnly = true)
public Set<AppointmentType> getAllAppointmentTypes() {
HashSet set = new HashSet();
set.addAll(getAppointmentTypeDAO().getAll());
return set;
}
/**
* @see org.openmrs.module.appointmentscheduling.api.AppointmentService#getAllAppointmentTypes(boolean)
*/
@Override
@Transactional(readOnly = true)
public List<AppointmentType> getAllAppointmentTypes(boolean includeRetired) {
return getAppointmentTypeDAO().getAll(includeRetired);
}
/**
* @see org.openmrs.module.appointmentscheduling.api.AppointmentService#getAppointmentType(java.lang.Integer)
*/
@Transactional(readOnly = true)
public AppointmentType getAppointmentType(Integer appointmentTypeId) {
return (AppointmentType) getAppointmentTypeDAO().getById(appointmentTypeId);
}
/**
* @see org.openmrs.module.appointmentscheduling.api.AppointmentService#getAppointmentTypeByUuid(java.lang.String)
*/
@Transactional(readOnly = true)
public AppointmentType getAppointmentTypeByUuid(String uuid) {
return (AppointmentType) getAppointmentTypeDAO().getByUuid(uuid);
}
/**
* @see org.openmrs.module.appointmentscheduling.api.AppointmentService#getAppointmentTypes(java.lang.String)
*/
@Transactional(readOnly = true)
public List<AppointmentType> getAppointmentTypes(String fuzzySearchPhrase) {
return getAppointmentTypeDAO().getAll(fuzzySearchPhrase);
}
/**
* @see org.openmrs.module.appointmentscheduling.api.AppointmentService#saveAppointmentType(org.openmrs.AppointmentType)
*/
public AppointmentType saveAppointmentType(AppointmentType appointmentType) throws APIException {
ValidateUtil.validate(appointmentType);
return (AppointmentType) getAppointmentTypeDAO().saveOrUpdate(appointmentType);
}
/**
* @see org.openmrs.module.appointmentscheduling.api.AppointmentService#retireAppointmentType(org.openmrs.AppointmentType,
* java.lang.String)
*/
public AppointmentType retireAppointmentType(AppointmentType appointmentType, String reason) {
return saveAppointmentType(appointmentType);
}
/**
* @see org.openmrs.module.appointmentscheduling.api.AppointmentService#unretireAppointmentType(org.openmrs.AppointmentType)
*/
public AppointmentType unretireAppointmentType(AppointmentType appointmentType) {
return saveAppointmentType(appointmentType);
}
/**
* @see org.openmrs.module.appointmentscheduling.api.AppointmentService#purgeAppointmentType(org.openmrs.AppointmentType)
*/
public void purgeAppointmentType(AppointmentType appointmentType) {
getAppointmentTypeDAO().delete(appointmentType);
}
//Appointment Block
/**
* @param dao the appointment block dao to set
*/
public void setAppointmentBlockDAO(AppointmentBlockDAO appointmentBlockDAO) {
this.appointmentBlockDAO = appointmentBlockDAO;
}
/**
* @return the appointment block dao
*/
public AppointmentBlockDAO getAppointmentBlockDAO() {
return appointmentBlockDAO;
}
/**
* @see org.openmrs.module.appointmentscheduling.api.AppointmentService#getAllAppointmentBlocks()
*/
@Transactional(readOnly = true)
public List<AppointmentBlock> getAllAppointmentBlocks() {
return getAppointmentBlockDAO().getAll();
}
/**
* @see org.openmrs.module.appointmentscheduling.api.AppointmentService#getAllAppointmentBlocks(boolean)
*/
@Override
@Transactional(readOnly = true)
public List<AppointmentBlock> getAllAppointmentBlocks(boolean includeVoided) {
return getAppointmentBlockDAO().getAllData(includeVoided);
}
/**
* @see org.openmrs.module.appointmentscheduling.api.AppointmentService#getAppointmentBlock(java.lang.Integer)
*/
@Transactional(readOnly = true)
public AppointmentBlock getAppointmentBlock(Integer appointmentBlockId) {
return (AppointmentBlock) getAppointmentBlockDAO().getById(appointmentBlockId);
}
/**
* @see org.openmrs.module.appointmentscheduling.api.AppointmentService#getAppointmentBlockByUuid(java.lang.String)
*/
@Transactional(readOnly = true)
public AppointmentBlock getAppointmentBlockByUuid(String uuid) {
return (AppointmentBlock) getAppointmentBlockDAO().getByUuid(uuid);
}
/**
* @see org.openmrs.module.appointmentscheduling.api.AppointmentService#saveAppointmentBlock(org.openmrs.AppointmentBlock)
*/
public AppointmentBlock saveAppointmentBlock(AppointmentBlock appointmentBlock) throws APIException {
ValidateUtil.validate(appointmentBlock);
return (AppointmentBlock) getAppointmentBlockDAO().saveOrUpdate(appointmentBlock);
}
/**
* @see org.openmrs.module.appointmentscheduling.api.AppointmentService#voidAppointmentBlock(org.openmrs.AppointmentBlock,
* java.lang.String)
*/
public AppointmentBlock voidAppointmentBlock(AppointmentBlock appointmentBlock, String reason) {
return saveAppointmentBlock(appointmentBlock);
}
/**
* @see org.openmrs.module.appointmentscheduling.api.AppointmentService#unvoidAppointmentBlock(org.openmrs.AppointmentBlock)
*/
public AppointmentBlock unvoidAppointmentBlock(AppointmentBlock appointmentBlock) {
return saveAppointmentBlock(appointmentBlock);
}
/**
* @see org.openmrs.module.appointmentscheduling.api.AppointmentService#purgeAppointmentBlock(org.openmrs.AppointmentBlock)
*/
public void purgeAppointmentBlock(AppointmentBlock appointmentBlock) {
getAppointmentBlockDAO().delete(appointmentBlock);
}
public void setAppointmentDAO(AppointmentDAO appointmentDAO) {
this.appointmentDAO = appointmentDAO;
}
/**
* @see org.openmrs.module.appointmentscheduling.api.AppointmentService#getAppointmentBlocks(java.util.Date,java.util.Date,java.util.String,org.openmrs.Provider,org.openmrs.AppointmentType)
* )
*/
@Transactional(readOnly = true)
public List<AppointmentBlock> getAppointmentBlocks(Date fromDate, Date toDate, String locations, Provider provider,
- AppointmentType appointmentType) {
+ AppointmentType appointmentType) {
return getAppointmentBlockDAO().getAppointmentBlocks(fromDate, toDate, locations, provider, appointmentType);
}
/**
* @see org.openmrs.module.appointmentscheduling.api.AppointmentService#getOverlappingAppointmentBlocks(org.openmrs.AppointmentBlock)
* )
*/
@Transactional(readOnly = true)
public List<AppointmentBlock> getOverlappingAppointmentBlocks(AppointmentBlock appointmentBlock) {
return getAppointmentBlockDAO().getOverlappingAppointmentBlocks(appointmentBlock);
}
//Appointment
/**
* @return the appointment dao
*/
public AppointmentDAO getAppointmentDAO() {
return appointmentDAO;
}
@Override
@Transactional(readOnly = true)
public List<Appointment> getAllAppointments() {
return getAppointmentDAO().getAll();
}
@Override
@Transactional(readOnly = true)
public List<Appointment> getAllAppointments(boolean includeVoided) {
return getAppointmentDAO().getAllData(includeVoided);
}
@Override
@Transactional(readOnly = true)
public Appointment getAppointment(Integer appointmentId) {
return (Appointment) getAppointmentDAO().getById(appointmentId);
}
@Override
@Transactional(readOnly = true)
public Appointment getAppointmentByUuid(String uuid) {
return (Appointment) getAppointmentDAO().getByUuid(uuid);
}
@Override
public Appointment saveAppointment(Appointment appointment) throws APIException {
ValidateUtil.validate(appointment);
return (Appointment) getAppointmentDAO().saveOrUpdate(appointment);
}
@Override
public Appointment voidAppointment(Appointment appointment, String reason) {
return saveAppointment(appointment);
}
@Override
public Appointment unvoidAppointment(Appointment appointment) {
return saveAppointment(appointment);
}
@Override
public void purgeAppointment(Appointment appointment) {
getAppointmentDAO().delete(appointment);
}
@Override
@Transactional(readOnly = true)
public List<Appointment> getAppointmentsOfPatient(Patient patient) {
return getAppointmentDAO().getAppointmentsByPatient(patient);
}
@Override
@Transactional(readOnly = true)
public Appointment getAppointmentByVisit(Visit visit) {
return getAppointmentDAO().getAppointmentByVisit(visit);
}
//TimeSlot
/**
* @param dao the time slot dao to set
*/
public void setTimeSlotDAO(TimeSlotDAO timeSlotDAO) {
this.timeSlotDAO = timeSlotDAO;
}
/**
* @return the time slot dao
*/
public TimeSlotDAO getTimeSlotDAO() {
return timeSlotDAO;
}
@Override
public TimeSlot saveTimeSlot(TimeSlot timeSlot) throws APIException {
ValidateUtil.validate(timeSlot);
return (TimeSlot) getTimeSlotDAO().saveOrUpdate(timeSlot);
}
@Override
@Transactional(readOnly = true)
public List<TimeSlot> getAllTimeSlots() {
return getTimeSlotDAO().getAll();
}
@Override
@Transactional(readOnly = true)
public List<TimeSlot> getAllTimeSlots(boolean includeVoided) {
return getTimeSlotDAO().getAllData(includeVoided);
}
@Override
@Transactional(readOnly = true)
public TimeSlot getTimeSlot(Integer timeSlotId) {
return (TimeSlot) getTimeSlotDAO().getById(timeSlotId);
}
@Override
@Transactional(readOnly = true)
public TimeSlot getTimeSlotByUuid(String uuid) {
return (TimeSlot) getTimeSlotDAO().getByUuid(uuid);
}
@Override
public TimeSlot voidTimeSlot(TimeSlot timeSlot, String reason) {
return saveTimeSlot(timeSlot);
}
@Override
public TimeSlot unvoidTimeSlot(TimeSlot timeSlot) {
return saveTimeSlot(timeSlot);
}
@Override
public void purgeTimeSlot(TimeSlot timeSlot) {
getTimeSlotDAO().delete(timeSlot);
}
@Override
public List<Appointment> getAppointmentsInTimeSlot(TimeSlot timeSlot) {
return getTimeSlotDAO().getAppointmentsInTimeSlot(timeSlot);
}
@Override
@Transactional(readOnly = true)
public List<TimeSlot> getTimeSlotsInAppointmentBlock(AppointmentBlock appointmentBlock) {
return getTimeSlotDAO().getTimeSlotsByAppointmentBlock(appointmentBlock);
}
//AppointmentStatusHistory
/**
* @param dao the appointment status history dao to set
*/
public void setAppointmentStatusHistoryDAO(AppointmentStatusHistoryDAO appointmentStatusHistoryDAO) {
this.appointmentStatusHistoryDAO = appointmentStatusHistoryDAO;
}
/**
* @return the appointment status dao
*/
public AppointmentStatusHistoryDAO getAppointmentStatusHistoryDAO() {
return appointmentStatusHistoryDAO;
}
/**
* @see org.openmrs.module.appointmentscheduling.api.AppointmentService#getAllAppointmentStatusHistories()
*/
@Transactional(readOnly = true)
public List<AppointmentStatusHistory> getAllAppointmentStatusHistories() {
return getAppointmentStatusHistoryDAO().getAll();
}
/**
* @see org.openmrs.module.appointmentscheduling.api.AppointmentService#getAppointmentStatusHistory(java.lang.Integer)
*/
@Transactional(readOnly = true)
public AppointmentStatusHistory getAppointmentStatusHistory(Integer appointmentStatusHistoryId) {
return (AppointmentStatusHistory) getAppointmentStatusHistoryDAO().getById(appointmentStatusHistoryId);
}
/**
* @see org.openmrs.module.appointmentscheduling.api.AppointmentService#getAppointmentStatusHistories(java.lang.String)
*/
@Transactional(readOnly = true)
public List<AppointmentStatusHistory> getAppointmentStatusHistories(AppointmentStatus status) {
return getAppointmentStatusHistoryDAO().getAll(status);
}
/**
* @see org.openmrs.module.appointmentscheduling.api.AppointmentService#saveAppointmentStatusHistory(org.openmrs.AppointmentStatusHistory)
*/
public AppointmentStatusHistory saveAppointmentStatusHistory(AppointmentStatusHistory appointmentStatusHistory)
- throws APIException {
+ throws APIException {
ValidateUtil.validate(appointmentStatusHistory);
return (AppointmentStatusHistory) getAppointmentStatusHistoryDAO().saveOrUpdate(appointmentStatusHistory);
}
@Override
@Transactional(readOnly = true)
public Appointment getLastAppointment(Patient patient) {
return getAppointmentDAO().getLastAppointment(patient);
}
@Override
@Transactional(readOnly = true)
public List<TimeSlot> getTimeSlotsByConstraints(AppointmentType appointmentType, Date fromDate, Date toDate,
- Provider provider, Location location) throws APIException {
+ Provider provider, Location location) throws APIException {
List<TimeSlot> suitableTimeSlots = getTimeSlotsByConstraintsIncludingFull(appointmentType, fromDate, toDate,
provider, location);
List<TimeSlot> availableTimeSlots = new LinkedList<TimeSlot>();
Integer duration = appointmentType.getDuration();
for (TimeSlot slot : suitableTimeSlots) {
//Filter by time left
if (getTimeLeftInTimeSlot(slot) >= duration)
availableTimeSlots.add(slot);
}
return availableTimeSlots;
}
@Override
@Transactional(readOnly = true)
public List<TimeSlot> getTimeSlotsByConstraintsIncludingFull(AppointmentType appointmentType, Date fromDate,
- Date toDate, Provider provider, Location location)
- throws APIException {
+ Date toDate, Provider provider, Location location) throws APIException {
List<TimeSlot> suitableTimeSlots = getTimeSlotDAO().getTimeSlotsByConstraints(appointmentType, fromDate, toDate,
provider);
List<TimeSlot> availableTimeSlots = new LinkedList<TimeSlot>();
// Used to update the session to the correct one
if (location != null)
location = Context.getLocationService().getLocation(location.getId());
Set<Location> relevantLocations = getAllLocationDescendants(location, null);
relevantLocations.add(location);
for (TimeSlot slot : suitableTimeSlots) {
//Filter by location
if (location != null) {
if (relevantLocations.contains(slot.getAppointmentBlock().getLocation()))
availableTimeSlots.add(slot);
} else
availableTimeSlots.add(slot);
}
return availableTimeSlots;
}
@Override
@Transactional(readOnly = true)
public List<String> getPatientIdentifiersRepresentation(Patient patient) {
LinkedList<String> identifiers = new LinkedList<String>();
if (patient == null)
return identifiers;
for (PatientIdentifier identifier : patient.getIdentifiers()) {
//Representation format: <identifier type name> : <identifier value>
//for example: "OpenMRS Identification Number: 7532AM-1"
String representation = identifier.getIdentifierType().getName() + ": " + identifier.getIdentifier();
//Put preferred identifier first.
if (identifier.getPreferred())
identifiers.add(0, representation);
//Insert to the end of the list
else
identifiers.add(identifiers.size(), representation);
}
return identifiers;
}
@Override
@Transactional(readOnly = true)
public Integer getTimeLeftInTimeSlot(TimeSlot timeSlot) {
Integer timeLeft = null;
if (timeSlot == null)
return timeLeft;
Date startDate = timeSlot.getStartDate();
Date endDate = timeSlot.getEndDate();
//Calculate total number of minutes in the time slot.
timeLeft = (int) ((endDate.getTime() / 60000) - (startDate.getTime() / 60000));
//Subtract from time left the amounts of minutes already scheduled
//Should not take into consideration cancelled or missed appointments
List<Appointment> appointments = getAppointmentsInTimeSlot(timeSlot);
for (Appointment appointment : appointments) {
if (!appointment.isVoided() && appointment.getStatus() != AppointmentStatus.CANCELLED
&& appointment.getStatus() != AppointmentStatus.MISSED)
timeLeft -= appointment.getAppointmentType().getDuration();
}
return timeLeft;
}
@Override
@Transactional(readOnly = true)
public Set<Location> getAllLocationDescendants(Location location, Set<Location> descendants) {
if (descendants == null)
descendants = new HashSet<Location>();
if (location != null) {
Set<Location> childLocations = location.getChildLocations();
for (Location childLocation : childLocations) {
descendants.add(childLocation);
getAllLocationDescendants(childLocation, descendants);
}
}
return descendants;
}
@Override
@Transactional(readOnly = true)
public List<Appointment> getAppointmentsByConstraints(Date fromDate, Date toDate, Location location, Provider provider,
- AppointmentType type, AppointmentStatus status)
- throws APIException {
+ AppointmentType type, AppointmentStatus status) throws APIException {
List<Appointment> appointments = appointmentDAO.getAppointmentsByConstraints(fromDate, toDate, provider, type,
status);
List<Appointment> appointmentsInLocation = new LinkedList<Appointment>();
// Used to update the session to the correct one
if (location != null)
location = Context.getLocationService().getLocation(location.getId());
Set<Location> relevantLocations = getAllLocationDescendants(location, null);
relevantLocations.add(location);
for (Appointment appointment : appointments) {
boolean satisfyingConstraints = true;
//Filter by location
if (location != null) {
if (relevantLocations.contains(appointment.getTimeSlot().getAppointmentBlock().getLocation()))
appointmentsInLocation.add(appointment);
} else
appointmentsInLocation.add(appointment);
}
return appointmentsInLocation;
}
@Override
@Transactional(readOnly = true)
public Date getAppointmentCurrentStatusStartDate(Appointment appointment) {
return appointmentStatusHistoryDAO.getStartDateOfCurrentStatus(appointment);
}
@Override
public void changeAppointmentStatus(Appointment appointment, AppointmentStatus newStatus) {
if (appointment != null) {
AppointmentStatusHistory history = new AppointmentStatusHistory();
history.setAppointment(appointment);
history.setEndDate(new Date());
history.setStartDate(getAppointmentCurrentStatusStartDate(appointment));
history.setStatus(appointment.getStatus());
saveAppointmentStatusHistory(history);
appointment.setStatus(newStatus);
saveAppointment(appointment);
}
}
@Override
@Transactional(readOnly = true)
public List<Provider> getAllProvidersSorted(boolean includeRetired) {
List<Provider> providers = Context.getProviderService().getAllProviders(includeRetired);
Collections.sort(providers, new Comparator<Provider>() {
public int compare(Provider pr1, Provider pr2) {
return pr1.getName().toLowerCase().compareTo(pr2.getName().toLowerCase());
}
});
return providers;
}
@Override
@Transactional(readOnly = true)
public List<AppointmentType> getAllAppointmentTypesSorted(boolean includeRetired) {
List<AppointmentType> appointmentTypes = Context.getService(AppointmentService.class).getAllAppointmentTypes(
includeRetired);
Collections.sort(appointmentTypes, new Comparator<AppointmentType>() {
public int compare(AppointmentType at1, AppointmentType at2) {
return at1.getName().toLowerCase().compareTo(at2.getName().toLowerCase());
}
});
return appointmentTypes;
}
@Override
@Transactional(readOnly = true)
public Map<AppointmentType, Double> getAverageHistoryDurationByConditions(Date fromDate, Date endDate,
- AppointmentStatus status) {
+ AppointmentStatus status) {
Map<AppointmentType, Double> averages = new HashMap<AppointmentType, Double>();
Map<AppointmentType, Integer> counters = new HashMap<AppointmentType, Integer>();
List<AppointmentStatusHistory> histories = appointmentStatusHistoryDAO.getHistoriesByInterval(fromDate, endDate,
status);
//Clean Not-Reasonable Durations
Map<AppointmentStatusHistory, Double> durations = new HashMap<AppointmentStatusHistory, Double>();
// 60 seconds * 1000 milliseconds in 1 minute
int minutesConversion = 60000;
+ int minutesInADay = 1440;
for (AppointmentStatusHistory history : histories) {
Date startDate = history.getStartDate();
Date toDate = history.getEndDate();
Double duration = (double) ((toDate.getTime() / minutesConversion) - (startDate.getTime() / minutesConversion));
- durations.put(history, duration);
+ //Not reasonable to be more than a day
+ if (duration < minutesInADay)
+ durations.put(history, duration);
}
Double[] data = new Double[durations.size()];
int i = 0;
for (Map.Entry<AppointmentStatusHistory, Double> entry : durations.entrySet()) {
//Added Math.sqrt in order to lower the mean and variance
data[i] = Math.sqrt(entry.getValue());
i++;
}
// Compute Intervals
double[] boundaries = confidenceInterval(data);
//
//sum up the durations by type
for (Map.Entry<AppointmentStatusHistory, Double> entry : durations.entrySet()) {
AppointmentType type = entry.getKey().getAppointment().getAppointmentType();
Double duration = entry.getValue();
//Added Math.sqrt in order to lower the mean and variance
if ((Math.sqrt(duration) <= boundaries[1])) {
if (averages.containsKey(type)) {
averages.put(type, averages.get(type) + duration);
counters.put(type, counters.get(type) + 1);
} else {
averages.put(type, duration);
counters.put(type, 1);
}
}
}
// Compute average
for (Map.Entry<AppointmentType, Integer> counter : counters.entrySet())
averages.put(counter.getKey(), averages.get(counter.getKey()) / counter.getValue());
return averages;
}
@Transactional(readOnly = true)
public Map<Provider, Double> getAverageHistoryDurationByConditionsPerProvider(Date fromDate, Date endDate,
- AppointmentStatus status) {
+ AppointmentStatus status) {
Map<Provider, Double> averages = new HashMap<Provider, Double>();
Map<Provider, Integer> counters = new HashMap<Provider, Integer>();
List<AppointmentStatusHistory> histories = appointmentStatusHistoryDAO.getHistoriesByInterval(fromDate, endDate,
status);
//Clean Not-Reasonable Durations
Map<AppointmentStatusHistory, Double> durations = new HashMap<AppointmentStatusHistory, Double>();
// 60 seconds * 1000 milliseconds in 1 minute
int minutesConversion = 60000;
+ int minutesInADay = 1440;
for (AppointmentStatusHistory history : histories) {
Date startDate = history.getStartDate();
Date toDate = history.getEndDate();
Double duration = (double) ((toDate.getTime() / minutesConversion) - (startDate.getTime() / minutesConversion));
-
- if (duration > 0)
+ //Not reasonable to be more than a day
+ if (duration > 0 && duration < minutesInADay)
durations.put(history, duration);
}
Double[] data = new Double[durations.size()];
int i = 0;
for (Map.Entry<AppointmentStatusHistory, Double> entry : durations.entrySet()) {
//Added Math.sqrt in order to lower the mean and variance
data[i] = Math.sqrt(entry.getValue());
i++;
}
// Compute Intervals
double[] boundaries = confidenceInterval(data);
//
//sum up the durations by type
for (Map.Entry<AppointmentStatusHistory, Double> entry : durations.entrySet()) {
Provider provider = entry.getKey().getAppointment().getTimeSlot().getAppointmentBlock().getProvider();
Double duration = entry.getValue();
//Added Math.sqrt in order to lower the mean and variance
if ((Math.sqrt(duration) <= boundaries[1])) {
if (averages.containsKey(provider)) {
averages.put(provider, averages.get(provider) + duration);
counters.put(provider, counters.get(provider) + 1);
} else {
averages.put(provider, duration);
counters.put(provider, 1);
}
}
}
// Compute average
for (Map.Entry<Provider, Integer> counter : counters.entrySet())
averages.put(counter.getKey(), averages.get(counter.getKey()) / counter.getValue());
return averages;
}
@Override
@Transactional(readOnly = true)
public Integer getHistoryCountByConditions(Date fromDate, Date endDate, AppointmentStatus status) {
List<AppointmentStatusHistory> histories = appointmentStatusHistoryDAO.getHistoriesByInterval(fromDate, endDate,
status);
return histories.size();
}
@Override
@Transactional(readOnly = true)
public Map<AppointmentType, Integer> getAppointmentTypeDistribution(Date fromDate, Date toDate) {
List<AppointmentType> unretiredTypes = Context.getService(AppointmentService.class).getAllAppointmentTypes(false);
Map<AppointmentType, Integer> distribution = new HashMap<AppointmentType, Integer>();
for (AppointmentType type : unretiredTypes) {
Integer countOfType = appointmentTypeDAO.getAppointmentTypeCount(fromDate, toDate, type);
if (countOfType > 0)
distribution.put(type, countOfType);
}
return distribution;
}
private double[] confidenceInterval(Double[] data) {
//Empty Dataset
if (data.length == 0)
return new double[] { 0.0, 0.0 };
//Initialization
double mean = 0;
int count = data.length;
int df = count - 1;
//If Dataset consists of only one item
if (df == 0)
return new double[] { Double.MIN_VALUE, Double.MAX_VALUE };
double alpha = 0.05;
double tStat = StudentT.tTable(df, alpha);
//Compute Mean
for (double val : data)
mean += val;
mean = mean / count;
//Compute Variance
double variance = 0;
for (double val : data)
variance += Math.pow((val - mean), 2);
variance = variance / df;
//If deviation is small - Suspected as "Clean of Noise"
if (Math.sqrt(variance) <= 1)
return new double[] { Double.MIN_VALUE, Double.MAX_VALUE };
//Compute Confidence Interval Bounds.
double[] boundaries = new double[2];
double factor = tStat * (Math.sqrt(variance) / Math.sqrt(count));
boundaries[0] = mean - factor;
boundaries[1] = mean + factor;
return boundaries;
}
}
| false | false | null | null |
diff --git a/src/main/java/org/apache/log4j/xml/DOMConfigurator.java b/src/main/java/org/apache/log4j/xml/DOMConfigurator.java
index 0683dc48..15b04661 100644
--- a/src/main/java/org/apache/log4j/xml/DOMConfigurator.java
+++ b/src/main/java/org/apache/log4j/xml/DOMConfigurator.java
@@ -1,1021 +1,1021 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.log4j.xml;
import org.apache.log4j.Appender;
import org.apache.log4j.Layout;
import org.apache.log4j.Level;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.log4j.config.PropertySetter;
import org.apache.log4j.helpers.FileWatchdog;
import org.apache.log4j.helpers.Loader;
import org.apache.log4j.helpers.LogLog;
import org.apache.log4j.helpers.OptionConverter;
import org.apache.log4j.or.RendererMap;
import org.apache.log4j.spi.AppenderAttachable;
import org.apache.log4j.spi.Configurator;
import org.apache.log4j.spi.ErrorHandler;
import org.apache.log4j.spi.Filter;
import org.apache.log4j.spi.LoggerFactory;
import org.apache.log4j.spi.LoggerRepository;
import org.apache.log4j.spi.OptionHandler;
import org.apache.log4j.spi.RendererSupport;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.FactoryConfigurationError;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.Hashtable;
import java.util.Properties;
// Contributors: Mark Womack
// Arun Katkere
/**
Use this class to initialize the log4j environment using a DOM tree.
<p>The DTD is specified in <a
href="log4j.dtd"><b>log4j.dtd</b></a>.
<p>Sometimes it is useful to see how log4j is reading configuration
files. You can enable log4j internal logging by defining the
<b>log4j.debug</b> variable on the java command
line. Alternatively, set the <code>debug</code> attribute in the
<code>log4j:configuration</code> element. As in
<pre>
<log4j:configuration <b>debug="true"</b> xmlns:log4j="http://jakarta.apache.org/log4j/">
...
</log4j:configuration>
</pre>
<p>There are sample XML files included in the package.
@author Christopher Taylor
@author Ceki Gülcü
@author Anders Kristensen
@since 0.8.3 */
public class DOMConfigurator implements Configurator {
static final String CONFIGURATION_TAG = "log4j:configuration";
static final String OLD_CONFIGURATION_TAG = "configuration";
static final String RENDERER_TAG = "renderer";
static final String APPENDER_TAG = "appender";
static final String APPENDER_REF_TAG = "appender-ref";
static final String PARAM_TAG = "param";
static final String LAYOUT_TAG = "layout";
static final String CATEGORY = "category";
static final String LOGGER = "logger";
static final String LOGGER_REF = "logger-ref";
static final String CATEGORY_FACTORY_TAG = "categoryFactory";
static final String LOGGER_FACTORY_TAG = "loggerFactory";
static final String NAME_ATTR = "name";
static final String CLASS_ATTR = "class";
static final String VALUE_ATTR = "value";
static final String ROOT_TAG = "root";
static final String ROOT_REF = "root-ref";
static final String LEVEL_TAG = "level";
static final String PRIORITY_TAG = "priority";
static final String FILTER_TAG = "filter";
static final String ERROR_HANDLER_TAG = "errorHandler";
static final String REF_ATTR = "ref";
static final String ADDITIVITY_ATTR = "additivity";
static final String THRESHOLD_ATTR = "threshold";
static final String CONFIG_DEBUG_ATTR = "configDebug";
static final String INTERNAL_DEBUG_ATTR = "debug";
static final String RENDERING_CLASS_ATTR = "renderingClass";
static final String RENDERED_CLASS_ATTR = "renderedClass";
static final String EMPTY_STR = "";
static final Class[] ONE_STRING_PARAM = new Class[] {String.class};
final static String dbfKey = "javax.xml.parsers.DocumentBuilderFactory";
// key: appenderName, value: appender
Hashtable appenderBag;
Properties props;
LoggerRepository repository;
protected LoggerFactory catFactory = null;
/**
No argument constructor.
*/
public
DOMConfigurator () {
appenderBag = new Hashtable();
}
/**
Used internally to parse appenders by IDREF name.
*/
protected
Appender findAppenderByName(Document doc, String appenderName) {
Appender appender = (Appender) appenderBag.get(appenderName);
if(appender != null) {
return appender;
} else {
// Doesn't work on DOM Level 1 :
// Element element = doc.getElementById(appenderName);
// Endre's hack:
Element element = null;
NodeList list = doc.getElementsByTagName("appender");
for (int t=0; t < list.getLength(); t++) {
Node node = list.item(t);
NamedNodeMap map= node.getAttributes();
Node attrNode = map.getNamedItem("name");
if (appenderName.equals(attrNode.getNodeValue())) {
element = (Element) node;
break;
}
}
// Hack finished.
if(element == null) {
LogLog.error("No appender named ["+appenderName+"] could be found.");
return null;
} else {
appender = parseAppender(element);
appenderBag.put(appenderName, appender);
return appender;
}
}
}
/**
Used internally to parse appenders by IDREF element.
*/
protected
Appender findAppenderByReference(Element appenderRef) {
String appenderName = subst(appenderRef.getAttribute(REF_ATTR));
Document doc = appenderRef.getOwnerDocument();
return findAppenderByName(doc, appenderName);
}
/**
* Delegates unrecognized content to created instance if
* it supports UnrecognizedElementParser.
* @since 1.2.15
* @param instance instance, may be null.
* @param element element, may not be null.
* @param props properties
* @throws IOException thrown if configuration of owner object
* should be abandoned.
*/
private static void parseUnrecognizedElement(final Object instance,
final Element element,
final Properties props) throws Exception {
boolean recognized = false;
if (instance instanceof UnrecognizedElementHandler) {
recognized = ((UnrecognizedElementHandler) instance).parseUnrecognizedElement(
element, props);
}
if (!recognized) {
LogLog.warn("Unrecognized element " + element.getNodeName());
}
}
/**
* Delegates unrecognized content to created instance if
* it supports UnrecognizedElementParser and catches and
* logs any exception.
* @since 1.2.15
* @param instance instance, may be null.
* @param element element, may not be null.
* @param props properties
*/
private static void quietParseUnrecognizedElement(final Object instance,
final Element element,
final Properties props) {
try {
parseUnrecognizedElement(instance, element, props);
} catch (Exception ex) {
LogLog.error("Error in extension content: ", ex);
}
}
/**
Used internally to parse an appender element.
*/
protected
Appender parseAppender (Element appenderElement) {
String className = subst(appenderElement.getAttribute(CLASS_ATTR));
LogLog.debug("Class name: [" + className+']');
try {
Object instance = Loader.loadClass(className).newInstance();
Appender appender = (Appender)instance;
PropertySetter propSetter = new PropertySetter(appender);
appender.setName(subst(appenderElement.getAttribute(NAME_ATTR)));
NodeList children = appenderElement.getChildNodes();
final int length = children.getLength();
for (int loop = 0; loop < length; loop++) {
Node currentNode = children.item(loop);
/* We're only interested in Elements */
if (currentNode.getNodeType() == Node.ELEMENT_NODE) {
Element currentElement = (Element)currentNode;
// Parse appender parameters
if (currentElement.getTagName().equals(PARAM_TAG)) {
setParameter(currentElement, propSetter);
}
// Set appender layout
else if (currentElement.getTagName().equals(LAYOUT_TAG)) {
appender.setLayout(parseLayout(currentElement));
}
// Add filters
else if (currentElement.getTagName().equals(FILTER_TAG)) {
parseFilters(currentElement, appender);
}
else if (currentElement.getTagName().equals(ERROR_HANDLER_TAG)) {
parseErrorHandler(currentElement, appender);
}
else if (currentElement.getTagName().equals(APPENDER_REF_TAG)) {
String refName = subst(currentElement.getAttribute(REF_ATTR));
if(appender instanceof AppenderAttachable) {
AppenderAttachable aa = (AppenderAttachable) appender;
LogLog.debug("Attaching appender named ["+ refName+
"] to appender named ["+ appender.getName()+"].");
aa.addAppender(findAppenderByReference(currentElement));
} else {
LogLog.error("Requesting attachment of appender named ["+
refName+ "] to appender named ["+ appender.getName()+
"] which does not implement org.apache.log4j.spi.AppenderAttachable.");
}
} else {
parseUnrecognizedElement(instance, currentElement, props);
}
}
}
propSetter.activate();
return appender;
}
/* Yes, it's ugly. But all of these exceptions point to the same
problem: we can't create an Appender */
catch (Exception oops) {
LogLog.error("Could not create an Appender. Reported error follows.",
oops);
return null;
}
}
/**
Used internally to parse an {@link ErrorHandler} element.
*/
protected
void parseErrorHandler(Element element, Appender appender) {
ErrorHandler eh = (ErrorHandler) OptionConverter.instantiateByClassName(
subst(element.getAttribute(CLASS_ATTR)),
org.apache.log4j.spi.ErrorHandler.class,
null);
if(eh != null) {
eh.setAppender(appender);
PropertySetter propSetter = new PropertySetter(eh);
NodeList children = element.getChildNodes();
final int length = children.getLength();
for (int loop = 0; loop < length; loop++) {
Node currentNode = children.item(loop);
if (currentNode.getNodeType() == Node.ELEMENT_NODE) {
Element currentElement = (Element) currentNode;
String tagName = currentElement.getTagName();
if(tagName.equals(PARAM_TAG)) {
setParameter(currentElement, propSetter);
} else if(tagName.equals(APPENDER_REF_TAG)) {
eh.setBackupAppender(findAppenderByReference(currentElement));
} else if(tagName.equals(LOGGER_REF)) {
String loggerName = currentElement.getAttribute(REF_ATTR);
Logger logger = (catFactory == null) ? repository.getLogger(loggerName)
: repository.getLogger(loggerName, catFactory);
eh.setLogger(logger);
} else if(tagName.equals(ROOT_REF)) {
Logger root = repository.getRootLogger();
eh.setLogger(root);
} else {
- quietParseUnrecognizedElement(eh, element, props);
+ quietParseUnrecognizedElement(eh, currentElement, props);
}
}
}
propSetter.activate();
appender.setErrorHandler(eh);
}
}
/**
Used internally to parse a filter element.
*/
protected
void parseFilters(Element element, Appender appender) {
String clazz = subst(element.getAttribute(CLASS_ATTR));
Filter filter = (Filter) OptionConverter.instantiateByClassName(clazz,
Filter.class, null);
if(filter != null) {
PropertySetter propSetter = new PropertySetter(filter);
NodeList children = element.getChildNodes();
final int length = children.getLength();
for (int loop = 0; loop < length; loop++) {
Node currentNode = children.item(loop);
if (currentNode.getNodeType() == Node.ELEMENT_NODE) {
Element currentElement = (Element) currentNode;
String tagName = currentElement.getTagName();
if(tagName.equals(PARAM_TAG)) {
setParameter(currentElement, propSetter);
} else {
- quietParseUnrecognizedElement(filter, element, props);
+ quietParseUnrecognizedElement(filter, currentElement, props);
}
}
}
propSetter.activate();
LogLog.debug("Adding filter of type ["+filter.getClass()
+"] to appender named ["+appender.getName()+"].");
appender.addFilter(filter);
}
}
/**
Used internally to parse an category element.
*/
protected
void parseCategory (Element loggerElement) {
// Create a new org.apache.log4j.Category object from the <category> element.
String catName = subst(loggerElement.getAttribute(NAME_ATTR));
Logger cat;
String className = subst(loggerElement.getAttribute(CLASS_ATTR));
if(EMPTY_STR.equals(className)) {
LogLog.debug("Retreiving an instance of org.apache.log4j.Logger.");
cat = (catFactory == null) ? repository.getLogger(catName) : repository.getLogger(catName, catFactory);
}
else {
LogLog.debug("Desired logger sub-class: ["+className+']');
try {
Class clazz = Loader.loadClass(className);
Method getInstanceMethod = clazz.getMethod("getLogger",
ONE_STRING_PARAM);
cat = (Logger) getInstanceMethod.invoke(null, new Object[] {catName});
} catch (Exception oops) {
LogLog.error("Could not retrieve category ["+catName+
"]. Reported error follows.", oops);
return;
}
}
// Setting up a category needs to be an atomic operation, in order
// to protect potential log operations while category
// configuration is in progress.
synchronized(cat) {
boolean additivity = OptionConverter.toBoolean(
subst(loggerElement.getAttribute(ADDITIVITY_ATTR)),
true);
LogLog.debug("Setting ["+cat.getName()+"] additivity to ["+additivity+"].");
cat.setAdditivity(additivity);
parseChildrenOfLoggerElement(loggerElement, cat, false);
}
}
/**
Used internally to parse the category factory element.
*/
protected
void parseCategoryFactory(Element factoryElement) {
String className = subst(factoryElement.getAttribute(CLASS_ATTR));
if(EMPTY_STR.equals(className)) {
LogLog.error("Category Factory tag " + CLASS_ATTR + " attribute not found.");
LogLog.debug("No Category Factory configured.");
}
else {
LogLog.debug("Desired category factory: ["+className+']');
Object factory = OptionConverter.instantiateByClassName(className,
LoggerFactory.class,
null);
if (factory instanceof LoggerFactory) {
catFactory = (LoggerFactory) factory;
} else {
LogLog.error("Category Factory class " + className + " does not implement org.apache.log4j.LoggerFactory");
}
PropertySetter propSetter = new PropertySetter(factory);
Element currentElement = null;
Node currentNode = null;
NodeList children = factoryElement.getChildNodes();
final int length = children.getLength();
for (int loop=0; loop < length; loop++) {
currentNode = children.item(loop);
if (currentNode.getNodeType() == Node.ELEMENT_NODE) {
currentElement = (Element)currentNode;
if (currentElement.getTagName().equals(PARAM_TAG)) {
setParameter(currentElement, propSetter);
} else {
- quietParseUnrecognizedElement(factory, factoryElement, props);
+ quietParseUnrecognizedElement(factory, currentElement, props);
}
}
}
}
}
/**
Used internally to parse the roor category element.
*/
protected
void parseRoot (Element rootElement) {
Logger root = repository.getRootLogger();
// category configuration needs to be atomic
synchronized(root) {
parseChildrenOfLoggerElement(rootElement, root, true);
}
}
/**
Used internally to parse the children of a category element.
*/
protected
void parseChildrenOfLoggerElement(Element catElement,
Logger cat, boolean isRoot) {
PropertySetter propSetter = new PropertySetter(cat);
// Remove all existing appenders from cat. They will be
// reconstructed if need be.
cat.removeAllAppenders();
NodeList children = catElement.getChildNodes();
final int length = children.getLength();
for (int loop = 0; loop < length; loop++) {
Node currentNode = children.item(loop);
if (currentNode.getNodeType() == Node.ELEMENT_NODE) {
Element currentElement = (Element) currentNode;
String tagName = currentElement.getTagName();
if (tagName.equals(APPENDER_REF_TAG)) {
Element appenderRef = (Element) currentNode;
Appender appender = findAppenderByReference(appenderRef);
String refName = subst(appenderRef.getAttribute(REF_ATTR));
if(appender != null)
LogLog.debug("Adding appender named ["+ refName+
"] to category ["+cat.getName()+"].");
else
LogLog.debug("Appender named ["+ refName + "] not found.");
cat.addAppender(appender);
} else if(tagName.equals(LEVEL_TAG)) {
parseLevel(currentElement, cat, isRoot);
} else if(tagName.equals(PRIORITY_TAG)) {
parseLevel(currentElement, cat, isRoot);
} else if(tagName.equals(PARAM_TAG)) {
setParameter(currentElement, propSetter);
} else {
- quietParseUnrecognizedElement(cat, catElement, props);
+ quietParseUnrecognizedElement(cat, currentElement, props);
}
}
}
propSetter.activate();
}
/**
Used internally to parse a layout element.
*/
protected
Layout parseLayout (Element layout_element) {
String className = subst(layout_element.getAttribute(CLASS_ATTR));
LogLog.debug("Parsing layout of class: \""+className+"\"");
try {
Object instance = Loader.loadClass(className).newInstance();
Layout layout = (Layout)instance;
PropertySetter propSetter = new PropertySetter(layout);
NodeList params = layout_element.getChildNodes();
final int length = params.getLength();
for (int loop = 0; loop < length; loop++) {
Node currentNode = (Node)params.item(loop);
if (currentNode.getNodeType() == Node.ELEMENT_NODE) {
Element currentElement = (Element) currentNode;
String tagName = currentElement.getTagName();
if(tagName.equals(PARAM_TAG)) {
setParameter(currentElement, propSetter);
} else {
- parseUnrecognizedElement(instance, layout_element, props);
+ parseUnrecognizedElement(instance, currentElement, props);
}
}
}
propSetter.activate();
return layout;
}
catch (Exception oops) {
LogLog.error("Could not create the Layout. Reported error follows.",
oops);
return null;
}
}
protected
void parseRenderer(Element element) {
String renderingClass = subst(element.getAttribute(RENDERING_CLASS_ATTR));
String renderedClass = subst(element.getAttribute(RENDERED_CLASS_ATTR));
if(repository instanceof RendererSupport) {
RendererMap.addRenderer((RendererSupport) repository, renderedClass,
renderingClass);
}
}
/**
Used internally to parse a level element.
*/
protected
void parseLevel(Element element, Logger logger, boolean isRoot) {
String catName = logger.getName();
if(isRoot) {
catName = "root";
}
String priStr = subst(element.getAttribute(VALUE_ATTR));
LogLog.debug("Level value for "+catName+" is ["+priStr+"].");
if(INHERITED.equalsIgnoreCase(priStr) || NULL.equalsIgnoreCase(priStr)) {
if(isRoot) {
LogLog.error("Root level cannot be inherited. Ignoring directive.");
} else {
logger.setLevel(null);
}
} else {
String className = subst(element.getAttribute(CLASS_ATTR));
if(EMPTY_STR.equals(className)) {
logger.setLevel(OptionConverter.toLevel(priStr, Level.DEBUG));
} else {
LogLog.debug("Desired Level sub-class: ["+className+']');
try {
Class clazz = Loader.loadClass(className);
Method toLevelMethod = clazz.getMethod("toLevel",
ONE_STRING_PARAM);
Level pri = (Level) toLevelMethod.invoke(null,
new Object[] {priStr});
logger.setLevel(pri);
} catch (Exception oops) {
LogLog.error("Could not create level ["+priStr+
"]. Reported error follows.", oops);
return;
}
}
}
LogLog.debug(catName + " level set to " + logger.getLevel());
}
protected
void setParameter(Element elem, PropertySetter propSetter) {
setParameter(elem, propSetter, props);
}
/**
Configure log4j using a <code>configuration</code> element as
defined in the log4j.dtd.
*/
static
public
void configure (Element element) {
DOMConfigurator configurator = new DOMConfigurator();
configurator.doConfigure(element, LogManager.getLoggerRepository());
}
/**
Like {@link #configureAndWatch(String, long)} except that the
default delay as defined by {@link FileWatchdog#DEFAULT_DELAY} is
used.
@param configFilename A log4j configuration file in XML format.
*/
static
public
void configureAndWatch(String configFilename) {
configureAndWatch(configFilename, FileWatchdog.DEFAULT_DELAY);
}
/**
Read the configuration file <code>configFilename</code> if it
exists. Moreover, a thread will be created that will periodically
check if <code>configFilename</code> has been created or
modified. The period is determined by the <code>delay</code>
argument. If a change or file creation is detected, then
<code>configFilename</code> is read to configure log4j.
@param configFilename A log4j configuration file in XML format.
@param delay The delay in milliseconds to wait between each check.
*/
static
public
void configureAndWatch(String configFilename, long delay) {
XMLWatchdog xdog = new XMLWatchdog(configFilename);
xdog.setDelay(delay);
xdog.start();
}
private interface ParseAction {
Document parse(final DocumentBuilder parser) throws SAXException, IOException;
}
public
void doConfigure(final String filename, LoggerRepository repository) {
ParseAction action = new ParseAction() {
public Document parse(final DocumentBuilder parser) throws SAXException, IOException {
return parser.parse(new File(filename));
}
public String toString() {
return "file [" + filename + "]";
}
};
doConfigure(action, repository);
}
public
void doConfigure(final URL url, LoggerRepository repository) {
ParseAction action = new ParseAction() {
public Document parse(final DocumentBuilder parser) throws SAXException, IOException {
return parser.parse(url.toString());
}
public String toString() {
return "url [" + url.toString() + "]";
}
};
doConfigure(action, repository);
}
/**
Configure log4j by reading in a log4j.dtd compliant XML
configuration file.
*/
public
void doConfigure(final InputStream inputStream, LoggerRepository repository)
throws FactoryConfigurationError {
ParseAction action = new ParseAction() {
public Document parse(final DocumentBuilder parser) throws SAXException, IOException {
InputSource inputSource = new InputSource(inputStream);
inputSource.setSystemId("dummy://log4j.dtd");
return parser.parse(inputSource);
}
public String toString() {
return "input stream [" + inputStream.toString() + "]";
}
};
doConfigure(action, repository);
}
/**
Configure log4j by reading in a log4j.dtd compliant XML
configuration file.
*/
public
void doConfigure(final Reader reader, LoggerRepository repository)
throws FactoryConfigurationError {
ParseAction action = new ParseAction() {
public Document parse(final DocumentBuilder parser) throws SAXException, IOException {
InputSource inputSource = new InputSource(reader);
inputSource.setSystemId("dummy://log4j.dtd");
return parser.parse(inputSource);
}
public String toString() {
return "reader [" + reader.toString() + "]";
}
};
doConfigure(action, repository);
}
/**
Configure log4j by reading in a log4j.dtd compliant XML
configuration file.
*/
protected
void doConfigure(final InputSource inputSource, LoggerRepository repository)
throws FactoryConfigurationError {
if (inputSource.getSystemId() == null) {
inputSource.setSystemId("dummy://log4j.dtd");
}
ParseAction action = new ParseAction() {
public Document parse(final DocumentBuilder parser) throws SAXException, IOException {
return parser.parse(inputSource);
}
public String toString() {
return "input source [" + inputSource.toString() + "]";
}
};
doConfigure(action, repository);
}
private final void doConfigure(final ParseAction action, final LoggerRepository repository)
throws FactoryConfigurationError {
DocumentBuilderFactory dbf = null;
this.repository = repository;
try {
LogLog.debug("System property is :"+
OptionConverter.getSystemProperty(dbfKey,
null));
dbf = DocumentBuilderFactory.newInstance();
LogLog.debug("Standard DocumentBuilderFactory search succeded.");
LogLog.debug("DocumentBuilderFactory is: "+dbf.getClass().getName());
} catch(FactoryConfigurationError fce) {
Exception e = fce.getException();
LogLog.debug("Could not instantiate a DocumentBuilderFactory.", e);
throw fce;
}
try {
dbf.setValidating(true);
DocumentBuilder docBuilder = dbf.newDocumentBuilder();
docBuilder.setErrorHandler(new SAXErrorHandler());
docBuilder.setEntityResolver(new Log4jEntityResolver());
Document doc = action.parse(docBuilder);
parse(doc.getDocumentElement());
} catch (Exception e) {
// I know this is miserable...
LogLog.error("Could not parse "+ action.toString() + ".", e);
}
}
/**
Configure by taking in an DOM element.
*/
public void doConfigure(Element element, LoggerRepository repository) {
this.repository = repository;
parse(element);
}
/**
A static version of {@link #doConfigure(String, LoggerRepository)}. */
static
public
void configure(String filename) throws FactoryConfigurationError {
new DOMConfigurator().doConfigure(filename,
LogManager.getLoggerRepository());
}
/**
A static version of {@link #doConfigure(URL, LoggerRepository)}.
*/
static
public
void configure(URL url) throws FactoryConfigurationError {
new DOMConfigurator().doConfigure(url, LogManager.getLoggerRepository());
}
/**
Used internally to configure the log4j framework by parsing a DOM
tree of XML elements based on <a
href="doc-files/log4j.dtd">log4j.dtd</a>.
*/
protected
void parse(Element element) {
String rootElementName = element.getTagName();
if (!rootElementName.equals(CONFIGURATION_TAG)) {
if(rootElementName.equals(OLD_CONFIGURATION_TAG)) {
LogLog.warn("The <"+OLD_CONFIGURATION_TAG+
"> element has been deprecated.");
LogLog.warn("Use the <"+CONFIGURATION_TAG+"> element instead.");
} else {
LogLog.error("DOM element is - not a <"+CONFIGURATION_TAG+"> element.");
return;
}
}
String debugAttrib = subst(element.getAttribute(INTERNAL_DEBUG_ATTR));
LogLog.debug("debug attribute= \"" + debugAttrib +"\".");
// if the log4j.dtd is not specified in the XML file, then the
// "debug" attribute is returned as the empty string.
if(!debugAttrib.equals("") && !debugAttrib.equals("null")) {
LogLog.setInternalDebugging(OptionConverter.toBoolean(debugAttrib, true));
} else {
LogLog.debug("Ignoring " + INTERNAL_DEBUG_ATTR + " attribute.");
}
String confDebug = subst(element.getAttribute(CONFIG_DEBUG_ATTR));
if(!confDebug.equals("") && !confDebug.equals("null")) {
LogLog.warn("The \""+CONFIG_DEBUG_ATTR+"\" attribute is deprecated.");
LogLog.warn("Use the \""+INTERNAL_DEBUG_ATTR+"\" attribute instead.");
LogLog.setInternalDebugging(OptionConverter.toBoolean(confDebug, true));
}
String thresholdStr = subst(element.getAttribute(THRESHOLD_ATTR));
LogLog.debug("Threshold =\"" + thresholdStr +"\".");
if(!"".equals(thresholdStr) && !"null".equals(thresholdStr)) {
repository.setThreshold(thresholdStr);
}
//Hashtable appenderBag = new Hashtable(11);
/* Building Appender objects, placing them in a local namespace
for future reference */
// First configure each category factory under the root element.
// Category factories need to be configured before any of
// categories they support.
//
String tagName = null;
Element currentElement = null;
Node currentNode = null;
NodeList children = element.getChildNodes();
final int length = children.getLength();
for (int loop = 0; loop < length; loop++) {
currentNode = children.item(loop);
if (currentNode.getNodeType() == Node.ELEMENT_NODE) {
currentElement = (Element) currentNode;
tagName = currentElement.getTagName();
if (tagName.equals(CATEGORY_FACTORY_TAG) || tagName.equals(LOGGER_FACTORY_TAG)) {
parseCategoryFactory(currentElement);
}
}
}
for (int loop = 0; loop < length; loop++) {
currentNode = children.item(loop);
if (currentNode.getNodeType() == Node.ELEMENT_NODE) {
currentElement = (Element) currentNode;
tagName = currentElement.getTagName();
if (tagName.equals(CATEGORY) || tagName.equals(LOGGER)) {
parseCategory(currentElement);
} else if (tagName.equals(ROOT_TAG)) {
parseRoot(currentElement);
} else if(tagName.equals(RENDERER_TAG)) {
parseRenderer(currentElement);
} else if (!(tagName.equals(APPENDER_TAG)
|| tagName.equals(CATEGORY_FACTORY_TAG)
|| tagName.equals(LOGGER_FACTORY_TAG))) {
quietParseUnrecognizedElement(repository, currentElement, props);
}
}
}
}
protected
String subst(final String value) {
return subst(value, props);
}
/**
* Substitutes property value for any references in expression.
*
* @param value value from configuration file, may contain
* literal text, property references or both
* @param props properties.
* @return evaluated expression, may still contain expressions
* if unable to expand.
* @since 1.2.15
*/
public static String subst(final String value, final Properties props) {
try {
return OptionConverter.substVars(value, props);
} catch (IllegalArgumentException e) {
LogLog.warn("Could not perform variable substitution.", e);
return value;
}
}
/**
* Sets a parameter based from configuration file content.
*
* @param elem param element, may not be null.
* @param propSetter property setter, may not be null.
* @param props properties
* @since 1.2.15
*/
public static void setParameter(final Element elem,
final PropertySetter propSetter,
final Properties props) {
String name = subst(elem.getAttribute("name"), props);
String value = (elem.getAttribute("value"));
value = subst(OptionConverter.convertSpecialChars(value), props);
propSetter.setProperty(name, value);
}
/**
* Creates an object and processes any nested param elements
* but does not call activateOptions. If the class also supports
* UnrecognizedElementParser, the parseUnrecognizedElement method
* will be call for any child elements other than param.
*
* @param element element, may not be null.
* @param props properties
* @param expectedClass interface or class expected to be implemented
* by created class
* @return created class or null.
* @throws Exception thrown if the contain object should be abandoned.
* @since 1.2.15
*/
public static Object parseElement(final Element element,
final Properties props,
final Class expectedClass) throws Exception {
String clazz = subst(element.getAttribute("class"), props);
Object instance = OptionConverter.instantiateByClassName(clazz,
expectedClass, null);
if (instance != null) {
PropertySetter propSetter = new PropertySetter(instance);
NodeList children = element.getChildNodes();
final int length = children.getLength();
for (int loop = 0; loop < length; loop++) {
Node currentNode = children.item(loop);
if (currentNode.getNodeType() == Node.ELEMENT_NODE) {
Element currentElement = (Element) currentNode;
String tagName = currentElement.getTagName();
if (tagName.equals("param")) {
setParameter(currentElement, propSetter, props);
} else {
parseUnrecognizedElement(instance, currentElement, props);
}
}
}
return instance;
}
return null;
}
}
class XMLWatchdog extends FileWatchdog {
XMLWatchdog(String filename) {
super(filename);
}
/**
Call {@link DOMConfigurator#configure(String)} with the
<code>filename</code> to reconfigure log4j. */
public
void doOnChange() {
new DOMConfigurator().doConfigure(filename,
LogManager.getLoggerRepository());
}
}
| false | false | null | null |
diff --git a/src/editor/inspections/bugs/GlobalCreationOutsideOfMainChunk.java b/src/editor/inspections/bugs/GlobalCreationOutsideOfMainChunk.java
index 06b425c4..2a976f23 100644
--- a/src/editor/inspections/bugs/GlobalCreationOutsideOfMainChunk.java
+++ b/src/editor/inspections/bugs/GlobalCreationOutsideOfMainChunk.java
@@ -1,83 +1,83 @@
/*
* Copyright 2011 Jon S Akhtar (Sylvanaar)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sylvanaar.idea.Lua.editor.inspections.bugs;
import com.intellij.codeHighlighting.HighlightDisplayLevel;
import com.intellij.codeInspection.LocalQuickFix;
import com.intellij.codeInspection.ProblemsHolder;
import com.intellij.psi.PsiElementVisitor;
import com.intellij.psi.util.PsiTreeUtil;
import com.sylvanaar.idea.Lua.editor.inspections.AbstractInspection;
import com.sylvanaar.idea.Lua.lang.psi.LuaPsiFile;
import com.sylvanaar.idea.Lua.lang.psi.expressions.LuaDeclarationExpression;
import com.sylvanaar.idea.Lua.lang.psi.statements.LuaBlock;
import com.sylvanaar.idea.Lua.lang.psi.symbols.LuaGlobal;
import com.sylvanaar.idea.Lua.lang.psi.visitor.LuaElementVisitor;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;
/**
* Created by IntelliJ IDEA.
* User: Jon S Akhtar
* Date: 7/4/11
* Time: 10:11 AM
*/
public class GlobalCreationOutsideOfMainChunk extends AbstractInspection {
@Nls
@NotNull
@Override
public String getDisplayName() {
return "Suspicious global creation";
}
@Override
public String getStaticDescription() {
return "Looks for creation of globals in scopes other than the main chunk";
}
@NotNull
@Override
public String getGroupDisplayName() {
return PROBABLE_BUGS;
}
@NotNull
@Override
public HighlightDisplayLevel getDefaultLevel() {
return HighlightDisplayLevel.WARNING;
}
@NotNull
@Override
public PsiElementVisitor buildVisitor(@NotNull final ProblemsHolder holder, boolean isOnTheFly) {
return new LuaElementVisitor() {
public void visitDeclarationExpression(LuaDeclarationExpression var) {
super.visitDeclarationExpression(var);
if (var instanceof LuaGlobal) {
- LuaBlock block = PsiTreeUtil.getParentOfType(var, LuaBlock.class, LuaPsiFile.class);
+ LuaBlock block = PsiTreeUtil.getParentOfType(var, LuaBlock.class);
if (block == null) return;
- if (block.getParent() instanceof LuaPsiFile)
+ if (block instanceof LuaPsiFile)
return;
holder.registerProblem(var, "Suspicious global creation ("+var.getName()+")", LocalQuickFix.EMPTY_ARRAY);
}
}
};
}
}
| false | true | public PsiElementVisitor buildVisitor(@NotNull final ProblemsHolder holder, boolean isOnTheFly) {
return new LuaElementVisitor() {
public void visitDeclarationExpression(LuaDeclarationExpression var) {
super.visitDeclarationExpression(var);
if (var instanceof LuaGlobal) {
LuaBlock block = PsiTreeUtil.getParentOfType(var, LuaBlock.class, LuaPsiFile.class);
if (block == null) return;
if (block.getParent() instanceof LuaPsiFile)
return;
holder.registerProblem(var, "Suspicious global creation ("+var.getName()+")", LocalQuickFix.EMPTY_ARRAY);
}
}
};
}
| public PsiElementVisitor buildVisitor(@NotNull final ProblemsHolder holder, boolean isOnTheFly) {
return new LuaElementVisitor() {
public void visitDeclarationExpression(LuaDeclarationExpression var) {
super.visitDeclarationExpression(var);
if (var instanceof LuaGlobal) {
LuaBlock block = PsiTreeUtil.getParentOfType(var, LuaBlock.class);
if (block == null) return;
if (block instanceof LuaPsiFile)
return;
holder.registerProblem(var, "Suspicious global creation ("+var.getName()+")", LocalQuickFix.EMPTY_ARRAY);
}
}
};
}
|
diff --git a/wififixer/src/org/wahtod/wififixer/WifiFixerService.java b/wififixer/src/org/wahtod/wififixer/WifiFixerService.java
index b2c0ac6..1644107 100644
--- a/wififixer/src/org/wahtod/wififixer/WifiFixerService.java
+++ b/wififixer/src/org/wahtod/wififixer/WifiFixerService.java
@@ -1,1596 +1,1616 @@
/*Copyright [2010] [David Van de Ven]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.wahtod.wififixer;
import java.io.IOException;
import java.net.InetAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpHead;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.ConnectivityManager;
import android.net.DhcpInfo;
import android.net.wifi.ScanResult;
import android.net.wifi.SupplicantState;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.PowerManager;
import android.preference.PreferenceManager;
import android.text.format.Formatter;
import android.widget.Toast;
public class WifiFixerService extends Service {
/*
* Hey, if you're poking into this, and have the brains to figure out my
* code, you can afford to donate. I don't need a fancy auth scheme.
*/
// Intent Constants
public static final String FIXWIFI = "FIXWIFI";
private static final String AUTHSTRING = "31415927";
// For Auth
private static final String AUTHEXTRA = "IRRADIATED";
private static final String AUTH = "AUTH";
// Wake Lock Tag
private static final String WFWAKELOCK = "WFWakeLock";
// Runnable Constants for handler
private static final int MAIN = 0;
private static final int REPAIR = 1;
private static final int RECONNECT = 2;
private static final int WIFITASK = 3;
private static final int TEMPLOCK_ON = 4;
private static final int TEMPLOCK_OFF = 5;
private static final int WIFI_OFF = 6;
private static final int WIFI_ON = 7;
private static final int SLEEPCHECK = 8;
+ private static final int N1FIX = 9;
/*
* Constants for wifirepair values
*/
private static final int W_REASSOCIATE = 0;
private static final int W_RECONNECT = 1;
private static final int W_REPAIR = 2;
// ID For notification
private static final int NOTIFID = 31337;
private static final int ERR_NOTIF = 7972;
// Wifi Lock tag
private static final String WFLOCK_TAG = "WFLock";
// Supplicant Constants
private static final String SCANNING = "SCANNING";
private static final String DISCONNECTED = "DISCONNECTED";
private static final String INACTIVE = "INACTIVE";
private static final String COMPLETED = "COMPLETED";
// Target for header check
private static final String H_TARGET = "http://www.google.com";
private static URI headURI;
// Logging Intent
private static final String LOGINTENT = "org.wahtod.wififixer.LogService.LOG";
// ms for IsReachable
private final static int REACHABLE = 3000;
private final static int HTTPREACH = 8000;
// ms for main loop sleep
private final static int LOOPWAIT = 10000;
// ms for sleep loop check
private final static long SLEEPWAIT = 60000;
// ms for lock delays
private final static int LOCKWAIT = 5000;
// ms to wait after trying to connect
private static final int CONNECTWAIT = 10000;
// for Dbm
private static final int DBM_DEFAULT = -100;
// *****************************
final static String APP_NAME = "WifiFixerService";
// Flags
private boolean cleanup = false;
private boolean haslock = false;
private boolean prefschanged = false;
private boolean wifishouldbeon = false;
/*
* preferences key constants
*/
private static final String WIFILOCK_KEY = "WiFiLock";
private static final String NOTIF_KEY = "Notifications";
private static final String SCREEN_KEY = "SCREEN";
private static final String DISABLE_KEY = "Disable";
private static final String WIDGET_KEY = "WidgetBehavior";
private static final String LOG_KEY = "SLOG";
private static final String SUPFIX_KEY = "SUPFIX";
private static final String SUPFIX_DEFAULT = "SPFDEF";
/*
* Preferences currently used in list form.
*/
private static final List<String> prefsList = Arrays
.asList(WIFILOCK_KEY, DISABLE_KEY, SCREEN_KEY, WIDGET_KEY,
SUPFIX_KEY, NOTIF_KEY, LOG_KEY);
/*
* prefsList maps to values
*/
private final static int lockpref = 0;
private final static int runpref = 1;
private final static int screenpref = 2;
private final static int widgetpref = 3;
private final static int supfixpref = 4;
private final static int notifpref = 5;
private final static int loggingpref = 6;
// logging flag, local for performance
private static boolean logging = false;
/*
*
*/
// Locks and such
private static boolean templock = false;
private static boolean screenisoff = false;
private static boolean shouldrun = true;
// various
private static int wifirepair = W_REASSOCIATE;
private static final int HTTP_NULL = -1;
private static int lastnid = HTTP_NULL;
private static String cachedIP;
// Empty string
private final static String EMPTYSTRING = "";
// Wifi Fix flags
private static boolean pendingscan = false;
private static boolean pendingwifitoggle = false;
private static boolean pendingreconnect = false;
// misc types
private static String lastssid = EMPTYSTRING;
private static int version = MAIN;
// Public Utilities
private static WifiManager wm;
private static WifiInfo myWifi;
private static WifiManager.WifiLock lock;
private static SharedPreferences settings;
private static PowerManager.WakeLock wakelock;
private static DefaultHttpClient httpclient;
private static HttpParams httpparams;
private static HttpHead head;
private static HttpResponse response;
private static WFPreferences prefs = new WFPreferences();
/*
* Preferences object
*/
private static class WFPreferences extends Object {
private boolean[] keyVals = new boolean[prefsList.size()];
public void loadPrefs(final Context context) {
settings = PreferenceManager.getDefaultSharedPreferences(context);
/*
* Set defaults. Doing here instead of activity because service may
* be started first.
*/
PreferenceManager.setDefaultValues(context, R.xml.preferences,
false);
/*
* Pre-prefs load
*/
preLoad(context);
/*
* Load
*/
int index;
for (String prefkey : prefsList) {
/*
* Get index
*/
index = prefsList.indexOf(prefkey);
/*
* Before value changes from loading
*/
preValChanged(context, index);
/*
* Setting the value from prefs
*/
setFlag(index, settings.getBoolean(prefkey, false));
/*
* After value changes from loading
*/
postValChanged(context, index);
}
specialCase(context);
log(context);
}
private void preLoad(final Context context) {
/*
* Sets default for Supplicant Fix pref on < 2.0 to true
*/
if (!settings.getBoolean(SUPFIX_DEFAULT, false)) {
SharedPreferences.Editor edit = settings.edit();
edit.putBoolean(SUPFIX_DEFAULT, true);
int ver;
try {
ver = Integer
.valueOf(Build.VERSION.RELEASE.substring(0, 1));
} catch (NumberFormatException e) {
ver = 0;
}
if (logging)
wfLog(context, APP_NAME, context
.getString(R.string.version)
+ ver);
if (ver < 2) {
edit.putBoolean(SUPFIX_KEY, true);
}
edit.commit();
}
}
private void preValChanged(final Context context, final int index) {
switch (index) {
case loggingpref:
// Kill the Log Service if it's up
if (logging && !settings.getBoolean(LOG_KEY, false))
wfLog(context, LogService.DIE, null);
break;
}
}
private void postValChanged(final Context context, final int index) {
switch (index) {
case runpref:
// Check RUNPREF and set SHOULDRUN
// Make sure Main loop restarts if this is a change
if (getFlag(runpref)) {
ServiceAlarm.unsetAlarm(context);
shouldrun = false;
} else {
if (!shouldrun) {
shouldrun = true;
}
ServiceAlarm.setAlarm(context, true);
}
break;
case loggingpref:
/*
* Set logging flag
*/
logging = getFlag(loggingpref);
break;
}
}
private void specialCase(final Context context) {
/*
* Any special case code here
*/
}
private void log(final Context context) {
if (logging) {
wfLog(context, APP_NAME, context
.getString(R.string.loading_settings));
int index;
for (String prefkey : prefsList) {
index = prefsList.indexOf(prefkey);
if (keyVals[index])
wfLog(context, APP_NAME, prefkey);
}
}
}
public boolean getFlag(final int ikey) {
return keyVals[ikey];
}
public void setFlag(final int iKey, final boolean flag) {
keyVals[iKey] = flag;
}
};
/*
* Handler for rMain tick and other runnables
*/
private Handler hMain = new Handler() {
@Override
public void handleMessage(Message message) {
switch (message.what) {
case MAIN:
hMain.post(rMain);
break;
case REPAIR:
hMain.post(rRepair);
break;
case RECONNECT:
hMain.post(rReconnect);
break;
case WIFITASK:
hMain.post(rWifiTask);
break;
case TEMPLOCK_ON:
templock = true;
if (logging)
wfLog(getBaseContext(), APP_NAME,
getString(R.string.setting_temp_lock));
break;
case TEMPLOCK_OFF:
templock = false;
if (logging)
wfLog(getBaseContext(), APP_NAME,
getString(R.string.removing_temp_lock));
break;
case WIFI_OFF:
hMain.post(rWifiOff);
break;
case WIFI_ON:
hMain.post(rWifiOn);
break;
case SLEEPCHECK:
hMain.post(rSleepcheck);
break;
+
+ case N1FIX:
+ hMain.post(rN1fix);
+ break;
}
}
};
/*
* Runs second time supplicant nonresponsive
*/
private Runnable rRepair = new Runnable() {
public void run() {
if (!getIsWifiEnabled()) {
hMainWrapper(TEMPLOCK_OFF);
if (logging)
wfLog(getBaseContext(), APP_NAME,
getString(R.string.wifi_off_aborting_repair));
return;
}
if (isKnownAPinRange()) {
if (connectToAP(lastnid, true)
&& (getNetworkID(getBaseContext()) != HTTP_NULL)) {
pendingreconnect = false;
if (logging)
wfLog(getBaseContext(), APP_NAME,
getString(R.string.connected_to_network)
+ getNetworkID(getBaseContext()));
} else {
pendingreconnect = true;
toggleWifi();
if (logging)
wfLog(getBaseContext(), APP_NAME,
getString(R.string.toggling_wifi));
}
} else
hMainWrapper(TEMPLOCK_OFF);
}
};
/*
* Runs first time supplicant nonresponsive
*/
private Runnable rReconnect = new Runnable() {
public void run() {
if (!getIsWifiEnabled()) {
hMainWrapper(TEMPLOCK_OFF);
if (logging)
wfLog(getBaseContext(), APP_NAME,
getString(R.string.wifi_off_aborting_reconnect));
return;
}
if (isKnownAPinRange() && connectToAP(lastnid, true)
&& (getNetworkID(getBaseContext()) != HTTP_NULL)) {
pendingreconnect = false;
if (logging)
wfLog(getBaseContext(), APP_NAME,
getString(R.string.connected_to_network)
+ getNetworkID(getBaseContext()));
} else {
wifirepair = W_REASSOCIATE;
pendingscan = true;
startScan();
if (logging)
wfLog(
getBaseContext(),
APP_NAME,
getString(R.string.exiting_supplicant_fix_thread_starting_scan));
}
}
};
/*
* Main tick
*/
private Runnable rMain = new Runnable() {
public void run() {
// Queue next run of main runnable
hMainWrapper(MAIN, LOOPWAIT);
// Watchdog
if (!getIsWifiEnabled())
checkWifiState();
// Check Supplicant
if (!wm.pingSupplicant() && getIsWifiEnabled()) {
if (logging)
wfLog(
getBaseContext(),
APP_NAME,
getString(R.string.supplicant_nonresponsive_toggling_wifi));
toggleWifi();
} else if (!templock && !screenisoff)
fixWifi();
if (prefschanged)
checkLock(lock);
if (!shouldrun) {
if (logging) {
wfLog(getBaseContext(), APP_NAME,
getString(R.string.shouldrun_false_dying));
}
// Cleanup
cleanup();
}
}
};
/*
* Handles non-supplicant wifi fixes.
*/
private Runnable rWifiTask = new Runnable() {
public void run() {
switch (wifirepair) {
case W_REASSOCIATE:
// Let's try to reassociate first..
wm.reassociate();
if (logging)
wfLog(getBaseContext(), APP_NAME,
getString(R.string.reassociating));
tempLock(REACHABLE);
wifirepair++;
notifyWrap(getString(R.string.reassociating));
break;
case W_RECONNECT:
// Ok, now force reconnect..
wm.reconnect();
if (logging)
wfLog(getBaseContext(), APP_NAME,
getString(R.string.reconnecting));
tempLock(REACHABLE);
wifirepair++;
notifyWrap(getString(R.string.reconnecting));
break;
case W_REPAIR:
// Start Scan
pendingscan = true;
startScan();
wifirepair = W_REASSOCIATE;
if (logging)
wfLog(getBaseContext(), APP_NAME,
getString(R.string.repairing));
notifyWrap(getString(R.string.repairing));
break;
}
/*
* Remove wake lock if there is one
*/
wakeLock(getBaseContext(), false);
if (logging) {
wfLog(getBaseContext(), APP_NAME,
getString(R.string.fix_algorithm)
+ Integer.toString(wifirepair)
+ getString(R.string.lastnid)
+ Integer.toString(lastnid));
}
}
};
/*
* Turns off wifi
*/
private Runnable rWifiOff = new Runnable() {
public void run() {
wm.setWifiEnabled(false);
}
};
/*
* Turns on wifi
*/
private Runnable rWifiOn = new Runnable() {
public void run() {
wm.setWifiEnabled(true);
pendingwifitoggle = false;
wifishouldbeon = true;
wakeLock(getBaseContext(), false);
deleteNotification(NOTIFID);
}
};
/*
* Sleep tick if wifi is enabled and screenpref
*/
private Runnable rSleepcheck = new Runnable() {
public void run() {
/*
* This is all we want to do.
*/
fixWifi();
/*
* Post next run
*/
hMainWrapper(SLEEPCHECK, SLEEPWAIT);
}
};
/*
+ * N1 fix
+ */
+ private Runnable rN1fix = new Runnable() {
+ public void run() {
+ /*
+ * I think it's reassociating with a wake lock.
+ */
+ wm.reassociate();
+ wakeLock(getBaseContext(),false);
+ }
+
+ };
+
+ /*
* Handles intents we've registered for
*/
private BroadcastReceiver receiver = new BroadcastReceiver() {
public void onReceive(final Context context, final Intent intent) {
/*
* Dispatches the broadcast intent to the appropriate handler method
*/
String iAction = intent.getAction();
if ((iAction.equals(Intent.ACTION_SCREEN_ON))
|| (iAction.equals(Intent.ACTION_SCREEN_OFF)))
handleScreenAction(iAction);
else if (iAction.equals(WifiManager.WIFI_STATE_CHANGED_ACTION))
handleWifiState(intent);
else if (iAction
.equals(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION))
handleSupplicantIntent(intent);
else if (iAction.equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION))
handleWifiResults();
else if (iAction
.equals(android.net.ConnectivityManager.CONNECTIVITY_ACTION))
handleNetworkAction(getBaseContext());
else if (iAction.equals(FixerWidget.W_INTENT))
handleWidgetAction();
}
};
private void checkLock(WifiManager.WifiLock lock) {
if (!prefschanged) {
// Yeah, first run. Ok, if LOCKPREF true, acquire lock.
if (prefs.getFlag(lockpref)) {
lock.acquire();
haslock = true;
if (logging)
wfLog(this, APP_NAME,
getString(R.string.acquiring_wifi_lock));
}
} else {
// ok, this is when prefs have changed, soo..
prefschanged = false;
if (prefs.getFlag(lockpref) && haslock) {
// generate new lock
lock.acquire();
haslock = true;
if (logging)
wfLog(this, APP_NAME,
getString(R.string.acquiring_wifi_lock));
} else {
if (haslock && !prefs.getFlag(lockpref)) {
lock.release();
haslock = false;
if (logging)
wfLog(this, APP_NAME,
getString(R.string.releasing_wifi_lock));
}
}
}
}
private void cleanup() {
if (!cleanup) {
if (haslock && lock.isHeld())
lock.release();
unregisterReceiver(receiver);
hMain.removeMessages(MAIN);
cleanupPosts();
cleanup = true;
}
stopSelf();
}
private void cleanupPosts() {
hMain.removeMessages(RECONNECT);
hMain.removeMessages(REPAIR);
hMain.removeMessages(WIFITASK);
hMain.removeMessages(TEMPLOCK_ON);
}
private void clearQueue() {
hMain.removeMessages(RECONNECT);
hMain.removeMessages(REPAIR);
hMain.removeMessages(WIFITASK);
hMain.removeMessages(WIFI_OFF);
pendingscan = false;
pendingreconnect = false;
}
private static boolean checkNetwork(final Context context) {
boolean isup = false;
/*
* First check if wifi is current network
*/
if (!getIsOnWifi(context)) {
if (logging)
wfLog(context, APP_NAME, context
.getString(R.string.wifi_not_current_network));
return false;
}
/*
* Failover switch
*/
isup = icmpHostup(context);
if (!isup) {
isup = httpHostup(context);
if (isup)
wifirepair = W_REASSOCIATE;
} else
wifirepair = W_REASSOCIATE;
return isup;
}
private void checkWifiState() {
if (!getIsWifiEnabled() && wifishouldbeon) {
hMainWrapper(WIFI_ON);
}
}
private boolean connectToAP(int AP, boolean disableOthers) {
if (logging)
wfLog(this, APP_NAME, getString(R.string.connecting_to_network)
+ AP);
tempLock(CONNECTWAIT);
return wm.enableNetwork(AP, disableOthers);
}
private void deleteNotification(int id) {
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
nm.cancel(id);
}
private void fixWifi() {
if (getIsWifiEnabled(this, true)) {
if (getSupplicantState() == SupplicantState.ASSOCIATED
|| getSupplicantState() == SupplicantState.COMPLETED) {
if (!checkNetwork(this)) {
wifiRepair();
}
} else {
pendingscan = true;
tempLock(CONNECTWAIT);
}
}
}
private static boolean getHttpHeaders(final Context context)
throws IOException, URISyntaxException {
// Turns out the old way was better
// I just wasn't doing it right.
boolean isup = false;
int status = HTTP_NULL;
/*
* Reusing our Httpclient, only initializing first time
*/
if (httpclient == null) {
httpclient = new DefaultHttpClient();
headURI = new URI(H_TARGET);
head = new HttpHead(headURI);
httpparams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpparams, HTTPREACH);
HttpConnectionParams.setSoTimeout(httpparams, HTTPREACH);
HttpConnectionParams.setLinger(httpparams, REPAIR);
HttpConnectionParams.setStaleCheckingEnabled(httpparams, true);
httpclient.setParams(httpparams);
}
/*
* The next two lines actually perform the connection since it's the
* same, can re-use.
*/
response = httpclient.execute(head);
status = response.getStatusLine().getStatusCode();
if (status != HTTP_NULL)
isup = true;
if (logging) {
wfLog(context, APP_NAME, context.getString(R.string.http_status)
+ status);
}
return isup;
}
private static boolean getIsOnWifi(final Context context) {
boolean wifi = false;
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (cm.getActiveNetworkInfo() != null
&& cm.getActiveNetworkInfo().getType() == ConnectivityManager.TYPE_WIFI)
wifi = true;
return wifi;
}
private static boolean getIsWifiEnabled() {
boolean enabled = false;
if (wm.isWifiEnabled()) {
enabled = true;
} else {
/*
* it's false
*/
}
return enabled;
}
private static boolean getIsWifiEnabled(final Context context,
final boolean log) {
boolean enabled = false;
if (wm.isWifiEnabled()) {
if (logging)
wfLog(context, APP_NAME, context
.getString(R.string.wifi_is_enabled));
enabled = true;
} else {
if (logging && log)
wfLog(context, APP_NAME, context
.getString(R.string.wifi_is_disabled));
}
return enabled;
}
private static int getNetworkID(final Context context) {
WifiManager wm = getWifiManager(context);
myWifi = wm.getConnectionInfo();
int id = myWifi.getNetworkId();
if (id != HTTP_NULL) {
WifiFixerService.lastnid = id;
lastssid = myWifi.getSSID();
}
return id;
}
private void getPackageInfo() {
PackageManager pm = getPackageManager();
try {
// ---get the package info---
PackageInfo pi = pm.getPackageInfo(getString(R.string.packagename),
0);
// ---display the versioncode--
version = pi.versionCode;
} catch (NameNotFoundException e) {
/*
* If own package isn't found, something is horribly wrong.
*/
}
}
private static SupplicantState getSupplicantState() {
myWifi = wm.getConnectionInfo();
return myWifi.getSupplicantState();
}
private static WifiManager getWifiManager(final Context context) {
return (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
}
private void handleAuth(final Intent intent) {
if (intent.getStringExtra(AUTHEXTRA).contains(AUTHSTRING)) {
if (logging)
wfLog(this, APP_NAME, getString(R.string.authed));
// Ok, do the auth
settings = PreferenceManager.getDefaultSharedPreferences(this);
boolean IS_AUTHED = settings.getBoolean(
getString(R.string.isauthed), false);
if (!IS_AUTHED) {
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean(getString(R.string.isauthed), true);
editor.commit();
showNotification(getString(R.string.donatethanks),
getString(R.string.authorized), true);
}
}
}
private static void handleNetworkAction(final Context context) {
/*
* This action means network connectivty has changed but, we only want
* to run this code for wifi
*/
if (!getIsWifiEnabled() || !getIsOnWifi(context))
return;
icmpCache(context);
}
private void handleScreenAction(final String iAction) {
if (iAction.equals(Intent.ACTION_SCREEN_OFF)) {
screenisoff = true;
sleepCheck(true);
if (logging) {
wfLog(this, APP_NAME, getString(R.string.screen_off_handler));
if (!prefs.getFlag(screenpref))
wfLog(this, LogService.SCREEN_OFF, null);
}
} else {
if (logging) {
wfLog(this, APP_NAME, getString(R.string.screen_on_handler));
if (!prefs.getFlag(screenpref))
wfLog(this, LogService.SCREEN_ON, null);
}
screenisoff = false;
sleepCheck(false);
}
}
private void handleStart(final Intent intent) {
/*
* Handle null intent: might be from widget or from Android
*/
try {
if (intent.hasExtra(ServiceAlarm.ALARM)) {
if (intent.getBooleanExtra(ServiceAlarm.ALARM, false)) {
if (logging)
wfLog(this, APP_NAME, getString(R.string.alarm_intent));
}
} else {
String iAction = intent.getAction();
/*
* AUTH from donate service
*/
if (iAction.contains(AUTH)) {
handleAuth(intent);
return;
} else {
prefs.loadPrefs(this);
prefschanged = true;
if (logging)
wfLog(this, APP_NAME,
getString(R.string.normal_startup_or_reload));
}
}
} catch (NullPointerException e) {
if (logging) {
wfLog(this, APP_NAME, getString(R.string.tickled));
}
}
}
private void handleSupplicantIntent(final Intent intent) {
/*
* Get Supplicant New State
*/
String sState = intent.getParcelableExtra(WifiManager.EXTRA_NEW_STATE)
.toString();
/*
* Flush queue if connected
*
* Also clear any error notifications
*/
if (sState == COMPLETED) {
clearQueue();
notifCancel(ERR_NOTIF, this);
pendingscan = false;
pendingreconnect = false;
return;
}
/*
* New setting disabling supplicant fixes
*/
if (prefs.getFlag(supfixpref))
return;
/*
* The actual meat of the supplicant fixes
*/
handleSupplicantState(sState);
}
private void handleSupplicantState(final String sState) {
/*
* Dispatches appropriate supplicant fix
*/
if (!getIsWifiEnabled()) {
return;
} else if (screenisoff && !prefs.getFlag(screenpref))
return;
else if (sState == SCANNING) {
pendingscan = true;
} else if (sState == DISCONNECTED) {
pendingscan = true;
startScan();
notifyWrap(sState);
} else if (sState == INACTIVE) {
supplicantFix(true);
notifyWrap(sState);
}
if (logging && !screenisoff)
logSupplicant(sState);
}
private void handleWidgetAction() {
if (logging)
wfLog(this, APP_NAME, getString(R.string.widgetaction));
/*
* Handle widget action
*/
if (getIsWifiEnabled()) {
if (prefs.getFlag(widgetpref)) {
Toast.makeText(WifiFixerService.this,
getString(R.string.toggling_wifi), Toast.LENGTH_LONG)
.show();
toggleWifi();
} else {
Toast.makeText(WifiFixerService.this,
getString(R.string.reassociating), Toast.LENGTH_LONG)
.show();
wifirepair = W_REASSOCIATE;
wifiRepair();
}
} else
Toast.makeText(WifiFixerService.this,
getString(R.string.wifi_is_disabled), Toast.LENGTH_LONG)
.show();
}
private void handleWifiResults() {
hMainWrapper(TEMPLOCK_OFF);
if (!getIsWifiEnabled())
return;
if (!pendingscan) {
if (logging)
wfLog(this, APP_NAME, getString(R.string.nopendingscan));
return;
}
if (!pendingreconnect) {
pendingscan = false;
hMainWrapper(REPAIR);
if (logging)
wfLog(this, APP_NAME, getString(R.string.repairhandler));
} else {
pendingscan = false;
hMainWrapper(RECONNECT);
if (logging)
wfLog(this, APP_NAME, getString(R.string.reconnecthandler));
}
}
private void handleWifiState(final Intent intent) {
// What kind of state change is it?
int state = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE,
WifiManager.WIFI_STATE_UNKNOWN);
switch (state) {
case WifiManager.WIFI_STATE_ENABLED:
if (logging)
wfLog(this, APP_NAME, getString(R.string.wifi_state_enabled));
hMainWrapper(TEMPLOCK_OFF, LOCKWAIT);
wifishouldbeon = false;
break;
case WifiManager.WIFI_STATE_ENABLING:
if (logging)
wfLog(this, APP_NAME, getString(R.string.wifi_state_enabling));
break;
case WifiManager.WIFI_STATE_DISABLED:
if (logging)
wfLog(this, APP_NAME, getString(R.string.wifi_state_disabled));
hMainWrapper(TEMPLOCK_ON);
break;
case WifiManager.WIFI_STATE_DISABLING:
if (logging)
wfLog(this, APP_NAME, getString(R.string.wifi_state_disabling));
break;
case WifiManager.WIFI_STATE_UNKNOWN:
if (logging)
wfLog(this, APP_NAME, getString(R.string.wifi_state_unknown));
break;
}
}
/*
* Controlling all possible sources of race
*/
private boolean hMainWrapper(final int hmain) {
if (hMainCheck(hmain)) {
hMain.removeMessages(hmain);
return hMain.sendEmptyMessage(hmain);
} else {
hMain.removeMessages(hmain);
return hMain.sendEmptyMessageDelayed(hmain, REACHABLE);
}
}
private boolean hMainWrapper(final int hmain, final long delay) {
if (hMainCheck(hmain)) {
hMain.removeMessages(hmain);
return hMain.sendEmptyMessageDelayed(hmain, delay);
} else {
hMain.removeMessages(hmain);
return hMain.sendEmptyMessageDelayed(hmain, delay + REACHABLE);
}
}
private static boolean hMainCheck(final int hmain) {
if (templock) {
/*
* Check if is appropriate post and if lock exists
*/
if (hmain == RECONNECT || hmain == REPAIR || hmain == WIFITASK)
return false;
}
return true;
}
private static boolean httpHostup(final Context context) {
boolean isUp = false;
/*
* getHttpHeaders() does all the heavy lifting
*/
try {
isUp = getHttpHeaders(context);
} catch (IOException e) {
try {
/*
* Second try
*/
isUp = getHttpHeaders(context);
} catch (IOException e1) {
if (logging)
wfLog(context, APP_NAME, context
.getString(R.string.httpexception));
} catch (URISyntaxException e1) {
if (logging)
wfLog(context, APP_NAME, context
.getString(R.string.http_method));
}
} catch (URISyntaxException e) {
if (logging)
wfLog(context, APP_NAME, context
.getString(R.string.urlexception));
}
if (logging)
wfLog(context, APP_NAME, context.getString(R.string.http_method));
return isUp;
}
private static boolean icmpHostup(final Context context) {
boolean isUp = false;
/*
* If IP hasn't been cached yet cache it
*/
if (cachedIP == null)
icmpCache(context);
try {
if (InetAddress.getByName(cachedIP).isReachable(REACHABLE)) {
isUp = true;
if (logging)
wfLog(context, APP_NAME, context
.getString(R.string.icmp_success));
}
} catch (UnknownHostException e) {
if (logging)
wfLog(context, APP_NAME, context
.getString(R.string.unknownhostexception));
} catch (IOException e) {
if (logging)
wfLog(context, APP_NAME, context
.getString(R.string.ioexception));
}
if (logging)
wfLog(context, APP_NAME, context.getString(R.string.icmp_method)
+ cachedIP);
return isUp;
}
private static void icmpCache(final Context context) {
/*
* Caches DHCP gateway IP for ICMP check
*/
DhcpInfo info = wm.getDhcpInfo();
cachedIP = intToIp(info.gateway);
if (logging)
wfLog(context, APP_NAME, context.getString(R.string.cached_ip)
+ cachedIP);
}
private static String intToIp(final int i) {
return Formatter.formatIpAddress(i);
}
private boolean isKnownAPinRange() {
boolean state = false;
;
;
final List<ScanResult> wifiList = wm.getScanResults();
/*
* Catch null if scan results fires after wifi disabled or while wifi is
* in intermediate state
*/
if (wifiList == null) {
if (logging)
wfLog(this, APP_NAME, getString(R.string.null_scan_results));
return false;
}
/*
* wifiConfigs is just a reference to known networks.
*/
final List<WifiConfiguration> wifiConfigs = wm.getConfiguredNetworks();
/*
* Iterate the known networks over the scan results, adding found known
* networks.
*/
int best_id = HTTP_NULL;
int best_signal = DBM_DEFAULT;
String best_ssid = EMPTYSTRING;
if (logging)
wfLog(this, APP_NAME, getString(R.string.parsing_scan_results));
for (ScanResult sResult : wifiList) {
for (WifiConfiguration wfResult : wifiConfigs) {
/*
* Using .contains to find sResult.SSID in doublequoted string
*/
if (wfResult.SSID.contains(sResult.SSID)) {
if (logging) {
wfLog(this, APP_NAME, getString(R.string.found_ssid)
+ sResult.SSID);
wfLog(this, APP_NAME, getString(R.string.capabilities)
+ sResult.capabilities);
wfLog(this, APP_NAME, getString(R.string.signal_level)
+ sResult.level);
}
/*
* Comparing and storing best signal level
*/
if (sResult.level > best_signal) {
best_id = wfResult.networkId;
best_signal = sResult.level;
best_ssid = sResult.SSID;
}
state = true;
}
}
}
/*
* Set lastnid and lastssid to known network with highest level from
* scanresults
*
* if !state nothing was found
*/
if (state) {
lastnid = best_id;
lastssid = best_ssid;
if (logging)
wfLog(this, APP_NAME, getString(R.string.best_signal_ssid)
+ best_ssid + getString(R.string.signal_level)
+ best_signal);
} else {
if (logging)
wfLog(this, APP_NAME,
getString(R.string.no_known_networks_found));
}
return state;
}
private void logSupplicant(final String state) {
wfLog(this, APP_NAME, getString(R.string.supplicant_state) + state);
if (wm.pingSupplicant()) {
wfLog(this, APP_NAME, getString(R.string.supplicant_responded));
} else {
wfLog(this, APP_NAME, getString(R.string.supplicant_nonresponsive));
}
if (lastssid.length() < 2)
getNetworkID(getBaseContext());
wfLog(this, APP_NAME, getString(R.string.ssid) + lastssid);
}
private void notifyWrap(final String message) {
if (prefs.getFlag(notifpref)) {
showNotification(getString(R.string.wifi_connection_problem)
+ message, message, ERR_NOTIF);
}
}
private static void notifCancel(final int notif, final Context context) {
NotificationManager nm = (NotificationManager) context
.getSystemService(NOTIFICATION_SERVICE);
nm.cancel(notif);
}
@Override
public IBinder onBind(Intent intent) {
if (logging)
wfLog(this, APP_NAME, getString(R.string.onbind_intent)
+ intent.toString());
return null;
}
@Override
public void onCreate() {
wm = getWifiManager(this);
getPackageInfo();
if (logging) {
wfLog(this, APP_NAME, getString(R.string.wififixerservice_build)
+ version);
}
/*
* Seeing if this is more efficient
*/
prefs.loadPrefs(this);
// Setup, formerly in Run thread
setup();
hMain.sendEmptyMessage(MAIN);
refreshWidget(this);
if (logging)
wfLog(this, APP_NAME, getString(R.string.oncreate));
}
@Override
public void onDestroy() {
super.onDestroy();
cleanup();
}
@Override
public void onStart(Intent intent, int startId) {
handleStart(intent);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
handleStart(intent);
return START_STICKY;
}
private static void refreshWidget(final Context context) {
Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
int[] widgetids = { 0, 1, 2 };
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, widgetids);
intent.setClass(context, FixerWidget.class);
context.sendBroadcast(intent);
}
private void setup() {
// WIFI_MODE_FULL should p. much always be used
lock = wm.createWifiLock(WifiManager.WIFI_MODE_FULL, WFLOCK_TAG);
checkLock(lock);
/*
* Create filter, add intents we're looking for.
*/
IntentFilter myFilter = new IntentFilter();
// Wifi State filter
myFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
// Catch power events for battery savings
myFilter.addAction(Intent.ACTION_SCREEN_OFF);
myFilter.addAction(Intent.ACTION_SCREEN_ON);
// Supplicant State filter
myFilter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION);
// Network State filter
myFilter.addAction(android.net.ConnectivityManager.CONNECTIVITY_ACTION);
// wifi scan results available callback
myFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
// Widget Action
myFilter.addAction(FixerWidget.W_INTENT);
registerReceiver(receiver, myFilter);
}
private void sleepCheck(final boolean state) {
if (state && prefs.getFlag(screenpref) && getIsWifiEnabled()) {
/*
* Start sleep check
*/
hMainWrapper(SLEEPCHECK, SLEEPWAIT);
/*
- * Tentative N1 sleep fix
+ * N1 sleep fix take 2
*/
- wakeLock(this, true);
- wakeLock(this, false);
+ wakeLock(this, true);
+ hMainWrapper(N1FIX,REACHABLE);
+
} else {
/*
* Screen is on, remove any posts
*/
hMain.removeMessages(SLEEPCHECK);
}
}
private void showNotification(final String message,
final String tickerText, final boolean bSpecial) {
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
CharSequence from = getText(R.string.app_name);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(), 0);
if (bSpecial) {
contentIntent = PendingIntent.getActivity(this, 0, new Intent(
android.provider.Settings.ACTION_WIFI_SETTINGS), 0);
}
Notification notif = new Notification(R.drawable.icon, tickerText,
System.currentTimeMillis());
notif.setLatestEventInfo(this, from, message, contentIntent);
notif.flags = Notification.FLAG_AUTO_CANCEL;
// unique ID
nm.notify(4144, notif);
}
private void showNotification(final String message,
final String tickerText, final int id) {
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
CharSequence from = getText(R.string.app_name);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(), 0);
Notification notif = new Notification(R.drawable.icon, tickerText,
System.currentTimeMillis());
notif.setLatestEventInfo(this, from, message, contentIntent);
notif.flags = Notification.FLAG_AUTO_CANCEL;
// unique ID
nm.notify(id, notif);
}
private void startScan() {
// We want a lock after a scan
wm.startScan();
tempLock(LOCKWAIT);
}
private void supplicantFix(final boolean wftoggle) {
// Toggling wifi fixes the supplicant
pendingscan = true;
if (wftoggle)
toggleWifi();
startScan();
if (logging)
wfLog(this, APP_NAME, getString(R.string.running_supplicant_fix));
}
private void tempLock(final int time) {
hMainWrapper(TEMPLOCK_ON);
// Queue for later
hMainWrapper(TEMPLOCK_OFF, time);
}
private void toggleWifi() {
if (pendingwifitoggle)
return;
pendingwifitoggle = true;
cleanupPosts();
tempLock(CONNECTWAIT);
// Wake lock
wakeLock(this, true);
showNotification(getString(R.string.toggling_wifi),
getString(R.string.toggling_wifi), NOTIFID);
hMainWrapper(WIFI_OFF);
hMainWrapper(WIFI_ON, LOCKWAIT);
}
private static void wakeLock(final Context context, final boolean state) {
PowerManager pm = (PowerManager) context
.getSystemService(Context.POWER_SERVICE);
if (wakelock == null)
wakelock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
WFWAKELOCK);
if (state && !wakelock.isHeld()) {
wakelock.acquire();
if (logging)
wfLog(context, APP_NAME, context
.getString(R.string.acquiring_wake_lock));
} else if (wakelock.isHeld()) {
wakelock.release();
if (logging)
wfLog(context, APP_NAME, context
.getString(R.string.releasing_wake_lock));
}
}
private void wifiRepair() {
/*
* Queue rWifiTask runnable
*/
if (!screenisoff) {
hMainWrapper(WIFITASK);
if (logging)
wfLog(this, APP_NAME, getString(R.string.running_wifi_repair));
} else {
/*
* if screen off, try wake lock then resubmit to handler
*/
wakeLock(this, true);
hMainWrapper(WIFITASK, REACHABLE);
if (logging)
wfLog(this, APP_NAME,
getString(R.string.wifi_repair_post_failed));
}
}
private static void wfLog(final Context context, final String APP_NAME,
final String Message) {
Intent sendIntent = new Intent(LOGINTENT);
sendIntent.putExtra(LogService.APPNAME, APP_NAME);
sendIntent.putExtra(LogService.Message, Message);
context.startService(sendIntent);
}
}
| false | false | null | null |
diff --git a/src/edu/pdx/cawhite/math/Matrix.java b/src/edu/pdx/cawhite/math/Matrix.java
index 57768a5..7195679 100644
--- a/src/edu/pdx/cawhite/math/Matrix.java
+++ b/src/edu/pdx/cawhite/math/Matrix.java
@@ -1,464 +1,464 @@
/* Copyright (C) 2013, Cameron White
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the project nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
package edu.pdx.cawhite.math;
import edu.pdx.cawhite.math.Vector;
import edu.pdx.cawhite.iterators.BidirectionalIterator;
import edu.pdx.cawhite.iterators.IteratorException;
/**
* Abstract mathematical matrix.
*
* A matrix has a fixed number of rows and columns. Once created
* the number of rows and columns can not change.
*
* @author Cameron Brandon White
*/
public abstract class Matrix {
protected double[][] components;
public abstract Matrix.Iterator getIterator();
public abstract int getNumberOfRows();
public abstract int getNumberOfColumns();
/**
* Get the number of Vectors in the Matrix.
*
* @return The number of vectors in the Matrix.
*/
public int getNumberOfVectors() {
return this.components.length;
}
/**
* Get the Vector at the given index.
*
* @return The specified Vector
*/
public Vector getVector(int index) {
Vector vector = null;
try {
vector = new Vector(components[index]);
} catch (ArrayIndexOutOfBoundsException e) {
throw new IndexOutOfBoundsException();
} catch (LengthException e) {
assert false : "Fatal Programming Error";
}
return vector;
}
/**
* Get the array of components in the matrix.
*
* @return The matrix's components
*/
public double[][] getComponents() {
return this.components;
}
/**
* Set the components in the matrix
*
* @param components The new components
*/
public void setComponents(double[][] components) {
this.components = components;
}
/**
* Set the vector at the given index.
*
* The contents of the vector are copied into the matrix.
*
* @param index The index to put the new vector
* @param newVector The new vector
*/
public void setVector(int index, Vector newVector)
throws IndexOutOfBoundsException, LengthException {
Vector currentVector = this.getVector(index);
currentVector.copy(newVector);
}
/**
* Add this matrix with the other in a new matrix
*
* @param other The other matrix
* @return The new matrix.
*/
protected Matrix add(Matrix other, Matrix newMatrix)
throws MatrixSizeException {
return matrixOperation(other, newMatrix, new VectorOperation() {
public Vector operation(Vector a, Vector b, Vector c)
throws MatrixSizeException {
try {
return a.add(b, c);
} catch (LengthException e) {
throw new MatrixSizeException();
}
}
});
}
/**
* Add this matrix with the other in place.
*
* @param other The other matrix.
* @return This matrix modified.
*/
protected Matrix iadd(Matrix other) throws MatrixSizeException {
return iMatrixOperation(other, new IVectorOperation() {
public Vector operation(Vector a, Vector b)
throws MatrixSizeException {
try {
return a.iadd(b);
} catch (LengthException e) {
throw new MatrixSizeException();
}
}
});
}
/**
* Subtract this matrix from the other in place.
*
* @param other The other matrix.
* @return This matrix modified.
*/
protected Matrix isub(Matrix other) throws MatrixSizeException {
return iMatrixOperation(other, new IVectorOperation() {
public Vector operation(Vector a, Vector b)
throws MatrixSizeException {
try {
return a.isub(b);
} catch (LengthException e) {
throw new MatrixSizeException();
}
}
});
}
/**
* Multiply this matrix by the scalar in place.
*
* @param scalar The scalar to multiply by.
* @return This vector modified.
*/
protected Matrix imul(Double scalar) {
Iterator iterator = this.getIterator();
while (true) {
try {
Vector vector = iterator.get();
vector.imul(scalar);
iterator.next();
} catch (IteratorException e) {
break;
}
}
return this;
}
/**
* Operation preformed this matrix and another in place.
*/
protected Matrix iMatrixOperation(
Matrix other, IVectorOperation vectorOperation)
throws MatrixSizeException {
Iterator thisIterator = this.getIterator();
Iterator otherIterator = other.getIterator();
while (true) {
try {
Vector thisVector = thisIterator.get();
Vector otherVector = otherIterator.get();
vectorOperation.operation(thisVector, otherVector);
thisIterator.next();
otherIterator.next();
} catch (IteratorException e) {
break;
}
}
return this;
}
/**
* Multiply this matrix by the other Matrix in a new matrix
*
* @param other The other matrix.
* @return The new matrix.
*/
public Vector mul(Vector vector, Vector newVector)
throws LengthException {
Matrix.Iterator matrixIterator = this.getIterator();
Vector.Iterator vectorIterator = newVector.getIterator();
while (true) {
try {
Vector matrixVector = matrixIterator.get();
vectorIterator.set(matrixVector.dot(vector));
matrixIterator.next();
vectorIterator.next();
} catch (IteratorException e) {
break;
}
}
return newVector;
}
/**
* Multiply this matrix by the other Matrix in a new matrix
*
* @param other The other matrix.
* @return The new matrix.
*/
public Vector mul(Vector vector) throws LengthException {
Vector newVector = new Vector(vector.getLength());
return mul(vector, newVector);
}
/**
* Multiply this matrix by the scalar in a new matrix.
*
* @param scalar The scalar to multiply by.
* @return The new matrix.
*/
protected Matrix mul(Double scalar, Matrix newMatrix) {
Matrix.Iterator thisIterator = this.getIterator();
Matrix.Iterator newIterator = newMatrix.getIterator();
while (true) {
try {
Vector thisVector = thisIterator.get();
Vector newVector = newIterator.get();
thisVector.mul(scalar, newVector);
thisIterator.next();
newIterator.next();
} catch (IteratorException e) {
break;
}
}
return newMatrix;
}
/**
* Multiply this matrix by the other Matrix in a new matrix
*
* @param other The other matrix.
* @return The new matrix.
*/
protected Matrix mul(Matrix other, Matrix newMatrix)
throws MatrixSizeException {
Matrix.Iterator otherIterator = other.getIterator();
Matrix.Iterator newIterator = newMatrix.getIterator();
while (true) {
try {
Vector newVector = newIterator.get();
Vector otherVector = otherIterator.get();
mul(otherVector, newVector);
otherIterator.next();
newIterator.next();
} catch (IteratorException e) {
break;
} catch (LengthException e) {
throw new MatrixSizeException();
}
}
return newMatrix;
}
/**
* Operation proformed on this matrix and another.
*/
protected Matrix matrixOperation(
Matrix other, Matrix newMatrix,
VectorOperation vectorOperation)
throws MatrixSizeException {
Matrix.Iterator thisIterator = this.getIterator();
Matrix.Iterator otherIterator = other.getIterator();
Matrix.Iterator newIterator = newMatrix.getIterator();
while (true) {
try {
Vector thisVector = thisIterator.get();
Vector otherVector = otherIterator.get();
Vector newVector = newIterator.get();
vectorOperation.operation(thisVector, otherVector, newVector);
thisIterator.next();
otherIterator.next();
newIterator.next();
} catch (IteratorException e) {
break;
}
}
return newMatrix;
}
/**
* Subtract this matrix from the other in a new matrix.
*
* @param other The other matrix
* @return The new matrix.
*/
protected Matrix sub(Matrix other, Matrix newMatrix)
throws MatrixSizeException {
return matrixOperation(other, newMatrix, new VectorOperation() {
public Vector operation(Vector a, Vector b, Vector c)
throws MatrixSizeException {
try {
return a.sub(b, c);
} catch (LengthException e) {
throw new MatrixSizeException();
}
}
});
}
public interface IVectorOperation {
Vector operation(Vector a, Vector b) throws MatrixSizeException;
}
public interface VectorOperation {
Vector operation(Vector a, Vector b, Vector c) throws MatrixSizeException;
}
/**
* Iterator for the Matrix class
*/
- public abstract class Iterator extends BidirectionalIterator {
+ public class Iterator extends BidirectionalIterator {
protected int index;
/**
* Construct the iteractor to reference the first row in the
* matrix.
*/
public Iterator() {
this.index = 0;
}
/**
* Get the Vector referenced by the iterator
*/
public Vector get() throws IteratorException {
try {
return Matrix.this.getVector(index);
} catch (IndexOutOfBoundsException e) {
throw new IteratorException();
}
}
/**
* Set the Vector referenced by the iterator to the
* Vector specified by value.
*
* The vector specified by value is copied to the
* vector referenced by the iterator.
*
* @param value The new Vector
*/
public void set(Vector value)
throws IteratorException, LengthException {
try {
Matrix.this.setVector(index, value);
} catch (IndexOutOfBoundsException e) {
throw new IteratorException();
}
}
/**
* Reference the next vector in the matrix
*
* @throws IteratorException Thrown when the vector
* has no next element.
*/
public void next() throws IteratorException {
if (index >= getNumberOfRows() - 1)
throw new IteratorException();
index++;
}
/**
* Reference the previous vector in the matrix
*
* @throws IteratorException Thrown when the vector
* has no previous element.
*/
public void previous() throws IteratorException {
if (index <= 0)
throw new IteratorException();
index--;
}
/**
* Restart the iterator to reference the first vector
*/
public void restart() {
index = 0;
}
}
}
diff --git a/src/edu/pdx/cawhite/math/RowMatrix.java b/src/edu/pdx/cawhite/math/RowMatrix.java
index 6d2b230..a374aaf 100644
--- a/src/edu/pdx/cawhite/math/RowMatrix.java
+++ b/src/edu/pdx/cawhite/math/RowMatrix.java
@@ -1,228 +1,227 @@
/* Copyright (C) 2013, Cameron White
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the project nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
package edu.pdx.cawhite.math;
import edu.pdx.cawhite.iterators.IteratorException;
-import edu.pdx.cawhite.math.ColumnMatrix.Iterator;
/**
* Implements a mathematical row matrix
*
* A row matrix is a matrix that contains a list of
* row Vectors. The importance in difference between
* RowMatrix and ColumnMatrix is that certain matrix
* operations are optimized by the use of one of the
* other.
*
* @author Cameron Brandon White
*/
public class RowMatrix extends Matrix {
/**
* Construct a RowMatrix with the given components
*/
public RowMatrix(double[][] components) {
super();
this.components = components;
}
/**
* Create a matrix with the given number of rows and columns
*
* @param numberOfRows The number of rows the new matrix should have.
* @param numberOfCols The number of columns the new matrix should have.
*/
public RowMatrix(int numberOfRows, int numberOfColumns) {
super();
this.components = new double[numberOfRows][numberOfColumns];
}
/**
* Get the item at the given position.
*
* @param rowIndex The row index.
* @param columnIndex The column index.
* @return The item at the given position.
*/
public Double get(int rowIndex, int columnIndex) {
return this.components[rowIndex][columnIndex];
}
/**
* Get the iterator for the matrix.
*/
public Iterator getIterator() {
return this.new Iterator();
}
/**
* Get the number of rows the matrix has.
*
* @return the number of rows in the matrix
*/
public int getNumberOfRows() {
return this.components.length;
}
/**
* Get the number of columns the matrix has.
*
* @return The number of columns in the matrix.
*/
public int getNumberOfColumns() {
return this.components[0].length;
}
/**
* Set the item at the given position.
*
* @param rowIndex The row index.
* @param columnIndex The column index.
* @param item The new item.
*/
public void set(int rowIndex, int columnIndex, Double item) {
this.components[rowIndex][columnIndex] = item;
}
/**
* Add this matrix with the other in a new matrix
*
* @param other The other matrix
* @return The new matrix.
*/
public RowMatrix add(RowMatrix other)
throws MatrixSizeException {
RowMatrix newMatrix = new RowMatrix(getNumberOfRows(), getNumberOfColumns());
return (RowMatrix) super.add(other, newMatrix);
}
/**
* Add this matrix with the other in place.
*
* @param other The other matrix.
* @return This matrix modified.
*/
public RowMatrix iadd(RowMatrix other)
throws MatrixSizeException {
return (RowMatrix) super.iadd(other);
}
/**
* Subtract this matrix from the other in a new matrix.
*
* @param other The other matrix
* @return The new matrix.
*/
public RowMatrix sub(RowMatrix other)
throws MatrixSizeException {
RowMatrix newMatrix = new RowMatrix(getNumberOfRows(), getNumberOfColumns());
return (RowMatrix) super.sub(other, newMatrix);
}
/**
* Subtract this matrix from the other in place.
*
* @param other The other matrix.
* @return This matrix modified.
*/
public RowMatrix isub(RowMatrix other)
throws MatrixSizeException {
return (RowMatrix) super.isub(other);
}
/**
* Multiply this matrix by the scalar in a new matrix.
*
* @param scalar The scalar to multiply by.
* @return The new matrix.
*/
public RowMatrix mul(Double scalar) {
RowMatrix newMatrix = new RowMatrix(getNumberOfRows(),
getNumberOfColumns());
return (RowMatrix) mul(scalar, newMatrix);
}
/**
* Multiply this matrix by the scalar in place.
*
* @param scalar The scalar to multiply by.
* @return This vector modified.
*/
public RowMatrix imul(Double scalar) {
return (RowMatrix) super.imul(scalar);
}
/**
* Multiply this matrix by the other Matrix in a new matrix
*
* @param other The other matrix.
* @return The new matrix.
*/
public ColumnMatrix mul(ColumnMatrix other)
throws MatrixSizeException {
assert this.getNumberOfColumns() == other.getNumberOfRows();
ColumnMatrix newMatrix = new ColumnMatrix(getNumberOfRows(),
other.getNumberOfColumns());
return (ColumnMatrix) super.mul(other, newMatrix);
}
/**
* Operation preformed on this matrix and another.
*/
public RowMatrix matrixOperation(
RowMatrix other, VectorOperation vectorOperation)
throws MatrixSizeException {
RowMatrix newMatrix = new RowMatrix(getNumberOfRows(),
getNumberOfColumns());
return (RowMatrix) super.matrixOperation(other, newMatrix, vectorOperation);
}
/**
* Operation preformed on this matrix and another in-place.
*/
public RowMatrix iMatrixOperation(
RowMatrix other, IVectorOperation vectorOperation)
throws MatrixSizeException {
return (RowMatrix) super.iMatrixOperation(other, vectorOperation);
}
public void print() {
for(int i = 0; i < getNumberOfRows(); i++) {
for(int j = 0; j < getNumberOfColumns(); j++) {
System.out.print(this.get(i,j));
System.out.print(" ");
}
System.out.println();
}
}
}
\ No newline at end of file
| false | false | null | null |
diff --git a/policy/src/com/android/internal/policy/impl/HoneycombLockscreen.java b/policy/src/com/android/internal/policy/impl/HoneycombLockscreen.java
index 13916bdf..de5d6f58 100644
--- a/policy/src/com/android/internal/policy/impl/HoneycombLockscreen.java
+++ b/policy/src/com/android/internal/policy/impl/HoneycombLockscreen.java
@@ -1,1857 +1,1857 @@
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR 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.internal.policy.impl;
import com.android.internal.R;
import com.android.internal.telephony.IccCard;
import com.android.internal.telephony.TelephonyProperties;
import com.android.internal.widget.DigitalClock;
import com.android.internal.widget.FuzzyClock;
import com.android.internal.widget.KanjiClock;
import com.android.internal.widget.LockPatternUtils;
import com.android.internal.widget.UnlockRing;
import com.android.internal.widget.CircularSelector;
import com.android.internal.widget.SenseLikeLock;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.content.res.ColorStateList;
import android.database.Cursor;
import android.net.Uri;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.ColorFilter;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.BitmapDrawable;
import android.util.Log;
import android.media.AudioManager;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.ParcelFileDescriptor;
import android.os.SystemClock;
import android.os.SystemProperties;
import android.os.Vibrator;
import android.preference.MultiSelectListPreference;
import android.provider.Settings;
import android.provider.CmSystem.LockscreenStyle;
import android.provider.CallLog.Calls;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.PhoneLookup;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;
import android.content.ComponentName;
import android.telephony.TelephonyManager;
import java.util.ArrayList;
import java.util.List;
import java.util.Date;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
/**
* The screen within {@link LockPatternKeyguardView} that shows general
* information about the device depending on its state, and how to get past it,
* as applicable.
*/
class HoneycombLockscreen extends LinearLayout implements KeyguardScreen,
KeyguardUpdateMonitor.InfoCallback, KeyguardUpdateMonitor.SimStateCallback,
UnlockRing.OnTriggerListener, CircularSelector.OnCircularSelectorTriggerListener,
SenseLikeLock.OnSenseLikeSelectorTriggerListener {
private static final boolean DBG = false;
private static final String TAG = "Honeycomb";
private static final String ENABLE_MENU_KEY_FILE = "/data/local/enable_menu_key";
private static final Uri sArtworkUri = Uri.parse("content://media/external/audio/albumart");
private static final String SMS_CHANGED = "android.provider.Telephony.SMS_RECEIVED";
static final int CARRIER_TYPE_DEFAULT = 0;
static final int CARRIER_TYPE_SPN = 1;
static final int CARRIER_TYPE_PLMN = 2;
static final int CARRIER_TYPE_CUSTOM = 3;
private Status mStatus = Status.Normal;
private LockPatternUtils mLockPatternUtils;
private KeyguardUpdateMonitor mUpdateMonitor;
private KeyguardScreenCallback mCallback;
private TextView mCarrier;
private TextView mCusText;
private DigitalClock mClock;
private FuzzyClock mFuzzyClock;
private KanjiClock mKanjiClock;
private UnlockRing mSelector;
private CircularSelector mCircularSelector;
private SenseLikeLock mSenseRingSelector;
private TextView mDate;
private TextView mTime;
private TextView mAmPm;
private LinearLayout mStatusBox;
private TextView mStatusCharging;
private TextView mStatusAlarm;
private TextView mStatusCalendar;
private TextView mScreenLocked;
private TextView mEmergencyCallText;
private TextView mSmsCountView;
private TextView mMissedCallCountView;
private Button mEmergencyCallButton;
private ImageButton mPlayIcon;
private ImageButton mPauseIcon;
private ImageButton mRewindIcon;
private ImageButton mForwardIcon;
private ImageButton mAlbumArt;
private AudioManager am = (AudioManager)getContext().getSystemService(Context.AUDIO_SERVICE);
private boolean mWasMusicActive = am.isMusicActive();
private boolean mIsMusicActive = false;
private TextView mCustomMsg;
private TextView mNowPlaying;
// current configuration state of keyboard and display
private int mKeyboardHidden;
private int mCreationOrientation;
// are we showing battery information?
private boolean mShowingBatteryInfo = false;
// last known plugged in state
private boolean mPluggedIn = false;
// last known battery level
private int mBatteryLevel = 100;
private String mNextAlarm = null;
private String mNextCalendar = null;
private String mCharging = null;
private Drawable mChargingIcon = null;
private boolean mSilentMode;
private boolean mHideUnlockTab;
private AudioManager mAudioManager;
private String mDateFormatString;
private boolean mEnableMenuKeyInLockScreen;
private static final String TOGGLE_SILENT = "silent_mode";
private String mCustomAppName;
private Bitmap[] mCustomRingAppIcons = new Bitmap[4];
private static final String TOGGLE_FLASHLIGHT = "net.cactii.flash2.TOGGLE_FLASHLIGHT";
private boolean mTrackballUnlockScreen = (Settings.System.getInt(mContext.getContentResolver(),
Settings.System.TRACKBALL_UNLOCK_SCREEN, 0) == 1);
private boolean mMenuUnlockScreen = (Settings.System.getInt(mContext.getContentResolver(),
Settings.System.MENU_UNLOCK_SCREEN, 0) == 1);
private boolean mLockAlwaysBattery = (Settings.System.getInt(mContext.getContentResolver(),
Settings.System.LOCKSCREEN_ALWAYS_BATTERY, 0) == 1);
private int mClockColor = (Settings.System.getInt(mContext.getContentResolver(),
Settings.System.STATUS_BAR_LOCKSCREENCOLOR, 0xFF33B5E5)); // this value for color
private int mCarrierColor = (Settings.System.getInt(mContext.getContentResolver(),
Settings.System.STATUS_BAR_CARRIERCOLOR, 0xFF33B5E5)); // this value for color
private boolean mLockCalendarAlarm = (Settings.System.getInt(mContext.getContentResolver(),
Settings.System.LOCKSCREEN_CALENDAR_ALARM, 0) == 1);
private String[] mCalendars = MultiSelectListPreference.parseStoredValue(Settings.System.getString(
mContext.getContentResolver(), Settings.System.LOCKSCREEN_CALENDARS));
private boolean mLockCalendarRemindersOnly = (Settings.System.getInt(mContext.getContentResolver(),
Settings.System.LOCKSCREEN_CALENDAR_REMINDERS_ONLY, 0) == 1);
private long mLockCalendarLookahead = Settings.System.getLong(mContext.getContentResolver(),
Settings.System.LOCKSCREEN_CALENDAR_LOOKAHEAD, 10800000);
private boolean mLockMusicControls = (Settings.System.getInt(mContext.getContentResolver(),
Settings.System.LOCKSCREEN_MUSIC_CONTROLS, 0) == 1);
private boolean mNowPlayingToggle = (Settings.System.getInt(mContext.getContentResolver(),
Settings.System.LOCKSCREEN_NOW_PLAYING, 1) == 1);
private boolean mAlbumArtToggle = (Settings.System.getInt(mContext.getContentResolver(),
Settings.System.LOCKSCREEN_ALBUM_ART, 1) == 1);
private int mLockMusicHeadset = (Settings.System.getInt(mContext.getContentResolver(),
Settings.System.LOCKSCREEN_MUSIC_CONTROLS_HEADSET, 0));
private boolean useLockMusicHeadsetWired = ((mLockMusicHeadset == 1) || (mLockMusicHeadset == 3));
private boolean useLockMusicHeadsetBT = ((mLockMusicHeadset == 2) || (mLockMusicHeadset == 3));
private boolean mLockAlwaysMusic = (Settings.System.getInt(mContext.getContentResolver(),
Settings.System.LOCKSCREEN_ALWAYS_MUSIC_CONTROLS, 0) == 1);
private int mWidgetLayout = Settings.System.getInt(mContext.getContentResolver(),
Settings.System.LOCKSCREEN_WIDGETS_LAYOUT, 0);
private int mCarrierLabelType = (Settings.System.getInt(mContext.getContentResolver(),
Settings.System.CARRIER_LABEL_LOCKSCREEN_TYPE, CARRIER_TYPE_DEFAULT));
private String mCarrierLabelCustom = (Settings.System.getString(mContext.getContentResolver(),
Settings.System.CARRIER_LABEL_LOCKSCREEN_CUSTOM_STRING));
private String mCustomText = (Settings.System.getString(mContext.getContentResolver(),
Settings.System.CUSTOM_TEXT_STRING));
private boolean mCustomAppToggle = (Settings.System.getInt(mContext.getContentResolver(),
Settings.System.LOCKSCREEN_CUSTOM_APP_TOGGLE, 0) == 1);
private boolean mUseFuzzyClock = (Settings.System.getInt(mContext.getContentResolver(),
Settings.System.LOCKSCREEN_FUZZY_CLOCK, 1) == 1);
private boolean mUseKanjiClock = (Settings.System.getInt(mContext.getContentResolver(),
Settings.System.LOCKSCREEN_FUZZY_CLOCK, 1) == 2) || (Settings.System.getInt(mContext.getContentResolver(),
Settings.System.LOCKSCREEN_FUZZY_CLOCK, 1) == 3);
private boolean mLockMessage = (Settings.System.getInt(mContext.getContentResolver(),
Settings.System.LOCKSCREEN_MESSAGE, 1) != 1);
private int mLockscreenStyle = (Settings.System.getInt(mContext.getContentResolver(),
Settings.System.LOCKSCREEN_STYLE_PREF, 6));
private boolean mUseCircularLockscreen =
LockscreenStyle.getStyleById(mLockscreenStyle) == LockscreenStyle.Circular;
private boolean mUseSenseLockscreen =
LockscreenStyle.getStyleById(mLockscreenStyle) == LockscreenStyle.Sense;
private boolean mUseHoneyLockscreen =
LockscreenStyle.getStyleById(mLockscreenStyle) == LockscreenStyle.Honeycomb;
private String[] mCustomRingAppActivities = new String[] {
Settings.System.getString(mContext.getContentResolver(),
Settings.System.LOCKSCREEN_CUSTOM_RING_APP_ACTIVITIES[0]),
Settings.System.getString(mContext.getContentResolver(),
Settings.System.LOCKSCREEN_CUSTOM_RING_APP_ACTIVITIES[1]),
Settings.System.getString(mContext.getContentResolver(),
Settings.System.LOCKSCREEN_CUSTOM_RING_APP_ACTIVITIES[2]),
Settings.System.getString(mContext.getContentResolver(),
Settings.System.LOCKSCREEN_CUSTOM_RING_APP_ACTIVITIES[3])
};
private int smsCount = 0;
private int callCount = 0;
private long messagesId = 0;
private IntentFilter filter;
private Handler mSmsCallHandler;
private Intent[] mCustomApps = new Intent[4];
/**
* The status of this lock screen.
*/
enum Status {
/**
* Normal case (sim card present, it's not locked)
*/
Normal(true),
/**
* The sim card is 'network locked'.
*/
NetworkLocked(true),
/**
* The sim card is missing.
*/
SimMissing(false),
/**
* The sim card is missing, and this is the device isn't provisioned, so we don't let
* them get past the screen.
*/
SimMissingLocked(false),
/**
* The sim card is PUK locked, meaning they've entered the wrong sim unlock code too many
* times.
*/
SimPukLocked(false),
/**
* The sim card is locked.
*/
SimLocked(true);
private final boolean mShowStatusLines;
Status(boolean mShowStatusLines) {
this.mShowStatusLines = mShowStatusLines;
}
/**
* @return Whether the status lines (battery level and / or next alarm) are shown while
* in this state. Mostly dictated by whether this is room for them.
*/
public boolean showStatusLines() {
return mShowStatusLines;
}
}
/**
* In general, we enable unlocking the insecure key guard with the menu key. However, there are
* some cases where we wish to disable it, notably when the menu button placement or technology
* is prone to false positives.
*
* @return true if the menu key should be enabled
*/
private boolean shouldEnableMenuKey() {
final Resources res = getResources();
final boolean configDisabled = res.getBoolean(R.bool.config_disableMenuKeyInLockScreen);
final boolean isMonkey = SystemProperties.getBoolean("ro.monkey", false);
final boolean fileOverride = (new File(ENABLE_MENU_KEY_FILE)).exists();
return !configDisabled || isMonkey || fileOverride;
}
/**
* @param context Used to setup the view.
* @param configuration The current configuration. Used to use when selecting layout, etc.
* @param lockPatternUtils Used to know the state of the lock pattern settings.
* @param updateMonitor Used to register for updates on various keyguard related
* state, and query the initial state at setup.
* @param callback Used to communicate back to the host keyguard view.
*/
HoneycombLockscreen(Context context, Configuration configuration,
LockPatternUtils lockPatternUtils, KeyguardUpdateMonitor updateMonitor,
KeyguardScreenCallback callback) {
super(context);
mLockPatternUtils = lockPatternUtils;
mUpdateMonitor = updateMonitor;
mCallback = callback;
filter = new IntentFilter();
mSmsCallHandler = new Handler();
int CColours = mClockColor;
mEnableMenuKeyInLockScreen = shouldEnableMenuKey();
mCreationOrientation = configuration.orientation;
mKeyboardHidden = configuration.hardKeyboardHidden;
if (LockPatternKeyguardView.DEBUG_CONFIGURATION) {
Log.v(TAG, "***** CREATING LOCK SCREEN", new RuntimeException());
Log.v(TAG, "Cur orient=" + mCreationOrientation
+ " res orient=" + context.getResources().getConfiguration().orientation);
}
final LayoutInflater inflater = LayoutInflater.from(context);
if (DBG) Log.v(TAG, "Creation orientation = " + mCreationOrientation);
if (mUseFuzzyClock && mCreationOrientation != Configuration.ORIENTATION_LANDSCAPE){
inflater.inflate(R.layout.keyguard_screen_honey_fuzzyclock, this, true);
} else if (mUseKanjiClock && mCreationOrientation != Configuration.ORIENTATION_LANDSCAPE){
inflater.inflate(R.layout.keyguard_screen_honey_kanjiclock, this, true);
} else if (mCreationOrientation != Configuration.ORIENTATION_LANDSCAPE) {
inflater.inflate(R.layout.keyguard_screen_honey, this, true);
} else if (mUseFuzzyClock && (mCreationOrientation == Configuration.ORIENTATION_LANDSCAPE)) {
inflater.inflate(R.layout.keyguard_screen_honey_landscape_fuzzyclock, this, true);
} else if (mUseKanjiClock && (mCreationOrientation == Configuration.ORIENTATION_LANDSCAPE)) {
inflater.inflate(R.layout.keyguard_screen_honey_landscape_kanjiclock, this, true);
} else {
inflater.inflate(R.layout.keyguard_screen_honey_landscape, this, true);
}
ViewGroup lockWallpaper = (ViewGroup) findViewById(R.id.root);
setBackground(mContext,lockWallpaper);
mCarrier = (TextView) findViewById(R.id.carrier);
// Required for Marquee to work
mCarrier.setSelected(true);
mCarrier.setTextColor(mCarrierColor);
if ((Settings.System.getInt(mContext.getContentResolver(),
Settings.System.STATUS_BAR_STATUSBAR_CARRIER, 0) == 1) ||
(Settings.System.getInt(mContext.getContentResolver(),
Settings.System.STATUS_BAR_STATUSBAR_CARRIER_CENTER, 0) == 1) ||
(Settings.System.getInt(mContext.getContentResolver(),
Settings.System.STATUS_BAR_STATUSBAR_CARRIER_LEFT, 0) == 1)) {
mCarrier.setVisibility(View.INVISIBLE);
}
Settings.System.putInt(mContext.getContentResolver(), Settings.System.SHOW_STATUS_BAR_LOCK, 1);
mCusText = (TextView) findViewById(R.id.custext);
mCusText.setText(mCustomText);
mCusText.setTextColor(CColours);
if (mUseFuzzyClock){
mFuzzyClock = (FuzzyClock) findViewById(R.id.time);
} else if (mUseKanjiClock){
mKanjiClock = (KanjiClock) findViewById(R.id.time);
} else {
mClock = (DigitalClock) findViewById(R.id.time);
}
mTime = (TextView) findViewById(R.id.timeDisplay);
mTime.setTextColor(CColours);
if (mUseKanjiClock) {
} else {
mAmPm = (TextView) findViewById(R.id.am_pm);
mAmPm.setTextColor(CColours);
}
mDate = (TextView) findViewById(R.id.date);
mDate.setTextColor(CColours);
mStatusBox = (LinearLayout) findViewById(R.id.status_box);
mStatusCharging = (TextView) findViewById(R.id.status_charging);
mStatusCharging.setTextColor(CColours);
mStatusAlarm = (TextView) findViewById(R.id.status_alarm);
mStatusAlarm.setTextColor(CColours);
mStatusCalendar = (TextView) findViewById(R.id.status_calendar);
mStatusCalendar.setTextColor(CColours);
mCustomMsg = (TextView) findViewById(R.id.customMsg);
if (mCustomMsg != null) {
if (mLockPatternUtils.isShowCustomMsg()) {
mCustomMsg.setVisibility(View.VISIBLE);
mCustomMsg.setText(mLockPatternUtils.getCustomMsg());
mCustomMsg.setTextColor(CColours);
} else {
mCustomMsg.setVisibility(View.GONE);
}
}
mPlayIcon = (ImageButton) findViewById(R.id.musicControlPlay);
mPauseIcon = (ImageButton) findViewById(R.id.musicControlPause);
mRewindIcon = (ImageButton) findViewById(R.id.musicControlPrevious);
mForwardIcon = (ImageButton) findViewById(R.id.musicControlNext);
mAlbumArt = (ImageButton) findViewById(R.id.albumArt);
mNowPlaying = (TextView) findViewById(R.id.musicNowPlaying);
mNowPlaying.setSelected(true); // set focus to TextView to allow scrolling
mNowPlaying.setTextColor(CColours);
mScreenLocked = (TextView) findViewById(R.id.screenLocked);
mScreenLocked.setTextColor(CColours);
mSelector = (UnlockRing) findViewById(R.id.unlock_ring);
mCircularSelector = (CircularSelector) findViewById(R.id.circular_selector);
mSenseRingSelector = (SenseLikeLock) findViewById(R.id.sense_selector);
mSenseRingSelector.setOnSenseLikeSelectorTriggerListener(this);
mCircularSelector.setOnCircularSelectorTriggerListener(this);
mSelector.setOnTriggerListener(this);
setupSenseLikeRingShortcuts();
mEmergencyCallText = (TextView) findViewById(R.id.emergencyCallText);
mEmergencyCallButton = (Button) findViewById(R.id.emergencyCallButton);
mEmergencyCallButton.setText(R.string.lockscreen_emergency_call);
mSmsCountView = (TextView) findViewById(R.id.smssWidget);
mSmsCountView.setTextColor(CColours);
mMissedCallCountView = (TextView) findViewById(R.id.callsWidget);
mMissedCallCountView.setTextColor(CColours);
if (mLockMessage) {
mSmsCountView.setVisibility(View.INVISIBLE);
mMissedCallCountView.setVisibility(View.INVISIBLE);
}
mLockPatternUtils.updateEmergencyCallButtonState(mEmergencyCallButton);
mEmergencyCallButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mCallback.takeEmergencyCallAction();
}
});
mPlayIcon.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mCallback.pokeWakelock();
refreshMusicStatus();
if (!am.isMusicActive()) {
mPauseIcon.setVisibility(View.VISIBLE);
mPlayIcon.setVisibility(View.GONE);
mRewindIcon.setVisibility(View.VISIBLE);
mForwardIcon.setVisibility(View.VISIBLE);
sendMediaButtonEvent(KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE);
}
}
});
mPauseIcon.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mCallback.pokeWakelock();
refreshMusicStatus();
if (am.isMusicActive()) {
mPlayIcon.setVisibility(View.VISIBLE);
mPauseIcon.setVisibility(View.GONE);
mRewindIcon.setVisibility(View.GONE);
mForwardIcon.setVisibility(View.GONE);
sendMediaButtonEvent(KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE);
}
}
});
mRewindIcon.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mCallback.pokeWakelock();
sendMediaButtonEvent(KeyEvent.KEYCODE_MEDIA_PREVIOUS);
}
});
mForwardIcon.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mCallback.pokeWakelock();
sendMediaButtonEvent(KeyEvent.KEYCODE_MEDIA_NEXT);
}
});
mAlbumArt.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent musicIntent = new Intent(Intent.ACTION_VIEW);
musicIntent.setClassName("com.android.music","com.android.music.MediaPlaybackActivity");
musicIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getContext().startActivity(musicIntent);
mCallback.goToUnlockScreen();
Settings.System.putInt(mContext.getContentResolver(), Settings.System.SHOW_STATUS_BAR_LOCK, 0);
}
});
setFocusable(true);
setFocusableInTouchMode(true);
setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
mUpdateMonitor.registerInfoCallback(this);
mUpdateMonitor.registerSimStateCallback(this);
filter.addAction(SMS_CHANGED);
filter.addAction(TelephonyManager.ACTION_PHONE_STATE_CHANGED);
getContext().registerReceiver(mSmsCallListener, filter);
if (!mLockMessage) {
smsCount = SmsCallWidgetHelper.getUnreadSmsCount(getContext());
callCount = SmsCallWidgetHelper.getMissedCallCount(getContext());
setSmsWidget();
setCallWidget();
}
mAudioManager = (AudioManager) getContext().getSystemService(Context.AUDIO_SERVICE);
mSilentMode = isSilentMode();
if (mWidgetLayout == 1) {
setLenseWidgetsVisibility(View.INVISIBLE);
}
if (mTrackballUnlockScreen || mMenuUnlockScreen) {
mHideUnlockTab = true;
} else {
mHideUnlockTab = false;
}
resetStatusInfo(updateMonitor);
switch (mWidgetLayout) {
case 2:
centerWidgets();
break;
case 3:
alignWidgetsToRight();
break;
}
}
private void centerWidgets() {
RelativeLayout.LayoutParams layoutParams;
layoutParams = (RelativeLayout.LayoutParams) mCarrier.getLayoutParams();
layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
mCarrier.setLayoutParams(layoutParams);
mCarrier.setGravity(Gravity.CENTER_HORIZONTAL);
mStatusBox.setGravity(Gravity.CENTER_HORIZONTAL);
if (mUseFuzzyClock){
centerWidget(mFuzzyClock);
} else if (mUseKanjiClock) {
centerWidget(mKanjiClock);
} else {
centerWidget(mClock);
}
centerWidget(mDate);
centerWidget(mCusText);
centerWidget(mSmsCountView);
centerWidget(mMissedCallCountView);
centerWidget(mStatusCharging);
centerWidget(mStatusAlarm);
centerWidget(mStatusCalendar);
}
private void centerWidget(View view) {
ViewGroup.LayoutParams params = view.getLayoutParams();
if (params instanceof RelativeLayout.LayoutParams) {
RelativeLayout.LayoutParams p = (RelativeLayout.LayoutParams) params;
p.addRule(RelativeLayout.CENTER_HORIZONTAL, 1);
} else if (params instanceof LinearLayout.LayoutParams) {
LinearLayout.LayoutParams p = (LinearLayout.LayoutParams) params;
p.gravity = Gravity.CENTER_HORIZONTAL;
p.leftMargin = 0;
p.rightMargin = 0;
}
view.setLayoutParams(params);
}
private void alignWidgetsToRight() {
RelativeLayout.LayoutParams layoutParams;
layoutParams = (RelativeLayout.LayoutParams) mCarrier.getLayoutParams();
layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
mCarrier.setLayoutParams(layoutParams);
mCarrier.setGravity(Gravity.LEFT);
mStatusBox.setGravity(Gravity.LEFT);
if (mUseFuzzyClock){
alignWidgetToRight(mFuzzyClock);
} else if (mUseKanjiClock) {
alignWidgetToRight(mKanjiClock);
} else {
alignWidgetToRight(mClock);
}
alignWidgetToRight(mDate);
alignWidgetToRight(mCusText);
alignWidgetToRight(mSmsCountView);
alignWidgetToRight(mMissedCallCountView);
alignWidgetToRight(mStatusCharging);
alignWidgetToRight(mStatusAlarm);
alignWidgetToRight(mStatusCalendar);
}
private void alignWidgetToRight(View view) {
ViewGroup.LayoutParams params = view.getLayoutParams();
if (params instanceof RelativeLayout.LayoutParams) {
RelativeLayout.LayoutParams p = (RelativeLayout.LayoutParams) params;
p.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, 1);
p.addRule(RelativeLayout.ALIGN_PARENT_LEFT, 0);
} else if (params instanceof LinearLayout.LayoutParams) {
LinearLayout.LayoutParams p = (LinearLayout.LayoutParams) params;
p.gravity = Gravity.RIGHT;
}
view.setLayoutParams(params);
}
static void setBackground(Context bcontext, ViewGroup layout){
String mLockBack = Settings.System.getString(bcontext.getContentResolver(), Settings.System.LOCKSCREEN_BACKGROUND);
if (mLockBack!=null){
if (!mLockBack.isEmpty()){
try {
layout.setBackgroundColor(Integer.parseInt(mLockBack));
}catch(NumberFormatException e){
}
}else{
String lockWallpaper = "";
try {
lockWallpaper = bcontext.createPackageContext("com.cyanogenmod.cmparts", 0).getFilesDir()+"/lockwallpaper";
} catch (NameNotFoundException e1) {
}
if (!lockWallpaper.isEmpty()){
Bitmap lockb = BitmapFactory.decodeFile(lockWallpaper);
layout.setBackgroundDrawable(new BitmapDrawable(lockb));
}
}
}
}
static void handleHomeLongPress(Context context) {
int homeLongAction = (Settings.System.getInt(context.getContentResolver(),
Settings.System.LOCKSCREEN_LONG_HOME_ACTION, -1));
if (homeLongAction == 1) {
- Intent intent = new Intent(LockScreen.TOGGLE_FLASHLIGHT);
+ Intent intent = new Intent(HoneycombLockscreen.TOGGLE_FLASHLIGHT);
intent.putExtra("strobe", false);
intent.putExtra("period", 0);
intent.putExtra("bright", false);
context.sendBroadcast(intent);
}
}
private boolean isSilentMode() {
return mAudioManager.getRingerMode() != AudioManager.RINGER_MODE_NORMAL;
}
private boolean isAirplaneModeOn() {
return (Settings.System.getInt(mContext.getContentResolver(),
Settings.System.AIRPLANE_MODE_ON, 0) == 1);
}
private void updateRightTabResources() {
boolean vibe = mSilentMode
&& (mAudioManager.getRingerMode() == AudioManager.RINGER_MODE_VIBRATE);
}
private void resetStatusInfo(KeyguardUpdateMonitor updateMonitor) {
mShowingBatteryInfo = updateMonitor.shouldShowBatteryInfo();
mPluggedIn = updateMonitor.isDevicePluggedIn();
mBatteryLevel = updateMonitor.getBatteryLevel();
mIsMusicActive = am.isMusicActive();
mStatus = getCurrentStatus(updateMonitor.getSimState());
updateLayout(mStatus);
refreshBatteryStringAndIcon();
refreshAlarmDisplay();
refreshCalendarDisplay();
refreshMusicStatus();
refreshPlayingTitle();
mDateFormatString = getContext().getString(R.string.full_wday_month_day_no_year);
refreshTimeAndDateDisplay();
updateStatusLines();
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_DPAD_CENTER && mTrackballUnlockScreen)
|| (keyCode == KeyEvent.KEYCODE_MENU && mMenuUnlockScreen)
|| (keyCode == KeyEvent.KEYCODE_MENU && mEnableMenuKeyInLockScreen)) {
mCallback.goToUnlockScreen();
Settings.System.putInt(mContext.getContentResolver(), Settings.System.SHOW_STATUS_BAR_LOCK, 0);
return false;
} else if (keyCode == KeyEvent.KEYCODE_HOME) {
event.startTracking();
return true;
}
return false;
}
@Override
public boolean onKeyLongPress(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_HOME) {
handleHomeLongPress(mContext);
}
return false;
}
public void OnCircularSelectorGrabbedStateChanged(View v, int GrabState) {
// TODO Auto-generated method stub
mCallback.pokeWakelock();
}
/** {@inheritDoc} */
public void onTrigger(View v, int whichHandle) {
final String TOGGLE_SILENT = "silent_mode";
if (whichHandle == UnlockRing.OnTriggerListener.UNLOCK_HANDLE) {
mCallback.goToUnlockScreen();
Settings.System.putInt(mContext.getContentResolver(), Settings.System.SHOW_STATUS_BAR_LOCK, 0);
} else if (mCustomRingAppActivities[0] != null && mCustomAppToggle
&& whichHandle == UnlockRing.OnTriggerListener.QUADRANT_1) {
if (mCustomRingAppActivities[0].equals(TOGGLE_SILENT)) {
toggleSilentMode();
mCallback.pokeWakelock();
mSelector.reset(false);
} else {
try {
Intent i = Intent.parseUri(mCustomRingAppActivities[0], 0);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
mContext.startActivity(i);
mCallback.goToUnlockScreen();
Settings.System.putInt(mContext.getContentResolver(), Settings.System.SHOW_STATUS_BAR_LOCK, 0);
} catch (Exception e) {
}
}
} else if (mCustomRingAppActivities[1] != null && mCustomAppToggle
&& whichHandle == UnlockRing.OnTriggerListener.QUADRANT_2) {
if (mCustomRingAppActivities[1].equals(TOGGLE_SILENT)) {
toggleSilentMode();
mSelector.reset(false);
mCallback.pokeWakelock();
} else {
try {
Intent i = Intent.parseUri(mCustomRingAppActivities[1], 0);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
mContext.startActivity(i);
mCallback.goToUnlockScreen();
Settings.System.putInt(mContext.getContentResolver(), Settings.System.SHOW_STATUS_BAR_LOCK, 0);
} catch (Exception e) {
}
}
} else if (mCustomRingAppActivities[2] != null && mCustomAppToggle
&& whichHandle == UnlockRing.OnTriggerListener.QUADRANT_3) {
if (mCustomRingAppActivities[2].equals(TOGGLE_SILENT)) {
toggleSilentMode();
mSelector.reset(false);
mCallback.pokeWakelock();
} else {
try {
Intent i = Intent.parseUri(mCustomRingAppActivities[2], 0);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
mContext.startActivity(i);
mCallback.goToUnlockScreen();
Settings.System.putInt(mContext.getContentResolver(), Settings.System.SHOW_STATUS_BAR_LOCK, 0);
} catch (Exception e) {
}
}
} else if (mCustomRingAppActivities[3] != null && mCustomAppToggle
&& whichHandle == UnlockRing.OnTriggerListener.QUADRANT_4) {
if (mCustomRingAppActivities[3].equals(TOGGLE_SILENT)) {
toggleSilentMode();
mSelector.reset(false);
mCallback.pokeWakelock();
} else {
try {
Intent i = Intent.parseUri(mCustomRingAppActivities[3], 0);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
mContext.startActivity(i);
mCallback.goToUnlockScreen();
Settings.System.putInt(mContext.getContentResolver(), Settings.System.SHOW_STATUS_BAR_LOCK, 0);
} catch (Exception e) {
}
}
}
}
public void onCircularSelectorTrigger(View v, int Trigger) {
mCallback.goToUnlockScreen();
Settings.System.putInt(mContext.getContentResolver(), Settings.System.SHOW_STATUS_BAR_LOCK, 0);
}
/** {@inheritDoc} */
public void onGrabbedStateChange(View v, int grabbedState) {
if (grabbedState != UnlockRing.OnTriggerListener.NO_HANDLE) {
mCallback.pokeWakelock();
}
}
@Override
public void OnSenseLikeSelectorGrabbedStateChanged(View v, int GrabState) {
// TODO Auto-generated method stub
mCallback.pokeWakelock();
}
@Override
public void onSenseLikeSelectorTrigger(View v, int Trigger) {
// TODO Auto-generated method stub
Vibrator vibe = (Vibrator) mContext.getSystemService(Context.VIBRATOR_SERVICE);
long[] pattern = {0, 100};
switch(Trigger){
case SenseLikeLock.OnSenseLikeSelectorTriggerListener.LOCK_ICON_SHORTCUT_ONE_TRIGGERED:
vibe.vibrate(pattern, -1);
mCustomApps[0].addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
getContext().startActivity(mCustomApps[0]);
mCallback.goToUnlockScreen();
Settings.System.putInt(mContext.getContentResolver(), Settings.System.SHOW_STATUS_BAR_LOCK, 0);
break;
case SenseLikeLock.OnSenseLikeSelectorTriggerListener.LOCK_ICON_SHORTCUT_TWO_TRIGGERED:
vibe.vibrate(pattern, -1);
mCustomApps[1].addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
getContext().startActivity(mCustomApps[1]);
mCallback.goToUnlockScreen();
Settings.System.putInt(mContext.getContentResolver(), Settings.System.SHOW_STATUS_BAR_LOCK, 0);
break;
case SenseLikeLock.OnSenseLikeSelectorTriggerListener.LOCK_ICON_SHORTCUT_THREE_TRIGGERED:
vibe.vibrate(pattern, -1);
mCustomApps[2].addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
getContext().startActivity(mCustomApps[2]);
mCallback.goToUnlockScreen();
Settings.System.putInt(mContext.getContentResolver(), Settings.System.SHOW_STATUS_BAR_LOCK, 0);
break;
case SenseLikeLock.OnSenseLikeSelectorTriggerListener.LOCK_ICON_SHORTCUT_FOUR_TRIGGERED:
vibe.vibrate(pattern, -1);
mCustomApps[3].addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
getContext().startActivity(mCustomApps[3]);
mCallback.goToUnlockScreen();
Settings.System.putInt(mContext.getContentResolver(), Settings.System.SHOW_STATUS_BAR_LOCK, 0);
break;
case SenseLikeLock.OnSenseLikeSelectorTriggerListener.LOCK_ICON_TRIGGERED:
mCallback.goToUnlockScreen();
Settings.System.putInt(mContext.getContentResolver(), Settings.System.SHOW_STATUS_BAR_LOCK, 0);
break;
}
}
private void setupSenseLikeRingShortcuts(){
int numapps = 0;
Intent intent = new Intent();
PackageManager pm = mContext.getPackageManager();
mCustomApps = new Intent[4];
Drawable[] shortcutsicons;
for(int i = 0; i < mCustomRingAppActivities.length ; i++){
if(mCustomRingAppActivities[i] != null && mCustomAppToggle){
numapps++;
}
}
if(numapps != 4){
mCustomApps = mSenseRingSelector.setDefaultIntents();
for(int i = 0; i < 4; i++){
if(mCustomRingAppActivities[i] != null && mCustomAppToggle){
try{
intent = Intent.parseUri(mCustomRingAppActivities[i], 0);
}catch (java.net.URISyntaxException ex) {
// bogus; leave intent=null
}
}
}
numapps = 4;
}else for(int i = 0; i < numapps ; i++){
try{
intent = Intent.parseUri(mCustomRingAppActivities[i], 0);
}catch (java.net.URISyntaxException ex) {
if (DBG) Log.w(TAG, "Invalid hotseat intent: " + mCustomRingAppActivities[i]);
ex.printStackTrace();
}
ResolveInfo bestMatch = pm.resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY);
List<ResolveInfo> allMatches = pm.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
if (DBG) {
if (DBG) {
Log.d(TAG, "Best match for intent: " + bestMatch);
Log.d(TAG, "All matches: ");
}
for (ResolveInfo ri : allMatches) {
if (DBG)Log.d(TAG, " --> " + ri);
}
}
ComponentName com = new ComponentName(
bestMatch.activityInfo.applicationInfo.packageName,
bestMatch.activityInfo.name);
mCustomApps[i] = new Intent(Intent.ACTION_MAIN).setComponent(com);
}
shortcutsicons = new Drawable[numapps];
float iconScale =0.70f;
for(int i = 0; i < numapps ; i++){
try {
shortcutsicons[i] = pm.getActivityIcon(mCustomApps[i]);
shortcutsicons[i] = scaledDrawable(shortcutsicons[i], mContext ,iconScale);
} catch (ArrayIndexOutOfBoundsException ex) {
if (DBG) Log.w(TAG, "Missing shortcut_icons array item #" + i);
shortcutsicons[i] = null;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
shortcutsicons[i] = null;
//Do-Nothing
}
}
mSenseRingSelector.setShortCutsDrawables(shortcutsicons[0], shortcutsicons[1], shortcutsicons[2], shortcutsicons[3]);
}
private Drawable scaledDrawable(Drawable icon,Context context, float scale) {
final Resources resources=context.getResources();
int sIconHeight= (int) resources.getDimension(android.R.dimen.app_icon_size);
int sIconWidth = sIconHeight;
int width = sIconWidth;
int height = sIconHeight;
Bitmap original;
try{
original= Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
} catch (OutOfMemoryError e) {
return icon;
}
Canvas canvas = new Canvas(original);
canvas.setBitmap(original);
icon.setBounds(0,0, width, height);
icon.draw(canvas);
try{
Bitmap endImage=Bitmap.createScaledBitmap(original, (int)(width*scale), (int)(height*scale), true);
original.recycle();
return new FastBitmapDrawable(endImage);
} catch (OutOfMemoryError e) {
return icon;
}
}
public class FastBitmapDrawable extends Drawable {
private Bitmap mBitmap;
private int mWidth;
private int mHeight;
public FastBitmapDrawable(Bitmap b) {
mBitmap = b;
if (b != null) {
mWidth = mBitmap.getWidth();
mHeight = mBitmap.getHeight();
} else {
mWidth = mHeight = 0;
}
}
@Override
public void draw(Canvas canvas) {
canvas.drawBitmap(mBitmap, 0.0f, 0.0f, null);
}
@Override
public int getOpacity() {
return PixelFormat.TRANSLUCENT;
}
@Override
public void setAlpha(int alpha) {
}
@Override
public void setColorFilter(ColorFilter cf) {
}
@Override
public int getIntrinsicWidth() {
return mWidth;
}
@Override
public int getIntrinsicHeight() {
return mHeight;
}
@Override
public int getMinimumWidth() {
return mWidth;
}
@Override
public int getMinimumHeight() {
return mHeight;
}
public void setBitmap(Bitmap b) {
mBitmap = b;
if (b != null) {
mWidth = mBitmap.getWidth();
mHeight = mBitmap.getHeight();
} else {
mWidth = mHeight = 0;
}
}
public Bitmap getBitmap() {
return mBitmap;
}
}
/**
* Displays a message in a text view and then restores the previous text.
* @param textView The text view.
* @param text The text.
* @param color The color to apply to the text, or 0 if the existing color should be used.
* @param iconResourceId The left hand icon.
*/
private void toastMessage(final TextView textView, final String text, final int color, final int iconResourceId) {
if (mPendingR1 != null) {
textView.removeCallbacks(mPendingR1);
mPendingR1 = null;
}
if (mPendingR2 != null) {
mPendingR2.run(); // fire immediately, restoring non-toasted appearance
textView.removeCallbacks(mPendingR2);
mPendingR2 = null;
}
final String oldText = textView.getText().toString();
final ColorStateList oldColors = textView.getTextColors();
mPendingR1 = new Runnable() {
public void run() {
textView.setText(text);
if (color != 0) {
textView.setTextColor(color);
}
textView.setCompoundDrawablesWithIntrinsicBounds(iconResourceId, 0, 0, 0);
}
};
textView.postDelayed(mPendingR1, 0);
mPendingR2 = new Runnable() {
public void run() {
textView.setText(oldText);
textView.setTextColor(oldColors);
textView.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
}
};
textView.postDelayed(mPendingR2, 3500);
}
private Runnable mPendingR1;
private Runnable mPendingR2;
private void refreshAlarmDisplay() {
mNextAlarm = mLockPatternUtils.getNextAlarm();
updateStatusLines();
}
private void refreshCalendarDisplay() {
if (mLockCalendarAlarm) {
mNextCalendar = mLockPatternUtils.getNextCalendarAlarm(mLockCalendarLookahead,
mCalendars, mLockCalendarRemindersOnly);
} else {
mNextCalendar = null;
}
updateStatusLines();
}
/** {@inheritDoc} */
public void onRefreshBatteryInfo(boolean showBatteryInfo, boolean pluggedIn,
int batteryLevel) {
if (DBG) Log.d(TAG, "onRefreshBatteryInfo(" + showBatteryInfo + ", " + pluggedIn + ")");
mShowingBatteryInfo = showBatteryInfo;
mPluggedIn = pluggedIn;
mBatteryLevel = batteryLevel;
refreshBatteryStringAndIcon();
updateStatusLines();
}
private void refreshBatteryStringAndIcon() {
if (!mShowingBatteryInfo && !mLockAlwaysBattery) {
mCharging = null;
return;
}
if (mPluggedIn) {
mChargingIcon =
getContext().getResources().getDrawable(R.drawable.ic_lock_idle_charging);
if (mUpdateMonitor.isDeviceCharged()) {
mCharging = getContext().getString(R.string.lockscreen_charged, mBatteryLevel);
} else {
mCharging = getContext().getString(R.string.lockscreen_plugged_in, mBatteryLevel);
}
} else {
if (mBatteryLevel <= 20) {
mChargingIcon =
getContext().getResources().getDrawable(R.drawable.ic_lock_idle_low_battery);
mCharging = getContext().getString(R.string.lockscreen_low_battery, mBatteryLevel);
} else {
mChargingIcon =
getContext().getResources().getDrawable(R.drawable.ic_lock_idle_discharging);
mCharging = getContext().getString(R.string.lockscreen_discharging, mBatteryLevel);
}
}
}
private void refreshMusicStatus() {
if ((mWasMusicActive || mIsMusicActive || mLockAlwaysMusic
|| (mAudioManager.isWiredHeadsetOn() && useLockMusicHeadsetWired)
|| (mAudioManager.isBluetoothA2dpOn() && useLockMusicHeadsetBT)) && (mLockMusicControls)) {
if (am.isMusicActive()) {
mPauseIcon.setVisibility(View.VISIBLE);
mPlayIcon.setVisibility(View.GONE);
mRewindIcon.setVisibility(View.VISIBLE);
mForwardIcon.setVisibility(View.VISIBLE);
} else {
mPlayIcon.setVisibility(View.VISIBLE);
mPauseIcon.setVisibility(View.GONE);
mRewindIcon.setVisibility(View.GONE);
mForwardIcon.setVisibility(View.GONE);
}
} else {
mPlayIcon.setVisibility(View.GONE);
mPauseIcon.setVisibility(View.GONE);
mRewindIcon.setVisibility(View.GONE);
mForwardIcon.setVisibility(View.GONE);
}
}
private void refreshPlayingTitle() {
String nowPlaying = KeyguardViewMediator.NowPlaying();
boolean musicActive = am.isMusicActive() || am.isFmActive();
mNowPlaying.setText(nowPlaying);
mNowPlaying.setVisibility(View.GONE);
mAlbumArt.setVisibility(View.GONE);
if (musicActive && !TextUtils.isEmpty(nowPlaying) && mLockMusicControls) {
if (mNowPlayingToggle) {
mNowPlaying.setVisibility(View.VISIBLE);
mNowPlaying.setSelected(true); // set focus to TextView to allow scrolling
}
// Set album art
if (shouldShowAlbumArt()) {
Uri uri = getArtworkUri(getContext(), KeyguardViewMediator.SongId(),
KeyguardViewMediator.AlbumId());
if (uri != null) {
mAlbumArt.setImageURI(uri);
mAlbumArt.setVisibility(View.VISIBLE);
}
}
}
}
private boolean shouldShowAlbumArt() {
if (!mAlbumArtToggle) {
return false;
}
if (mHideUnlockTab) {
return false;
}
if (mUseSenseLockscreen || mUseHoneyLockscreen || mUseCircularLockscreen) {
return false;
}
return true;
}
private void sendMediaButtonEvent(int code) {
long eventtime = SystemClock.uptimeMillis();
Intent downIntent = new Intent(Intent.ACTION_MEDIA_BUTTON, null);
KeyEvent downEvent = new KeyEvent(eventtime, eventtime, KeyEvent.ACTION_DOWN, code, 0);
downIntent.putExtra(Intent.EXTRA_KEY_EVENT, downEvent);
getContext().sendOrderedBroadcast(downIntent, null);
Intent upIntent = new Intent(Intent.ACTION_MEDIA_BUTTON, null);
KeyEvent upEvent = new KeyEvent(eventtime, eventtime, KeyEvent.ACTION_UP, code, 0);
upIntent.putExtra(Intent.EXTRA_KEY_EVENT, upEvent);
getContext().sendOrderedBroadcast(upIntent, null);
}
/** {@inheritDoc} */
public void onTimeChanged() {
refreshTimeAndDateDisplay();
mSmsCallHandler.postDelayed(new Runnable() {
@Override
public void run() {
if (!mLockMessage) {
// get a new count and set indicator
smsCount = SmsCallWidgetHelper.getUnreadSmsCount(getContext());
callCount = SmsCallWidgetHelper.getMissedCallCount(getContext());
setCallWidget();
setSmsWidget();
}
}
},50);
}
/** {@inheritDoc} */
public void onMusicChanged() {
refreshPlayingTitle();
mSmsCallHandler.postDelayed(new Runnable() {
@Override
public void run() {
if (!mLockMessage) {
// get a new count and set indicator
smsCount = SmsCallWidgetHelper.getUnreadSmsCount(getContext());
callCount = SmsCallWidgetHelper.getMissedCallCount(getContext());
setCallWidget();
setSmsWidget();
}
}
},50);
}
private void refreshTimeAndDateDisplay() {
mDate.setText(DateFormat.format(mDateFormatString, new Date()));
}
private void updateStatusLines() {
if (!mStatus.showStatusLines() || mWidgetLayout == 1) {
mStatusBox.setVisibility(INVISIBLE);
} else {
mStatusBox.setVisibility(VISIBLE);
if (mCharging != null) {
mStatusCharging.setText(mCharging);
mStatusCharging.setCompoundDrawablesWithIntrinsicBounds(mChargingIcon, null, null, null);
mStatusCharging.setVisibility(VISIBLE);
} else {
mStatusCharging.setVisibility(GONE);
}
if (mNextAlarm != null) {
mStatusAlarm.setText(mNextAlarm);
mStatusAlarm.setVisibility(VISIBLE);
} else {
mStatusAlarm.setVisibility(GONE);
}
if (mNextCalendar != null) {
mStatusCalendar.setText(mNextCalendar);
mStatusCalendar.setVisibility(VISIBLE);
} else {
mStatusCalendar.setVisibility(GONE);
}
}
mSmsCallHandler.postDelayed(new Runnable() {
@Override
public void run() {
if (!mLockMessage) {
// get a new count and set indicator
smsCount = SmsCallWidgetHelper.getUnreadSmsCount(getContext());
callCount = SmsCallWidgetHelper.getMissedCallCount(getContext());
setCallWidget();
setSmsWidget();
}
}
},50);
}
/** {@inheritDoc} */
public void onRefreshCarrierInfo(CharSequence plmn, CharSequence spn) {
if (DBG) Log.d(TAG, "onRefreshCarrierInfo(" + plmn + ", " + spn + ")");
updateLayout(mStatus);
}
/**
* Determine the current status of the lock screen given the sim state and other stuff.
*/
private Status getCurrentStatus(IccCard.State simState) {
boolean missingAndNotProvisioned = (!mUpdateMonitor.isDeviceProvisioned()
&& simState == IccCard.State.ABSENT);
if (missingAndNotProvisioned) {
return Status.SimMissingLocked;
}
boolean presentButNotAvailable = isAirplaneModeOn();
if (presentButNotAvailable) {
return Status.Normal;
}
switch (simState) {
case ABSENT:
return Status.SimMissing;
case NETWORK_LOCKED:
return Status.SimMissingLocked;
case NOT_READY:
return Status.SimMissing;
case PIN_REQUIRED:
return Status.SimLocked;
case PUK_REQUIRED:
return Status.SimPukLocked;
case READY:
return Status.Normal;
case UNKNOWN:
return Status.SimMissing;
}
return Status.SimMissing;
}
/**
* Update the layout to match the current status.
*/
private void updateLayout(Status status) {
// The emergency call button no longer appears on this screen.
if (DBG) Log.d(TAG, "updateLayout: status=" + status);
mEmergencyCallButton.setVisibility(View.GONE); // in almost all cases
String realPlmn = SystemProperties.get(TelephonyProperties.PROPERTY_OPERATOR_ALPHA);
String plmn = (String) mUpdateMonitor.getTelephonyPlmn();
String spn = (String) mUpdateMonitor.getTelephonySpn();
switch (status) {
case Normal:
// text
if (plmn == null || plmn.equals(realPlmn)) {
mCarrier.setText(getCarrierString(
plmn, spn, mCarrierLabelType, mCarrierLabelCustom));
} else {
mCarrier.setText(getCarrierString(plmn, spn));
}
// Empty now, but used for sliding tab feedback
mScreenLocked.setText("");
// layout
mScreenLocked.setVisibility(View.VISIBLE);
setUnlockWidgetsState(true);
mEmergencyCallText.setVisibility(View.GONE);
break;
case NetworkLocked:
// The carrier string shows both sim card status (i.e. No Sim Card) and
// carrier's name and/or "Emergency Calls Only" status
mCarrier.setText(
getCarrierString(
mUpdateMonitor.getTelephonyPlmn(),
getContext().getText(R.string.lockscreen_network_locked_message)));
mScreenLocked.setText(R.string.lockscreen_instructions_when_pattern_disabled);
// layout
mScreenLocked.setVisibility(View.VISIBLE);
setUnlockWidgetsState(true);
mEmergencyCallText.setVisibility(View.GONE);
break;
case SimMissing:
// text
mCarrier.setText(R.string.lockscreen_missing_sim_message_short);
mScreenLocked.setText(R.string.lockscreen_missing_sim_instructions);
// layout
mScreenLocked.setVisibility(View.VISIBLE);
setUnlockWidgetsState(true);
mEmergencyCallText.setVisibility(View.VISIBLE);
// do not need to show the e-call button; user may unlock
break;
case SimMissingLocked:
// text
mCarrier.setText(
getCarrierString(
mUpdateMonitor.getTelephonyPlmn(),
getContext().getText(R.string.lockscreen_missing_sim_message_short)));
mScreenLocked.setText(R.string.lockscreen_missing_sim_instructions);
// layout
mScreenLocked.setVisibility(View.VISIBLE);
setUnlockWidgetsState(false);
mEmergencyCallText.setVisibility(View.VISIBLE);
mEmergencyCallButton.setVisibility(View.VISIBLE);
break;
case SimLocked:
// text
mCarrier.setText(
getCarrierString(
mUpdateMonitor.getTelephonyPlmn(),
getContext().getText(R.string.lockscreen_sim_locked_message)));
// layout
mScreenLocked.setVisibility(View.VISIBLE);
setUnlockWidgetsState(true);
mEmergencyCallText.setVisibility(View.GONE);
break;
case SimPukLocked:
// text
mCarrier.setText(
getCarrierString(
mUpdateMonitor.getTelephonyPlmn(),
getContext().getText(R.string.lockscreen_sim_puk_locked_message)));
mScreenLocked.setText(R.string.lockscreen_sim_puk_locked_instructions);
// layout
mScreenLocked.setVisibility(View.VISIBLE);
setUnlockWidgetsState(false);
mEmergencyCallText.setVisibility(View.VISIBLE);
mEmergencyCallButton.setVisibility(View.VISIBLE);
break;
}
}
private void setUnlockWidgetsState(boolean show) {
if (show) {
if (mUseSenseLockscreen) {
mSenseRingSelector.setVisibility(View.VISIBLE);
mCircularSelector.setVisibility(View.GONE);
mSelector.setVisibility(View.GONE);
} else if (mUseCircularLockscreen) {
mSenseRingSelector.setVisibility(View.GONE);
mCircularSelector.setVisibility(View.VISIBLE);
mSelector.setVisibility(View.GONE);
} else {
mSenseRingSelector.setVisibility(View.GONE);
mCircularSelector.setVisibility(View.GONE);
mSelector.setVisibility(View.VISIBLE);
}
} else {
mSenseRingSelector.setVisibility(View.GONE);
mCircularSelector.setVisibility(View.GONE);
mSelector.setVisibility(View.GONE);
}
}
static CharSequence getCarrierString(CharSequence telephonyPlmn, CharSequence telephonySpn) {
return getCarrierString(telephonyPlmn, telephonySpn, CARRIER_TYPE_DEFAULT, "");
}
static CharSequence getCarrierString(CharSequence telephonyPlmn, CharSequence telephonySpn,
int carrierLabelType, String carrierLabelCustom) {
switch (carrierLabelType) {
default:
case CARRIER_TYPE_DEFAULT:
if (telephonyPlmn != null && TextUtils.isEmpty(telephonySpn)) {
return telephonyPlmn;
} else if (telephonySpn != null && TextUtils.isEmpty(telephonyPlmn)) {
return telephonySpn;
} else if (telephonyPlmn != null && telephonySpn != null) {
return telephonyPlmn + "|" + telephonySpn;
}
return "";
case CARRIER_TYPE_SPN:
if (telephonySpn != null) {
return telephonySpn;
}
break;
case CARRIER_TYPE_PLMN:
if (telephonyPlmn != null) {
return telephonyPlmn;
}
break;
case CARRIER_TYPE_CUSTOM:
return carrierLabelCustom;
}
return "";
}
public void onSimStateChanged(IccCard.State simState) {
if (DBG) Log.d(TAG, "onSimStateChanged(" + simState + ")");
mStatus = getCurrentStatus(simState);
updateLayout(mStatus);
updateStatusLines();
}
void updateConfiguration() {
Configuration newConfig = getResources().getConfiguration();
if (newConfig.hardKeyboardHidden != mKeyboardHidden) {
mKeyboardHidden = newConfig.hardKeyboardHidden;
final boolean isKeyboardOpen = mKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_NO;
if (mUpdateMonitor.isKeyguardBypassEnabled() && isKeyboardOpen) {
mCallback.goToUnlockScreen();
Settings.System.putInt(mContext.getContentResolver(), Settings.System.SHOW_STATUS_BAR_LOCK, 0);
return;
}
}
if (newConfig.orientation != mCreationOrientation) {
mCallback.recreateMe(newConfig);
}
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
if (LockPatternKeyguardView.DEBUG_CONFIGURATION) {
Log.v(TAG, "***** LOCK ATTACHED TO WINDOW");
Log.v(TAG, "Cur orient=" + mCreationOrientation
+ ", new config=" + getResources().getConfiguration());
}
updateConfiguration();
}
/** {@inheritDoc} */
@Override
protected void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (LockPatternKeyguardView.DEBUG_CONFIGURATION) {
Log.w(TAG, "***** LOCK CONFIG CHANGING", new RuntimeException());
Log.v(TAG, "Cur orient=" + mCreationOrientation
+ ", new config=" + newConfig);
}
updateConfiguration();
}
/** {@inheritDoc} */
public boolean needsInput() {
return false;
}
/** {@inheritDoc} */
public void onPause() {
mSelector.enableUnlockMode();
if (mSmsCallListener != null) {
getContext().unregisterReceiver(mSmsCallListener);
mSmsCallListener = null;
}
}
/** {@inheritDoc} */
public void onResume() {
if (mUseFuzzyClock){
mFuzzyClock.updateTime();
} else if (mUseKanjiClock) {
mKanjiClock.updateTime();
} else {
mClock.updateTime();
}
resetStatusInfo(mUpdateMonitor);
mLockPatternUtils.updateEmergencyCallButtonState(mEmergencyCallButton);
mSelector.enableUnlockMode();
if (mSmsCallListener == null) {
getContext().registerReceiver(mSmsCallListener, filter);
}
}
private BroadcastReceiver mSmsCallListener = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(SMS_CHANGED) && !mLockMessage) {
mSmsCallHandler.postDelayed(new Runnable() {
@Override
public void run() {
if (!mLockMessage) {
// get a new count and set indicator
smsCount = SmsCallWidgetHelper.getUnreadSmsCount(getContext());
setSmsWidget();
}
}
},10);
} else if (action.equals(
TelephonyManager.
ACTION_PHONE_STATE_CHANGED) && !mLockMessage) {
mSmsCallHandler.postDelayed(new Runnable() {
@Override
public void run() {
if (!mLockMessage) {
// get a new count and set indicator
callCount = SmsCallWidgetHelper.getMissedCallCount(getContext());
setCallWidget();
}
}
},10);
}
};
};
private void setSmsWidget() {
if (mLockMessage) {
return;
}
messagesId = SmsCallWidgetHelper.getSmsId(getContext());
if (smsCount > 1) {
mSmsCountView.setText(Integer.toString(smsCount) + " Unread Messages");
} else if (smsCount == 1) {
mSmsCountView.setText("1 Unread Message");
} else {
mSmsCountView.setText("0 Unread Message");
}
}
private void setCallWidget() {
if (mLockMessage) {
return;
}
if (callCount > 1) {
mMissedCallCountView.setText(Integer.toString(callCount) + " Missed Calls");
} else if (callCount == 1) {
mMissedCallCountView.setText("1 Missed Call");
} else {
mMissedCallCountView.setText("0 Missed Call");
}
}
/** {@inheritDoc} */
public void cleanUp() {
mUpdateMonitor.removeCallback(this); // this must be first
mLockPatternUtils = null;
mUpdateMonitor = null;
mCallback = null;
}
/** {@inheritDoc} */
public void onRingerModeChanged(int state) {
boolean silent = AudioManager.RINGER_MODE_NORMAL != state;
if (silent != mSilentMode) {
mSilentMode = silent;
updateRightTabResources();
}
}
public void onPhoneStateChanged(String newState) {
mLockPatternUtils.updateEmergencyCallButtonState(mEmergencyCallButton);
}
private void toggleSilentMode() {
// tri state silent<->vibrate<->ring if silent mode is enabled, otherwise toggle silent mode
final boolean mVolumeControlSilent = Settings.System.getInt(mContext.getContentResolver(),
Settings.System.VOLUME_CONTROL_SILENT, 0) != 0;
mSilentMode = mVolumeControlSilent
? ((mAudioManager.getRingerMode() == AudioManager.RINGER_MODE_VIBRATE) || !mSilentMode)
: !mSilentMode;
if (mSilentMode) {
final boolean vibe = mVolumeControlSilent
? (mAudioManager.getRingerMode() != AudioManager.RINGER_MODE_VIBRATE)
: (Settings.System.getInt(
getContext().getContentResolver(),
Settings.System.VIBRATE_IN_SILENT, 1) == 1);
mAudioManager.setRingerMode(vibe
? AudioManager.RINGER_MODE_VIBRATE
: AudioManager.RINGER_MODE_SILENT);
} else {
mAudioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
}
String message = mSilentMode ?
getContext().getString(R.string.global_action_silent_mode_on_status) :
getContext().getString(R.string.global_action_silent_mode_off_status);
final int toastIcon = mSilentMode
? R.drawable.ic_lock_ringer_off
: R.drawable.ic_lock_ringer_on;
final int toastColor = mSilentMode
? getContext().getResources().getColor(R.color.keyguard_text_color_soundoff)
: getContext().getResources().getColor(R.color.keyguard_text_color_soundon);
toastMessage(mScreenLocked, message, toastColor, toastIcon);
}
// shameless kang of music widgets
public static Uri getArtworkUri(Context context, long song_id, long album_id) {
if (album_id < 0) {
// This is something that is not in the database, so get the album art directly
// from the file.
if (song_id >= 0) {
return getArtworkUriFromFile(context, song_id, -1);
}
return null;
}
ContentResolver res = context.getContentResolver();
Uri uri = ContentUris.withAppendedId(sArtworkUri, album_id);
if (uri != null) {
InputStream in = null;
try {
in = res.openInputStream(uri);
return uri;
} catch (FileNotFoundException ex) {
// The album art thumbnail does not actually exist. Maybe the user deleted it, or
// maybe it never existed to begin with.
return getArtworkUriFromFile(context, song_id, album_id);
} finally {
try {
if (in != null) {
in.close();
}
} catch (IOException ex) {
}
}
}
return null;
}
private static Uri getArtworkUriFromFile(Context context, long songid, long albumid) {
if (albumid < 0 && songid < 0) {
return null;
}
try {
if (albumid < 0) {
Uri uri = Uri.parse("content://media/external/audio/media/" + songid + "/albumart");
ParcelFileDescriptor pfd = context.getContentResolver().openFileDescriptor(uri, "r");
if (pfd != null) {
return uri;
}
} else {
Uri uri = ContentUris.withAppendedId(sArtworkUri, albumid);
ParcelFileDescriptor pfd = context.getContentResolver().openFileDescriptor(uri, "r");
if (pfd != null) {
return uri;
}
}
} catch (FileNotFoundException ex) {
//
}
return null;
}
/*
* enables or disables visibility of most lockscreen widgets
* depending on lense status
*/
private void setLenseWidgetsVisibility(int visibility){
if (mUseFuzzyClock){
mFuzzyClock.setVisibility(visibility);
} else if (mUseKanjiClock) {
mKanjiClock.setVisibility(visibility);
} else {
mClock.setVisibility(visibility);
}
mDate.setVisibility(visibility);
mCusText.setVisibility(visibility);
if (!mLockMessage) {
mSmsCountView.setVisibility(visibility);
mMissedCallCountView.setVisibility(visibility);
}
mTime.setVisibility(visibility);
if (mUseKanjiClock) {
} else {
mAmPm.setVisibility(visibility);
}
if ((Settings.System.getInt(mContext.getContentResolver(),
Settings.System.STATUS_BAR_STATUSBAR_CARRIER, 0) != 1) ||
(Settings.System.getInt(mContext.getContentResolver(),
Settings.System.STATUS_BAR_STATUSBAR_CARRIER_CENTER, 0) != 1) ||
(Settings.System.getInt(mContext.getContentResolver(),
Settings.System.STATUS_BAR_STATUSBAR_CARRIER_LEFT, 0) != 1)) {
mCarrier.setVisibility(visibility);
}
mNowPlaying.setVisibility(visibility);
mAlbumArt.setVisibility(visibility);
if (DateFormat.is24HourFormat(mContext)) {
if (mUseKanjiClock) {
} else {
mAmPm.setVisibility(View.INVISIBLE);
}
}
mNowPlayingToggle = false;
mAlbumArtToggle = false;
if (visibility == View.VISIBLE
&& (Settings.System.getInt(mContext.getContentResolver(),
Settings.System.LOCKSCREEN_NOW_PLAYING, 1) == 1))
mNowPlayingToggle = true;
if (visibility == View.VISIBLE
&& (Settings.System.getInt(mContext.getContentResolver(),
Settings.System.LOCKSCREEN_ALBUM_ART, 1) == 1))
mAlbumArtToggle = true;
}
private void runActivity(String uri) {
try {
Intent i = Intent.parseUri(uri, 0);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
mContext.startActivity(i);
mCallback.goToUnlockScreen();
Settings.System.putInt(mContext.getContentResolver(), Settings.System.SHOW_STATUS_BAR_LOCK, 0);
} catch (URISyntaxException e) {
} catch (ActivityNotFoundException e) {
}
}
}
| true | false | null | null |
diff --git a/src/com/android/calendar/AllInOneActivity.java b/src/com/android/calendar/AllInOneActivity.java
index 182190a7..85bcac04 100644
--- a/src/com/android/calendar/AllInOneActivity.java
+++ b/src/com/android/calendar/AllInOneActivity.java
@@ -1,613 +1,615 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR 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.calendar;
import static android.provider.Calendar.EVENT_BEGIN_TIME;
import static android.provider.Calendar.EVENT_END_TIME;
import static android.provider.Calendar.AttendeesColumns.ATTENDEE_STATUS;
import com.android.calendar.CalendarController.EventHandler;
import com.android.calendar.CalendarController.EventInfo;
import com.android.calendar.CalendarController.EventType;
import com.android.calendar.CalendarController.ViewType;
import com.android.calendar.agenda.AgendaFragment;
import com.android.calendar.month.MonthByWeekFragment;
import com.android.calendar.selectcalendars.SelectCalendarsFragment;
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.database.ContentObserver;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Calendar;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.text.format.DateUtils;
import android.text.format.Time;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.SearchView;
import android.widget.TextView;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;
public class AllInOneActivity extends Activity implements EventHandler,
OnSharedPreferenceChangeListener, SearchView.OnQueryChangeListener,
ActionBar.TabListener {
private static final String TAG = "AllInOneActivity";
private static final boolean DEBUG = false;
private static final String BUNDLE_KEY_RESTORE_TIME = "key_restore_time";
private static final String BUNDLE_KEY_RESTORE_EDIT = "key_restore_edit";
private static final String BUNDLE_KEY_EVENT_ID = "key_event_id";
private static final int HANDLER_KEY = 0;
private static CalendarController mController;
private static boolean mIsMultipane;
private boolean mOnSaveInstanceStateCalled = false;
private ContentResolver mContentResolver;
private int mPreviousView;
private int mCurrentView;
private boolean mPaused = true;
private boolean mUpdateOnResume = false;
private TextView mHomeTime;
private TextView mDateRange;
private String mTimeZone;
private long mViewEventId = -1;
private long mIntentEventStartMillis = -1;
private long mIntentEventEndMillis = -1;
private int mIntentAttendeeResponse = CalendarController.ATTENDEE_NO_RESPONSE;
// Action bar and Navigation bar (left side of Action bar)
private ActionBar mActionBar;
private ActionBar.Tab mDayTab;
private ActionBar.Tab mWeekTab;
private ActionBar.Tab mMonthTab;
private Runnable mHomeTimeUpdater = new Runnable() {
@Override
public void run() {
updateHomeClock();
}
};
// Create an observer so that we can update the views whenever a
// Calendar event changes.
private ContentObserver mObserver = new ContentObserver(new Handler()) {
@Override
public boolean deliverSelfNotifications() {
return true;
}
@Override
public void onChange(boolean selfChange) {
eventsChanged();
}
};
@Override
protected void onCreate(Bundle icicle) {
// setTheme(R.style.CalendarTheme_WithActionBarWallpaper);
super.onCreate(icicle);
// This needs to be created before setContentView
mController = CalendarController.getInstance(this);
// Get time from intent or icicle
long timeMillis = -1;
int viewType = -1;
boolean restoreEdit = false;
final Intent intent = getIntent();
if (icicle != null) {
timeMillis = icicle.getLong(BUNDLE_KEY_RESTORE_TIME);
restoreEdit = icicle.getBoolean(BUNDLE_KEY_RESTORE_EDIT, false);
viewType = ViewType.EDIT;
} else {
String action = intent.getAction();
if (Intent.ACTION_VIEW.equals(action)) {
// Open EventInfo later
timeMillis = parseViewAction(intent);
}
if (timeMillis == -1) {
timeMillis = Utils.timeFromIntentInMillis(intent);
}
}
if (!restoreEdit) {
viewType = Utils.getViewTypeFromIntentAndSharedPref(this);
}
mTimeZone = Utils.getTimeZone(this, mHomeTimeUpdater);
Time t = new Time(mTimeZone);
t.set(timeMillis);
if (icicle != null && intent != null) {
Log.d(TAG, "both, icicle:" + icicle.toString() + " intent:" + intent.toString());
} else {
Log.d(TAG, "not both, icicle:" + icicle + " intent:" + intent);
}
Resources res = getResources();
mIsMultipane =
(res.getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_XLARGE) != 0;
Utils.allowWeekForDetailView(mIsMultipane);
mDateRange = (TextView) getLayoutInflater().inflate(R.layout.date_range_title, null);
// setContentView must be called before configureActionBar
setContentView(R.layout.all_in_one);
// configureActionBar auto-selects the first tab you add, so we need to
// call it before we set up our own fragments to make sure it doesn't
// overwrite us
configureActionBar();
// Must be the first to register because this activity can modify the
// list of event handlers in it's handle method. This affects who the
// rest of the handlers the controller dispatches to are.
mController.registerEventHandler(HANDLER_KEY, this);
mHomeTime = (TextView) findViewById(R.id.home_time);
initFragments(timeMillis, viewType, icicle);
// Listen for changes that would require this to be refreshed
SharedPreferences prefs = GeneralPreferences.getSharedPreferences(this);
prefs.registerOnSharedPreferenceChangeListener(this);
mContentResolver = getContentResolver();
}
private long parseViewAction(final Intent intent) {
long timeMillis = -1;
Uri data = intent.getData();
if (data != null && data.isHierarchical()) {
List<String> path = data.getPathSegments();
if (path.size() == 2 && path.get(0).equals("events")) {
try {
mViewEventId = Long.valueOf(data.getLastPathSegment());
if(mViewEventId != -1) {
mIntentEventStartMillis = intent.getLongExtra(EVENT_BEGIN_TIME, 0);
mIntentEventEndMillis = intent.getLongExtra(EVENT_END_TIME, 0);
mIntentAttendeeResponse = intent.getIntExtra(
ATTENDEE_STATUS, CalendarController.ATTENDEE_NO_RESPONSE);
timeMillis = mIntentEventStartMillis;
}
} catch (NumberFormatException e) {
// Ignore if mViewEventId can't be parsed
}
}
}
return timeMillis;
}
private void configureActionBar() {
mActionBar = getActionBar();
mActionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
if (mActionBar == null) {
Log.w(TAG, "ActionBar is null.");
} else {
mDayTab = mActionBar.newTab();
mDayTab.setText(getString(R.string.day_view));
mDayTab.setTabListener(this);
mActionBar.addTab(mDayTab);
mWeekTab = mActionBar.newTab();
mWeekTab.setText(getString(R.string.week_view));
mWeekTab.setTabListener(this);
mActionBar.addTab(mWeekTab);
mMonthTab = mActionBar.newTab();
mMonthTab.setText(getString(R.string.month_view));
mMonthTab.setTabListener(this);
mActionBar.addTab(mMonthTab);
mActionBar.setCustomView(mDateRange);
mActionBar.setDisplayOptions(
ActionBar.DISPLAY_SHOW_CUSTOM | ActionBar.DISPLAY_SHOW_HOME);
}
}
@Override
protected void onResume() {
super.onResume();
mContentResolver.registerContentObserver(Calendar.Events.CONTENT_URI, true, mObserver);
if (mUpdateOnResume) {
initFragments(mController.getTime(), mController.getViewType(), null);
mUpdateOnResume = false;
}
updateHomeClock();
mPaused = false;
mOnSaveInstanceStateCalled = false;
if (mViewEventId != -1 && mIntentEventStartMillis != -1 && mIntentEventEndMillis != -1) {
mController.sendEventRelatedEventWithResponse(this, EventType.VIEW_EVENT, mViewEventId,
mIntentEventStartMillis, mIntentEventEndMillis, -1, -1,
mIntentAttendeeResponse);
mViewEventId = -1;
mIntentEventStartMillis = -1;
mIntentEventEndMillis = -1;
}
}
@Override
protected void onPause() {
super.onPause();
mPaused = true;
mHomeTime.removeCallbacks(mHomeTimeUpdater);
mContentResolver.unregisterContentObserver(mObserver);
if (isFinishing()) {
// Stop listening for changes that would require this to be refreshed
SharedPreferences prefs = GeneralPreferences.getSharedPreferences(this);
prefs.unregisterOnSharedPreferenceChangeListener(this);
}
// FRAG_TODO save highlighted days of the week;
if (mController.getViewType() != ViewType.EDIT) {
Utils.setDefaultView(this, mController.getViewType());
}
}
@Override
protected void onUserLeaveHint() {
mController.sendEvent(this, EventType.USER_HOME, null, null, -1, ViewType.CURRENT);
super.onUserLeaveHint();
}
@Override
public void onSaveInstanceState(Bundle outState) {
mOnSaveInstanceStateCalled = true;
super.onSaveInstanceState(outState);
outState.putLong(BUNDLE_KEY_RESTORE_TIME, mController.getTime());
if (mCurrentView == ViewType.EDIT) {
outState.putBoolean(BUNDLE_KEY_RESTORE_EDIT, true);
outState.putLong(BUNDLE_KEY_EVENT_ID, mController.getEventId());
}
}
@Override
protected void onDestroy() {
super.onDestroy();
SharedPreferences prefs = GeneralPreferences.getSharedPreferences(this);
prefs.unregisterOnSharedPreferenceChangeListener(this);
CalendarController.removeInstance(this);
}
private void initFragments(long timeMillis, int viewType, Bundle icicle) {
FragmentTransaction ft = getFragmentManager().openTransaction();
if (mIsMultipane) {
Fragment miniMonthFrag = new MonthByWeekFragment(timeMillis, true);
ft.replace(R.id.mini_month, miniMonthFrag);
mController.registerEventHandler(R.id.mini_month, (EventHandler) miniMonthFrag);
Fragment selectCalendarsFrag = new SelectCalendarsFragment();
ft.replace(R.id.calendar_list, selectCalendarsFrag);
}
if (!mIsMultipane || viewType == ViewType.EDIT) {
findViewById(R.id.mini_month).setVisibility(View.GONE);
findViewById(R.id.calendar_list).setVisibility(View.GONE);
}
EventInfo info = null;
if (viewType == ViewType.EDIT) {
mPreviousView = GeneralPreferences.getSharedPreferences(this).getInt(
GeneralPreferences.KEY_START_VIEW, GeneralPreferences.DEFAULT_START_VIEW);
long eventId = -1;
Intent intent = getIntent();
Uri data = intent.getData();
if (data != null) {
try {
eventId = Long.parseLong(data.getLastPathSegment());
} catch (NumberFormatException e) {
if (DEBUG) {
Log.d(TAG, "Create new event");
}
}
} else if (icicle != null && icicle.containsKey(BUNDLE_KEY_EVENT_ID)) {
eventId = icicle.getLong(BUNDLE_KEY_EVENT_ID);
}
long begin = intent.getLongExtra(EVENT_BEGIN_TIME, -1);
long end = intent.getLongExtra(EVENT_END_TIME, -1);
info = new EventInfo();
if (end != -1) {
info.endTime = new Time();
info.endTime.set(end);
}
if (begin != -1) {
info.startTime = new Time();
info.startTime.set(begin);
}
info.id = eventId;
// We set the viewtype so if the user presses back when they are
// done editing the controller knows we were in the Edit Event
// screen. Likewise for eventId
mController.setViewType(viewType);
mController.setEventId(eventId);
} else {
mPreviousView = viewType;
}
setMainPane(ft, R.id.main_pane, viewType, timeMillis, true, info);
ft.commit(); // this needs to be after setMainPane()
Time t = new Time(mTimeZone);
t.set(timeMillis);
if (viewType != ViewType.EDIT) {
mController.sendEvent(this, EventType.GO_TO, t, null, -1, viewType);
}
}
@Override
public void onBackPressed() {
if (mCurrentView == ViewType.EDIT || mCurrentView == ViewType.DETAIL) {
mController.sendEvent(this, EventType.GO_TO, null, null, -1, mPreviousView);
} else {
super.onBackPressed();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.all_in_one_title_bar, menu);
SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
if (searchView != null) {
searchView.setIconifiedByDefault(true);
searchView.setOnQueryChangeListener(this);
}
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Time t = null;
int viewType = ViewType.CURRENT;
switch (item.getItemId()) {
case R.id.action_refresh:
mController.refreshCalendars();
return true;
case R.id.action_today:
viewType = ViewType.CURRENT;
t = new Time(mTimeZone);
t.setToNow();
break;
case R.id.action_create_event:
mController.sendEventRelatedEvent(this, EventType.CREATE_EVENT, -1, 0, 0, 0, 0);
return true;
case R.id.action_settings:
mController.sendEvent(this, EventType.LAUNCH_SETTINGS, null, null, 0, 0);
return true;
default:
return false;
}
mController.sendEvent(this, EventType.GO_TO, t, null, -1, viewType);
return true;
}
@Override
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
if (key.equals(GeneralPreferences.KEY_WEEK_START_DAY)) {
if (mPaused) {
mUpdateOnResume = true;
} else {
initFragments(mController.getTime(), mController.getViewType(), null);
}
}
}
private void setMainPane(FragmentTransaction ft, int viewId, int viewType, long timeMillis,
boolean force, EventInfo e) {
if (mOnSaveInstanceStateCalled) {
return;
}
if (!force && mCurrentView == viewType) {
return;
}
if (viewType != mCurrentView) {
// The rules for this previous view are different than the
// controller's and are used for intercepting the back button.
if (mCurrentView != ViewType.EDIT && mCurrentView > 0) {
mPreviousView = mCurrentView;
}
mCurrentView = viewType;
}
// Create new fragment
Fragment frag;
switch (viewType) {
case ViewType.AGENDA:
frag = new AgendaFragment(timeMillis);
break;
case ViewType.DAY:
if (mActionBar != null && (mActionBar.getSelectedTab() != mDayTab)) {
mActionBar.selectTab(mDayTab);
}
frag = new DayFragment(timeMillis, 1);
break;
case ViewType.WEEK:
if (mActionBar != null && (mActionBar.getSelectedTab() != mWeekTab)) {
mActionBar.selectTab(mWeekTab);
}
frag = new DayFragment(timeMillis, 7);
break;
case ViewType.MONTH:
if (mActionBar != null && (mActionBar.getSelectedTab() != mMonthTab)) {
mActionBar.selectTab(mMonthTab);
}
frag = new MonthByWeekFragment(timeMillis, false);
break;
default:
throw new IllegalArgumentException(
"Must be Agenda, Day, Week, or Month ViewType, not " + viewType);
}
boolean doCommit = false;
if (ft == null) {
doCommit = true;
ft = getFragmentManager().openTransaction();
}
ft.replace(viewId, frag);
if (DEBUG) {
Log.d(TAG, "Adding handler with viewId " + viewId + " and type " + viewType);
}
// If the key is already registered this will replace it
mController.registerEventHandler(viewId, (EventHandler) frag);
if (doCommit) {
ft.commit();
}
}
private void setTitleInActionBar(EventInfo event) {
if (event.eventType != EventType.UPDATE_TITLE || mActionBar == null) {
return;
}
final long start = event.startTime.toMillis(false /* use isDst */);
final long end;
if (event.endTime != null) {
end = event.endTime.toMillis(false /* use isDst */);
} else {
end = start;
}
final String msg = Utils.formatDateRange(this, start, end, (int) event.extraLong);
mDateRange.setText(msg);
}
private void updateHomeClock() {
mTimeZone = Utils.getTimeZone(this, mHomeTimeUpdater);
if (mIsMultipane && (mCurrentView == ViewType.DAY || mCurrentView == ViewType.WEEK)
&& !TextUtils.equals(mTimeZone, Time.getCurrentTimezone())) {
Time time = new Time(mTimeZone);
time.setToNow();
long millis = time.toMillis(true);
boolean isDST = time.isDst != 0;
int flags = DateUtils.FORMAT_SHOW_TIME;
if (DateFormat.is24HourFormat(this)) {
flags |= DateUtils.FORMAT_24HOUR;
}
// Formats the time as
String timeString = (new StringBuilder(
Utils.formatDateRange(this, millis, millis, flags))).append(" ").append(
TimeZone.getTimeZone(mTimeZone).getDisplayName(
isDST, TimeZone.SHORT, Locale.getDefault())).toString();
mHomeTime.setText(timeString);
mHomeTime.setVisibility(View.VISIBLE);
// Update when the minute changes
mHomeTime.postDelayed(
mHomeTimeUpdater,
DateUtils.MINUTE_IN_MILLIS - (millis % DateUtils.MINUTE_IN_MILLIS));
} else {
mHomeTime.setVisibility(View.GONE);
}
}
@Override
public long getSupportedEventTypes() {
return EventType.GO_TO | EventType.VIEW_EVENT | EventType.UPDATE_TITLE;
}
@Override
public void handleEvent(EventInfo event) {
if (event.eventType == EventType.GO_TO) {
setMainPane(null, R.id.main_pane, event.viewType, event.startTime.toMillis(false),
false, event);
if (!mIsMultipane) {
return;
}
if (event.viewType == ViewType.MONTH) {
// hide minimonth and calendar frag
findViewById(R.id.mini_month).setVisibility(View.GONE);
findViewById(R.id.calendar_list).setVisibility(View.GONE);
+ findViewById(R.id.mini_month_container).setVisibility(View.GONE);
} else {
// show minimonth and calendar frag
findViewById(R.id.mini_month).setVisibility(View.VISIBLE);
findViewById(R.id.calendar_list).setVisibility(View.VISIBLE);
+ findViewById(R.id.mini_month_container).setVisibility(View.VISIBLE);
}
} else if (event.eventType == EventType.VIEW_EVENT) {
EventInfoFragment fragment = new EventInfoFragment(
event.id, event.startTime.toMillis(false), event.endTime.toMillis(false),
(int) event.extraLong);
fragment.setDialogParams(event.x, event.y);
fragment.show(getFragmentManager(), "EventInfoFragment");
} else if (event.eventType == EventType.UPDATE_TITLE) {
setTitleInActionBar(event);
}
updateHomeClock();
}
@Override
public void eventsChanged() {
mController.sendEvent(this, EventType.EVENTS_CHANGED, null, null, -1, ViewType.CURRENT);
}
@Override
public boolean onQueryTextChanged(String newText) {
return false;
}
@Override
public boolean onSubmitQuery(String query) {
mController.sendEvent(this, EventType.SEARCH, null, null, -1, ViewType.CURRENT, -1, query,
getComponentName());
return false;
}
@Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
if (tab == mDayTab && mCurrentView != ViewType.DAY) {
mController.sendEvent(this, EventType.GO_TO, null, null, -1, ViewType.DAY);
} else if (tab == mWeekTab && mCurrentView != ViewType.WEEK) {
mController.sendEvent(this, EventType.GO_TO, null, null, -1, ViewType.WEEK);
} else if (tab == mMonthTab && mCurrentView != ViewType.MONTH) {
mController.sendEvent(this, EventType.GO_TO, null, null, -1, ViewType.MONTH);
} else {
Log.w(TAG, "TabSelected event from unknown tab: " + tab);
}
}
@Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
@Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
}
diff --git a/src/com/android/calendar/month/MonthWeekEventsView.java b/src/com/android/calendar/month/MonthWeekEventsView.java
index 6eaae184..13828fe1 100644
--- a/src/com/android/calendar/month/MonthWeekEventsView.java
+++ b/src/com/android/calendar/month/MonthWeekEventsView.java
@@ -1,543 +1,546 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR 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.calendar.month;
import com.android.calendar.Event;
import com.android.calendar.R;
import com.android.calendar.Utils;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.graphics.Paint.Style;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.text.format.Time;
import android.util.Log;
import java.util.ArrayList;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
public class MonthWeekEventsView extends SimpleWeekView {
private static final String TAG = "MonthView";
public static final String VIEW_PARAMS_ORIENTATION = "orientation";
private static int TEXT_SIZE_MONTH_NUMBER = 32;
private static int TEXT_SIZE_EVENT = 14;
private static int TEXT_SIZE_MORE_EVENTS = 12;
private static int TEXT_SIZE_MONTH_NAME = 14;
private static int TEXT_SIZE_WEEK_NUM = 12;
private static final int DEFAULT_EDGE_SPACING = 4;
private static int PADDING_MONTH_NUMBER = 4;
private static int PADDING_WEEK_NUMBER = 16;
private static int DAY_SEPARATOR_OUTER_WIDTH = 5;
private static int DAY_SEPARATOR_INNER_WIDTH = 1;
private static int DAY_SEPARATOR_VERTICAL_LENGTH = 53;
private static int DAY_SEPARATOR_VERTICAL_LENGHT_PORTRAIT = 64;
private static int EVENT_X_OFFSET_LANDSCAPE = 44;
private static int EVENT_Y_OFFSET_LANDSCAPE = 11;
private static int EVENT_Y_OFFSET_PORTRAIT = 18;
private static int EVENT_SQUARE_WIDTH = 10;
private static int EVENT_SQUARE_BORDER = 1;
private static int EVENT_LINE_PADDING = 4;
private static int EVENT_RIGHT_PADDING = 4;
private static int EVENT_BOTTOM_PADDING = 15;
private static int SPACING_WEEK_NUMBER = 19;
private static boolean mScaled = false;
protected Time mToday = new Time();
protected boolean mHasToday = false;
protected int mTodayIndex = -1;
protected int mOrientation = Configuration.ORIENTATION_LANDSCAPE;
protected List<ArrayList<Event>> mEvents = null;
// This is for drawing the outlines around event chips and supports up to 5
// events being drawn on each day
protected float[] mEventOutlines = new float[5 * 4 * 4 * 7];
protected static StringBuilder mStringBuilder = new StringBuilder(50);
// TODO recreate formatter when locale changes
protected static Formatter mFormatter = new Formatter(mStringBuilder, Locale.getDefault());
protected Paint mMonthNamePaint;
protected TextPaint mEventPaint;
protected TextPaint mEventExtrasPaint;
protected Paint mWeekNumPaint;
protected Drawable mTodayDrawable;
protected int mMonthNumHeight;
protected int mEventHeight;
protected int mExtrasHeight;
protected int mWeekNumHeight;
protected int mMonthNumColor;
protected int mMonthNumOtherColor;
protected int mMonthNumTodayColor;
protected int mMonthNameColor;
protected int mMonthNameOtherColor;
protected int mMonthEventColor;
protected int mMonthEventExtraColor;
protected int mMonthEventOtherColor;
protected int mMonthEventExtraOtherColor;
protected int mMonthWeekNumColor;
protected int mEventChipOutlineColor = 0xFFFFFFFF;
protected int mDaySeparatorOuterColor = 0x33FFFFFF;
protected int mDaySeparatorInnerColor = 0x1A000000;
/**
* @param context
*/
public MonthWeekEventsView(Context context) {
super(context);
mPadding = DEFAULT_EDGE_SPACING;
if (mScale != 1 && !mScaled) {
PADDING_MONTH_NUMBER *= mScale;
PADDING_WEEK_NUMBER *= mScale;
SPACING_WEEK_NUMBER *= mScale;
TEXT_SIZE_MONTH_NUMBER *= mScale;
TEXT_SIZE_EVENT *= mScale;
TEXT_SIZE_MORE_EVENTS *= mScale;
TEXT_SIZE_MONTH_NAME *= mScale;
TEXT_SIZE_WEEK_NUM *= mScale;
DAY_SEPARATOR_OUTER_WIDTH *= mScale;
DAY_SEPARATOR_INNER_WIDTH *= mScale;
DAY_SEPARATOR_VERTICAL_LENGTH *= mScale;
DAY_SEPARATOR_VERTICAL_LENGHT_PORTRAIT *= mScale;
EVENT_X_OFFSET_LANDSCAPE *= mScale;
EVENT_Y_OFFSET_LANDSCAPE *= mScale;
EVENT_Y_OFFSET_PORTRAIT *= mScale;
EVENT_SQUARE_WIDTH *= mScale;
EVENT_LINE_PADDING *= mScale;
EVENT_BOTTOM_PADDING *= mScale;
EVENT_RIGHT_PADDING *= mScale;
mPadding = (int) (DEFAULT_EDGE_SPACING * mScale);
mScaled = true;
}
}
public void setEvents(List<ArrayList<Event>> sortedEvents) {
mEvents = sortedEvents;
if (sortedEvents == null) {
return;
}
if (sortedEvents.size() != mNumDays) {
if (Log.isLoggable(TAG, Log.ERROR)) {
Log.wtf(TAG, "Events size must be same as days displayed: size="
+ sortedEvents.size() + " days=" + mNumDays);
}
mEvents = null;
return;
}
}
protected void loadColors(Context context) {
Resources res = context.getResources();
mMonthWeekNumColor = res.getColor(R.color.month_week_num_color);
mMonthNumColor = res.getColor(R.color.month_day_number);
mMonthNumOtherColor = res.getColor(R.color.month_day_number_other);
mMonthNumTodayColor = res.getColor(R.color.month_today_number);
mMonthNameColor = mMonthNumColor;
mMonthNameOtherColor = mMonthNumOtherColor;
mMonthEventColor = res.getColor(R.color.month_event_color);
mMonthEventExtraColor = res.getColor(R.color.month_event_extra_color);
mMonthEventOtherColor = res.getColor(R.color.month_event_other_color);
mMonthEventExtraOtherColor = res.getColor(R.color.month_event_extra_other_color);
mTodayDrawable = res.getDrawable(R.drawable.today_blue_week_holo_light);
}
/**
* Sets up the text and style properties for painting. Override this if you
* want to use a different paint.
*/
@Override
protected void setPaintProperties() {
loadColors(mContext);
// TODO modify paint properties depending on isMini
p.setStyle(Style.FILL);
mMonthNumPaint = new Paint();
mMonthNumPaint.setFakeBoldText(false);
mMonthNumPaint.setAntiAlias(true);
mMonthNumPaint.setTextSize(TEXT_SIZE_MONTH_NUMBER);
mMonthNumPaint.setColor(mMonthNumColor);
mMonthNumPaint.setStyle(Style.FILL);
mMonthNumPaint.setTextAlign(Align.LEFT);
mMonthNumPaint.setTypeface(Typeface.DEFAULT_BOLD);
mMonthNumHeight = (int) (-mMonthNumPaint.ascent());
mEventPaint = new TextPaint();
mEventPaint.setFakeBoldText(false);
mEventPaint.setAntiAlias(true);
mEventPaint.setTextSize(TEXT_SIZE_EVENT);
mEventPaint.setColor(mMonthEventColor);
mEventHeight = (int) (-mEventPaint.ascent());
mEventExtrasPaint = new TextPaint();
mEventExtrasPaint.setFakeBoldText(false);
mEventExtrasPaint.setAntiAlias(true);
mEventExtrasPaint.setStrokeWidth(EVENT_SQUARE_BORDER);
mEventExtrasPaint.setTextSize(TEXT_SIZE_EVENT);
mEventExtrasPaint.setColor(mMonthEventExtraColor);
mEventExtrasPaint.setStyle(Style.FILL);
mEventExtrasPaint.setTextAlign(Align.LEFT);
mWeekNumPaint = new Paint();
mWeekNumPaint.setFakeBoldText(false);
mWeekNumPaint.setAntiAlias(true);
mWeekNumPaint.setTextSize(TEXT_SIZE_WEEK_NUM);
mWeekNumPaint.setColor(mWeekNumColor);
mWeekNumPaint.setStyle(Style.FILL);
mWeekNumPaint.setTextAlign(Align.RIGHT);
mWeekNumHeight = (int) (-mWeekNumPaint.ascent());
}
@Override
public void setWeekParams(HashMap<String, Integer> params, String tz) {
super.setWeekParams(params, tz);
if (params.containsKey(VIEW_PARAMS_ORIENTATION)) {
mOrientation = params.get(VIEW_PARAMS_ORIENTATION);
}
mToday.timezone = tz;
mToday.setToNow();
mToday.normalize(true);
int julianToday = Time.getJulianDay(mToday.toMillis(false), mToday.gmtoff);
if (julianToday >= mFirstJulianDay && julianToday < mFirstJulianDay + mNumDays) {
mHasToday = true;
mTodayIndex = julianToday - mFirstJulianDay;
} else {
mHasToday = false;
mTodayIndex = -1;
}
+ mNumCells = mNumDays + 1;
}
@Override
protected void onDraw(Canvas canvas) {
drawBackground(canvas);
drawWeekNums(canvas);
drawDaySeparators(canvas);
drawEvents(canvas);
}
@Override
protected void drawDaySeparators(Canvas canvas) {
// mDaySeparatorOuterColor
float lines[] = new float[8 * 4];
int count = 7 * 4;
int wkNumOffset = 0;
int effectiveWidth = mWidth - mPadding * 2;
count += 4;
wkNumOffset = 1;
effectiveWidth -= SPACING_WEEK_NUMBER;
lines[0] = mPadding;
lines[1] = DAY_SEPARATOR_OUTER_WIDTH / 2 + 1;
lines[2] = mWidth - mPadding;
lines[3] = lines[1];
int y0 = DAY_SEPARATOR_OUTER_WIDTH / 2 + DAY_SEPARATOR_INNER_WIDTH;
int y1;
if (mOrientation == Configuration.ORIENTATION_PORTRAIT) {
y1 = y0 + DAY_SEPARATOR_VERTICAL_LENGHT_PORTRAIT;
} else {
y1 = y0 + DAY_SEPARATOR_VERTICAL_LENGTH;
}
for (int i = 4; i < count;) {
int x = (i / 4 - wkNumOffset) * effectiveWidth / (mNumDays) + mPadding
+ (SPACING_WEEK_NUMBER * wkNumOffset);
lines[i++] = x;
lines[i++] = y0;
lines[i++] = x;
lines[i++] = y1;
}
p.setColor(mDaySeparatorOuterColor);
p.setStrokeWidth(DAY_SEPARATOR_OUTER_WIDTH);
canvas.drawLines(lines, 0, count, p);
p.setColor(mDaySeparatorInnerColor);
p.setStrokeWidth(DAY_SEPARATOR_INNER_WIDTH);
canvas.drawLines(lines, 0, count, p);
}
@Override
protected void drawBackground(Canvas canvas) {
if (mHasToday) {
p.setColor(mSelectedWeekBGColor);
} else {
return;
}
int wkNumOffset = 0;
int effectiveWidth = mWidth - mPadding * 2;
wkNumOffset = 1;
effectiveWidth -= SPACING_WEEK_NUMBER;
r.top = DAY_SEPARATOR_OUTER_WIDTH + 1;
r.bottom = mHeight;
r.left = (mTodayIndex) * effectiveWidth / (mNumDays) + mPadding
+ (SPACING_WEEK_NUMBER * wkNumOffset) + DAY_SEPARATOR_OUTER_WIDTH / 2 + 1;
r.right = (mTodayIndex + 1) * effectiveWidth / (mNumDays) + mPadding
+ (SPACING_WEEK_NUMBER * wkNumOffset) - DAY_SEPARATOR_OUTER_WIDTH / 2;
mTodayDrawable.setBounds(r);
mTodayDrawable.draw(canvas);
}
@Override
protected void drawWeekNums(Canvas canvas) {
int y;
int i = 0;
- int wkNumOffset = 0;
+ int offset = 0;
int effectiveWidth = mWidth - mPadding * 2;
int todayIndex = mTodayIndex;
int x = PADDING_WEEK_NUMBER + mPadding;
+ int numCount = mNumDays;
y = mWeekNumHeight + PADDING_MONTH_NUMBER;
if (mShowWeekNum) {
canvas.drawText(mDayNumbers[0], x, y, mWeekNumPaint);
+ numCount++;
+ i++;
+ todayIndex++;
+ offset++;
}
- i++;
- wkNumOffset = 1;
effectiveWidth -= SPACING_WEEK_NUMBER;
- todayIndex++;
y = (mMonthNumHeight + PADDING_MONTH_NUMBER);
boolean isFocusMonth = mFocusDay[i];
mMonthNumPaint.setColor(isFocusMonth ? mMonthNumColor : mMonthNumOtherColor);
- for (; i < mNumCells; i++) {
+ for (; i < numCount; i++) {
if (mHasToday && todayIndex == i) {
mMonthNumPaint.setColor(mMonthNumTodayColor);
if (i + 1 < mNumCells) {
// Make sure the color will be set back on the next
// iteration
isFocusMonth = !mFocusDay[i + 1];
}
} else if (mFocusDay[i] != isFocusMonth) {
isFocusMonth = mFocusDay[i];
mMonthNumPaint.setColor(isFocusMonth ? mMonthNumColor : mMonthNumOtherColor);
}
- x = (i - wkNumOffset) * effectiveWidth / (mNumDays) + mPadding + PADDING_MONTH_NUMBER
- + (SPACING_WEEK_NUMBER * wkNumOffset);
+ x = (i - offset) * effectiveWidth / (mNumDays) + mPadding + PADDING_MONTH_NUMBER
+ + SPACING_WEEK_NUMBER;
canvas.drawText(mDayNumbers[i], x, y, mMonthNumPaint);
}
}
protected void drawEvents(Canvas canvas) {
if (mEvents == null) {
return;
}
int wkNumOffset = 0;
int effectiveWidth = mWidth - mPadding * 2;
wkNumOffset = 1;
effectiveWidth -= SPACING_WEEK_NUMBER;
int day = -1;
int outlineCount = 0;
for (ArrayList<Event> eventDay : mEvents) {
day++;
if (eventDay == null || eventDay.size() == 0) {
continue;
}
int ySquare;
int xSquare = day * effectiveWidth / (mNumDays) + mPadding
+ (SPACING_WEEK_NUMBER * wkNumOffset);
if (mOrientation == Configuration.ORIENTATION_PORTRAIT) {
ySquare = EVENT_Y_OFFSET_PORTRAIT + mMonthNumHeight + PADDING_MONTH_NUMBER;
xSquare += PADDING_MONTH_NUMBER + 1;
} else {
ySquare = EVENT_Y_OFFSET_LANDSCAPE;
xSquare += EVENT_X_OFFSET_LANDSCAPE;
}
int rightEdge = (day + 1) * effectiveWidth / (mNumDays) + mPadding
+ (SPACING_WEEK_NUMBER * wkNumOffset) - EVENT_RIGHT_PADDING;
int eventCount = 0;
Iterator<Event> iter = eventDay.iterator();
while (iter.hasNext()) {
Event event = iter.next();
int newY = drawEvent(canvas, event, xSquare, ySquare, rightEdge, iter.hasNext());
if (newY == ySquare) {
break;
}
outlineCount = addChipOutline(mEventOutlines, outlineCount, xSquare, ySquare);
eventCount++;
ySquare = newY;
}
int remaining = eventDay.size() - eventCount;
if (remaining > 0) {
drawMoreEvents(canvas, remaining, xSquare);
}
}
if (outlineCount > 0) {
p.setColor(mEventChipOutlineColor);
p.setStrokeWidth(EVENT_SQUARE_BORDER);
canvas.drawLines(mEventOutlines, 0, outlineCount, p);
}
}
protected int addChipOutline(float[] lines, int count, int x, int y) {
// top of box
lines[count++] = x;
lines[count++] = y;
lines[count++] = x + EVENT_SQUARE_WIDTH;
lines[count++] = y;
// right side of box
lines[count++] = x + EVENT_SQUARE_WIDTH;
lines[count++] = y;
lines[count++] = x + EVENT_SQUARE_WIDTH;
lines[count++] = y + EVENT_SQUARE_WIDTH;
// left side of box
lines[count++] = x;
lines[count++] = y;
lines[count++] = x;
lines[count++] = y + EVENT_SQUARE_WIDTH + 1;
// bottom of box
lines[count++] = x;
lines[count++] = y + EVENT_SQUARE_WIDTH;
lines[count++] = x + EVENT_SQUARE_WIDTH;
lines[count++] = y + EVENT_SQUARE_WIDTH;
return count;
}
/**
* Attempts to draw the given event. Returns the y for the next event or the
* original y if the event will not fit. An event is considered to not fit
* if the event and its extras won't fit or if there are more events and the
* more events line would not fit after drawing this event.
*
* @param event the event to draw
* @param x the top left corner for this event's color chip
* @param y the top left corner for this event's color chip
* @return the y for the next event or the original y if it won't fit
*/
protected int drawEvent(
Canvas canvas, Event event, int x, int y, int rightEdge, boolean moreEvents) {
int requiredSpace = EVENT_LINE_PADDING + mEventHeight;
int multiplier = 1;
if (moreEvents) {
multiplier++;
}
if (!event.allDay) {
multiplier++;
}
requiredSpace *= multiplier;
if (requiredSpace + y >= mHeight - EVENT_BOTTOM_PADDING) {
// Not enough space, return
return y;
}
r.left = x;
r.right = x + EVENT_SQUARE_WIDTH;
r.top = y;
r.bottom = y + EVENT_SQUARE_WIDTH;
p.setColor(event.color);
canvas.drawRect(r, p);
int textX = x + EVENT_SQUARE_WIDTH + EVENT_LINE_PADDING;
int textY = y + mEventHeight - EVENT_LINE_PADDING / 2;
float avail = rightEdge - textX;
CharSequence text = TextUtils.ellipsize(
event.title, mEventPaint, avail, TextUtils.TruncateAt.END);
canvas.drawText(text.toString(), textX, textY, mEventPaint);
if (!event.allDay) {
textY += mEventHeight + EVENT_LINE_PADDING;
mStringBuilder.setLength(0);
text = DateUtils.formatDateRange(mContext, mFormatter, event.startMillis,
event.endMillis, DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_ABBREV_ALL,
Utils.getTimeZone(mContext, null)).toString();
text = TextUtils.ellipsize(text, mEventExtrasPaint, avail, TextUtils.TruncateAt.END);
canvas.drawText(text.toString(), textX, textY, mEventExtrasPaint);
}
return textY + EVENT_LINE_PADDING;
}
protected void drawMoreEvents(Canvas canvas, int remainingEvents, int x) {
float[] lines = new float[4 * 4];
int y = mHeight - EVENT_BOTTOM_PADDING + EVENT_LINE_PADDING / 2 - mEventHeight;
addChipOutline(lines, 0, x, y);
canvas.drawLines(lines, mEventExtrasPaint);
String text = mContext.getResources().getQuantityString(
R.plurals.month_more_events, remainingEvents);
y = mHeight - EVENT_BOTTOM_PADDING;
x += EVENT_SQUARE_WIDTH + EVENT_LINE_PADDING;
mEventExtrasPaint.setFakeBoldText(true);
canvas.drawText(String.format(text, remainingEvents), x, y, mEventExtrasPaint);
mEventExtrasPaint.setFakeBoldText(false);
}
@Override
protected void updateSelectionPositions() {
if (mHasSelectedDay) {
int selectedPosition = mSelectedDay - mWeekStart;
if (selectedPosition < 0) {
selectedPosition += 7;
}
int effectiveWidth = mWidth - mPadding * 2;
effectiveWidth -= SPACING_WEEK_NUMBER;
mSelectedLeft = selectedPosition * effectiveWidth / mNumDays + mPadding;
mSelectedRight = (selectedPosition + 1) * effectiveWidth / mNumDays + mPadding;
mSelectedLeft += SPACING_WEEK_NUMBER;
mSelectedRight += SPACING_WEEK_NUMBER;
}
}
@Override
public Time getDayFromLocation(float x) {
int dayStart = SPACING_WEEK_NUMBER + mPadding;
if (x < dayStart || x > mWidth - mPadding) {
return null;
}
// Selection is (x - start) / (pixels/day) == (x -s) * day / pixels
int dayPosition = (int) ((x - dayStart) * mNumDays / (mWidth - dayStart - mPadding));
int day = mFirstJulianDay + dayPosition;
Time time = new Time(mTimeZone);
if (mWeek == 0) {
// This week is weird...
if (day < Time.EPOCH_JULIAN_DAY) {
day++;
} else if (day == Time.EPOCH_JULIAN_DAY) {
time.set(1, 0, 1970);
time.normalize(true);
return time;
}
}
time.setJulianDay(day);
return time;
}
}
| false | false | null | null |