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/src/com/fsck/k9/activity/setup/AccountSetupCheckSettings.java b/src/com/fsck/k9/activity/setup/AccountSetupCheckSettings.java
index dad53476..c64928cf 100644
--- a/src/com/fsck/k9/activity/setup/AccountSetupCheckSettings.java
+++ b/src/com/fsck/k9/activity/setup/AccountSetupCheckSettings.java
@@ -1,400 +1,408 @@
package com.fsck.k9.activity.setup;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Process;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.fsck.k9.*;
import com.fsck.k9.activity.K9Activity;
import com.fsck.k9.controller.MessagingController;
import com.fsck.k9.mail.AuthenticationFailedException;
import com.fsck.k9.mail.CertificateValidationException;
import com.fsck.k9.mail.Store;
import com.fsck.k9.mail.Transport;
import com.fsck.k9.mail.store.TrustManagerFactory;
import com.fsck.k9.mail.store.WebDavStore;
import com.fsck.k9.mail.filter.Hex;
import java.security.cert.CertificateException;
import java.security.cert.CertificateEncodingException;
import java.security.cert.X509Certificate;
import java.security.NoSuchAlgorithmException;
import java.security.MessageDigest;
import java.util.Collection;
import java.util.List;
/**
* Checks the given settings to make sure that they can be used to send and
* receive mail.
*
* XXX NOTE: The manifest for this app has it ignore config changes, because
* it doesn't correctly deal with restarting while its thread is running.
*/
public class AccountSetupCheckSettings extends K9Activity implements OnClickListener {
public static final int ACTIVITY_REQUEST_CODE = 1;
private static final String EXTRA_ACCOUNT = "account";
private static final String EXTRA_CHECK_INCOMING = "checkIncoming";
private static final String EXTRA_CHECK_OUTGOING = "checkOutgoing";
private Handler mHandler = new Handler();
private ProgressBar mProgressBar;
private TextView mMessageView;
private Account mAccount;
private boolean mCheckIncoming;
private boolean mCheckOutgoing;
private boolean mCanceled;
private boolean mDestroyed;
public static void actionCheckSettings(Activity context, Account account,
boolean checkIncoming, boolean checkOutgoing) {
Intent i = new Intent(context, AccountSetupCheckSettings.class);
i.putExtra(EXTRA_ACCOUNT, account.getUuid());
i.putExtra(EXTRA_CHECK_INCOMING, checkIncoming);
i.putExtra(EXTRA_CHECK_OUTGOING, checkOutgoing);
context.startActivityForResult(i, ACTIVITY_REQUEST_CODE);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.account_setup_check_settings);
mMessageView = (TextView)findViewById(R.id.message);
mProgressBar = (ProgressBar)findViewById(R.id.progress);
((Button)findViewById(R.id.cancel)).setOnClickListener(this);
setMessage(R.string.account_setup_check_settings_retr_info_msg);
mProgressBar.setIndeterminate(true);
String accountUuid = getIntent().getStringExtra(EXTRA_ACCOUNT);
mAccount = Preferences.getPreferences(this).getAccount(accountUuid);
mCheckIncoming = getIntent().getBooleanExtra(EXTRA_CHECK_INCOMING, false);
mCheckOutgoing = getIntent().getBooleanExtra(EXTRA_CHECK_OUTGOING, false);
new Thread() {
@Override
public void run() {
Store store = null;
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
try {
if (mDestroyed) {
return;
}
if (mCanceled) {
finish();
return;
}
if (mCheckIncoming) {
store = mAccount.getRemoteStore();
if (store instanceof WebDavStore) {
setMessage(R.string.account_setup_check_settings_authenticate);
} else {
setMessage(R.string.account_setup_check_settings_check_incoming_msg);
}
store.checkSettings();
if (store instanceof WebDavStore) {
setMessage(R.string.account_setup_check_settings_fetch);
}
MessagingController.getInstance(getApplication()).listFoldersSynchronous(mAccount, true, null);
MessagingController.getInstance(getApplication()).synchronizeMailbox(mAccount, mAccount.getInboxFolderName(), null, null);
}
if (mDestroyed) {
return;
}
if (mCanceled) {
finish();
return;
}
if (mCheckOutgoing) {
if (!(mAccount.getRemoteStore() instanceof WebDavStore)) {
setMessage(R.string.account_setup_check_settings_check_outgoing_msg);
}
Transport transport = Transport.getInstance(mAccount);
transport.close();
transport.open();
transport.close();
}
if (mDestroyed) {
return;
}
if (mCanceled) {
finish();
return;
}
setResult(RESULT_OK);
finish();
} catch (final AuthenticationFailedException afe) {
Log.e(K9.LOG_TAG, "Error while testing settings", afe);
showErrorDialog(
R.string.account_setup_failed_dlg_auth_message_fmt,
afe.getMessage() == null ? "" : afe.getMessage());
} catch (final CertificateValidationException cve) {
Log.e(K9.LOG_TAG, "Error while testing settings", cve);
- acceptKeyDialog(
- R.string.account_setup_failed_dlg_certificate_message_fmt,
- cve);
+
+ // Avoid NullPointerException in acceptKeyDialog()
+ if (TrustManagerFactory.getLastCertChain() != null) {
+ acceptKeyDialog(
+ R.string.account_setup_failed_dlg_certificate_message_fmt,
+ cve);
+ } else {
+ showErrorDialog(
+ R.string.account_setup_failed_dlg_server_message_fmt,
+ (cve.getMessage() == null ? "" : cve.getMessage()));
+ }
} catch (final Throwable t) {
Log.e(K9.LOG_TAG, "Error while testing settings", t);
showErrorDialog(
R.string.account_setup_failed_dlg_server_message_fmt,
(t.getMessage() == null ? "" : t.getMessage()));
}
}
}
.start();
}
@Override
public void onDestroy() {
super.onDestroy();
mDestroyed = true;
mCanceled = true;
}
private void setMessage(final int resId) {
mHandler.post(new Runnable() {
public void run() {
if (mDestroyed) {
return;
}
mMessageView.setText(getString(resId));
}
});
}
private void showErrorDialog(final int msgResId, final Object... args) {
mHandler.post(new Runnable() {
public void run() {
if (mDestroyed) {
return;
}
mProgressBar.setIndeterminate(false);
new AlertDialog.Builder(AccountSetupCheckSettings.this)
.setTitle(getString(R.string.account_setup_failed_dlg_title))
.setMessage(getString(msgResId, args))
.setCancelable(true)
.setNegativeButton(
getString(R.string.account_setup_failed_dlg_continue_action),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
mCanceled = false;
setResult(RESULT_OK);
finish();
}
})
.setPositiveButton(
getString(R.string.account_setup_failed_dlg_edit_details_action),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.show();
}
});
}
private void acceptKeyDialog(final int msgResId, final Object... args) {
mHandler.post(new Runnable() {
public void run() {
if (mDestroyed) {
return;
}
final X509Certificate[] chain = TrustManagerFactory.getLastCertChain();
String exMessage = "Unknown Error";
Exception ex = ((Exception)args[0]);
if (ex != null) {
if (ex.getCause() != null) {
if (ex.getCause().getCause() != null) {
exMessage = ex.getCause().getCause().getMessage();
} else {
exMessage = ex.getCause().getMessage();
}
} else {
exMessage = ex.getMessage();
}
}
mProgressBar.setIndeterminate(false);
StringBuilder chainInfo = new StringBuilder(100);
MessageDigest sha1 = null;
try {
sha1 = MessageDigest.getInstance("SHA-1");
} catch (NoSuchAlgorithmException e) {
Log.e(K9.LOG_TAG, "Error while initializing MessageDigest", e);
}
for (int i = 0; i < chain.length; i++) {
// display certificate chain information
//TODO: localize this strings
chainInfo.append("Certificate chain[").append(i).append("]:\n");
chainInfo.append("Subject: ").append(chain[i].getSubjectDN().toString()).append("\n");
// display SubjectAltNames too
// (the user may be mislead into mistrusting a certificate
// by a subjectDN not matching the server even though a
// SubjectAltName matches)
try {
final Collection < List<? >> subjectAlternativeNames = chain[i].getSubjectAlternativeNames();
if (subjectAlternativeNames != null) {
// The list of SubjectAltNames may be very long
//TODO: localize this string
StringBuilder altNamesText = new StringBuilder();
altNamesText.append("Subject has ").append(subjectAlternativeNames.size()).append(" alternative names\n");
// we need these for matching
String storeURIHost = (Uri.parse(mAccount.getStoreUri())).getHost();
String transportURIHost = (Uri.parse(mAccount.getTransportUri())).getHost();
for (List<?> subjectAlternativeName : subjectAlternativeNames) {
Integer type = (Integer)subjectAlternativeName.get(0);
Object value = subjectAlternativeName.get(1);
String name = "";
switch (type.intValue()) {
case 0:
Log.w(K9.LOG_TAG, "SubjectAltName of type OtherName not supported.");
continue;
case 1: // RFC822Name
name = (String)value;
break;
case 2: // DNSName
name = (String)value;
break;
case 3:
Log.w(K9.LOG_TAG, "unsupported SubjectAltName of type x400Address");
continue;
case 4:
Log.w(K9.LOG_TAG, "unsupported SubjectAltName of type directoryName");
continue;
case 5:
Log.w(K9.LOG_TAG, "unsupported SubjectAltName of type ediPartyName");
continue;
case 6: // Uri
name = (String)value;
break;
case 7: // ip-address
name = (String)value;
break;
default:
Log.w(K9.LOG_TAG, "unsupported SubjectAltName of unknown type");
continue;
}
// if some of the SubjectAltNames match the store or transport -host,
// display them
if (name.equalsIgnoreCase(storeURIHost) || name.equalsIgnoreCase(transportURIHost)) {
//TODO: localize this string
altNamesText.append("Subject(alt): ").append(name).append(",...\n");
} else if (name.startsWith("*.")) {
if (storeURIHost.endsWith(name.substring(2)) || transportURIHost.endsWith(name.substring(2))) {
//TODO: localize this string
altNamesText.append("Subject(alt): ").append(name).append(",...\n");
}
}
}
chainInfo.append(altNamesText);
}
} catch (Exception e1) {
// don't fail just because of subjectAltNames
Log.w(K9.LOG_TAG, "cannot display SubjectAltNames in dialog", e1);
}
chainInfo.append("Issuer: ").append(chain[i].getIssuerDN().toString()).append("\n");
if (sha1 != null) {
sha1.reset();
try {
char[] sha1sum = Hex.encodeHex(sha1.digest(chain[i].getEncoded()));
chainInfo.append("Fingerprint (SHA-1): ").append(new String(sha1sum)).append("\n");
} catch (CertificateEncodingException e) {
Log.e(K9.LOG_TAG, "Error while encoding certificate", e);
}
}
}
new AlertDialog.Builder(AccountSetupCheckSettings.this)
.setTitle(getString(R.string.account_setup_failed_dlg_invalid_certificate_title))
//.setMessage(getString(R.string.account_setup_failed_dlg_invalid_certificate)
.setMessage(getString(msgResId, exMessage)
+ " " + chainInfo.toString()
)
.setCancelable(true)
.setPositiveButton(
getString(R.string.account_setup_failed_dlg_invalid_certificate_accept),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
try {
String alias = mAccount.getUuid();
if (mCheckIncoming) {
alias = alias + ".incoming";
}
if (mCheckOutgoing) {
alias = alias + ".outgoing";
}
TrustManagerFactory.addCertificateChain(alias, chain);
} catch (CertificateException e) {
showErrorDialog(
R.string.account_setup_failed_dlg_certificate_message_fmt,
e.getMessage() == null ? "" : e.getMessage());
}
AccountSetupCheckSettings.actionCheckSettings(AccountSetupCheckSettings.this, mAccount,
mCheckIncoming, mCheckOutgoing);
}
})
.setNegativeButton(
getString(R.string.account_setup_failed_dlg_invalid_certificate_reject),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.show();
}
});
}
@Override
public void onActivityResult(int reqCode, int resCode, Intent data) {
setResult(resCode);
finish();
}
private void onCancel() {
mCanceled = true;
setMessage(R.string.account_setup_check_settings_canceling_msg);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.cancel:
onCancel();
break;
}
}
}
diff --git a/src/com/fsck/k9/mail/store/TrustManagerFactory.java b/src/com/fsck/k9/mail/store/TrustManagerFactory.java
index b6ead8d9..32c9f457 100644
--- a/src/com/fsck/k9/mail/store/TrustManagerFactory.java
+++ b/src/com/fsck/k9/mail/store/TrustManagerFactory.java
@@ -1,215 +1,217 @@
package com.fsck.k9.mail.store;
import android.app.Application;
import android.content.Context;
import android.util.Log;
import com.fsck.k9.K9;
import com.fsck.k9.helper.DomainNameChecker;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;
public final class TrustManagerFactory {
private static final String LOG_TAG = "TrustManagerFactory";
private static X509TrustManager defaultTrustManager;
private static X509TrustManager unsecureTrustManager;
private static X509TrustManager localTrustManager;
private static X509Certificate[] lastCertChain = null;
private static File keyStoreFile;
private static KeyStore keyStore;
private static class SimpleX509TrustManager implements X509TrustManager {
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
}
private static class SecureX509TrustManager implements X509TrustManager {
private static final Map<String, SecureX509TrustManager> mTrustManager =
new HashMap<String, SecureX509TrustManager>();
private final String mHost;
private SecureX509TrustManager(String host) {
mHost = host;
}
public synchronized static X509TrustManager getInstance(String host) {
SecureX509TrustManager trustManager;
if (mTrustManager.containsKey(host)) {
trustManager = mTrustManager.get(host);
} else {
trustManager = new SecureX509TrustManager(host);
mTrustManager.put(host, trustManager);
}
return trustManager;
}
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
defaultTrustManager.checkClientTrusted(chain, authType);
}
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
+ // FIXME: Using a static field to store the certificate chain is a bad idea. Instead
+ // create a CertificateException subclass and store the chain there.
TrustManagerFactory.setLastCertChain(chain);
try {
defaultTrustManager.checkServerTrusted(chain, authType);
} catch (CertificateException e) {
localTrustManager.checkServerTrusted(new X509Certificate[] {chain[0]}, authType);
}
if (!DomainNameChecker.match(chain[0], mHost)) {
try {
String dn = chain[0].getSubjectDN().toString();
if ((dn != null) && (dn.equalsIgnoreCase(keyStore.getCertificateAlias(chain[0])))) {
return;
}
} catch (KeyStoreException e) {
throw new CertificateException("Certificate cannot be verified; KeyStore Exception: " + e);
}
throw new CertificateException("Certificate domain name does not match "
+ mHost);
}
}
public X509Certificate[] getAcceptedIssuers() {
return defaultTrustManager.getAcceptedIssuers();
}
}
static {
try {
javax.net.ssl.TrustManagerFactory tmf = javax.net.ssl.TrustManagerFactory.getInstance("X509");
Application app = K9.app;
keyStoreFile = new File(app.getDir("KeyStore", Context.MODE_PRIVATE) + File.separator + "KeyStore.bks");
keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
java.io.FileInputStream fis;
try {
fis = new java.io.FileInputStream(keyStoreFile);
} catch (FileNotFoundException e1) {
fis = null;
}
try {
keyStore.load(fis, "".toCharArray());
//if (fis != null) {
// fis.close();
//}
} catch (IOException e) {
Log.e(LOG_TAG, "KeyStore IOException while initializing TrustManagerFactory ", e);
keyStore = null;
} catch (CertificateException e) {
Log.e(LOG_TAG, "KeyStore CertificateException while initializing TrustManagerFactory ", e);
keyStore = null;
}
tmf.init(keyStore);
TrustManager[] tms = tmf.getTrustManagers();
if (tms != null) {
for (TrustManager tm : tms) {
if (tm instanceof X509TrustManager) {
localTrustManager = (X509TrustManager)tm;
break;
}
}
}
tmf = javax.net.ssl.TrustManagerFactory.getInstance("X509");
tmf.init((KeyStore)null);
tms = tmf.getTrustManagers();
if (tms != null) {
for (TrustManager tm : tms) {
if (tm instanceof X509TrustManager) {
defaultTrustManager = (X509TrustManager) tm;
break;
}
}
}
} catch (NoSuchAlgorithmException e) {
Log.e(LOG_TAG, "Unable to get X509 Trust Manager ", e);
} catch (KeyStoreException e) {
Log.e(LOG_TAG, "Key Store exception while initializing TrustManagerFactory ", e);
}
unsecureTrustManager = new SimpleX509TrustManager();
}
private TrustManagerFactory() {
}
public static X509TrustManager get(String host, boolean secure) {
return secure ? SecureX509TrustManager.getInstance(host) :
unsecureTrustManager;
}
public static KeyStore getKeyStore() {
return keyStore;
}
public static void setLastCertChain(X509Certificate[] chain) {
lastCertChain = chain;
}
public static X509Certificate[] getLastCertChain() {
return lastCertChain;
}
public static void addCertificateChain(String alias, X509Certificate[] chain) throws CertificateException {
try {
javax.net.ssl.TrustManagerFactory tmf = javax.net.ssl.TrustManagerFactory.getInstance("X509");
for (X509Certificate element : chain) {
keyStore.setCertificateEntry
(element.getSubjectDN().toString(), element);
}
tmf.init(keyStore);
TrustManager[] tms = tmf.getTrustManagers();
if (tms != null) {
for (TrustManager tm : tms) {
if (tm instanceof X509TrustManager) {
localTrustManager = (X509TrustManager) tm;
break;
}
}
}
java.io.FileOutputStream keyStoreStream;
try {
keyStoreStream = new java.io.FileOutputStream(keyStoreFile);
keyStore.store(keyStoreStream, "".toCharArray());
keyStoreStream.close();
} catch (FileNotFoundException e) {
throw new CertificateException("Unable to write KeyStore: " + e.getMessage());
} catch (CertificateException e) {
throw new CertificateException("Unable to write KeyStore: " + e.getMessage());
} catch (IOException e) {
throw new CertificateException("Unable to write KeyStore: " + e.getMessage());
}
} catch (NoSuchAlgorithmException e) {
Log.e(LOG_TAG, "Unable to get X509 Trust Manager ", e);
} catch (KeyStoreException e) {
Log.e(LOG_TAG, "Key Store exception while initializing TrustManagerFactory ", e);
}
}
}
| false | false | null | null |
diff --git a/client/src/test/java/org/apache/abdera/test/client/TestSuite.java b/client/src/test/java/org/apache/abdera/test/client/TestSuite.java
index ff26d814..85ac42a9 100644
--- a/client/src/test/java/org/apache/abdera/test/client/TestSuite.java
+++ b/client/src/test/java/org/apache/abdera/test/client/TestSuite.java
@@ -1,32 +1,32 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. 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. For additional information regarding
* copyright in this work, please see the NOTICE file in the top level
* directory of this distribution.
*/
package org.apache.abdera.test.client;
import org.apache.abdera.test.client.cache.*;
public class TestSuite extends junit.framework.TestSuite {
public static void main(String[] args)
{
junit.textui.TestRunner.run(new TestSuite());
}
public TestSuite()
{
- addTestSuite(CacheTests.class);
+ addTestSuite(CacheTest.class);
}
}
| true | false | null | null |
diff --git a/src/com/android/launcher3/Folder.java b/src/com/android/launcher3/Folder.java
index bb3993efc..c70cbe0a5 100644
--- a/src/com/android/launcher3/Folder.java
+++ b/src/com/android/launcher3/Folder.java
@@ -1,1241 +1,1241 @@
/*
* 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.launcher3;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.PointF;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.text.InputType;
import android.text.Selection;
import android.text.Spannable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.ActionMode;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityManager;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Interpolator;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import com.android.launcher3.FolderInfo.FolderListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
/**
* Represents a set of icons chosen by the user or generated by the system.
*/
public class Folder extends LinearLayout implements DragSource, View.OnClickListener,
View.OnLongClickListener, DropTarget, FolderListener, TextView.OnEditorActionListener,
View.OnFocusChangeListener {
private static final String TAG = "Launcher.Folder";
protected DragController mDragController;
protected Launcher mLauncher;
protected FolderInfo mInfo;
static final int STATE_NONE = -1;
static final int STATE_SMALL = 0;
static final int STATE_ANIMATING = 1;
static final int STATE_OPEN = 2;
private int mExpandDuration;
protected CellLayout mContent;
private ScrollView mScrollView;
private final LayoutInflater mInflater;
private final IconCache mIconCache;
private int mState = STATE_NONE;
private static final int REORDER_ANIMATION_DURATION = 230;
private static final int REORDER_DELAY = 250;
private static final int ON_EXIT_CLOSE_DELAY = 800;
private boolean mRearrangeOnClose = false;
private FolderIcon mFolderIcon;
private int mMaxCountX;
private int mMaxCountY;
private int mMaxVisibleX;
private int mMaxVisibleY;
private int mMaxContentAreaHeight = 0;
private int mMaxNumItems;
private ArrayList<View> mItemsInReadingOrder = new ArrayList<View>();
private Drawable mIconDrawable;
boolean mItemsInvalidated = false;
private ShortcutInfo mCurrentDragInfo;
private View mCurrentDragView;
boolean mSuppressOnAdd = false;
private int[] mTargetCell = new int[2];
private int[] mPreviousTargetCell = new int[2];
private int[] mEmptyCell = new int[2];
private Alarm mReorderAlarm = new Alarm();
private Alarm mOnExitAlarm = new Alarm();
private int mFolderNameHeight;
private Rect mTempRect = new Rect();
private boolean mDragInProgress = false;
private boolean mDeleteFolderOnDropCompleted = false;
private boolean mSuppressFolderDeletion = false;
private boolean mItemAddedBackToSelfViaIcon = false;
FolderEditText mFolderName;
private float mFolderIconPivotX;
private float mFolderIconPivotY;
private static final int SCROLL_CUT_OFF_AMOUNT = 60;
private static final float MAX_SCROLL_VELOCITY = 1500f;
private boolean mIsEditingName = false;
private InputMethodManager mInputMethodManager;
private static String sDefaultFolderName;
private static String sHintText;
private int DRAG_MODE_NONE = 0;
private int DRAG_MODE_REORDER = 1;
private int mDragMode = DRAG_MODE_NONE;
private boolean mDestroyed;
private AutoScroller mAutoScroller;
private Runnable mDeferredAction;
private boolean mDeferDropAfterUninstall;
private boolean mUninstallSuccessful;
/**
* Used to inflate the Workspace from XML.
*
* @param context The application's context.
* @param attrs The attribtues set containing the Workspace's customization values.
*/
public Folder(Context context, AttributeSet attrs) {
super(context, attrs);
setAlwaysDrawnWithCacheEnabled(false);
mInflater = LayoutInflater.from(context);
mIconCache = (LauncherAppState.getInstance()).getIconCache();
Resources res = getResources();
mMaxCountX = mMaxVisibleX = res.getInteger(R.integer.folder_max_count_x);
mMaxCountY = mMaxVisibleY = res.getInteger(R.integer.folder_max_count_y);
mMaxNumItems = res.getInteger(R.integer.folder_max_num_items);
if (mMaxCountY == -1) {
// -2 indicates unlimited
mMaxCountY = Integer.MAX_VALUE;
mMaxVisibleX = LauncherModel.getCellCountX() + 1;
}
if (mMaxNumItems == -1) {
// -2 indicates unlimited
mMaxNumItems = Integer.MAX_VALUE;
mMaxVisibleY = LauncherModel.getCellCountY() + 1;
}
if (mMaxCountX == 0) {
mMaxCountX = mMaxVisibleX = LauncherModel.getCellCountX();
mMaxVisibleX++;
}
if (mMaxCountY == 0) {
mMaxCountY = mMaxVisibleY = LauncherModel.getCellCountY();
mMaxVisibleY++;
}
if (mMaxNumItems == 0) {
mMaxNumItems = mMaxCountX * mMaxCountY;
if (mMaxNumItems < 0) {
mMaxNumItems = Integer.MAX_VALUE;
}
}
mInputMethodManager = (InputMethodManager)
getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
mExpandDuration = res.getInteger(R.integer.config_folderAnimDuration);
if (sDefaultFolderName == null) {
sDefaultFolderName = res.getString(R.string.folder_name);
}
if (sHintText == null) {
sHintText = res.getString(R.string.folder_hint_text);
}
mLauncher = (Launcher) context;
// We need this view to be focusable in touch mode so that when text editing of the folder
// name is complete, we have something to focus on, thus hiding the cursor and giving
// reliable behvior when clicking the text field (since it will always gain focus on click).
setFocusableInTouchMode(true);
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
mScrollView = (ScrollView) findViewById(R.id.scroll_view);
mContent = (CellLayout) findViewById(R.id.folder_content);
// Beyond this height, the area scrolls
mContent.setGridSize(mMaxVisibleX, mMaxVisibleY);
mMaxContentAreaHeight = mContent.getDesiredHeight() - SCROLL_CUT_OFF_AMOUNT;
mContent.setGridSize(0, 0);
mContent.getShortcutsAndWidgets().setMotionEventSplittingEnabled(false);
mContent.setInvertIfRtl(true);
mFolderName = (FolderEditText) findViewById(R.id.folder_name);
mFolderName.setFolder(this);
mFolderName.setOnFocusChangeListener(this);
// We find out how tall the text view wants to be (it is set to wrap_content), so that
// we can allocate the appropriate amount of space for it.
int measureSpec = MeasureSpec.UNSPECIFIED;
mFolderName.measure(measureSpec, measureSpec);
mFolderNameHeight = mFolderName.getMeasuredHeight();
// We disable action mode for now since it messes up the view on phones
mFolderName.setCustomSelectionActionModeCallback(mActionModeCallback);
mFolderName.setOnEditorActionListener(this);
mFolderName.setSelectAllOnFocus(true);
mFolderName.setInputType(mFolderName.getInputType() |
InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS | InputType.TYPE_TEXT_FLAG_CAP_WORDS);
mAutoScroller = new AutoScroller(mScrollView);
mAutoScroller.setMaximumVelocityAbsolute(MAX_SCROLL_VELOCITY, MAX_SCROLL_VELOCITY);
mAutoScroller.setExtendsBeyondEdges(false);
}
private ActionMode.Callback mActionModeCallback = new ActionMode.Callback() {
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
return false;
}
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
return false;
}
public void onDestroyActionMode(ActionMode mode) {
}
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
};
public void onClick(View v) {
Object tag = v.getTag();
if (tag instanceof ShortcutInfo) {
mLauncher.onClick(v);
}
}
public boolean onLongClick(View v) {
// Return if global dragging is not enabled
if (!mLauncher.isDraggingEnabled()) return true;
Object tag = v.getTag();
if (tag instanceof ShortcutInfo) {
ShortcutInfo item = (ShortcutInfo) tag;
if (!v.isInTouchMode()) {
return false;
}
mLauncher.dismissFolderCling(null);
mLauncher.getWorkspace().onDragStartedWithItem(v);
mLauncher.getWorkspace().beginDragShared(v, this);
mIconDrawable = ((TextView) v).getCompoundDrawables()[1];
mCurrentDragInfo = item;
mEmptyCell[0] = item.cellX;
mEmptyCell[1] = item.cellY;
mCurrentDragView = v;
mContent.removeView(mCurrentDragView);
mInfo.remove(mCurrentDragInfo);
mDragInProgress = true;
mItemAddedBackToSelfViaIcon = false;
}
return true;
}
public boolean isEditingName() {
return mIsEditingName;
}
public void startEditingFolderName() {
mFolderName.setHint("");
mIsEditingName = true;
}
public void dismissEditingName() {
mInputMethodManager.hideSoftInputFromWindow(getWindowToken(), 0);
doneEditingFolderName(true);
}
public void doneEditingFolderName(boolean commit) {
mFolderName.setHint(sHintText);
// Convert to a string here to ensure that no other state associated with the text field
// gets saved.
String newTitle = mFolderName.getText().toString();
mInfo.setTitle(newTitle);
LauncherModel.updateItemInDatabase(mLauncher, mInfo);
if (commit) {
sendCustomAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED,
String.format(getContext().getString(R.string.folder_renamed), newTitle));
}
// In order to clear the focus from the text field, we set the focus on ourself. This
// ensures that every time the field is clicked, focus is gained, giving reliable behavior.
requestFocus();
Selection.setSelection((Spannable) mFolderName.getText(), 0, 0);
mIsEditingName = false;
}
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_DONE) {
dismissEditingName();
return true;
}
return false;
}
public View getEditTextRegion() {
return mFolderName;
}
public Drawable getDragDrawable() {
return mIconDrawable;
}
/**
* We need to handle touch events to prevent them from falling through to the workspace below.
*/
@Override
public boolean onTouchEvent(MotionEvent ev) {
return true;
}
public void setDragController(DragController dragController) {
mDragController = dragController;
}
void setFolderIcon(FolderIcon icon) {
mFolderIcon = icon;
}
@Override
public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
// When the folder gets focus, we don't want to announce the list of items.
return true;
}
/**
* @return the FolderInfo object associated with this folder
*/
FolderInfo getInfo() {
return mInfo;
}
private class GridComparator implements Comparator<ShortcutInfo> {
int mNumCols;
public GridComparator(int numCols) {
mNumCols = numCols;
}
@Override
public int compare(ShortcutInfo lhs, ShortcutInfo rhs) {
int lhIndex = lhs.cellY * mNumCols + lhs.cellX;
int rhIndex = rhs.cellY * mNumCols + rhs.cellX;
return (lhIndex - rhIndex);
}
}
private void placeInReadingOrder(ArrayList<ShortcutInfo> items) {
int maxX = 0;
int count = items.size();
for (int i = 0; i < count; i++) {
ShortcutInfo item = items.get(i);
if (item.cellX > maxX) {
maxX = item.cellX;
}
}
GridComparator gridComparator = new GridComparator(maxX + 1);
Collections.sort(items, gridComparator);
final int countX = mContent.getCountX();
for (int i = 0; i < count; i++) {
int x = i % countX;
int y = i / countX;
ShortcutInfo item = items.get(i);
item.cellX = x;
item.cellY = y;
}
}
void bind(FolderInfo info) {
mInfo = info;
ArrayList<ShortcutInfo> children = info.contents;
ArrayList<ShortcutInfo> overflow = new ArrayList<ShortcutInfo>();
setupContentForNumItems(children.size());
placeInReadingOrder(children);
int count = 0;
for (int i = 0; i < children.size(); i++) {
ShortcutInfo child = (ShortcutInfo) children.get(i);
if (!createAndAddShortcut(child)) {
overflow.add(child);
} else {
count++;
}
}
// We rearrange the items in case there are any empty gaps
setupContentForNumItems(count);
// If our folder has too many items we prune them from the list. This is an issue
// when upgrading from the old Folders implementation which could contain an unlimited
// number of items.
for (ShortcutInfo item: overflow) {
mInfo.remove(item);
LauncherModel.deleteItemFromDatabase(mLauncher, item);
}
mItemsInvalidated = true;
updateTextViewFocus();
mInfo.addListener(this);
if (!sDefaultFolderName.contentEquals(mInfo.title)) {
mFolderName.setText(mInfo.title);
} else {
mFolderName.setText("");
}
updateItemLocationsInDatabase();
}
/**
* Creates a new UserFolder, inflated from R.layout.user_folder.
*
* @param context The application's context.
*
* @return A new UserFolder.
*/
static Folder fromXml(Context context) {
return (Folder) LayoutInflater.from(context).inflate(R.layout.user_folder, null);
}
/**
* This method is intended to make the UserFolder to be visually identical in size and position
* to its associated FolderIcon. This allows for a seamless transition into the expanded state.
*/
private void positionAndSizeAsIcon() {
if (!(getParent() instanceof DragLayer)) return;
setScaleX(0.8f);
setScaleY(0.8f);
setAlpha(0f);
mState = STATE_SMALL;
}
public void animateOpen() {
positionAndSizeAsIcon();
if (!(getParent() instanceof DragLayer)) return;
centerAboutIcon();
PropertyValuesHolder alpha = PropertyValuesHolder.ofFloat("alpha", 1);
PropertyValuesHolder scaleX = PropertyValuesHolder.ofFloat("scaleX", 1.0f);
PropertyValuesHolder scaleY = PropertyValuesHolder.ofFloat("scaleY", 1.0f);
final ObjectAnimator oa =
LauncherAnimUtils.ofPropertyValuesHolder(this, alpha, scaleX, scaleY);
oa.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationStart(Animator animation) {
sendCustomAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED,
String.format(getContext().getString(R.string.folder_opened),
mContent.getCountX(), mContent.getCountY()));
mState = STATE_ANIMATING;
}
@Override
public void onAnimationEnd(Animator animation) {
mState = STATE_OPEN;
setLayerType(LAYER_TYPE_NONE, null);
Cling cling = mLauncher.showFirstRunFoldersCling();
if (cling != null) {
cling.bringToFront();
}
setFocusOnFirstChild();
}
});
oa.setDuration(mExpandDuration);
setLayerType(LAYER_TYPE_HARDWARE, null);
oa.start();
}
private void sendCustomAccessibilityEvent(int type, String text) {
AccessibilityManager accessibilityManager = (AccessibilityManager)
getContext().getSystemService(Context.ACCESSIBILITY_SERVICE);
if (accessibilityManager.isEnabled()) {
AccessibilityEvent event = AccessibilityEvent.obtain(type);
onInitializeAccessibilityEvent(event);
event.getText().add(text);
accessibilityManager.sendAccessibilityEvent(event);
}
}
private void setFocusOnFirstChild() {
View firstChild = mContent.getChildAt(0, 0);
if (firstChild != null) {
firstChild.requestFocus();
}
}
public void animateClosed() {
if (!(getParent() instanceof DragLayer)) return;
PropertyValuesHolder alpha = PropertyValuesHolder.ofFloat("alpha", 0);
PropertyValuesHolder scaleX = PropertyValuesHolder.ofFloat("scaleX", 0.9f);
PropertyValuesHolder scaleY = PropertyValuesHolder.ofFloat("scaleY", 0.9f);
final ObjectAnimator oa =
LauncherAnimUtils.ofPropertyValuesHolder(this, alpha, scaleX, scaleY);
oa.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
onCloseComplete();
setLayerType(LAYER_TYPE_NONE, null);
mState = STATE_SMALL;
}
@Override
public void onAnimationStart(Animator animation) {
sendCustomAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED,
getContext().getString(R.string.folder_closed));
mState = STATE_ANIMATING;
}
});
oa.setDuration(mExpandDuration);
setLayerType(LAYER_TYPE_HARDWARE, null);
oa.start();
}
void notifyDataSetChanged() {
// recreate all the children if the data set changes under us. We may want to do this more
// intelligently (ie just removing the views that should no longer exist)
mContent.removeAllViewsInLayout();
bind(mInfo);
}
public boolean acceptDrop(DragObject d) {
final ItemInfo item = (ItemInfo) d.dragInfo;
final int itemType = item.itemType;
return ((itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION ||
itemType == LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT) &&
!isFull());
}
protected boolean findAndSetEmptyCells(ShortcutInfo item) {
int[] emptyCell = new int[2];
if (mContent.findCellForSpan(emptyCell, item.spanX, item.spanY)) {
item.cellX = emptyCell[0];
item.cellY = emptyCell[1];
return true;
} else {
return false;
}
}
protected boolean createAndAddShortcut(ShortcutInfo item) {
final TextView textView =
(TextView) mInflater.inflate(R.layout.application, this, false);
textView.setCompoundDrawablesWithIntrinsicBounds(null,
new FastBitmapDrawable(item.getIcon(mIconCache)), null, null);
textView.setText(item.title);
textView.setTag(item);
textView.setOnClickListener(this);
textView.setOnLongClickListener(this);
// We need to check here to verify that the given item's location isn't already occupied
// by another item.
if (mContent.getChildAt(item.cellX, item.cellY) != null || item.cellX < 0 || item.cellY < 0
|| item.cellX >= mContent.getCountX() || item.cellY >= mContent.getCountY()) {
// This shouldn't happen, log it.
Log.e(TAG, "Folder order not properly persisted during bind");
if (!findAndSetEmptyCells(item)) {
return false;
}
}
CellLayout.LayoutParams lp =
new CellLayout.LayoutParams(item.cellX, item.cellY, item.spanX, item.spanY);
boolean insert = false;
textView.setOnKeyListener(new FolderKeyEventListener());
mContent.addViewToCellLayout(textView, insert ? 0 : -1, (int)item.id, lp, true);
return true;
}
public void onDragEnter(DragObject d) {
mPreviousTargetCell[0] = -1;
mPreviousTargetCell[1] = -1;
mOnExitAlarm.cancelAlarm();
}
OnAlarmListener mReorderAlarmListener = new OnAlarmListener() {
public void onAlarm(Alarm alarm) {
realTimeReorder(mEmptyCell, mTargetCell);
}
};
boolean readingOrderGreaterThan(int[] v1, int[] v2) {
if (v1[1] > v2[1] || (v1[1] == v2[1] && v1[0] > v2[0])) {
return true;
} else {
return false;
}
}
private void realTimeReorder(int[] empty, int[] target) {
boolean wrap;
int startX;
int endX;
int startY;
int delay = 0;
float delayAmount = 30;
if (readingOrderGreaterThan(target, empty)) {
wrap = empty[0] >= mContent.getCountX() - 1;
startY = wrap ? empty[1] + 1 : empty[1];
for (int y = startY; y <= target[1]; y++) {
startX = y == empty[1] ? empty[0] + 1 : 0;
endX = y < target[1] ? mContent.getCountX() - 1 : target[0];
for (int x = startX; x <= endX; x++) {
View v = mContent.getChildAt(x,y);
if (mContent.animateChildToPosition(v, empty[0], empty[1],
REORDER_ANIMATION_DURATION, delay, true, true)) {
empty[0] = x;
empty[1] = y;
delay += delayAmount;
delayAmount *= 0.9;
}
}
}
} else {
wrap = empty[0] == 0;
startY = wrap ? empty[1] - 1 : empty[1];
for (int y = startY; y >= target[1]; y--) {
startX = y == empty[1] ? empty[0] - 1 : mContent.getCountX() - 1;
endX = y > target[1] ? 0 : target[0];
for (int x = startX; x >= endX; x--) {
View v = mContent.getChildAt(x,y);
if (mContent.animateChildToPosition(v, empty[0], empty[1],
REORDER_ANIMATION_DURATION, delay, true, true)) {
empty[0] = x;
empty[1] = y;
delay += delayAmount;
delayAmount *= 0.9;
}
}
}
}
}
public boolean isLayoutRtl() {
return (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
}
private Rect getDragObjectDrawingRect(View dragView, float[] r) {
final Rect drawingRect = mTempRect;
drawingRect.left = (int) r[0];
drawingRect.top = (int) r[1];
drawingRect.right = drawingRect.left + dragView.getMeasuredWidth();
drawingRect.bottom = drawingRect.top + dragView.getMeasuredHeight();
return drawingRect;
}
public void onDragOver(DragObject d) {
int scrollOffset = mScrollView.getScrollY();
float[] r = getDragViewVisualCenter(d.x, d.y, d.xOffset, d.yOffset, d.dragView, null);
r[0] -= getPaddingLeft();
r[1] -= getPaddingTop();
if (!mAutoScroller.onTouch(this, getDragObjectDrawingRect(d.dragView, r))) {
mTargetCell = mContent.findNearestArea((int) r[0], (int) r[1] + scrollOffset, 1, 1,
mTargetCell);
if (isLayoutRtl()) {
mTargetCell[0] = mContent.getCountX() - mTargetCell[0] - 1;
}
if (mTargetCell[0] != mPreviousTargetCell[0]
|| mTargetCell[1] != mPreviousTargetCell[1]) {
mReorderAlarm.cancelAlarm();
mReorderAlarm.setOnAlarmListener(mReorderAlarmListener);
mReorderAlarm.setAlarm(REORDER_DELAY);
mPreviousTargetCell[0] = mTargetCell[0];
mPreviousTargetCell[1] = mTargetCell[1];
mDragMode = DRAG_MODE_REORDER;
} else {
mDragMode = DRAG_MODE_NONE;
}
}
}
// This is used to compute the visual center of the dragView. The idea is that
// the visual center represents the user's interpretation of where the item is, and hence
// is the appropriate point to use when determining drop location.
private float[] getDragViewVisualCenter(int x, int y, int xOffset, int yOffset,
DragView dragView, float[] recycle) {
float res[];
if (recycle == null) {
res = new float[2];
} else {
res = recycle;
}
// These represent the visual top and left of drag view if a dragRect was provided.
// If a dragRect was not provided, then they correspond to the actual view left and
// top, as the dragRect is in that case taken to be the entire dragView.
// R.dimen.dragViewOffsetY.
int left = x - xOffset;
int top = y - yOffset;
// In order to find the visual center, we shift by half the dragRect
res[0] = left + dragView.getDragRegion().width() / 2;
res[1] = top + dragView.getDragRegion().height() / 2;
return res;
}
OnAlarmListener mOnExitAlarmListener = new OnAlarmListener() {
public void onAlarm(Alarm alarm) {
completeDragExit();
}
};
public void completeDragExit() {
mLauncher.closeFolder();
mCurrentDragInfo = null;
mCurrentDragView = null;
mSuppressOnAdd = false;
mRearrangeOnClose = true;
}
public void onDragExit(DragObject d) {
// Exiting folder; stop the auto scroller.
mAutoScroller.stop();
// We only close the folder if this is a true drag exit, ie. not because
// a drop has occurred above the folder.
if (!d.dragComplete) {
mOnExitAlarm.setOnAlarmListener(mOnExitAlarmListener);
mOnExitAlarm.setAlarm(ON_EXIT_CLOSE_DELAY);
}
mReorderAlarm.cancelAlarm();
mDragMode = DRAG_MODE_NONE;
}
public void onDropCompleted(final View target, final DragObject d,
final boolean isFlingToDelete, final boolean success) {
if (mDeferDropAfterUninstall) {
mDeferredAction = new Runnable() {
public void run() {
onDropCompleted(target, d, isFlingToDelete, success);
mDeferredAction = null;
}
};
return;
}
boolean beingCalledAfterUninstall = mDeferredAction != null;
boolean successfulDrop =
success && (!beingCalledAfterUninstall || mUninstallSuccessful);
if (successfulDrop) {
if (mDeleteFolderOnDropCompleted && !mItemAddedBackToSelfViaIcon) {
replaceFolderWithFinalItem();
}
} else {
setupContentForNumItems(getItemCount());
// The drag failed, we need to return the item to the folder
mFolderIcon.onDrop(d);
}
if (target != this) {
if (mOnExitAlarm.alarmPending()) {
mOnExitAlarm.cancelAlarm();
- if (successfulDrop) {
+ if (!successfulDrop) {
mSuppressFolderDeletion = true;
}
completeDragExit();
}
}
mDeleteFolderOnDropCompleted = false;
mDragInProgress = false;
mItemAddedBackToSelfViaIcon = false;
mCurrentDragInfo = null;
mCurrentDragView = null;
mSuppressOnAdd = false;
// Reordering may have occured, and we need to save the new item locations. We do this once
// at the end to prevent unnecessary database operations.
updateItemLocationsInDatabaseBatch();
}
public void deferCompleteDropAfterUninstallActivity() {
mDeferDropAfterUninstall = true;
}
public void onUninstallActivityReturned(boolean success) {
mDeferDropAfterUninstall = false;
mUninstallSuccessful = success;
if (mDeferredAction != null) {
mDeferredAction.run();
}
}
@Override
public boolean supportsFlingToDelete() {
return true;
}
public void onFlingToDelete(DragObject d, int x, int y, PointF vec) {
// Do nothing
}
@Override
public void onFlingToDeleteCompleted() {
// Do nothing
}
private void updateItemLocationsInDatabase() {
ArrayList<View> list = getItemsInReadingOrder();
for (int i = 0; i < list.size(); i++) {
View v = list.get(i);
ItemInfo info = (ItemInfo) v.getTag();
LauncherModel.moveItemInDatabase(mLauncher, info, mInfo.id, 0,
info.cellX, info.cellY);
}
}
private void updateItemLocationsInDatabaseBatch() {
ArrayList<View> list = getItemsInReadingOrder();
ArrayList<ItemInfo> items = new ArrayList<ItemInfo>();
for (int i = 0; i < list.size(); i++) {
View v = list.get(i);
ItemInfo info = (ItemInfo) v.getTag();
items.add(info);
}
LauncherModel.moveItemsInDatabase(mLauncher, items, mInfo.id, 0);
}
public void addItemLocationsInDatabase() {
ArrayList<View> list = getItemsInReadingOrder();
for (int i = 0; i < list.size(); i++) {
View v = list.get(i);
ItemInfo info = (ItemInfo) v.getTag();
LauncherModel.addItemToDatabase(mLauncher, info, mInfo.id, 0,
info.cellX, info.cellY, false);
}
}
public void notifyDrop() {
if (mDragInProgress) {
mItemAddedBackToSelfViaIcon = true;
}
}
public boolean isDropEnabled() {
return true;
}
private void setupContentDimensions(int count) {
ArrayList<View> list = getItemsInReadingOrder();
int countX = mContent.getCountX();
int countY = mContent.getCountY();
boolean done = false;
while (!done) {
int oldCountX = countX;
int oldCountY = countY;
if (countX * countY < count) {
// Current grid is too small, expand it
if ((countX <= countY || countY == mMaxCountY) && countX < mMaxCountX) {
countX++;
} else if (countY < mMaxCountY) {
countY++;
}
if (countY == 0) countY++;
} else if ((countY - 1) * countX >= count && countY >= countX) {
countY = Math.max(0, countY - 1);
} else if ((countX - 1) * countY >= count) {
countX = Math.max(0, countX - 1);
}
done = countX == oldCountX && countY == oldCountY;
}
mContent.setGridSize(countX, countY);
arrangeChildren(list);
}
public boolean isFull() {
return getItemCount() >= mMaxNumItems;
}
private void centerAboutIcon() {
DragLayer.LayoutParams lp = (DragLayer.LayoutParams) getLayoutParams();
int width = getPaddingLeft() + getPaddingRight() + mContent.getDesiredWidth();
int height = getFolderHeight();
DragLayer parent = (DragLayer) mLauncher.findViewById(R.id.drag_layer);
float scale = parent.getDescendantRectRelativeToSelf(mFolderIcon, mTempRect);
int centerX = (int) (mTempRect.left + mTempRect.width() * scale / 2);
int centerY = (int) (mTempRect.top + mTempRect.height() * scale / 2);
int centeredLeft = centerX - width / 2;
int centeredTop = centerY - height / 2;
int currentPage = mLauncher.getWorkspace().getCurrentPage();
// In case the workspace is scrolling, we need to use the final scroll to compute
// the folders bounds.
mLauncher.getWorkspace().setFinalScrollForPageChange(currentPage);
// We first fetch the currently visible CellLayoutChildren
CellLayout currentLayout = (CellLayout) mLauncher.getWorkspace().getChildAt(currentPage);
ShortcutAndWidgetContainer boundingLayout = currentLayout.getShortcutsAndWidgets();
Rect bounds = new Rect();
parent.getDescendantRectRelativeToSelf(boundingLayout, bounds);
// We reset the workspaces scroll
mLauncher.getWorkspace().resetFinalScrollForPageChange(currentPage);
// We need to bound the folder to the currently visible CellLayoutChildren
int left = Math.min(Math.max(bounds.left, centeredLeft),
bounds.left + bounds.width() - width);
int top = Math.min(Math.max(bounds.top, centeredTop),
bounds.top + bounds.height() - height);
// If the folder doesn't fit within the bounds, center it about the desired bounds
if (width >= bounds.width()) {
left = bounds.left + (bounds.width() - width) / 2;
}
if (height >= bounds.height()) {
top = bounds.top + (bounds.height() - height) / 2;
}
int folderPivotX = width / 2 + (centeredLeft - left);
int folderPivotY = height / 2 + (centeredTop - top);
setPivotX(folderPivotX);
setPivotY(folderPivotY);
mFolderIconPivotX = (int) (mFolderIcon.getMeasuredWidth() *
(1.0f * folderPivotX / width));
mFolderIconPivotY = (int) (mFolderIcon.getMeasuredHeight() *
(1.0f * folderPivotY / height));
lp.width = width;
lp.height = height;
lp.x = left;
lp.y = top;
}
float getPivotXForIconAnimation() {
return mFolderIconPivotX;
}
float getPivotYForIconAnimation() {
return mFolderIconPivotY;
}
private void setupContentForNumItems(int count) {
setupContentDimensions(count);
DragLayer.LayoutParams lp = (DragLayer.LayoutParams) getLayoutParams();
if (lp == null) {
lp = new DragLayer.LayoutParams(0, 0);
lp.customPosition = true;
setLayoutParams(lp);
}
centerAboutIcon();
}
private int getFolderHeight() {
int contentAreaHeight = mContent.getDesiredHeight();
if (contentAreaHeight >= mMaxContentAreaHeight) {
// Subtract a bit so the user can see that it's scrollable.
contentAreaHeight = mMaxContentAreaHeight;
}
int height = getPaddingTop() + getPaddingBottom() + contentAreaHeight
+ mFolderNameHeight;
return height;
}
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int contentAreaHeight = mContent.getDesiredHeight();
if (contentAreaHeight >= mMaxContentAreaHeight) {
// Subtract a bit so the user can see that it's scrollable.
contentAreaHeight = mMaxContentAreaHeight;
}
int width = getPaddingLeft() + getPaddingRight() + mContent.getDesiredWidth();
int height = getFolderHeight();
int contentAreaWidthSpec = MeasureSpec.makeMeasureSpec(mContent.getDesiredWidth(),
MeasureSpec.EXACTLY);
int contentAreaHeightSpec = MeasureSpec.makeMeasureSpec(contentAreaHeight,
MeasureSpec.EXACTLY);
mContent.setFixedSize(mContent.getDesiredWidth(), mContent.getDesiredHeight());
mScrollView.measure(contentAreaWidthSpec, contentAreaHeightSpec);
mFolderName.measure(contentAreaWidthSpec,
MeasureSpec.makeMeasureSpec(mFolderNameHeight, MeasureSpec.EXACTLY));
setMeasuredDimension(width, height);
}
private void arrangeChildren(ArrayList<View> list) {
int[] vacant = new int[2];
if (list == null) {
list = getItemsInReadingOrder();
}
mContent.removeAllViews();
for (int i = 0; i < list.size(); i++) {
View v = list.get(i);
mContent.getVacantCell(vacant, 1, 1);
CellLayout.LayoutParams lp = (CellLayout.LayoutParams) v.getLayoutParams();
lp.cellX = vacant[0];
lp.cellY = vacant[1];
ItemInfo info = (ItemInfo) v.getTag();
if (info.cellX != vacant[0] || info.cellY != vacant[1]) {
info.cellX = vacant[0];
info.cellY = vacant[1];
LauncherModel.addOrMoveItemInDatabase(mLauncher, info, mInfo.id, 0,
info.cellX, info.cellY);
}
boolean insert = false;
mContent.addViewToCellLayout(v, insert ? 0 : -1, (int)info.id, lp, true);
}
mItemsInvalidated = true;
}
public int getItemCount() {
return mContent.getShortcutsAndWidgets().getChildCount();
}
public View getItemAt(int index) {
return mContent.getShortcutsAndWidgets().getChildAt(index);
}
private void onCloseComplete() {
DragLayer parent = (DragLayer) getParent();
if (parent != null) {
parent.removeView(this);
}
mDragController.removeDropTarget((DropTarget) this);
clearFocus();
mFolderIcon.requestFocus();
if (mRearrangeOnClose) {
setupContentForNumItems(getItemCount());
mRearrangeOnClose = false;
}
if (getItemCount() <= 1) {
if (!mDragInProgress && !mSuppressFolderDeletion) {
replaceFolderWithFinalItem();
} else if (mDragInProgress) {
mDeleteFolderOnDropCompleted = true;
}
}
mSuppressFolderDeletion = false;
}
private void replaceFolderWithFinalItem() {
// Add the last remaining child to the workspace in place of the folder
Runnable onCompleteRunnable = new Runnable() {
@Override
public void run() {
CellLayout cellLayout = mLauncher.getCellLayout(mInfo.container, mInfo.screenId);
View child = null;
// Move the item from the folder to the workspace, in the position of the folder
if (getItemCount() == 1) {
ShortcutInfo finalItem = mInfo.contents.get(0);
child = mLauncher.createShortcut(R.layout.application, cellLayout,
finalItem);
LauncherModel.addOrMoveItemInDatabase(mLauncher, finalItem, mInfo.container,
mInfo.screenId, mInfo.cellX, mInfo.cellY);
}
if (getItemCount() <= 1) {
// Remove the folder
LauncherModel.deleteItemFromDatabase(mLauncher, mInfo);
cellLayout.removeView(mFolderIcon);
if (mFolderIcon instanceof DropTarget) {
mDragController.removeDropTarget((DropTarget) mFolderIcon);
}
mLauncher.removeFolder(mInfo);
}
// We add the child after removing the folder to prevent both from existing at
// the same time in the CellLayout.
if (child != null) {
mLauncher.getWorkspace().addInScreen(child, mInfo.container, mInfo.screenId,
mInfo.cellX, mInfo.cellY, mInfo.spanX, mInfo.spanY);
}
}
};
View finalChild = getItemAt(0);
if (finalChild != null) {
mFolderIcon.performDestroyAnimation(finalChild, onCompleteRunnable);
}
mDestroyed = true;
}
boolean isDestroyed() {
return mDestroyed;
}
// This method keeps track of the last item in the folder for the purposes
// of keyboard focus
private void updateTextViewFocus() {
View lastChild = getItemAt(getItemCount() - 1);
getItemAt(getItemCount() - 1);
if (lastChild != null) {
mFolderName.setNextFocusDownId(lastChild.getId());
mFolderName.setNextFocusRightId(lastChild.getId());
mFolderName.setNextFocusLeftId(lastChild.getId());
mFolderName.setNextFocusUpId(lastChild.getId());
}
}
public void onDrop(DragObject d) {
ShortcutInfo item;
if (d.dragInfo instanceof ApplicationInfo) {
// Came from all apps -- make a copy
item = ((ApplicationInfo) d.dragInfo).makeShortcut();
item.spanX = 1;
item.spanY = 1;
} else {
item = (ShortcutInfo) d.dragInfo;
}
// Dragged from self onto self, currently this is the only path possible, however
// we keep this as a distinct code path.
if (item == mCurrentDragInfo) {
ShortcutInfo si = (ShortcutInfo) mCurrentDragView.getTag();
CellLayout.LayoutParams lp = (CellLayout.LayoutParams) mCurrentDragView.getLayoutParams();
si.cellX = lp.cellX = mEmptyCell[0];
si.cellX = lp.cellY = mEmptyCell[1];
mContent.addViewToCellLayout(mCurrentDragView, -1, (int)item.id, lp, true);
if (d.dragView.hasDrawn()) {
mLauncher.getDragLayer().animateViewIntoPosition(d.dragView, mCurrentDragView);
} else {
d.deferDragViewCleanupPostAnimation = false;
mCurrentDragView.setVisibility(VISIBLE);
}
mItemsInvalidated = true;
setupContentDimensions(getItemCount());
mSuppressOnAdd = true;
}
mInfo.add(item);
}
// This is used so the item doesn't immediately appear in the folder when added. In one case
// we need to create the illusion that the item isn't added back to the folder yet, to
// to correspond to the animation of the icon back into the folder. This is
public void hideItem(ShortcutInfo info) {
View v = getViewForInfo(info);
v.setVisibility(INVISIBLE);
}
public void showItem(ShortcutInfo info) {
View v = getViewForInfo(info);
v.setVisibility(VISIBLE);
}
public void onAdd(ShortcutInfo item) {
mItemsInvalidated = true;
// If the item was dropped onto this open folder, we have done the work associated
// with adding the item to the folder, as indicated by mSuppressOnAdd being set
if (mSuppressOnAdd) return;
if (!findAndSetEmptyCells(item)) {
// The current layout is full, can we expand it?
setupContentForNumItems(getItemCount() + 1);
findAndSetEmptyCells(item);
}
createAndAddShortcut(item);
LauncherModel.addOrMoveItemInDatabase(
mLauncher, item, mInfo.id, 0, item.cellX, item.cellY);
}
public void onRemove(ShortcutInfo item) {
mItemsInvalidated = true;
// If this item is being dragged from this open folder, we have already handled
// the work associated with removing the item, so we don't have to do anything here.
if (item == mCurrentDragInfo) return;
View v = getViewForInfo(item);
mContent.removeView(v);
if (mState == STATE_ANIMATING) {
mRearrangeOnClose = true;
} else {
setupContentForNumItems(getItemCount());
}
if (getItemCount() <= 1) {
replaceFolderWithFinalItem();
}
}
private View getViewForInfo(ShortcutInfo item) {
for (int j = 0; j < mContent.getCountY(); j++) {
for (int i = 0; i < mContent.getCountX(); i++) {
View v = mContent.getChildAt(i, j);
if (v.getTag() == item) {
return v;
}
}
}
return null;
}
public void onItemsChanged() {
updateTextViewFocus();
}
public void onTitleChanged(CharSequence title) {
}
public ArrayList<View> getItemsInReadingOrder() {
if (mItemsInvalidated) {
mItemsInReadingOrder.clear();
for (int j = 0; j < mContent.getCountY(); j++) {
for (int i = 0; i < mContent.getCountX(); i++) {
View v = mContent.getChildAt(i, j);
if (v != null) {
mItemsInReadingOrder.add(v);
}
}
}
mItemsInvalidated = false;
}
return mItemsInReadingOrder;
}
public void getLocationInDragLayer(int[] loc) {
mLauncher.getDragLayer().getLocationInDragLayer(this, loc);
}
public void onFocusChange(View v, boolean hasFocus) {
if (v == mFolderName && hasFocus) {
startEditingFolderName();
}
}
@Override
public void getHitRectRelativeToDragLayer(Rect outRect) {
getHitRect(outRect);
}
}
diff --git a/src/com/android/launcher3/Launcher.java b/src/com/android/launcher3/Launcher.java
index fa9627973..b1fbd751c 100644
--- a/src/com/android/launcher3/Launcher.java
+++ b/src/com/android/launcher3/Launcher.java
@@ -1,4227 +1,4233 @@
/*
* 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.launcher3;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
import android.animation.ValueAnimator;
import android.animation.ValueAnimator.AnimatorUpdateListener;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityOptions;
import android.app.SearchManager;
import android.appwidget.AppWidgetHostView;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProviderInfo;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.ComponentCallbacks2;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.database.ContentObserver;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
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.StrictMode;
import android.os.SystemClock;
import android.provider.Settings;
import android.speech.RecognizerIntent;
import android.text.Selection;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.method.TextKeyListener;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.HapticFeedbackConstants;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.Surface;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.WindowManager;
import android.view.accessibility.AccessibilityEvent;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.DecelerateInterpolator;
import android.view.inputmethod.InputMethodManager;
import android.widget.Advanceable;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.launcher3.DropTarget.DragObject;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileDescriptor;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Default launcher application.
*/
public class Launcher extends Activity
implements View.OnClickListener, OnLongClickListener, LauncherModel.Callbacks,
View.OnTouchListener {
static final String TAG = "Launcher";
static final boolean LOGD = false;
static final boolean PROFILE_STARTUP = false;
static final boolean DEBUG_WIDGETS = false;
static final boolean DEBUG_STRICT_MODE = false;
static final boolean DEBUG_RESUME_TIME = false;
private static final int MENU_GROUP_WALLPAPER = 1;
private static final int MENU_WALLPAPER_SETTINGS = Menu.FIRST + 1;
private static final int MENU_MANAGE_APPS = MENU_WALLPAPER_SETTINGS + 1;
private static final int MENU_SYSTEM_SETTINGS = MENU_MANAGE_APPS + 1;
private static final int MENU_HELP = MENU_SYSTEM_SETTINGS + 1;
private static final int REQUEST_CREATE_SHORTCUT = 1;
private static final int REQUEST_CREATE_APPWIDGET = 5;
private static final int REQUEST_PICK_APPLICATION = 6;
private static final int REQUEST_PICK_SHORTCUT = 7;
private static final int REQUEST_PICK_APPWIDGET = 9;
private static final int REQUEST_PICK_WALLPAPER = 10;
private static final int REQUEST_BIND_APPWIDGET = 11;
/**
* IntentStarter uses request codes starting with this. This must be greater than all activity
* request codes used internally.
*/
protected static final int REQUEST_LAST = 100;
static final String EXTRA_SHORTCUT_DUPLICATE = "duplicate";
static final int SCREEN_COUNT = 5;
static final int DEFAULT_SCREEN = 2;
private static final String PREFERENCES = "launcher.preferences";
// To turn on these properties, type
// adb shell setprop log.tag.PROPERTY_NAME [VERBOSE | SUPPRESS]
static final String FORCE_ENABLE_ROTATION_PROPERTY = "launcher_force_rotate";
static final String DUMP_STATE_PROPERTY = "launcher_dump_state";
// The Intent extra that defines whether to ignore the launch animation
static final String INTENT_EXTRA_IGNORE_LAUNCH_ANIMATION =
"com.android.launcher3.intent.extra.shortcut.INGORE_LAUNCH_ANIMATION";
// Type: int
private static final String RUNTIME_STATE_CURRENT_SCREEN = "launcher.current_screen";
// Type: int
private static final String RUNTIME_STATE = "launcher.state";
// Type: int
private static final String RUNTIME_STATE_PENDING_ADD_CONTAINER = "launcher.add_container";
// Type: int
private static final String RUNTIME_STATE_PENDING_ADD_SCREEN = "launcher.add_screen";
// Type: int
private static final String RUNTIME_STATE_PENDING_ADD_CELL_X = "launcher.add_cell_x";
// Type: int
private static final String RUNTIME_STATE_PENDING_ADD_CELL_Y = "launcher.add_cell_y";
// Type: boolean
private static final String RUNTIME_STATE_PENDING_FOLDER_RENAME = "launcher.rename_folder";
// Type: long
private static final String RUNTIME_STATE_PENDING_FOLDER_RENAME_ID = "launcher.rename_folder_id";
// Type: int
private static final String RUNTIME_STATE_PENDING_ADD_SPAN_X = "launcher.add_span_x";
// Type: int
private static final String RUNTIME_STATE_PENDING_ADD_SPAN_Y = "launcher.add_span_y";
// Type: parcelable
private static final String RUNTIME_STATE_PENDING_ADD_WIDGET_INFO = "launcher.add_widget_info";
private static final String TOOLBAR_ICON_METADATA_NAME = "com.android.launcher.toolbar_icon";
private static final String TOOLBAR_SEARCH_ICON_METADATA_NAME =
"com.android.launcher.toolbar_search_icon";
private static final String TOOLBAR_VOICE_SEARCH_ICON_METADATA_NAME =
"com.android.launcher.toolbar_voice_search_icon";
public static final String SHOW_WEIGHT_WATCHER = "debug.show_mem";
/** The different states that Launcher can be in. */
private enum State { NONE, WORKSPACE, APPS_CUSTOMIZE, APPS_CUSTOMIZE_SPRING_LOADED };
private State mState = State.WORKSPACE;
private AnimatorSet mStateAnimation;
private AnimatorSet mDividerAnimator;
static final int APPWIDGET_HOST_ID = 1024;
private static final int EXIT_SPRINGLOADED_MODE_SHORT_TIMEOUT = 300;
private static final int EXIT_SPRINGLOADED_MODE_LONG_TIMEOUT = 600;
private static final int SHOW_CLING_DURATION = 550;
private static final int DISMISS_CLING_DURATION = 250;
private static final Object sLock = new Object();
private static int sScreen = DEFAULT_SCREEN;
// How long to wait before the new-shortcut animation automatically pans the workspace
private static int NEW_APPS_ANIMATION_INACTIVE_TIMEOUT_SECONDS = 10;
private static int NEW_APPS_ANIMATION_DELAY = 500;
private final BroadcastReceiver mCloseSystemDialogsReceiver
= new CloseSystemDialogsIntentReceiver();
private final ContentObserver mWidgetObserver = new AppWidgetResetObserver();
private LayoutInflater mInflater;
private Workspace mWorkspace;
private View mQsbDivider;
private View mLauncherView;
private DragLayer mDragLayer;
private DragController mDragController;
private View mWeightWatcher;
private AppWidgetManager mAppWidgetManager;
private LauncherAppWidgetHost mAppWidgetHost;
private ItemInfo mPendingAddInfo = new ItemInfo();
private AppWidgetProviderInfo mPendingAddWidgetInfo;
private int[] mTmpAddItemCellCoordinates = new int[2];
private FolderInfo mFolderInfo;
private Hotseat mHotseat;
private View mAllAppsButton;
private SearchDropTargetBar mSearchDropTargetBar;
private AppsCustomizeTabHost mAppsCustomizeTabHost;
private AppsCustomizePagedView mAppsCustomizeContent;
private boolean mAutoAdvanceRunning = false;
private Bundle mSavedState;
// We set the state in both onCreate and then onNewIntent in some cases, which causes both
// scroll issues (because the workspace may not have been measured yet) and extra work.
// Instead, just save the state that we need to restore Launcher to, and commit it in onResume.
private State mOnResumeState = State.NONE;
private SpannableStringBuilder mDefaultKeySsb = null;
private boolean mWorkspaceLoading = true;
private boolean mPaused = true;
private boolean mRestoring;
private boolean mWaitingForResult;
private boolean mOnResumeNeedsLoad;
private ArrayList<Runnable> mBindOnResumeCallbacks = new ArrayList<Runnable>();
private ArrayList<Runnable> mOnResumeCallbacks = new ArrayList<Runnable>();
// Keep track of whether the user has left launcher
private static boolean sPausedFromUserAction = false;
private Bundle mSavedInstanceState;
private LauncherModel mModel;
private IconCache mIconCache;
private boolean mUserPresent = true;
private boolean mVisible = false;
private boolean mAttached = false;
private static final boolean DISABLE_CLINGS = true;
private static LocaleConfiguration sLocaleConfiguration = null;
private static HashMap<Long, FolderInfo> sFolders = new HashMap<Long, FolderInfo>();
private Intent mAppMarketIntent = null;
// Related to the auto-advancing of widgets
private final int ADVANCE_MSG = 1;
private final int mAdvanceInterval = 20000;
private final int mAdvanceStagger = 250;
private long mAutoAdvanceSentTime;
private long mAutoAdvanceTimeLeft = -1;
private HashMap<View, AppWidgetProviderInfo> mWidgetsToAdvance =
new HashMap<View, AppWidgetProviderInfo>();
// Determines how long to wait after a rotation before restoring the screen orientation to
// match the sensor state.
private final int mRestoreScreenOrientationDelay = 500;
// External icons saved in case of resource changes, orientation, etc.
private static Drawable.ConstantState[] sGlobalSearchIcon = new Drawable.ConstantState[2];
private static Drawable.ConstantState[] sVoiceSearchIcon = new Drawable.ConstantState[2];
private static Drawable.ConstantState[] sAppMarketIcon = new Drawable.ConstantState[2];
private Drawable mWorkspaceBackgroundDrawable;
private final ArrayList<Integer> mSynchronouslyBoundPages = new ArrayList<Integer>();
static final ArrayList<String> sDumpLogs = new ArrayList<String>();
// We only want to get the SharedPreferences once since it does an FS stat each time we get
// it from the context.
private SharedPreferences mSharedPrefs;
private static ArrayList<ComponentName> mIntentsOnWorkspaceFromUpgradePath = null;
// Holds the page that we need to animate to, and the icon views that we need to animate up
// when we scroll to that page on resume.
private long mNewShortcutAnimateScreenId = -1;
private ArrayList<View> mNewShortcutAnimateViews = new ArrayList<View>();
private ImageView mFolderIconImageView;
private Bitmap mFolderIconBitmap;
private Canvas mFolderIconCanvas;
private Rect mRectForFolderAnimation = new Rect();
private BubbleTextView mWaitingForResume;
private HideFromAccessibilityHelper mHideFromAccessibilityHelper
= new HideFromAccessibilityHelper();
private Runnable mBuildLayersRunnable = new Runnable() {
public void run() {
if (mWorkspace != null) {
mWorkspace.buildPageHardwareLayers();
}
}
};
private static ArrayList<PendingAddArguments> sPendingAddList
= new ArrayList<PendingAddArguments>();
private static boolean sForceEnableRotation = isPropertyEnabled(FORCE_ENABLE_ROTATION_PROPERTY);
private static class PendingAddArguments {
int requestCode;
Intent intent;
long container;
long screenId;
int cellX;
int cellY;
}
private static boolean isPropertyEnabled(String propertyName) {
return Log.isLoggable(propertyName, Log.VERBOSE);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
if (DEBUG_STRICT_MODE) {
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads()
.detectDiskWrites()
.detectNetwork() // or .detectAll() for all detectable problems
.penaltyLog()
.build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
.detectLeakedSqlLiteObjects()
.detectLeakedClosableObjects()
.penaltyLog()
.penaltyDeath()
.build());
}
super.onCreate(savedInstanceState);
// the LauncherApplication should call this, but in case of Instrumentation it might not be present yet
LauncherAppState.setApplicationContext(getApplicationContext());
LauncherAppState app = LauncherAppState.getInstance();
mSharedPrefs = getSharedPreferences(LauncherAppState.getSharedPreferencesKey(),
Context.MODE_PRIVATE);
mModel = app.setLauncher(this);
mIconCache = app.getIconCache();
mDragController = new DragController(this);
mInflater = getLayoutInflater();
mAppWidgetManager = AppWidgetManager.getInstance(this);
mAppWidgetHost = new LauncherAppWidgetHost(this, APPWIDGET_HOST_ID);
mAppWidgetHost.startListening();
// If we are getting an onCreate, we can actually preempt onResume and unset mPaused here,
// this also ensures that any synchronous binding below doesn't re-trigger another
// LauncherModel load.
mPaused = false;
if (PROFILE_STARTUP) {
android.os.Debug.startMethodTracing(
Environment.getExternalStorageDirectory() + "/launcher");
}
checkForLocaleChange();
setContentView(R.layout.launcher);
setupViews();
showFirstRunWorkspaceCling();
registerContentObservers();
lockAllApps();
mSavedState = savedInstanceState;
restoreState(mSavedState);
// Update customization drawer _after_ restoring the states
if (mAppsCustomizeContent != null) {
mAppsCustomizeContent.onPackagesUpdated(
LauncherModel.getSortedWidgetsAndShortcuts(this));
}
if (PROFILE_STARTUP) {
android.os.Debug.stopMethodTracing();
}
if (!mRestoring) {
if (sPausedFromUserAction) {
// If the user leaves launcher, then we should just load items asynchronously when
// they return.
mModel.startLoader(true, -1);
} else {
// We only load the page synchronously if the user rotates (or triggers a
// configuration change) while launcher is in the foreground
mModel.startLoader(true, mWorkspace.getCurrentPage());
}
}
// For handling default keys
mDefaultKeySsb = new SpannableStringBuilder();
Selection.setSelection(mDefaultKeySsb, 0);
IntentFilter filter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
registerReceiver(mCloseSystemDialogsReceiver, filter);
updateGlobalIcons();
// On large interfaces, we want the screen to auto-rotate based on the current orientation
unlockScreenOrientation(true);
}
protected void onUserLeaveHint() {
super.onUserLeaveHint();
sPausedFromUserAction = true;
}
/** To be overriden by subclasses to hint to Launcher that we have custom content */
protected boolean hasCustomContentToLeft() {
return false;
}
private void updateGlobalIcons() {
boolean searchVisible = false;
boolean voiceVisible = false;
// If we have a saved version of these external icons, we load them up immediately
int coi = getCurrentOrientationIndexForGlobalIcons();
if (sGlobalSearchIcon[coi] == null || sVoiceSearchIcon[coi] == null ||
sAppMarketIcon[coi] == null) {
updateAppMarketIcon();
searchVisible = updateGlobalSearchIcon();
voiceVisible = updateVoiceSearchIcon(searchVisible);
}
if (sGlobalSearchIcon[coi] != null) {
updateGlobalSearchIcon(sGlobalSearchIcon[coi]);
searchVisible = true;
}
if (sVoiceSearchIcon[coi] != null) {
updateVoiceSearchIcon(sVoiceSearchIcon[coi]);
voiceVisible = true;
}
if (sAppMarketIcon[coi] != null) {
updateAppMarketIcon(sAppMarketIcon[coi]);
}
if (mSearchDropTargetBar != null) {
mSearchDropTargetBar.onSearchPackagesChanged(searchVisible, voiceVisible);
}
}
private void checkForLocaleChange() {
if (sLocaleConfiguration == null) {
new AsyncTask<Void, Void, LocaleConfiguration>() {
@Override
protected LocaleConfiguration doInBackground(Void... unused) {
LocaleConfiguration localeConfiguration = new LocaleConfiguration();
readConfiguration(Launcher.this, localeConfiguration);
return localeConfiguration;
}
@Override
protected void onPostExecute(LocaleConfiguration result) {
sLocaleConfiguration = result;
checkForLocaleChange(); // recursive, but now with a locale configuration
}
}.execute();
return;
}
final Configuration configuration = getResources().getConfiguration();
final String previousLocale = sLocaleConfiguration.locale;
final String locale = configuration.locale.toString();
final int previousMcc = sLocaleConfiguration.mcc;
final int mcc = configuration.mcc;
final int previousMnc = sLocaleConfiguration.mnc;
final int mnc = configuration.mnc;
boolean localeChanged = !locale.equals(previousLocale) || mcc != previousMcc || mnc != previousMnc;
if (localeChanged) {
sLocaleConfiguration.locale = locale;
sLocaleConfiguration.mcc = mcc;
sLocaleConfiguration.mnc = mnc;
mIconCache.flush();
final LocaleConfiguration localeConfiguration = sLocaleConfiguration;
new Thread("WriteLocaleConfiguration") {
@Override
public void run() {
writeConfiguration(Launcher.this, localeConfiguration);
}
}.start();
}
}
private static class LocaleConfiguration {
public String locale;
public int mcc = -1;
public int mnc = -1;
}
private static void readConfiguration(Context context, LocaleConfiguration configuration) {
DataInputStream in = null;
try {
in = new DataInputStream(context.openFileInput(PREFERENCES));
configuration.locale = in.readUTF();
configuration.mcc = in.readInt();
configuration.mnc = in.readInt();
} catch (FileNotFoundException e) {
// Ignore
} catch (IOException e) {
// Ignore
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
// Ignore
}
}
}
}
private static void writeConfiguration(Context context, LocaleConfiguration configuration) {
DataOutputStream out = null;
try {
out = new DataOutputStream(context.openFileOutput(PREFERENCES, MODE_PRIVATE));
out.writeUTF(configuration.locale);
out.writeInt(configuration.mcc);
out.writeInt(configuration.mnc);
out.flush();
} catch (FileNotFoundException e) {
// Ignore
} catch (IOException e) {
//noinspection ResultOfMethodCallIgnored
context.getFileStreamPath(PREFERENCES).delete();
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
// Ignore
}
}
}
}
public LayoutInflater getInflater() {
return mInflater;
}
public DragLayer getDragLayer() {
return mDragLayer;
}
boolean isDraggingEnabled() {
// We prevent dragging when we are loading the workspace as it is possible to pick up a view
// that is subsequently removed from the workspace in startBinding().
return !mModel.isLoadingWorkspace();
}
static int getScreen() {
synchronized (sLock) {
return sScreen;
}
}
static void setScreen(int screen) {
synchronized (sLock) {
sScreen = screen;
}
}
/**
* Returns whether we should delay spring loaded mode -- for shortcuts and widgets that have
* a configuration step, this allows the proper animations to run after other transitions.
*/
private boolean completeAdd(PendingAddArguments args) {
boolean result = false;
switch (args.requestCode) {
case REQUEST_PICK_APPLICATION:
completeAddApplication(args.intent, args.container, args.screenId, args.cellX,
args.cellY);
break;
case REQUEST_PICK_SHORTCUT:
processShortcut(args.intent);
break;
case REQUEST_CREATE_SHORTCUT:
completeAddShortcut(args.intent, args.container, args.screenId, args.cellX,
args.cellY);
result = true;
break;
case REQUEST_CREATE_APPWIDGET:
int appWidgetId = args.intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1);
completeAddAppWidget(appWidgetId, args.container, args.screenId, null, null);
result = true;
break;
case REQUEST_PICK_WALLPAPER:
// We just wanted the activity result here so we can clear mWaitingForResult
break;
}
// Before adding this resetAddInfo(), after a shortcut was added to a workspace screen,
// if you turned the screen off and then back while in All Apps, Launcher would not
// return to the workspace. Clearing mAddInfo.container here fixes this issue
resetAddInfo();
return result;
}
@Override
protected void onActivityResult(
final int requestCode, final int resultCode, final Intent data) {
if (requestCode == REQUEST_BIND_APPWIDGET) {
int appWidgetId = data != null ?
data.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1) : -1;
if (resultCode == RESULT_CANCELED) {
completeTwoStageWidgetDrop(RESULT_CANCELED, appWidgetId);
} else if (resultCode == RESULT_OK) {
addAppWidgetImpl(appWidgetId, mPendingAddInfo, null, mPendingAddWidgetInfo);
}
return;
}
boolean delayExitSpringLoadedMode = false;
boolean isWidgetDrop = (requestCode == REQUEST_PICK_APPWIDGET ||
requestCode == REQUEST_CREATE_APPWIDGET);
mWaitingForResult = false;
// We have special handling for widgets
if (isWidgetDrop) {
int appWidgetId = data != null ?
data.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1) : -1;
if (appWidgetId < 0) {
Log.e(TAG, "Error: appWidgetId (EXTRA_APPWIDGET_ID) was not returned from the \\" +
"widget configuration activity.");
completeTwoStageWidgetDrop(RESULT_CANCELED, appWidgetId);
} else {
completeTwoStageWidgetDrop(resultCode, appWidgetId);
}
return;
}
// The pattern used here is that a user PICKs a specific application,
// which, depending on the target, might need to CREATE the actual target.
// For example, the user would PICK_SHORTCUT for "Music playlist", and we
// launch over to the Music app to actually CREATE_SHORTCUT.
if (resultCode == RESULT_OK && mPendingAddInfo.container != ItemInfo.NO_ID) {
final PendingAddArguments args = new PendingAddArguments();
args.requestCode = requestCode;
args.intent = data;
args.container = mPendingAddInfo.container;
args.screenId = mPendingAddInfo.screenId;
args.cellX = mPendingAddInfo.cellX;
args.cellY = mPendingAddInfo.cellY;
if (isWorkspaceLocked()) {
sPendingAddList.add(args);
} else {
delayExitSpringLoadedMode = completeAdd(args);
}
}
mDragLayer.clearAnimatedView();
// Exit spring loaded mode if necessary after cancelling the configuration of a widget
exitSpringLoadedDragModeDelayed((resultCode != RESULT_CANCELED), delayExitSpringLoadedMode,
null);
}
private void completeTwoStageWidgetDrop(final int resultCode, final int appWidgetId) {
CellLayout cellLayout =
(CellLayout) mWorkspace.getScreenWithId(mPendingAddInfo.screenId);
Runnable onCompleteRunnable = null;
int animationType = 0;
AppWidgetHostView boundWidget = null;
if (resultCode == RESULT_OK) {
animationType = Workspace.COMPLETE_TWO_STAGE_WIDGET_DROP_ANIMATION;
final AppWidgetHostView layout = mAppWidgetHost.createView(this, appWidgetId,
mPendingAddWidgetInfo);
boundWidget = layout;
onCompleteRunnable = new Runnable() {
@Override
public void run() {
completeAddAppWidget(appWidgetId, mPendingAddInfo.container,
mPendingAddInfo.screenId, layout, null);
exitSpringLoadedDragModeDelayed((resultCode != RESULT_CANCELED), false,
null);
}
};
} else if (resultCode == RESULT_CANCELED) {
animationType = Workspace.CANCEL_TWO_STAGE_WIDGET_DROP_ANIMATION;
onCompleteRunnable = new Runnable() {
@Override
public void run() {
exitSpringLoadedDragModeDelayed((resultCode != RESULT_CANCELED), false,
null);
}
};
}
if (mDragLayer.getAnimatedView() != null) {
mWorkspace.animateWidgetDrop(mPendingAddInfo, cellLayout,
(DragView) mDragLayer.getAnimatedView(), onCompleteRunnable,
animationType, boundWidget, true);
} else {
// The animated view may be null in the case of a rotation during widget configuration
onCompleteRunnable.run();
}
}
@Override
protected void onStop() {
super.onStop();
FirstFrameAnimatorHelper.setIsVisible(false);
}
@Override
protected void onStart() {
super.onStart();
FirstFrameAnimatorHelper.setIsVisible(true);
}
@Override
protected void onResume() {
long startTime = 0;
if (DEBUG_RESUME_TIME) {
startTime = System.currentTimeMillis();
Log.v(TAG, "Launcher.onResume()");
}
super.onResume();
// Restore the previous launcher state
if (mOnResumeState == State.WORKSPACE) {
showWorkspace(false);
} else if (mOnResumeState == State.APPS_CUSTOMIZE) {
showAllApps(false);
}
mOnResumeState = State.NONE;
// Background was set to gradient in onPause(), restore to black if in all apps.
setWorkspaceBackground(mState == State.WORKSPACE);
// Process any items that were added while Launcher was away
InstallShortcutReceiver.flushInstallQueue(this);
mPaused = false;
sPausedFromUserAction = false;
if (mRestoring || mOnResumeNeedsLoad) {
mWorkspaceLoading = true;
mModel.startLoader(true, -1);
mRestoring = false;
mOnResumeNeedsLoad = false;
}
if (mBindOnResumeCallbacks.size() > 0) {
// We might have postponed some bind calls until onResume (see waitUntilResume) --
// execute them here
long startTimeCallbacks = 0;
if (DEBUG_RESUME_TIME) {
startTimeCallbacks = System.currentTimeMillis();
}
if (mAppsCustomizeContent != null) {
mAppsCustomizeContent.setBulkBind(true);
}
for (int i = 0; i < mBindOnResumeCallbacks.size(); i++) {
mBindOnResumeCallbacks.get(i).run();
}
if (mAppsCustomizeContent != null) {
mAppsCustomizeContent.setBulkBind(false);
}
mBindOnResumeCallbacks.clear();
if (DEBUG_RESUME_TIME) {
Log.d(TAG, "Time spent processing callbacks in onResume: " +
(System.currentTimeMillis() - startTimeCallbacks));
}
}
+ if (mOnResumeCallbacks.size() > 0) {
+ for (int i = 0; i < mOnResumeCallbacks.size(); i++) {
+ mOnResumeCallbacks.get(i).run();
+ }
+ mOnResumeCallbacks.clear();
+ }
// Reset the pressed state of icons that were locked in the press state while activities
// were launching
if (mWaitingForResume != null) {
// Resets the previous workspace icon press state
mWaitingForResume.setStayPressed(false);
}
if (mAppsCustomizeContent != null) {
// Resets the previous all apps icon press state
mAppsCustomizeContent.resetDrawableState();
}
// It is possible that widgets can receive updates while launcher is not in the foreground.
// Consequently, the widgets will be inflated in the orientation of the foreground activity
// (framework issue). On resuming, we ensure that any widgets are inflated for the current
// orientation.
getWorkspace().reinflateWidgetsIfNecessary();
// Again, as with the above scenario, it's possible that one or more of the global icons
// were updated in the wrong orientation.
updateGlobalIcons();
if (DEBUG_RESUME_TIME) {
Log.d(TAG, "Time spent in onResume: " + (System.currentTimeMillis() - startTime));
}
}
@Override
protected void onPause() {
// NOTE: We want all transitions from launcher to act as if the wallpaper were enabled
// to be consistent. So re-enable the flag here, and we will re-disable it as necessary
// when Launcher resumes and we are still in AllApps.
updateWallpaperVisibility(true);
super.onPause();
mPaused = true;
mDragController.cancelDrag();
mDragController.resetLastGestureUpTime();
}
protected void onFinishBindingItems() {
}
QSBScroller mQsbScroller = new QSBScroller() {
int scrollY = 0;
@Override
public void setScrollY(int scroll) {
scrollY = scroll;
if (mWorkspace.isOnOrMovingToCustomContent()) {
mSearchDropTargetBar.setTranslationY(- scrollY);
}
}
};
public void resetQSBScroll() {
mSearchDropTargetBar.animate().translationY(0).start();
}
public interface CustomContentCallbacks {
// Custom content is completely shown
public void onShow();
// Custom content is completely hidden
public void onHide();
}
public interface QSBScroller {
public void setScrollY(int scrollY);
}
// Add a fullscreen unpadded view to the workspace to the left all other screens.
public QSBScroller addToCustomContentPage(View customContent) {
return addToCustomContentPage(customContent, null);
}
public QSBScroller addToCustomContentPage(View customContent,
CustomContentCallbacks callbacks) {
mWorkspace.addToCustomContentPage(customContent, callbacks);
return mQsbScroller;
}
// The custom content needs to offset its content to account for the QSB
public int getTopOffsetForCustomContent() {
return mWorkspace.getPaddingTop();
}
@Override
public Object onRetainNonConfigurationInstance() {
// Flag the loader to stop early before switching
mModel.stopLoader();
if (mAppsCustomizeContent != null) {
mAppsCustomizeContent.surrender();
}
return Boolean.TRUE;
}
// We can't hide the IME if it was forced open. So don't bother
/*
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (hasFocus) {
final InputMethodManager inputManager = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
WindowManager.LayoutParams lp = getWindow().getAttributes();
inputManager.hideSoftInputFromWindow(lp.token, 0, new android.os.ResultReceiver(new
android.os.Handler()) {
protected void onReceiveResult(int resultCode, Bundle resultData) {
Log.d(TAG, "ResultReceiver got resultCode=" + resultCode);
}
});
Log.d(TAG, "called hideSoftInputFromWindow from onWindowFocusChanged");
}
}
*/
private boolean acceptFilter() {
final InputMethodManager inputManager = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
return !inputManager.isFullscreenMode();
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
final int uniChar = event.getUnicodeChar();
final boolean handled = super.onKeyDown(keyCode, event);
final boolean isKeyNotWhitespace = uniChar > 0 && !Character.isWhitespace(uniChar);
if (!handled && acceptFilter() && isKeyNotWhitespace) {
boolean gotKey = TextKeyListener.getInstance().onKeyDown(mWorkspace, mDefaultKeySsb,
keyCode, event);
if (gotKey && mDefaultKeySsb != null && mDefaultKeySsb.length() > 0) {
// something usable has been typed - start a search
// the typed text will be retrieved and cleared by
// showSearchDialog()
// If there are multiple keystrokes before the search dialog takes focus,
// onSearchRequested() will be called for every keystroke,
// but it is idempotent, so it's fine.
return onSearchRequested();
}
}
// Eat the long press event so the keyboard doesn't come up.
if (keyCode == KeyEvent.KEYCODE_MENU && event.isLongPress()) {
return true;
}
return handled;
}
private String getTypedText() {
return mDefaultKeySsb.toString();
}
private void clearTypedText() {
mDefaultKeySsb.clear();
mDefaultKeySsb.clearSpans();
Selection.setSelection(mDefaultKeySsb, 0);
}
/**
* Given the integer (ordinal) value of a State enum instance, convert it to a variable of type
* State
*/
private static State intToState(int stateOrdinal) {
State state = State.WORKSPACE;
final State[] stateValues = State.values();
for (int i = 0; i < stateValues.length; i++) {
if (stateValues[i].ordinal() == stateOrdinal) {
state = stateValues[i];
break;
}
}
return state;
}
/**
* Restores the previous state, if it exists.
*
* @param savedState The previous state.
*/
private void restoreState(Bundle savedState) {
if (savedState == null) {
return;
}
State state = intToState(savedState.getInt(RUNTIME_STATE, State.WORKSPACE.ordinal()));
if (state == State.APPS_CUSTOMIZE) {
mOnResumeState = State.APPS_CUSTOMIZE;
}
int currentScreen = savedState.getInt(RUNTIME_STATE_CURRENT_SCREEN, -1);
if (currentScreen > -1) {
mWorkspace.setRestorePage(currentScreen);
}
final long pendingAddContainer = savedState.getLong(RUNTIME_STATE_PENDING_ADD_CONTAINER, -1);
final long pendingAddScreen = savedState.getLong(RUNTIME_STATE_PENDING_ADD_SCREEN, -1);
if (pendingAddContainer != ItemInfo.NO_ID && pendingAddScreen > -1) {
mPendingAddInfo.container = pendingAddContainer;
mPendingAddInfo.screenId = pendingAddScreen;
mPendingAddInfo.cellX = savedState.getInt(RUNTIME_STATE_PENDING_ADD_CELL_X);
mPendingAddInfo.cellY = savedState.getInt(RUNTIME_STATE_PENDING_ADD_CELL_Y);
mPendingAddInfo.spanX = savedState.getInt(RUNTIME_STATE_PENDING_ADD_SPAN_X);
mPendingAddInfo.spanY = savedState.getInt(RUNTIME_STATE_PENDING_ADD_SPAN_Y);
mPendingAddWidgetInfo = savedState.getParcelable(RUNTIME_STATE_PENDING_ADD_WIDGET_INFO);
mWaitingForResult = true;
mRestoring = true;
}
boolean renameFolder = savedState.getBoolean(RUNTIME_STATE_PENDING_FOLDER_RENAME, false);
if (renameFolder) {
long id = savedState.getLong(RUNTIME_STATE_PENDING_FOLDER_RENAME_ID);
mFolderInfo = mModel.getFolderById(this, sFolders, id);
mRestoring = true;
}
// Restore the AppsCustomize tab
if (mAppsCustomizeTabHost != null) {
String curTab = savedState.getString("apps_customize_currentTab");
if (curTab != null) {
mAppsCustomizeTabHost.setContentTypeImmediate(
mAppsCustomizeTabHost.getContentTypeForTabTag(curTab));
mAppsCustomizeContent.loadAssociatedPages(
mAppsCustomizeContent.getCurrentPage());
}
int currentIndex = savedState.getInt("apps_customize_currentIndex");
mAppsCustomizeContent.restorePageForIndex(currentIndex);
}
}
/**
* Finds all the views we need and configure them properly.
*/
private void setupViews() {
final DragController dragController = mDragController;
mLauncherView = findViewById(R.id.launcher);
mDragLayer = (DragLayer) findViewById(R.id.drag_layer);
mWorkspace = (Workspace) mDragLayer.findViewById(R.id.workspace);
mQsbDivider = findViewById(R.id.qsb_divider);
mLauncherView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
mWorkspaceBackgroundDrawable = getResources().getDrawable(R.drawable.workspace_bg);
// Setup the drag layer
mDragLayer.setup(this, dragController);
// Setup the hotseat
mHotseat = (Hotseat) findViewById(R.id.hotseat);
if (mHotseat != null) {
mHotseat.setup(this);
}
// Setup the workspace
mWorkspace.setHapticFeedbackEnabled(false);
mWorkspace.setOnLongClickListener(this);
mWorkspace.setup(dragController);
dragController.addDragListener(mWorkspace);
// Get the search/delete bar
mSearchDropTargetBar = (SearchDropTargetBar) mDragLayer.findViewById(R.id.qsb_bar);
// Setup AppsCustomize
mAppsCustomizeTabHost = (AppsCustomizeTabHost) findViewById(R.id.apps_customize_pane);
mAppsCustomizeContent = (AppsCustomizePagedView)
mAppsCustomizeTabHost.findViewById(R.id.apps_customize_pane_content);
mAppsCustomizeContent.setup(this, dragController);
// Setup the drag controller (drop targets have to be added in reverse order in priority)
dragController.setDragScoller(mWorkspace);
dragController.setScrollView(mDragLayer);
dragController.setMoveTarget(mWorkspace);
dragController.addDropTarget(mWorkspace);
if (mSearchDropTargetBar != null) {
mSearchDropTargetBar.setup(this, dragController);
}
if (getResources().getBoolean(R.bool.debug_memory_enabled)) {
Log.v(TAG, "adding WeightWatcher");
mWeightWatcher = new WeightWatcher(this);
mWeightWatcher.setAlpha(0.5f);
((FrameLayout) mLauncherView).addView(mWeightWatcher,
new FrameLayout.LayoutParams(
FrameLayout.LayoutParams.MATCH_PARENT,
FrameLayout.LayoutParams.WRAP_CONTENT,
Gravity.BOTTOM)
);
boolean show = shouldShowWeightWatcher();
mWeightWatcher.setVisibility(show ? View.VISIBLE : View.GONE);
}
}
/**
* Creates a view representing a shortcut.
*
* @param info The data structure describing the shortcut.
*
* @return A View inflated from R.layout.application.
*/
View createShortcut(ShortcutInfo info) {
return createShortcut(R.layout.application,
(ViewGroup) mWorkspace.getChildAt(mWorkspace.getCurrentPage()), info);
}
/**
* Creates a view representing a shortcut inflated from the specified resource.
*
* @param layoutResId The id of the XML layout used to create the shortcut.
* @param parent The group the shortcut belongs to.
* @param info The data structure describing the shortcut.
*
* @return A View inflated from layoutResId.
*/
View createShortcut(int layoutResId, ViewGroup parent, ShortcutInfo info) {
BubbleTextView favorite = (BubbleTextView) mInflater.inflate(layoutResId, parent, false);
favorite.applyFromShortcutInfo(info, mIconCache);
favorite.setOnClickListener(this);
return favorite;
}
/**
* Add an application shortcut to the workspace.
*
* @param data The intent describing the application.
* @param cellInfo The position on screen where to create the shortcut.
*/
void completeAddApplication(Intent data, long container, long screenId, int cellX, int cellY) {
final int[] cellXY = mTmpAddItemCellCoordinates;
final CellLayout layout = getCellLayout(container, screenId);
// First we check if we already know the exact location where we want to add this item.
if (cellX >= 0 && cellY >= 0) {
cellXY[0] = cellX;
cellXY[1] = cellY;
} else if (!layout.findCellForSpan(cellXY, 1, 1)) {
showOutOfSpaceMessage(isHotseatLayout(layout));
return;
}
final ShortcutInfo info = mModel.getShortcutInfo(getPackageManager(), data, this);
if (info != null) {
info.setActivity(this, data.getComponent(), Intent.FLAG_ACTIVITY_NEW_TASK |
Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
info.container = ItemInfo.NO_ID;
mWorkspace.addApplicationShortcut(info, layout, container, screenId, cellXY[0], cellXY[1],
isWorkspaceLocked(), cellX, cellY);
} else {
Log.e(TAG, "Couldn't find ActivityInfo for selected application: " + data);
}
}
/**
* Add a shortcut to the workspace.
*
* @param data The intent describing the shortcut.
* @param cellInfo The position on screen where to create the shortcut.
*/
private void completeAddShortcut(Intent data, long container, long screenId, int cellX,
int cellY) {
int[] cellXY = mTmpAddItemCellCoordinates;
int[] touchXY = mPendingAddInfo.dropPos;
CellLayout layout = getCellLayout(container, screenId);
boolean foundCellSpan = false;
ShortcutInfo info = mModel.infoFromShortcutIntent(this, data, null);
if (info == null) {
return;
}
final View view = createShortcut(info);
// First we check if we already know the exact location where we want to add this item.
if (cellX >= 0 && cellY >= 0) {
cellXY[0] = cellX;
cellXY[1] = cellY;
foundCellSpan = true;
// If appropriate, either create a folder or add to an existing folder
if (mWorkspace.createUserFolderIfNecessary(view, container, layout, cellXY, 0,
true, null,null)) {
return;
}
DragObject dragObject = new DragObject();
dragObject.dragInfo = info;
if (mWorkspace.addToExistingFolderIfNecessary(view, layout, cellXY, 0, dragObject,
true)) {
return;
}
} else if (touchXY != null) {
// when dragging and dropping, just find the closest free spot
int[] result = layout.findNearestVacantArea(touchXY[0], touchXY[1], 1, 1, cellXY);
foundCellSpan = (result != null);
} else {
foundCellSpan = layout.findCellForSpan(cellXY, 1, 1);
}
if (!foundCellSpan) {
showOutOfSpaceMessage(isHotseatLayout(layout));
return;
}
LauncherModel.addItemToDatabase(this, info, container, screenId, cellXY[0], cellXY[1], false);
if (!mRestoring) {
mWorkspace.addInScreen(view, container, screenId, cellXY[0], cellXY[1], 1, 1,
isWorkspaceLocked());
}
}
static int[] getSpanForWidget(Context context, ComponentName component, int minWidth,
int minHeight) {
Rect padding = AppWidgetHostView.getDefaultPaddingForWidget(context, component, null);
// We want to account for the extra amount of padding that we are adding to the widget
// to ensure that it gets the full amount of space that it has requested
int requiredWidth = minWidth + padding.left + padding.right;
int requiredHeight = minHeight + padding.top + padding.bottom;
return CellLayout.rectToCell(context.getResources(), requiredWidth, requiredHeight, null);
}
static int[] getSpanForWidget(Context context, AppWidgetProviderInfo info) {
return getSpanForWidget(context, info.provider, info.minWidth, info.minHeight);
}
static int[] getMinSpanForWidget(Context context, AppWidgetProviderInfo info) {
return getSpanForWidget(context, info.provider, info.minResizeWidth, info.minResizeHeight);
}
static int[] getSpanForWidget(Context context, PendingAddWidgetInfo info) {
return getSpanForWidget(context, info.componentName, info.minWidth, info.minHeight);
}
static int[] getMinSpanForWidget(Context context, PendingAddWidgetInfo info) {
return getSpanForWidget(context, info.componentName, info.minResizeWidth,
info.minResizeHeight);
}
/**
* Add a widget to the workspace.
*
* @param appWidgetId The app widget id
* @param cellInfo The position on screen where to create the widget.
*/
private void completeAddAppWidget(final int appWidgetId, long container, long screenId,
AppWidgetHostView hostView, AppWidgetProviderInfo appWidgetInfo) {
if (appWidgetInfo == null) {
appWidgetInfo = mAppWidgetManager.getAppWidgetInfo(appWidgetId);
}
// Calculate the grid spans needed to fit this widget
CellLayout layout = getCellLayout(container, screenId);
int[] minSpanXY = getMinSpanForWidget(this, appWidgetInfo);
int[] spanXY = getSpanForWidget(this, appWidgetInfo);
// Try finding open space on Launcher screen
// We have saved the position to which the widget was dragged-- this really only matters
// if we are placing widgets on a "spring-loaded" screen
int[] cellXY = mTmpAddItemCellCoordinates;
int[] touchXY = mPendingAddInfo.dropPos;
int[] finalSpan = new int[2];
boolean foundCellSpan = false;
if (mPendingAddInfo.cellX >= 0 && mPendingAddInfo.cellY >= 0) {
cellXY[0] = mPendingAddInfo.cellX;
cellXY[1] = mPendingAddInfo.cellY;
spanXY[0] = mPendingAddInfo.spanX;
spanXY[1] = mPendingAddInfo.spanY;
foundCellSpan = true;
} else if (touchXY != null) {
// when dragging and dropping, just find the closest free spot
int[] result = layout.findNearestVacantArea(
touchXY[0], touchXY[1], minSpanXY[0], minSpanXY[1], spanXY[0],
spanXY[1], cellXY, finalSpan);
spanXY[0] = finalSpan[0];
spanXY[1] = finalSpan[1];
foundCellSpan = (result != null);
} else {
foundCellSpan = layout.findCellForSpan(cellXY, minSpanXY[0], minSpanXY[1]);
}
if (!foundCellSpan) {
if (appWidgetId != -1) {
// Deleting an app widget ID is a void call but writes to disk before returning
// to the caller...
new Thread("deleteAppWidgetId") {
public void run() {
mAppWidgetHost.deleteAppWidgetId(appWidgetId);
}
}.start();
}
showOutOfSpaceMessage(isHotseatLayout(layout));
return;
}
// Build Launcher-specific widget info and save to database
LauncherAppWidgetInfo launcherInfo = new LauncherAppWidgetInfo(appWidgetId,
appWidgetInfo.provider);
launcherInfo.spanX = spanXY[0];
launcherInfo.spanY = spanXY[1];
launcherInfo.minSpanX = mPendingAddInfo.minSpanX;
launcherInfo.minSpanY = mPendingAddInfo.minSpanY;
LauncherModel.addItemToDatabase(this, launcherInfo,
container, screenId, cellXY[0], cellXY[1], false);
if (!mRestoring) {
if (hostView == null) {
// Perform actual inflation because we're live
launcherInfo.hostView = mAppWidgetHost.createView(this, appWidgetId, appWidgetInfo);
launcherInfo.hostView.setAppWidget(appWidgetId, appWidgetInfo);
} else {
// The AppWidgetHostView has already been inflated and instantiated
launcherInfo.hostView = hostView;
}
launcherInfo.hostView.setTag(launcherInfo);
launcherInfo.hostView.setVisibility(View.VISIBLE);
launcherInfo.notifyWidgetSizeChanged(this);
mWorkspace.addInScreen(launcherInfo.hostView, container, screenId, cellXY[0], cellXY[1],
launcherInfo.spanX, launcherInfo.spanY, isWorkspaceLocked());
addWidgetToAutoAdvanceIfNeeded(launcherInfo.hostView, appWidgetInfo);
}
resetAddInfo();
}
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (Intent.ACTION_SCREEN_OFF.equals(action)) {
mUserPresent = false;
mDragLayer.clearAllResizeFrames();
updateRunning();
// Reset AllApps to its initial state only if we are not in the middle of
// processing a multi-step drop
if (mAppsCustomizeTabHost != null && mPendingAddInfo.container == ItemInfo.NO_ID) {
mAppsCustomizeTabHost.reset();
showWorkspace(false);
}
} else if (Intent.ACTION_USER_PRESENT.equals(action)) {
mUserPresent = true;
updateRunning();
}
}
};
@Override
public void onAttachedToWindow() {
super.onAttachedToWindow();
// Listen for broadcasts related to user-presence
final IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_SCREEN_OFF);
filter.addAction(Intent.ACTION_USER_PRESENT);
registerReceiver(mReceiver, filter);
FirstFrameAnimatorHelper.initializeDrawListener(getWindow().getDecorView());
mAttached = true;
mVisible = true;
}
@Override
public void onDetachedFromWindow() {
super.onDetachedFromWindow();
mVisible = false;
if (mAttached) {
unregisterReceiver(mReceiver);
mAttached = false;
}
updateRunning();
}
public void onWindowVisibilityChanged(int visibility) {
mVisible = visibility == View.VISIBLE;
updateRunning();
// The following code used to be in onResume, but it turns out onResume is called when
// you're in All Apps and click home to go to the workspace. onWindowVisibilityChanged
// is a more appropriate event to handle
if (mVisible) {
mAppsCustomizeTabHost.onWindowVisible();
if (!mWorkspaceLoading) {
final ViewTreeObserver observer = mWorkspace.getViewTreeObserver();
// We want to let Launcher draw itself at least once before we force it to build
// layers on all the workspace pages, so that transitioning to Launcher from other
// apps is nice and speedy.
observer.addOnDrawListener(new ViewTreeObserver.OnDrawListener() {
private boolean mStarted = false;
public void onDraw() {
if (mStarted) return;
mStarted = true;
// We delay the layer building a bit in order to give
// other message processing a time to run. In particular
// this avoids a delay in hiding the IME if it was
// currently shown, because doing that may involve
// some communication back with the app.
mWorkspace.postDelayed(mBuildLayersRunnable, 500);
final ViewTreeObserver.OnDrawListener listener = this;
mWorkspace.post(new Runnable() {
public void run() {
if (mWorkspace != null &&
mWorkspace.getViewTreeObserver() != null) {
mWorkspace.getViewTreeObserver().
removeOnDrawListener(listener);
}
}
});
return;
}
});
}
// When Launcher comes back to foreground, a different Activity might be responsible for
// the app market intent, so refresh the icon
updateAppMarketIcon();
clearTypedText();
}
}
private void sendAdvanceMessage(long delay) {
mHandler.removeMessages(ADVANCE_MSG);
Message msg = mHandler.obtainMessage(ADVANCE_MSG);
mHandler.sendMessageDelayed(msg, delay);
mAutoAdvanceSentTime = System.currentTimeMillis();
}
private void updateRunning() {
boolean autoAdvanceRunning = mVisible && mUserPresent && !mWidgetsToAdvance.isEmpty();
if (autoAdvanceRunning != mAutoAdvanceRunning) {
mAutoAdvanceRunning = autoAdvanceRunning;
if (autoAdvanceRunning) {
long delay = mAutoAdvanceTimeLeft == -1 ? mAdvanceInterval : mAutoAdvanceTimeLeft;
sendAdvanceMessage(delay);
} else {
if (!mWidgetsToAdvance.isEmpty()) {
mAutoAdvanceTimeLeft = Math.max(0, mAdvanceInterval -
(System.currentTimeMillis() - mAutoAdvanceSentTime));
}
mHandler.removeMessages(ADVANCE_MSG);
mHandler.removeMessages(0); // Remove messages sent using postDelayed()
}
}
}
private final Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (msg.what == ADVANCE_MSG) {
int i = 0;
for (View key: mWidgetsToAdvance.keySet()) {
final View v = key.findViewById(mWidgetsToAdvance.get(key).autoAdvanceViewId);
final int delay = mAdvanceStagger * i;
if (v instanceof Advanceable) {
postDelayed(new Runnable() {
public void run() {
((Advanceable) v).advance();
}
}, delay);
}
i++;
}
sendAdvanceMessage(mAdvanceInterval);
}
}
};
void addWidgetToAutoAdvanceIfNeeded(View hostView, AppWidgetProviderInfo appWidgetInfo) {
if (appWidgetInfo == null || appWidgetInfo.autoAdvanceViewId == -1) return;
View v = hostView.findViewById(appWidgetInfo.autoAdvanceViewId);
if (v instanceof Advanceable) {
mWidgetsToAdvance.put(hostView, appWidgetInfo);
((Advanceable) v).fyiWillBeAdvancedByHostKThx();
updateRunning();
}
}
void removeWidgetToAutoAdvance(View hostView) {
if (mWidgetsToAdvance.containsKey(hostView)) {
mWidgetsToAdvance.remove(hostView);
updateRunning();
}
}
public void removeAppWidget(LauncherAppWidgetInfo launcherInfo) {
removeWidgetToAutoAdvance(launcherInfo.hostView);
launcherInfo.hostView = null;
}
void showOutOfSpaceMessage(boolean isHotseatLayout) {
int strId = (isHotseatLayout ? R.string.hotseat_out_of_space : R.string.out_of_space);
Toast.makeText(this, getString(strId), Toast.LENGTH_SHORT).show();
}
public LauncherAppWidgetHost getAppWidgetHost() {
return mAppWidgetHost;
}
public LauncherModel getModel() {
return mModel;
}
public void closeSystemDialogs() {
getWindow().closeAllPanels();
// Whatever we were doing is hereby canceled.
mWaitingForResult = false;
}
@Override
protected void onNewIntent(Intent intent) {
long startTime = 0;
if (DEBUG_RESUME_TIME) {
startTime = System.currentTimeMillis();
}
super.onNewIntent(intent);
// Close the menu
if (Intent.ACTION_MAIN.equals(intent.getAction())) {
// also will cancel mWaitingForResult.
closeSystemDialogs();
final boolean alreadyOnHome =
((intent.getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT)
!= Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
Runnable processIntent = new Runnable() {
public void run() {
if (mWorkspace == null) {
// Can be cases where mWorkspace is null, this prevents a NPE
return;
}
Folder openFolder = mWorkspace.getOpenFolder();
// In all these cases, only animate if we're already on home
mWorkspace.exitWidgetResizeMode();
if (alreadyOnHome && mState == State.WORKSPACE && !mWorkspace.isTouchActive() &&
openFolder == null) {
mWorkspace.moveToDefaultScreen(true);
}
closeFolder();
exitSpringLoadedDragMode();
// If we are already on home, then just animate back to the workspace,
// otherwise, just wait until onResume to set the state back to Workspace
if (alreadyOnHome) {
showWorkspace(true);
} else {
mOnResumeState = State.WORKSPACE;
}
final View v = getWindow().peekDecorView();
if (v != null && v.getWindowToken() != null) {
InputMethodManager imm = (InputMethodManager)getSystemService(
INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
}
// Reset AllApps to its initial state
if (!alreadyOnHome && mAppsCustomizeTabHost != null) {
mAppsCustomizeTabHost.reset();
}
}
};
if (alreadyOnHome && !mWorkspace.hasWindowFocus()) {
// Delay processing of the intent to allow the status bar animation to finish
// first in order to avoid janky animations.
mWorkspace.postDelayed(processIntent, 350);
} else {
// Process the intent immediately.
processIntent.run();
}
}
if (DEBUG_RESUME_TIME) {
Log.d(TAG, "Time spent in onNewIntent: " + (System.currentTimeMillis() - startTime));
}
}
@Override
public void onRestoreInstanceState(Bundle state) {
super.onRestoreInstanceState(state);
for (int page: mSynchronouslyBoundPages) {
mWorkspace.restoreInstanceStateForChild(page);
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
outState.putInt(RUNTIME_STATE_CURRENT_SCREEN, mWorkspace.getNextPage());
super.onSaveInstanceState(outState);
outState.putInt(RUNTIME_STATE, mState.ordinal());
// We close any open folder since it will not be re-opened, and we need to make sure
// this state is reflected.
closeFolder();
if (mPendingAddInfo.container != ItemInfo.NO_ID && mPendingAddInfo.screenId > -1 &&
mWaitingForResult) {
outState.putLong(RUNTIME_STATE_PENDING_ADD_CONTAINER, mPendingAddInfo.container);
outState.putLong(RUNTIME_STATE_PENDING_ADD_SCREEN, mPendingAddInfo.screenId);
outState.putInt(RUNTIME_STATE_PENDING_ADD_CELL_X, mPendingAddInfo.cellX);
outState.putInt(RUNTIME_STATE_PENDING_ADD_CELL_Y, mPendingAddInfo.cellY);
outState.putInt(RUNTIME_STATE_PENDING_ADD_SPAN_X, mPendingAddInfo.spanX);
outState.putInt(RUNTIME_STATE_PENDING_ADD_SPAN_Y, mPendingAddInfo.spanY);
outState.putParcelable(RUNTIME_STATE_PENDING_ADD_WIDGET_INFO, mPendingAddWidgetInfo);
}
if (mFolderInfo != null && mWaitingForResult) {
outState.putBoolean(RUNTIME_STATE_PENDING_FOLDER_RENAME, true);
outState.putLong(RUNTIME_STATE_PENDING_FOLDER_RENAME_ID, mFolderInfo.id);
}
// Save the current AppsCustomize tab
if (mAppsCustomizeTabHost != null) {
String currentTabTag = mAppsCustomizeTabHost.getCurrentTabTag();
if (currentTabTag != null) {
outState.putString("apps_customize_currentTab", currentTabTag);
}
int currentIndex = mAppsCustomizeContent.getSaveInstanceStateIndex();
outState.putInt("apps_customize_currentIndex", currentIndex);
}
}
@Override
public void onDestroy() {
super.onDestroy();
// Remove all pending runnables
mHandler.removeMessages(ADVANCE_MSG);
mHandler.removeMessages(0);
mWorkspace.removeCallbacks(mBuildLayersRunnable);
// Stop callbacks from LauncherModel
LauncherAppState app = (LauncherAppState.getInstance());
mModel.stopLoader();
app.setLauncher(null);
try {
mAppWidgetHost.stopListening();
} catch (NullPointerException ex) {
Log.w(TAG, "problem while stopping AppWidgetHost during Launcher destruction", ex);
}
mAppWidgetHost = null;
mWidgetsToAdvance.clear();
TextKeyListener.getInstance().release();
// Disconnect any of the callbacks and drawables associated with ItemInfos on the workspace
// to prevent leaking Launcher activities on orientation change.
if (mModel != null) {
mModel.unbindItemInfosAndClearQueuedBindRunnables();
}
getContentResolver().unregisterContentObserver(mWidgetObserver);
unregisterReceiver(mCloseSystemDialogsReceiver);
mDragLayer.clearAllResizeFrames();
((ViewGroup) mWorkspace.getParent()).removeAllViews();
mWorkspace.removeAllViews();
mWorkspace = null;
mDragController = null;
LauncherAnimUtils.onDestroyActivity();
}
public DragController getDragController() {
return mDragController;
}
@Override
public void startActivityForResult(Intent intent, int requestCode) {
if (requestCode >= 0) mWaitingForResult = true;
super.startActivityForResult(intent, requestCode);
}
/**
* Indicates that we want global search for this activity by setting the globalSearch
* argument for {@link #startSearch} to true.
*/
@Override
public void startSearch(String initialQuery, boolean selectInitialQuery,
Bundle appSearchData, boolean globalSearch) {
showWorkspace(true);
if (initialQuery == null) {
// Use any text typed in the launcher as the initial query
initialQuery = getTypedText();
}
if (appSearchData == null) {
appSearchData = new Bundle();
appSearchData.putString("source", "launcher-search");
}
Rect sourceBounds = new Rect();
if (mSearchDropTargetBar != null) {
sourceBounds = mSearchDropTargetBar.getSearchBarBounds();
}
startSearch(initialQuery, selectInitialQuery,
appSearchData, sourceBounds);
}
public void startSearch(String initialQuery,
boolean selectInitialQuery, Bundle appSearchData, Rect sourceBounds) {
startGlobalSearch(initialQuery, selectInitialQuery,
appSearchData, sourceBounds);
}
/**
* Starts the global search activity. This code is a copied from SearchManager
*/
private void startGlobalSearch(String initialQuery,
boolean selectInitialQuery, Bundle appSearchData, Rect sourceBounds) {
final SearchManager searchManager =
(SearchManager) getSystemService(Context.SEARCH_SERVICE);
ComponentName globalSearchActivity = searchManager.getGlobalSearchActivity();
if (globalSearchActivity == null) {
Log.w(TAG, "No global search activity found.");
return;
}
Intent intent = new Intent(SearchManager.INTENT_ACTION_GLOBAL_SEARCH);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setComponent(globalSearchActivity);
// Make sure that we have a Bundle to put source in
if (appSearchData == null) {
appSearchData = new Bundle();
} else {
appSearchData = new Bundle(appSearchData);
}
// Set source to package name of app that starts global search, if not set already.
if (!appSearchData.containsKey("source")) {
appSearchData.putString("source", getPackageName());
}
intent.putExtra(SearchManager.APP_DATA, appSearchData);
if (!TextUtils.isEmpty(initialQuery)) {
intent.putExtra(SearchManager.QUERY, initialQuery);
}
if (selectInitialQuery) {
intent.putExtra(SearchManager.EXTRA_SELECT_QUERY, selectInitialQuery);
}
intent.setSourceBounds(sourceBounds);
try {
startActivity(intent);
} catch (ActivityNotFoundException ex) {
Log.e(TAG, "Global search activity not found: " + globalSearchActivity);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
if (isWorkspaceLocked()) {
return false;
}
super.onCreateOptionsMenu(menu);
Intent manageApps = new Intent(Settings.ACTION_MANAGE_ALL_APPLICATIONS_SETTINGS);
manageApps.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
Intent settings = new Intent(android.provider.Settings.ACTION_SETTINGS);
settings.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
String helpUrl = getString(R.string.help_url);
Intent help = new Intent(Intent.ACTION_VIEW, Uri.parse(helpUrl));
help.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
menu.add(MENU_GROUP_WALLPAPER, MENU_WALLPAPER_SETTINGS, 0, R.string.menu_wallpaper)
.setIcon(android.R.drawable.ic_menu_gallery)
.setAlphabeticShortcut('W');
menu.add(0, MENU_MANAGE_APPS, 0, R.string.menu_manage_apps)
.setIcon(android.R.drawable.ic_menu_manage)
.setIntent(manageApps)
.setAlphabeticShortcut('M');
menu.add(0, MENU_SYSTEM_SETTINGS, 0, R.string.menu_settings)
.setIcon(android.R.drawable.ic_menu_preferences)
.setIntent(settings)
.setAlphabeticShortcut('P');
if (!helpUrl.isEmpty()) {
menu.add(0, MENU_HELP, 0, R.string.menu_help)
.setIcon(android.R.drawable.ic_menu_help)
.setIntent(help)
.setAlphabeticShortcut('H');
}
return true;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
if (mAppsCustomizeTabHost.isTransitioning()) {
return false;
}
boolean allAppsVisible = (mAppsCustomizeTabHost.getVisibility() == View.VISIBLE);
menu.setGroupVisible(MENU_GROUP_WALLPAPER, !allAppsVisible);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_WALLPAPER_SETTINGS:
startWallpaper();
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public boolean onSearchRequested() {
startSearch(null, false, null, true);
// Use a custom animation for launching search
return true;
}
public boolean isWorkspaceLocked() {
return mWorkspaceLoading || mWaitingForResult;
}
private void resetAddInfo() {
mPendingAddInfo.container = ItemInfo.NO_ID;
mPendingAddInfo.screenId = -1;
mPendingAddInfo.cellX = mPendingAddInfo.cellY = -1;
mPendingAddInfo.spanX = mPendingAddInfo.spanY = -1;
mPendingAddInfo.minSpanX = mPendingAddInfo.minSpanY = -1;
mPendingAddInfo.dropPos = null;
}
void addAppWidgetImpl(final int appWidgetId, ItemInfo info, AppWidgetHostView boundWidget,
AppWidgetProviderInfo appWidgetInfo) {
if (appWidgetInfo.configure != null) {
mPendingAddWidgetInfo = appWidgetInfo;
// Launch over to configure widget, if needed
Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_CONFIGURE);
intent.setComponent(appWidgetInfo.configure);
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
startActivityForResultSafely(intent, REQUEST_CREATE_APPWIDGET);
} else {
// Otherwise just add it
completeAddAppWidget(appWidgetId, info.container, info.screenId, boundWidget,
appWidgetInfo);
// Exit spring loaded mode if necessary after adding the widget
exitSpringLoadedDragModeDelayed(true, false, null);
}
}
/**
* Process a shortcut drop.
*
* @param componentName The name of the component
* @param screenId The ID of the screen where it should be added
* @param cell The cell it should be added to, optional
* @param position The location on the screen where it was dropped, optional
*/
void processShortcutFromDrop(ComponentName componentName, long container, long screenId,
int[] cell, int[] loc) {
resetAddInfo();
mPendingAddInfo.container = container;
mPendingAddInfo.screenId = screenId;
mPendingAddInfo.dropPos = loc;
if (cell != null) {
mPendingAddInfo.cellX = cell[0];
mPendingAddInfo.cellY = cell[1];
}
Intent createShortcutIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT);
createShortcutIntent.setComponent(componentName);
processShortcut(createShortcutIntent);
}
/**
* Process a widget drop.
*
* @param info The PendingAppWidgetInfo of the widget being added.
* @param screenId The ID of the screen where it should be added
* @param cell The cell it should be added to, optional
* @param position The location on the screen where it was dropped, optional
*/
void addAppWidgetFromDrop(PendingAddWidgetInfo info, long container, long screenId,
int[] cell, int[] span, int[] loc) {
resetAddInfo();
mPendingAddInfo.container = info.container = container;
mPendingAddInfo.screenId = info.screenId = screenId;
mPendingAddInfo.dropPos = loc;
mPendingAddInfo.minSpanX = info.minSpanX;
mPendingAddInfo.minSpanY = info.minSpanY;
if (cell != null) {
mPendingAddInfo.cellX = cell[0];
mPendingAddInfo.cellY = cell[1];
}
if (span != null) {
mPendingAddInfo.spanX = span[0];
mPendingAddInfo.spanY = span[1];
}
AppWidgetHostView hostView = info.boundWidget;
int appWidgetId;
if (hostView != null) {
appWidgetId = hostView.getAppWidgetId();
addAppWidgetImpl(appWidgetId, info, hostView, info.info);
} else {
// In this case, we either need to start an activity to get permission to bind
// the widget, or we need to start an activity to configure the widget, or both.
appWidgetId = getAppWidgetHost().allocateAppWidgetId();
Bundle options = info.bindOptions;
boolean success = false;
if (options != null) {
success = mAppWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,
info.componentName, options);
} else {
success = mAppWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,
info.componentName);
}
if (success) {
addAppWidgetImpl(appWidgetId, info, null, info.info);
} else {
mPendingAddWidgetInfo = info.info;
Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_BIND);
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_PROVIDER, info.componentName);
// TODO: we need to make sure that this accounts for the options bundle.
// intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_OPTIONS, options);
startActivityForResult(intent, REQUEST_BIND_APPWIDGET);
}
}
}
void processShortcut(Intent intent) {
// Handle case where user selected "Applications"
String applicationName = getResources().getString(R.string.group_applications);
String shortcutName = intent.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
if (applicationName != null && applicationName.equals(shortcutName)) {
Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
Intent pickIntent = new Intent(Intent.ACTION_PICK_ACTIVITY);
pickIntent.putExtra(Intent.EXTRA_INTENT, mainIntent);
pickIntent.putExtra(Intent.EXTRA_TITLE, getText(R.string.title_select_application));
startActivityForResultSafely(pickIntent, REQUEST_PICK_APPLICATION);
} else {
startActivityForResultSafely(intent, REQUEST_CREATE_SHORTCUT);
}
}
void processWallpaper(Intent intent) {
startActivityForResult(intent, REQUEST_PICK_WALLPAPER);
}
FolderIcon addFolder(CellLayout layout, long container, final long screenId, int cellX,
int cellY) {
final FolderInfo folderInfo = new FolderInfo();
folderInfo.title = getText(R.string.folder_name);
// Update the model
LauncherModel.addItemToDatabase(Launcher.this, folderInfo, container, screenId, cellX, cellY,
false);
sFolders.put(folderInfo.id, folderInfo);
// Create the view
FolderIcon newFolder =
FolderIcon.fromXml(R.layout.folder_icon, this, layout, folderInfo, mIconCache);
mWorkspace.addInScreen(newFolder, container, screenId, cellX, cellY, 1, 1,
isWorkspaceLocked());
return newFolder;
}
void removeFolder(FolderInfo folder) {
sFolders.remove(folder.id);
}
private void startWallpaper() {
showWorkspace(true);
final Intent pickWallpaper = new Intent(Intent.ACTION_SET_WALLPAPER);
Intent chooser = Intent.createChooser(pickWallpaper,
getText(R.string.chooser_wallpaper));
// NOTE: Adds a configure option to the chooser if the wallpaper supports it
// Removed in Eclair MR1
// WallpaperManager wm = (WallpaperManager)
// getSystemService(Context.WALLPAPER_SERVICE);
// WallpaperInfo wi = wm.getWallpaperInfo();
// if (wi != null && wi.getSettingsActivity() != null) {
// LabeledIntent li = new LabeledIntent(getPackageName(),
// R.string.configure_wallpaper, 0);
// li.setClassName(wi.getPackageName(), wi.getSettingsActivity());
// chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] { li });
// }
startActivityForResult(chooser, REQUEST_PICK_WALLPAPER);
}
/**
* Registers various content observers. The current implementation registers
* only a favorites observer to keep track of the favorites applications.
*/
private void registerContentObservers() {
ContentResolver resolver = getContentResolver();
resolver.registerContentObserver(LauncherProvider.CONTENT_APPWIDGET_RESET_URI,
true, mWidgetObserver);
}
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (event.getKeyCode()) {
case KeyEvent.KEYCODE_HOME:
return true;
case KeyEvent.KEYCODE_VOLUME_DOWN:
if (isPropertyEnabled(DUMP_STATE_PROPERTY)) {
dumpState();
return true;
}
break;
}
} else if (event.getAction() == KeyEvent.ACTION_UP) {
switch (event.getKeyCode()) {
case KeyEvent.KEYCODE_HOME:
return true;
}
}
return super.dispatchKeyEvent(event);
}
@Override
public void onBackPressed() {
if (isAllAppsVisible()) {
showWorkspace(true);
} else if (mWorkspace.getOpenFolder() != null) {
Folder openFolder = mWorkspace.getOpenFolder();
if (openFolder.isEditingName()) {
openFolder.dismissEditingName();
} else {
closeFolder();
}
} else {
mWorkspace.exitWidgetResizeMode();
// Back button is a no-op here, but give at least some feedback for the button press
mWorkspace.showOutlinesTemporarily();
}
}
/**
* Re-listen when widgets are reset.
*/
private void onAppWidgetReset() {
if (mAppWidgetHost != null) {
mAppWidgetHost.startListening();
}
}
/**
* Launches the intent referred by the clicked shortcut.
*
* @param v The view representing the clicked shortcut.
*/
public void onClick(View v) {
// Make sure that rogue clicks don't get through while allapps is launching, or after the
// view has detached (it's possible for this to happen if the view is removed mid touch).
if (v.getWindowToken() == null) {
return;
}
if (!mWorkspace.isFinishedSwitchingState()) {
return;
}
Object tag = v.getTag();
if (tag instanceof ShortcutInfo) {
// Open shortcut
final Intent intent = ((ShortcutInfo) tag).intent;
// Check for special shortcuts
if (intent.getComponent() != null) {
final String shortcutClass = intent.getComponent().getClassName();
if (shortcutClass.equals(WidgetAdder.class.getName())) {
showAllApps(true);
return;
} else if (shortcutClass.equals(MemoryDumpActivity.class.getName())) {
MemoryDumpActivity.startDump(this);
return;
} else if (shortcutClass.equals(ToggleWeightWatcher.class.getName())) {
toggleShowWeightWatcher();
return;
}
}
// Start activities
int[] pos = new int[2];
v.getLocationOnScreen(pos);
intent.setSourceBounds(new Rect(pos[0], pos[1],
pos[0] + v.getWidth(), pos[1] + v.getHeight()));
boolean success = startActivitySafely(v, intent, tag);
if (success && v instanceof BubbleTextView) {
mWaitingForResume = (BubbleTextView) v;
mWaitingForResume.setStayPressed(true);
}
} else if (tag instanceof FolderInfo) {
if (v instanceof FolderIcon) {
FolderIcon fi = (FolderIcon) v;
handleFolderClick(fi);
}
} else if (v == mAllAppsButton) {
if (isAllAppsVisible()) {
showWorkspace(true);
} else {
onClickAllAppsButton(v);
}
}
}
public boolean onTouch(View v, MotionEvent event) {
// this is an intercepted event being forwarded from mWorkspace;
// clicking anywhere on the workspace causes the customization drawer to slide down
if (event.getAction() == MotionEvent.ACTION_DOWN) {
showWorkspace(true);
}
return false;
}
/**
* Event handler for the search button
*
* @param v The view that was clicked.
*/
public void onClickSearchButton(View v) {
v.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY);
onSearchRequested();
}
/**
* Event handler for the voice button
*
* @param v The view that was clicked.
*/
public void onClickVoiceButton(View v) {
v.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY);
startVoice();
}
public void startVoice() {
try {
final SearchManager searchManager =
(SearchManager) getSystemService(Context.SEARCH_SERVICE);
ComponentName activityName = searchManager.getGlobalSearchActivity();
Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
if (activityName != null) {
intent.setPackage(activityName.getPackageName());
}
startActivity(null, intent, "onClickVoiceButton");
} catch (ActivityNotFoundException e) {
Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivitySafely(null, intent, "onClickVoiceButton");
}
}
/**
* Event handler for the "grid" button that appears on the home screen, which
* enters all apps mode.
*
* @param v The view that was clicked.
*/
public void onClickAllAppsButton(View v) {
showAllApps(true);
}
public void onTouchDownAllAppsButton(View v) {
// Provide the same haptic feedback that the system offers for virtual keys.
v.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY);
}
public void onClickAppMarketButton(View v) {
if (mAppMarketIntent != null) {
startActivitySafely(v, mAppMarketIntent, "app market");
} else {
Log.e(TAG, "Invalid app market intent.");
}
}
void startApplicationDetailsActivity(ComponentName componentName) {
String packageName = componentName.getPackageName();
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
Uri.fromParts("package", packageName, null));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
startActivitySafely(null, intent, "startApplicationDetailsActivity");
}
// returns true if the activity was started
boolean startApplicationUninstallActivity(ComponentName componentName, int flags) {
if ((flags & ApplicationInfo.DOWNLOADED_FLAG) == 0) {
// System applications cannot be installed. For now, show a toast explaining that.
// We may give them the option of disabling apps this way.
int messageId = R.string.uninstall_system_app_text;
Toast.makeText(this, messageId, Toast.LENGTH_SHORT).show();
return false;
} else {
String packageName = componentName.getPackageName();
String className = componentName.getClassName();
Intent intent = new Intent(
Intent.ACTION_DELETE, Uri.fromParts("package", packageName, className));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
startActivity(intent);
return true;
}
}
boolean startActivity(View v, Intent intent, Object tag) {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
try {
// Only launch using the new animation if the shortcut has not opted out (this is a
// private contract between launcher and may be ignored in the future).
boolean useLaunchAnimation = (v != null) &&
!intent.hasExtra(INTENT_EXTRA_IGNORE_LAUNCH_ANIMATION);
if (useLaunchAnimation) {
ActivityOptions opts = ActivityOptions.makeScaleUpAnimation(v, 0, 0,
v.getMeasuredWidth(), v.getMeasuredHeight());
startActivity(intent, opts.toBundle());
} else {
startActivity(intent);
}
return true;
} catch (SecurityException e) {
Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
Log.e(TAG, "Launcher does not have the permission to launch " + intent +
". Make sure to create a MAIN intent-filter for the corresponding activity " +
"or use the exported attribute for this activity. "
+ "tag="+ tag + " intent=" + intent, e);
}
return false;
}
boolean startActivitySafely(View v, Intent intent, Object tag) {
boolean success = false;
try {
success = startActivity(v, intent, tag);
} catch (ActivityNotFoundException e) {
Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
Log.e(TAG, "Unable to launch. tag=" + tag + " intent=" + intent, e);
}
return success;
}
void startActivityForResultSafely(Intent intent, int requestCode) {
try {
startActivityForResult(intent, requestCode);
} catch (ActivityNotFoundException e) {
Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
} catch (SecurityException e) {
Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
Log.e(TAG, "Launcher does not have the permission to launch " + intent +
". Make sure to create a MAIN intent-filter for the corresponding activity " +
"or use the exported attribute for this activity.", e);
}
}
private void handleFolderClick(FolderIcon folderIcon) {
final FolderInfo info = folderIcon.getFolderInfo();
Folder openFolder = mWorkspace.getFolderForTag(info);
// If the folder info reports that the associated folder is open, then verify that
// it is actually opened. There have been a few instances where this gets out of sync.
if (info.opened && openFolder == null) {
Log.d(TAG, "Folder info marked as open, but associated folder is not open. Screen: "
+ info.screenId + " (" + info.cellX + ", " + info.cellY + ")");
info.opened = false;
}
if (!info.opened && !folderIcon.getFolder().isDestroyed()) {
// Close any open folder
closeFolder();
// Open the requested folder
openFolder(folderIcon);
} else {
// Find the open folder...
int folderScreen;
if (openFolder != null) {
folderScreen = mWorkspace.getPageForView(openFolder);
// .. and close it
closeFolder(openFolder);
if (folderScreen != mWorkspace.getCurrentPage()) {
// Close any folder open on the current screen
closeFolder();
// Pull the folder onto this screen
openFolder(folderIcon);
}
}
}
}
/**
* This method draws the FolderIcon to an ImageView and then adds and positions that ImageView
* in the DragLayer in the exact absolute location of the original FolderIcon.
*/
private void copyFolderIconToImage(FolderIcon fi) {
final int width = fi.getMeasuredWidth();
final int height = fi.getMeasuredHeight();
// Lazy load ImageView, Bitmap and Canvas
if (mFolderIconImageView == null) {
mFolderIconImageView = new ImageView(this);
}
if (mFolderIconBitmap == null || mFolderIconBitmap.getWidth() != width ||
mFolderIconBitmap.getHeight() != height) {
mFolderIconBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
mFolderIconCanvas = new Canvas(mFolderIconBitmap);
}
DragLayer.LayoutParams lp;
if (mFolderIconImageView.getLayoutParams() instanceof DragLayer.LayoutParams) {
lp = (DragLayer.LayoutParams) mFolderIconImageView.getLayoutParams();
} else {
lp = new DragLayer.LayoutParams(width, height);
}
// The layout from which the folder is being opened may be scaled, adjust the starting
// view size by this scale factor.
float scale = mDragLayer.getDescendantRectRelativeToSelf(fi, mRectForFolderAnimation);
lp.customPosition = true;
lp.x = mRectForFolderAnimation.left;
lp.y = mRectForFolderAnimation.top;
lp.width = (int) (scale * width);
lp.height = (int) (scale * height);
mFolderIconCanvas.drawColor(0, PorterDuff.Mode.CLEAR);
fi.draw(mFolderIconCanvas);
mFolderIconImageView.setImageBitmap(mFolderIconBitmap);
if (fi.getFolder() != null) {
mFolderIconImageView.setPivotX(fi.getFolder().getPivotXForIconAnimation());
mFolderIconImageView.setPivotY(fi.getFolder().getPivotYForIconAnimation());
}
// Just in case this image view is still in the drag layer from a previous animation,
// we remove it and re-add it.
if (mDragLayer.indexOfChild(mFolderIconImageView) != -1) {
mDragLayer.removeView(mFolderIconImageView);
}
mDragLayer.addView(mFolderIconImageView, lp);
if (fi.getFolder() != null) {
fi.getFolder().bringToFront();
}
}
private void growAndFadeOutFolderIcon(FolderIcon fi) {
if (fi == null) return;
PropertyValuesHolder alpha = PropertyValuesHolder.ofFloat("alpha", 0);
PropertyValuesHolder scaleX = PropertyValuesHolder.ofFloat("scaleX", 1.5f);
PropertyValuesHolder scaleY = PropertyValuesHolder.ofFloat("scaleY", 1.5f);
FolderInfo info = (FolderInfo) fi.getTag();
if (info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
CellLayout cl = (CellLayout) fi.getParent().getParent();
CellLayout.LayoutParams lp = (CellLayout.LayoutParams) fi.getLayoutParams();
cl.setFolderLeaveBehindCell(lp.cellX, lp.cellY);
}
// Push an ImageView copy of the FolderIcon into the DragLayer and hide the original
copyFolderIconToImage(fi);
fi.setVisibility(View.INVISIBLE);
ObjectAnimator oa = LauncherAnimUtils.ofPropertyValuesHolder(mFolderIconImageView, alpha,
scaleX, scaleY);
oa.setDuration(getResources().getInteger(R.integer.config_folderAnimDuration));
oa.start();
}
private void shrinkAndFadeInFolderIcon(final FolderIcon fi) {
if (fi == null) return;
PropertyValuesHolder alpha = PropertyValuesHolder.ofFloat("alpha", 1.0f);
PropertyValuesHolder scaleX = PropertyValuesHolder.ofFloat("scaleX", 1.0f);
PropertyValuesHolder scaleY = PropertyValuesHolder.ofFloat("scaleY", 1.0f);
final CellLayout cl = (CellLayout) fi.getParent().getParent();
// We remove and re-draw the FolderIcon in-case it has changed
mDragLayer.removeView(mFolderIconImageView);
copyFolderIconToImage(fi);
ObjectAnimator oa = LauncherAnimUtils.ofPropertyValuesHolder(mFolderIconImageView, alpha,
scaleX, scaleY);
oa.setDuration(getResources().getInteger(R.integer.config_folderAnimDuration));
oa.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
if (cl != null) {
cl.clearFolderLeaveBehind();
// Remove the ImageView copy of the FolderIcon and make the original visible.
mDragLayer.removeView(mFolderIconImageView);
fi.setVisibility(View.VISIBLE);
}
}
});
oa.start();
}
/**
* Opens the user folder described by the specified tag. The opening of the folder
* is animated relative to the specified View. If the View is null, no animation
* is played.
*
* @param folderInfo The FolderInfo describing the folder to open.
*/
public void openFolder(FolderIcon folderIcon) {
Folder folder = folderIcon.getFolder();
FolderInfo info = folder.mInfo;
info.opened = true;
// Just verify that the folder hasn't already been added to the DragLayer.
// There was a one-off crash where the folder had a parent already.
if (folder.getParent() == null) {
mDragLayer.addView(folder);
mDragController.addDropTarget((DropTarget) folder);
} else {
Log.w(TAG, "Opening folder (" + folder + ") which already has a parent (" +
folder.getParent() + ").");
}
folder.animateOpen();
growAndFadeOutFolderIcon(folderIcon);
// Notify the accessibility manager that this folder "window" has appeared and occluded
// the workspace items
folder.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
getDragLayer().sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
}
public void closeFolder() {
Folder folder = mWorkspace.getOpenFolder();
if (folder != null) {
if (folder.isEditingName()) {
folder.dismissEditingName();
}
closeFolder(folder);
// Dismiss the folder cling
dismissFolderCling(null);
}
}
void closeFolder(Folder folder) {
folder.getInfo().opened = false;
ViewGroup parent = (ViewGroup) folder.getParent().getParent();
if (parent != null) {
FolderIcon fi = (FolderIcon) mWorkspace.getViewForTag(folder.mInfo);
shrinkAndFadeInFolderIcon(fi);
}
folder.animateClosed();
// Notify the accessibility manager that this folder "window" has disappeard and no
// longer occludeds the workspace items
getDragLayer().sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
}
public boolean onLongClick(View v) {
if (!isDraggingEnabled()) return false;
if (isWorkspaceLocked()) return false;
if (mState != State.WORKSPACE) return false;
if (!(v instanceof CellLayout)) {
v = (View) v.getParent().getParent();
}
resetAddInfo();
CellLayout.CellInfo longClickCellInfo = (CellLayout.CellInfo) v.getTag();
// This happens when long clicking an item with the dpad/trackball
if (longClickCellInfo == null) {
return true;
}
// The hotseat touch handling does not go through Workspace, and we always allow long press
// on hotseat items.
final View itemUnderLongClick = longClickCellInfo.cell;
boolean allowLongPress = isHotseatLayout(v) || mWorkspace.allowLongPress();
if (allowLongPress && !mDragController.isDragging()) {
if (itemUnderLongClick == null) {
// User long pressed on empty space
mWorkspace.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS,
HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING);
// Disabling reordering until we sort out some issues.
if (mWorkspace.getIdForScreen((CellLayout) v) >= 0) {
mWorkspace.startReordering();
} else {
startWallpaper();
}
} else {
if (!(itemUnderLongClick instanceof Folder)) {
// User long pressed on an item
mWorkspace.startDrag(longClickCellInfo);
}
}
}
return true;
}
boolean isHotseatLayout(View layout) {
return mHotseat != null && layout != null &&
(layout instanceof CellLayout) && (layout == mHotseat.getLayout());
}
Hotseat getHotseat() {
return mHotseat;
}
SearchDropTargetBar getSearchBar() {
return mSearchDropTargetBar;
}
/**
* Returns the CellLayout of the specified container at the specified screen.
*/
CellLayout getCellLayout(long container, long screenId) {
if (container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
if (mHotseat != null) {
return mHotseat.getLayout();
} else {
return null;
}
} else {
return (CellLayout) mWorkspace.getScreenWithId(screenId);
}
}
Workspace getWorkspace() {
return mWorkspace;
}
public boolean isAllAppsVisible() {
return (mState == State.APPS_CUSTOMIZE) || (mOnResumeState == State.APPS_CUSTOMIZE);
}
/**
* Helper method for the cameraZoomIn/cameraZoomOut animations
* @param view The view being animated
* @param scaleFactor The scale factor used for the zoom
*/
private void setPivotsForZoom(View view, float scaleFactor) {
view.setPivotX(view.getWidth() / 2.0f);
view.setPivotY(view.getHeight() / 2.0f);
}
void disableWallpaperIfInAllApps() {
// Only disable it if we are in all apps
if (isAllAppsVisible()) {
if (mAppsCustomizeTabHost != null &&
!mAppsCustomizeTabHost.isTransitioning()) {
updateWallpaperVisibility(false);
}
}
}
private void setWorkspaceBackground(boolean workspace) {
mLauncherView.setBackground(workspace ?
mWorkspaceBackgroundDrawable : null);
}
void updateWallpaperVisibility(boolean visible) {
int wpflags = visible ? WindowManager.LayoutParams.FLAG_SHOW_WALLPAPER : 0;
int curflags = getWindow().getAttributes().flags
& WindowManager.LayoutParams.FLAG_SHOW_WALLPAPER;
if (wpflags != curflags) {
getWindow().setFlags(wpflags, WindowManager.LayoutParams.FLAG_SHOW_WALLPAPER);
}
setWorkspaceBackground(visible);
}
private void dispatchOnLauncherTransitionPrepare(View v, boolean animated, boolean toWorkspace) {
if (v instanceof LauncherTransitionable) {
((LauncherTransitionable) v).onLauncherTransitionPrepare(this, animated, toWorkspace);
}
}
private void dispatchOnLauncherTransitionStart(View v, boolean animated, boolean toWorkspace) {
if (v instanceof LauncherTransitionable) {
((LauncherTransitionable) v).onLauncherTransitionStart(this, animated, toWorkspace);
}
// Update the workspace transition step as well
dispatchOnLauncherTransitionStep(v, 0f);
}
private void dispatchOnLauncherTransitionStep(View v, float t) {
if (v instanceof LauncherTransitionable) {
((LauncherTransitionable) v).onLauncherTransitionStep(this, t);
}
}
private void dispatchOnLauncherTransitionEnd(View v, boolean animated, boolean toWorkspace) {
if (v instanceof LauncherTransitionable) {
((LauncherTransitionable) v).onLauncherTransitionEnd(this, animated, toWorkspace);
}
// Update the workspace transition step as well
dispatchOnLauncherTransitionStep(v, 1f);
}
/**
* Things to test when changing the following seven functions.
* - Home from workspace
* - from center screen
* - from other screens
* - Home from all apps
* - from center screen
* - from other screens
* - Back from all apps
* - from center screen
* - from other screens
* - Launch app from workspace and quit
* - with back
* - with home
* - Launch app from all apps and quit
* - with back
* - with home
* - Go to a screen that's not the default, then all
* apps, and launch and app, and go back
* - with back
* -with home
* - On workspace, long press power and go back
* - with back
* - with home
* - On all apps, long press power and go back
* - with back
* - with home
* - On workspace, power off
* - On all apps, power off
* - Launch an app and turn off the screen while in that app
* - Go back with home key
* - Go back with back key TODO: make this not go to workspace
* - From all apps
* - From workspace
* - Enter and exit car mode (becuase it causes an extra configuration changed)
* - From all apps
* - From the center workspace
* - From another workspace
*/
/**
* Zoom the camera out from the workspace to reveal 'toView'.
* Assumes that the view to show is anchored at either the very top or very bottom
* of the screen.
*/
private void showAppsCustomizeHelper(final boolean animated, final boolean springLoaded) {
if (mStateAnimation != null) {
mStateAnimation.setDuration(0);
mStateAnimation.cancel();
mStateAnimation = null;
}
final Resources res = getResources();
final int duration = res.getInteger(R.integer.config_appsCustomizeZoomInTime);
final int fadeDuration = res.getInteger(R.integer.config_appsCustomizeFadeInTime);
final float scale = (float) res.getInteger(R.integer.config_appsCustomizeZoomScaleFactor);
final View fromView = mWorkspace;
final AppsCustomizeTabHost toView = mAppsCustomizeTabHost;
final int startDelay =
res.getInteger(R.integer.config_workspaceAppsCustomizeAnimationStagger);
setPivotsForZoom(toView, scale);
// Shrink workspaces away if going to AppsCustomize from workspace
Animator workspaceAnim =
mWorkspace.getChangeStateAnimation(Workspace.State.SMALL, animated);
if (animated) {
toView.setScaleX(scale);
toView.setScaleY(scale);
final LauncherViewPropertyAnimator scaleAnim = new LauncherViewPropertyAnimator(toView);
scaleAnim.
scaleX(1f).scaleY(1f).
setDuration(duration).
setInterpolator(new Workspace.ZoomOutInterpolator());
toView.setVisibility(View.VISIBLE);
toView.setAlpha(0f);
final ObjectAnimator alphaAnim = LauncherAnimUtils
.ofFloat(toView, "alpha", 0f, 1f)
.setDuration(fadeDuration);
alphaAnim.setInterpolator(new DecelerateInterpolator(1.5f));
alphaAnim.addUpdateListener(new AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
if (animation == null) {
throw new RuntimeException("animation is null");
}
float t = (Float) animation.getAnimatedValue();
dispatchOnLauncherTransitionStep(fromView, t);
dispatchOnLauncherTransitionStep(toView, t);
}
});
// toView should appear right at the end of the workspace shrink
// animation
mStateAnimation = LauncherAnimUtils.createAnimatorSet();
mStateAnimation.play(scaleAnim).after(startDelay);
mStateAnimation.play(alphaAnim).after(startDelay);
mStateAnimation.addListener(new AnimatorListenerAdapter() {
boolean animationCancelled = false;
@Override
public void onAnimationStart(Animator animation) {
updateWallpaperVisibility(true);
// Prepare the position
toView.setTranslationX(0.0f);
toView.setTranslationY(0.0f);
toView.setVisibility(View.VISIBLE);
toView.bringToFront();
}
@Override
public void onAnimationEnd(Animator animation) {
dispatchOnLauncherTransitionEnd(fromView, animated, false);
dispatchOnLauncherTransitionEnd(toView, animated, false);
if (mWorkspace != null
&& !springLoaded
&& !LauncherAppState.getInstance().isScreenLarge()) {
hideDockDivider();
}
if (!animationCancelled) {
updateWallpaperVisibility(false);
}
// Hide the search bar
if (mSearchDropTargetBar != null) {
mSearchDropTargetBar.hideSearchBar(false);
}
}
@Override
public void onAnimationCancel(Animator animation) {
animationCancelled = true;
}
});
if (workspaceAnim != null) {
mStateAnimation.play(workspaceAnim);
}
boolean delayAnim = false;
dispatchOnLauncherTransitionPrepare(fromView, animated, false);
dispatchOnLauncherTransitionPrepare(toView, animated, false);
// If any of the objects being animated haven't been measured/laid out
// yet, delay the animation until we get a layout pass
if ((((LauncherTransitionable) toView).getContent().getMeasuredWidth() == 0) ||
(mWorkspace.getMeasuredWidth() == 0) ||
(toView.getMeasuredWidth() == 0)) {
delayAnim = true;
}
final AnimatorSet stateAnimation = mStateAnimation;
final Runnable startAnimRunnable = new Runnable() {
public void run() {
// Check that mStateAnimation hasn't changed while
// we waited for a layout/draw pass
if (mStateAnimation != stateAnimation)
return;
setPivotsForZoom(toView, scale);
dispatchOnLauncherTransitionStart(fromView, animated, false);
dispatchOnLauncherTransitionStart(toView, animated, false);
LauncherAnimUtils.startAnimationAfterNextDraw(mStateAnimation, toView);
}
};
if (delayAnim) {
final ViewTreeObserver observer = toView.getViewTreeObserver();
observer.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
public void onGlobalLayout() {
startAnimRunnable.run();
toView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
});
} else {
startAnimRunnable.run();
}
} else {
toView.setTranslationX(0.0f);
toView.setTranslationY(0.0f);
toView.setScaleX(1.0f);
toView.setScaleY(1.0f);
toView.setVisibility(View.VISIBLE);
toView.bringToFront();
if (!springLoaded && !LauncherAppState.getInstance().isScreenLarge()) {
hideDockDivider();
// Hide the search bar
if (mSearchDropTargetBar != null) {
mSearchDropTargetBar.hideSearchBar(false);
}
}
dispatchOnLauncherTransitionPrepare(fromView, animated, false);
dispatchOnLauncherTransitionStart(fromView, animated, false);
dispatchOnLauncherTransitionEnd(fromView, animated, false);
dispatchOnLauncherTransitionPrepare(toView, animated, false);
dispatchOnLauncherTransitionStart(toView, animated, false);
dispatchOnLauncherTransitionEnd(toView, animated, false);
updateWallpaperVisibility(false);
}
}
/**
* Zoom the camera back into the workspace, hiding 'fromView'.
* This is the opposite of showAppsCustomizeHelper.
* @param animated If true, the transition will be animated.
*/
private void hideAppsCustomizeHelper(State toState, final boolean animated,
final boolean springLoaded, final Runnable onCompleteRunnable) {
if (mStateAnimation != null) {
mStateAnimation.setDuration(0);
mStateAnimation.cancel();
mStateAnimation = null;
}
Resources res = getResources();
final int duration = res.getInteger(R.integer.config_appsCustomizeZoomOutTime);
final int fadeOutDuration =
res.getInteger(R.integer.config_appsCustomizeFadeOutTime);
final float scaleFactor = (float)
res.getInteger(R.integer.config_appsCustomizeZoomScaleFactor);
final View fromView = mAppsCustomizeTabHost;
final View toView = mWorkspace;
Animator workspaceAnim = null;
if (toState == State.WORKSPACE) {
int stagger = res.getInteger(R.integer.config_appsCustomizeWorkspaceAnimationStagger);
workspaceAnim = mWorkspace.getChangeStateAnimation(
Workspace.State.NORMAL, animated, stagger);
} else if (toState == State.APPS_CUSTOMIZE_SPRING_LOADED) {
workspaceAnim = mWorkspace.getChangeStateAnimation(
Workspace.State.SPRING_LOADED, animated);
}
setPivotsForZoom(fromView, scaleFactor);
updateWallpaperVisibility(true);
showHotseat(animated);
if (animated) {
final LauncherViewPropertyAnimator scaleAnim =
new LauncherViewPropertyAnimator(fromView);
scaleAnim.
scaleX(scaleFactor).scaleY(scaleFactor).
setDuration(duration).
setInterpolator(new Workspace.ZoomInInterpolator());
final ObjectAnimator alphaAnim = LauncherAnimUtils
.ofFloat(fromView, "alpha", 1f, 0f)
.setDuration(fadeOutDuration);
alphaAnim.setInterpolator(new AccelerateDecelerateInterpolator());
alphaAnim.addUpdateListener(new AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
float t = 1f - (Float) animation.getAnimatedValue();
dispatchOnLauncherTransitionStep(fromView, t);
dispatchOnLauncherTransitionStep(toView, t);
}
});
mStateAnimation = LauncherAnimUtils.createAnimatorSet();
dispatchOnLauncherTransitionPrepare(fromView, animated, true);
dispatchOnLauncherTransitionPrepare(toView, animated, true);
mAppsCustomizeContent.pauseScrolling();
mStateAnimation.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
updateWallpaperVisibility(true);
fromView.setVisibility(View.GONE);
dispatchOnLauncherTransitionEnd(fromView, animated, true);
dispatchOnLauncherTransitionEnd(toView, animated, true);
if (onCompleteRunnable != null) {
onCompleteRunnable.run();
}
mAppsCustomizeContent.updateCurrentPageScroll();
mAppsCustomizeContent.resumeScrolling();
}
});
mStateAnimation.playTogether(scaleAnim, alphaAnim);
if (workspaceAnim != null) {
mStateAnimation.play(workspaceAnim);
}
dispatchOnLauncherTransitionStart(fromView, animated, true);
dispatchOnLauncherTransitionStart(toView, animated, true);
LauncherAnimUtils.startAnimationAfterNextDraw(mStateAnimation, toView);
} else {
fromView.setVisibility(View.GONE);
dispatchOnLauncherTransitionPrepare(fromView, animated, true);
dispatchOnLauncherTransitionStart(fromView, animated, true);
dispatchOnLauncherTransitionEnd(fromView, animated, true);
dispatchOnLauncherTransitionPrepare(toView, animated, true);
dispatchOnLauncherTransitionStart(toView, animated, true);
dispatchOnLauncherTransitionEnd(toView, animated, true);
}
}
@Override
public void onTrimMemory(int level) {
super.onTrimMemory(level);
if (level >= ComponentCallbacks2.TRIM_MEMORY_MODERATE) {
mAppsCustomizeTabHost.onTrimMemory();
}
}
@Override
public void onWindowFocusChanged(boolean hasFocus) {
if (!hasFocus) {
// When another window occludes launcher (like the notification shade, or recents),
// ensure that we enable the wallpaper flag so that transitions are done correctly.
updateWallpaperVisibility(true);
} else {
// When launcher has focus again, disable the wallpaper if we are in AllApps
mWorkspace.postDelayed(new Runnable() {
@Override
public void run() {
disableWallpaperIfInAllApps();
}
}, 500);
}
}
void showWorkspace(boolean animated) {
showWorkspace(animated, null);
}
void showWorkspace(boolean animated, Runnable onCompleteRunnable) {
if (mState != State.WORKSPACE) {
boolean wasInSpringLoadedMode = (mState == State.APPS_CUSTOMIZE_SPRING_LOADED);
mWorkspace.setVisibility(View.VISIBLE);
hideAppsCustomizeHelper(State.WORKSPACE, animated, false, onCompleteRunnable);
// Show the search bar (only animate if we were showing the drop target bar in spring
// loaded mode)
if (mSearchDropTargetBar != null) {
mSearchDropTargetBar.showSearchBar(wasInSpringLoadedMode);
}
// We only need to animate in the dock divider if we're going from spring loaded mode
showDockDivider(animated && wasInSpringLoadedMode);
// Set focus to the AppsCustomize button
if (mAllAppsButton != null) {
mAllAppsButton.requestFocus();
}
}
// Change the state *after* we've called all the transition code
mState = State.WORKSPACE;
// Resume the auto-advance of widgets
mUserPresent = true;
updateRunning();
// Send an accessibility event to announce the context change
getWindow().getDecorView()
.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
onWorkspaceShown(animated);
}
public void onWorkspaceShown(boolean animated) {
}
void showAllApps(boolean animated) {
if (mState != State.WORKSPACE) return;
showAppsCustomizeHelper(animated, false);
mAppsCustomizeTabHost.requestFocus();
// Change the state *after* we've called all the transition code
mState = State.APPS_CUSTOMIZE;
// Pause the auto-advance of widgets until we are out of AllApps
mUserPresent = false;
updateRunning();
closeFolder();
// Send an accessibility event to announce the context change
getWindow().getDecorView()
.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
}
void enterSpringLoadedDragMode() {
if (isAllAppsVisible()) {
hideAppsCustomizeHelper(State.APPS_CUSTOMIZE_SPRING_LOADED, true, true, null);
hideDockDivider();
mState = State.APPS_CUSTOMIZE_SPRING_LOADED;
}
}
void exitSpringLoadedDragModeDelayed(final boolean successfulDrop, boolean extendedDelay,
final Runnable onCompleteRunnable) {
if (mState != State.APPS_CUSTOMIZE_SPRING_LOADED) return;
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
if (successfulDrop) {
// Before we show workspace, hide all apps again because
// exitSpringLoadedDragMode made it visible. This is a bit hacky; we should
// clean up our state transition functions
mAppsCustomizeTabHost.setVisibility(View.GONE);
showWorkspace(true, onCompleteRunnable);
} else {
exitSpringLoadedDragMode();
}
}
}, (extendedDelay ?
EXIT_SPRINGLOADED_MODE_LONG_TIMEOUT :
EXIT_SPRINGLOADED_MODE_SHORT_TIMEOUT));
}
void exitSpringLoadedDragMode() {
if (mState == State.APPS_CUSTOMIZE_SPRING_LOADED) {
final boolean animated = true;
final boolean springLoaded = true;
showAppsCustomizeHelper(animated, springLoaded);
mState = State.APPS_CUSTOMIZE;
}
// Otherwise, we are not in spring loaded mode, so don't do anything.
}
void hideDockDivider() {
if (mQsbDivider != null) {
mQsbDivider.setVisibility(View.INVISIBLE);
}
}
void showDockDivider(boolean animated) {
if (mQsbDivider != null) {
mQsbDivider.setVisibility(View.VISIBLE);
if (mDividerAnimator != null) {
mDividerAnimator.cancel();
mQsbDivider.setAlpha(1f);
mDividerAnimator = null;
}
if (animated) {
mDividerAnimator = LauncherAnimUtils.createAnimatorSet();
mDividerAnimator.playTogether(LauncherAnimUtils.ofFloat(mQsbDivider, "alpha", 1f));
int duration = 0;
if (mSearchDropTargetBar != null) {
duration = mSearchDropTargetBar.getTransitionInDuration();
}
mDividerAnimator.setDuration(duration);
mDividerAnimator.start();
}
}
}
void lockAllApps() {
// TODO
}
void unlockAllApps() {
// TODO
}
/**
* Shows the hotseat area.
*/
void showHotseat(boolean animated) {
if (!LauncherAppState.getInstance().isScreenLarge()) {
if (animated) {
if (mHotseat.getAlpha() != 1f) {
int duration = 0;
if (mSearchDropTargetBar != null) {
duration = mSearchDropTargetBar.getTransitionInDuration();
}
mHotseat.animate().alpha(1f).setDuration(duration);
}
} else {
mHotseat.setAlpha(1f);
}
}
}
/**
* Hides the hotseat area.
*/
void hideHotseat(boolean animated) {
if (!LauncherAppState.getInstance().isScreenLarge()) {
if (animated) {
if (mHotseat.getAlpha() != 0f) {
int duration = 0;
if (mSearchDropTargetBar != null) {
duration = mSearchDropTargetBar.getTransitionOutDuration();
}
mHotseat.animate().alpha(0f).setDuration(duration);
}
} else {
mHotseat.setAlpha(0f);
}
}
}
/**
* Add an item from all apps or customize onto the given workspace screen.
* If layout is null, add to the current screen.
*/
void addExternalItemToScreen(ItemInfo itemInfo, final CellLayout layout) {
if (!mWorkspace.addExternalItemToScreen(itemInfo, layout)) {
showOutOfSpaceMessage(isHotseatLayout(layout));
}
}
/** Maps the current orientation to an index for referencing orientation correct global icons */
private int getCurrentOrientationIndexForGlobalIcons() {
// default - 0, landscape - 1
switch (getResources().getConfiguration().orientation) {
case Configuration.ORIENTATION_LANDSCAPE:
return 1;
default:
return 0;
}
}
private Drawable getExternalPackageToolbarIcon(ComponentName activityName, String resourceName) {
try {
PackageManager packageManager = getPackageManager();
// Look for the toolbar icon specified in the activity meta-data
Bundle metaData = packageManager.getActivityInfo(
activityName, PackageManager.GET_META_DATA).metaData;
if (metaData != null) {
int iconResId = metaData.getInt(resourceName);
if (iconResId != 0) {
Resources res = packageManager.getResourcesForActivity(activityName);
return res.getDrawable(iconResId);
}
}
} catch (NameNotFoundException e) {
// This can happen if the activity defines an invalid drawable
Log.w(TAG, "Failed to load toolbar icon; " + activityName.flattenToShortString() +
" not found", e);
} catch (Resources.NotFoundException nfe) {
// This can happen if the activity defines an invalid drawable
Log.w(TAG, "Failed to load toolbar icon from " + activityName.flattenToShortString(),
nfe);
}
return null;
}
// if successful in getting icon, return it; otherwise, set button to use default drawable
private Drawable.ConstantState updateTextButtonWithIconFromExternalActivity(
int buttonId, ComponentName activityName, int fallbackDrawableId,
String toolbarResourceName) {
Drawable toolbarIcon = getExternalPackageToolbarIcon(activityName, toolbarResourceName);
Resources r = getResources();
int w = r.getDimensionPixelSize(R.dimen.toolbar_external_icon_width);
int h = r.getDimensionPixelSize(R.dimen.toolbar_external_icon_height);
TextView button = (TextView) findViewById(buttonId);
// If we were unable to find the icon via the meta-data, use a generic one
if (toolbarIcon == null) {
toolbarIcon = r.getDrawable(fallbackDrawableId);
toolbarIcon.setBounds(0, 0, w, h);
if (button != null) {
button.setCompoundDrawables(toolbarIcon, null, null, null);
}
return null;
} else {
toolbarIcon.setBounds(0, 0, w, h);
if (button != null) {
button.setCompoundDrawables(toolbarIcon, null, null, null);
}
return toolbarIcon.getConstantState();
}
}
// if successful in getting icon, return it; otherwise, set button to use default drawable
private Drawable.ConstantState updateButtonWithIconFromExternalActivity(
int buttonId, ComponentName activityName, int fallbackDrawableId,
String toolbarResourceName) {
ImageView button = (ImageView) findViewById(buttonId);
Drawable toolbarIcon = getExternalPackageToolbarIcon(activityName, toolbarResourceName);
if (button != null) {
// If we were unable to find the icon via the meta-data, use a
// generic one
if (toolbarIcon == null) {
button.setImageResource(fallbackDrawableId);
} else {
button.setImageDrawable(toolbarIcon);
}
}
return toolbarIcon != null ? toolbarIcon.getConstantState() : null;
}
private void updateTextButtonWithDrawable(int buttonId, Drawable d) {
TextView button = (TextView) findViewById(buttonId);
button.setCompoundDrawables(d, null, null, null);
}
private void updateButtonWithDrawable(int buttonId, Drawable.ConstantState d) {
ImageView button = (ImageView) findViewById(buttonId);
button.setImageDrawable(d.newDrawable(getResources()));
}
private void invalidatePressedFocusedStates(View container, View button) {
if (container instanceof HolographicLinearLayout) {
HolographicLinearLayout layout = (HolographicLinearLayout) container;
layout.invalidatePressedFocusedStates();
} else if (button instanceof HolographicImageView) {
HolographicImageView view = (HolographicImageView) button;
view.invalidatePressedFocusedStates();
}
}
private boolean updateGlobalSearchIcon() {
final View searchButtonContainer = findViewById(R.id.search_button_container);
final ImageView searchButton = (ImageView) findViewById(R.id.search_button);
final View voiceButtonContainer = findViewById(R.id.voice_button_container);
final View voiceButton = findViewById(R.id.voice_button);
final SearchManager searchManager =
(SearchManager) getSystemService(Context.SEARCH_SERVICE);
ComponentName activityName = searchManager.getGlobalSearchActivity();
if (activityName != null) {
int coi = getCurrentOrientationIndexForGlobalIcons();
sGlobalSearchIcon[coi] = updateButtonWithIconFromExternalActivity(
R.id.search_button, activityName, R.drawable.ic_home_search_normal_holo,
TOOLBAR_SEARCH_ICON_METADATA_NAME);
if (sGlobalSearchIcon[coi] == null) {
sGlobalSearchIcon[coi] = updateButtonWithIconFromExternalActivity(
R.id.search_button, activityName, R.drawable.ic_home_search_normal_holo,
TOOLBAR_ICON_METADATA_NAME);
}
if (searchButtonContainer != null) searchButtonContainer.setVisibility(View.VISIBLE);
searchButton.setVisibility(View.VISIBLE);
invalidatePressedFocusedStates(searchButtonContainer, searchButton);
return true;
} else {
// We disable both search and voice search when there is no global search provider
if (searchButtonContainer != null) searchButtonContainer.setVisibility(View.GONE);
if (voiceButtonContainer != null) voiceButtonContainer.setVisibility(View.GONE);
searchButton.setVisibility(View.GONE);
voiceButton.setVisibility(View.GONE);
setVoiceButtonProxyVisible(false);
return false;
}
}
private void updateGlobalSearchIcon(Drawable.ConstantState d) {
final View searchButtonContainer = findViewById(R.id.search_button_container);
final View searchButton = (ImageView) findViewById(R.id.search_button);
updateButtonWithDrawable(R.id.search_button, d);
invalidatePressedFocusedStates(searchButtonContainer, searchButton);
}
private boolean updateVoiceSearchIcon(boolean searchVisible) {
final View voiceButtonContainer = findViewById(R.id.voice_button_container);
final View voiceButton = findViewById(R.id.voice_button);
// We only show/update the voice search icon if the search icon is enabled as well
final SearchManager searchManager =
(SearchManager) getSystemService(Context.SEARCH_SERVICE);
ComponentName globalSearchActivity = searchManager.getGlobalSearchActivity();
ComponentName activityName = null;
if (globalSearchActivity != null) {
// Check if the global search activity handles voice search
Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
intent.setPackage(globalSearchActivity.getPackageName());
activityName = intent.resolveActivity(getPackageManager());
}
if (activityName == null) {
// Fallback: check if an activity other than the global search activity
// resolves this
Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
activityName = intent.resolveActivity(getPackageManager());
}
if (searchVisible && activityName != null) {
int coi = getCurrentOrientationIndexForGlobalIcons();
sVoiceSearchIcon[coi] = updateButtonWithIconFromExternalActivity(
R.id.voice_button, activityName, R.drawable.ic_home_voice_search_holo,
TOOLBAR_VOICE_SEARCH_ICON_METADATA_NAME);
if (sVoiceSearchIcon[coi] == null) {
sVoiceSearchIcon[coi] = updateButtonWithIconFromExternalActivity(
R.id.voice_button, activityName, R.drawable.ic_home_voice_search_holo,
TOOLBAR_ICON_METADATA_NAME);
}
if (voiceButtonContainer != null) voiceButtonContainer.setVisibility(View.VISIBLE);
voiceButton.setVisibility(View.VISIBLE);
setVoiceButtonProxyVisible(true);
invalidatePressedFocusedStates(voiceButtonContainer, voiceButton);
return true;
} else {
if (voiceButtonContainer != null) voiceButtonContainer.setVisibility(View.GONE);
voiceButton.setVisibility(View.GONE);
setVoiceButtonProxyVisible(false);
return false;
}
}
private void updateVoiceSearchIcon(Drawable.ConstantState d) {
final View voiceButtonContainer = findViewById(R.id.voice_button_container);
final View voiceButton = findViewById(R.id.voice_button);
updateButtonWithDrawable(R.id.voice_button, d);
invalidatePressedFocusedStates(voiceButtonContainer, voiceButton);
}
public void setVoiceButtonProxyVisible(boolean visible) {
final View voiceButtonProxy = findViewById(R.id.voice_button_proxy);
if (voiceButtonProxy != null) {
voiceButtonProxy.setVisibility(visible ? View.VISIBLE : View.GONE);
}
}
/**
* Sets the app market icon
*/
private void updateAppMarketIcon() {
final View marketButton = findViewById(R.id.market_button);
Intent intent = new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_APP_MARKET);
// Find the app market activity by resolving an intent.
// (If multiple app markets are installed, it will return the ResolverActivity.)
ComponentName activityName = intent.resolveActivity(getPackageManager());
if (activityName != null) {
int coi = getCurrentOrientationIndexForGlobalIcons();
mAppMarketIntent = intent;
sAppMarketIcon[coi] = updateTextButtonWithIconFromExternalActivity(
R.id.market_button, activityName, R.drawable.ic_launcher_market_holo,
TOOLBAR_ICON_METADATA_NAME);
marketButton.setVisibility(View.VISIBLE);
} else {
// We should hide and disable the view so that we don't try and restore the visibility
// of it when we swap between drag & normal states from IconDropTarget subclasses.
marketButton.setVisibility(View.GONE);
marketButton.setEnabled(false);
}
}
private void updateAppMarketIcon(Drawable.ConstantState d) {
// Ensure that the new drawable we are creating has the approprate toolbar icon bounds
Resources r = getResources();
Drawable marketIconDrawable = d.newDrawable(r);
int w = r.getDimensionPixelSize(R.dimen.toolbar_external_icon_width);
int h = r.getDimensionPixelSize(R.dimen.toolbar_external_icon_height);
marketIconDrawable.setBounds(0, 0, w, h);
updateTextButtonWithDrawable(R.id.market_button, marketIconDrawable);
}
@Override
public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
final boolean result = super.dispatchPopulateAccessibilityEvent(event);
final List<CharSequence> text = event.getText();
text.clear();
// Populate event with a fake title based on the current state.
if (mState == State.APPS_CUSTOMIZE) {
text.add(getString(R.string.all_apps_button_label));
} else {
text.add(getString(R.string.all_apps_home_button_label));
}
return result;
}
/**
* Receives notifications when system dialogs are to be closed.
*/
private class CloseSystemDialogsIntentReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
closeSystemDialogs();
}
}
/**
* Receives notifications whenever the appwidgets are reset.
*/
private class AppWidgetResetObserver extends ContentObserver {
public AppWidgetResetObserver() {
super(new Handler());
}
@Override
public void onChange(boolean selfChange) {
onAppWidgetReset();
}
}
/**
* If the activity is currently paused, signal that we need to run the passed Runnable
* in onResume.
*
* This needs to be called from incoming places where resources might have been loaded
* while we are paused. That is becaues the Configuration might be wrong
* when we're not running, and if it comes back to what it was when we
* were paused, we are not restarted.
*
* Implementation of the method from LauncherModel.Callbacks.
*
* @return true if we are currently paused. The caller might be able to
* skip some work in that case since we will come back again.
*/
private boolean waitUntilResume(Runnable run, boolean deletePreviousRunnables) {
if (mPaused) {
Log.i(TAG, "Deferring update until onResume");
if (deletePreviousRunnables) {
while (mBindOnResumeCallbacks.remove(run)) {
}
}
mBindOnResumeCallbacks.add(run);
return true;
} else {
return false;
}
}
private boolean waitUntilResume(Runnable run) {
return waitUntilResume(run, false);
}
public void addOnResumeCallback(Runnable run) {
- mBindOnResumeCallbacks.add(run);
+ mOnResumeCallbacks.add(run);
}
public void removeOnResumeCallback(Runnable run) {
- mBindOnResumeCallbacks.remove(run);
+ mOnResumeCallbacks.remove(run);
}
/**
* If the activity is currently paused, signal that we need to re-run the loader
* in onResume.
*
* This needs to be called from incoming places where resources might have been loaded
* while we are paused. That is becaues the Configuration might be wrong
* when we're not running, and if it comes back to what it was when we
* were paused, we are not restarted.
*
* Implementation of the method from LauncherModel.Callbacks.
*
* @return true if we are currently paused. The caller might be able to
* skip some work in that case since we will come back again.
*/
public boolean setLoadOnResume() {
if (mPaused) {
Log.i(TAG, "setLoadOnResume");
mOnResumeNeedsLoad = true;
return true;
} else {
return false;
}
}
/**
* Implementation of the method from LauncherModel.Callbacks.
*/
public int getCurrentWorkspaceScreen() {
if (mWorkspace != null) {
return mWorkspace.getCurrentPage();
} else {
return SCREEN_COUNT / 2;
}
}
/**
* Refreshes the shortcuts shown on the workspace.
*
* Implementation of the method from LauncherModel.Callbacks.
*/
public void startBinding() {
// If we're starting binding all over again, clear any bind calls we'd postponed in
// the past (see waitUntilResume) -- we don't need them since we're starting binding
// from scratch again
mBindOnResumeCallbacks.clear();
final Workspace workspace = mWorkspace;
mNewShortcutAnimateScreenId = -1;
mNewShortcutAnimateViews.clear();
mWorkspace.clearDropTargets();
int count = workspace.getChildCount();
for (int i = 0; i < count; i++) {
// Use removeAllViewsInLayout() to avoid an extra requestLayout() and invalidate().
final CellLayout layoutParent = (CellLayout) workspace.getChildAt(i);
layoutParent.removeAllViewsInLayout();
}
mWidgetsToAdvance.clear();
if (mHotseat != null) {
mHotseat.resetLayout();
}
}
@Override
public void bindScreens(ArrayList<Long> orderedScreenIds) {
bindAddScreens(orderedScreenIds);
mWorkspace.addExtraEmptyScreen();
}
@Override
public void bindAddScreens(ArrayList<Long> orderedScreenIds) {
int count = orderedScreenIds.size();
for (int i = 0; i < count; i++) {
mWorkspace.insertNewWorkspaceScreenBeforeEmptyScreen(orderedScreenIds.get(i), false);
}
}
private boolean shouldShowWeightWatcher() {
String spKey = LauncherAppState.getSharedPreferencesKey();
SharedPreferences sp = getSharedPreferences(spKey, Context.MODE_PRIVATE);
boolean show = sp.getBoolean(SHOW_WEIGHT_WATCHER, true);
return show;
}
private void toggleShowWeightWatcher() {
String spKey = LauncherAppState.getSharedPreferencesKey();
SharedPreferences sp = getSharedPreferences(spKey, Context.MODE_PRIVATE);
boolean show = sp.getBoolean(SHOW_WEIGHT_WATCHER, true);
show = !show;
SharedPreferences.Editor editor = sp.edit();
editor.putBoolean(SHOW_WEIGHT_WATCHER, show);
editor.commit();
if (mWeightWatcher != null) {
mWeightWatcher.setVisibility(show ? View.VISIBLE : View.GONE);
}
}
/**
* Bind the items start-end from the list.
*
* Implementation of the method from LauncherModel.Callbacks.
*/
public void bindItems(final ArrayList<ItemInfo> shortcuts, final int start, final int end,
final boolean forceAnimateIcons) {
if (waitUntilResume(new Runnable() {
public void run() {
bindItems(shortcuts, start, end, forceAnimateIcons);
}
})) {
return;
}
// Get the list of added shortcuts and intersect them with the set of shortcuts here
Set<String> newApps = new HashSet<String>();
newApps = mSharedPrefs.getStringSet(InstallShortcutReceiver.NEW_APPS_LIST_KEY, newApps);
final AnimatorSet anim = LauncherAnimUtils.createAnimatorSet();
final Collection<Animator> bounceAnims = new ArrayList<Animator>();
Workspace workspace = mWorkspace;
for (int i = start; i < end; i++) {
final ItemInfo item = shortcuts.get(i);
// Short circuit if we are loading dock items for a configuration which has no dock
if (item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT &&
mHotseat == null) {
continue;
}
switch (item.itemType) {
case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
ShortcutInfo info = (ShortcutInfo) item;
String uri = info.intent.toUri(0).toString();
View shortcut = createShortcut(info);
/*
* TODO: FIX collision case
*/
if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
CellLayout cl = mWorkspace.getScreenWithId(item.screenId);
if (cl != null && cl.isOccupied(item.cellX, item.cellY)) {
throw new RuntimeException("OCCUPIED");
}
}
workspace.addInScreenFromBind(shortcut, item.container, item.screenId, item.cellX,
item.cellY, 1, 1);
boolean animateIconUp = false;
synchronized (newApps) {
if (newApps.contains(uri)) {
animateIconUp = newApps.remove(uri);
}
}
if (forceAnimateIcons) {
// Animate all the applications up now
shortcut.setAlpha(0f);
shortcut.setScaleX(0f);
shortcut.setScaleY(0f);
bounceAnims.add(createNewAppBounceAnimation(shortcut, i));
} else if (animateIconUp) {
// Prepare the view to be animated up
shortcut.setAlpha(0f);
shortcut.setScaleX(0f);
shortcut.setScaleY(0f);
mNewShortcutAnimateScreenId = item.screenId;
if (!mNewShortcutAnimateViews.contains(shortcut)) {
mNewShortcutAnimateViews.add(shortcut);
}
}
break;
case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
FolderIcon newFolder = FolderIcon.fromXml(R.layout.folder_icon, this,
(ViewGroup) workspace.getChildAt(workspace.getCurrentPage()),
(FolderInfo) item, mIconCache);
workspace.addInScreenFromBind(newFolder, item.container, item.screenId, item.cellX,
item.cellY, 1, 1);
break;
default:
throw new RuntimeException("Invalid Item Type");
}
}
if (forceAnimateIcons) {
// We post the animation slightly delayed to prevent slowdowns when we are loading
// right after we return to launcher.
mWorkspace.postDelayed(new Runnable() {
public void run() {
anim.playTogether(bounceAnims);
anim.start();
}
}, NEW_APPS_ANIMATION_DELAY);
}
workspace.requestLayout();
}
/**
* Implementation of the method from LauncherModel.Callbacks.
*/
public void bindFolders(final HashMap<Long, FolderInfo> folders) {
if (waitUntilResume(new Runnable() {
public void run() {
bindFolders(folders);
}
})) {
return;
}
sFolders.clear();
sFolders.putAll(folders);
}
/**
* Add the views for a widget to the workspace.
*
* Implementation of the method from LauncherModel.Callbacks.
*/
public void bindAppWidget(final LauncherAppWidgetInfo item) {
if (waitUntilResume(new Runnable() {
public void run() {
bindAppWidget(item);
}
})) {
return;
}
final long start = DEBUG_WIDGETS ? SystemClock.uptimeMillis() : 0;
if (DEBUG_WIDGETS) {
Log.d(TAG, "bindAppWidget: " + item);
}
final Workspace workspace = mWorkspace;
final int appWidgetId = item.appWidgetId;
final AppWidgetProviderInfo appWidgetInfo = mAppWidgetManager.getAppWidgetInfo(appWidgetId);
if (DEBUG_WIDGETS) {
Log.d(TAG, "bindAppWidget: id=" + item.appWidgetId + " belongs to component " + appWidgetInfo.provider);
}
item.hostView = mAppWidgetHost.createView(this, appWidgetId, appWidgetInfo);
item.hostView.setTag(item);
item.onBindAppWidget(this);
workspace.addInScreen(item.hostView, item.container, item.screenId, item.cellX,
item.cellY, item.spanX, item.spanY, false);
addWidgetToAutoAdvanceIfNeeded(item.hostView, appWidgetInfo);
workspace.requestLayout();
if (DEBUG_WIDGETS) {
Log.d(TAG, "bound widget id="+item.appWidgetId+" in "
+ (SystemClock.uptimeMillis()-start) + "ms");
}
}
public void onPageBoundSynchronously(int page) {
mSynchronouslyBoundPages.add(page);
}
/**
* Callback saying that there aren't any more items to bind.
*
* Implementation of the method from LauncherModel.Callbacks.
*/
public void finishBindingItems(final boolean upgradePath) {
if (waitUntilResume(new Runnable() {
public void run() {
finishBindingItems(upgradePath);
}
})) {
return;
}
if (mSavedState != null) {
if (!mWorkspace.hasFocus()) {
mWorkspace.getChildAt(mWorkspace.getCurrentPage()).requestFocus();
}
mSavedState = null;
}
// Create the custom content page here before onLayout to prevent flashing
if (!mWorkspace.hasCustomContent() && hasCustomContentToLeft()) {
mWorkspace.createCustomContentPage();
}
mWorkspace.restoreInstanceStateForRemainingPages();
// If we received the result of any pending adds while the loader was running (e.g. the
// widget configuration forced an orientation change), process them now.
for (int i = 0; i < sPendingAddList.size(); i++) {
completeAdd(sPendingAddList.get(i));
}
sPendingAddList.clear();
// Update the market app icon as necessary (the other icons will be managed in response to
// package changes in bindSearchablesChanged()
updateAppMarketIcon();
// Animate up any icons as necessary
if (mVisible || mWorkspaceLoading) {
Runnable newAppsRunnable = new Runnable() {
@Override
public void run() {
runNewAppsAnimation(false);
}
};
boolean willSnapPage = mNewShortcutAnimateScreenId > -1 &&
mNewShortcutAnimateScreenId != mWorkspace.getCurrentPage();
if (canRunNewAppsAnimation()) {
// If the user has not interacted recently, then either snap to the new page to show
// the new-apps animation or just run them if they are to appear on the current page
if (willSnapPage) {
mWorkspace.snapToScreenId(mNewShortcutAnimateScreenId, newAppsRunnable);
} else {
runNewAppsAnimation(false);
}
} else {
// If the user has interacted recently, then just add the items in place if they
// are on another page (or just normally if they are added to the current page)
runNewAppsAnimation(willSnapPage);
}
}
mWorkspaceLoading = false;
if (upgradePath) {
mWorkspace.stripDuplicateApps();
mIntentsOnWorkspaceFromUpgradePath = mWorkspace.stripDuplicateApps();
}
mWorkspace.post(new Runnable() {
@Override
public void run() {
onFinishBindingItems();
}
});
}
private boolean canRunNewAppsAnimation() {
long diff = System.currentTimeMillis() - mDragController.getLastGestureUpTime();
return diff > (NEW_APPS_ANIMATION_INACTIVE_TIMEOUT_SECONDS * 1000);
}
private ValueAnimator createNewAppBounceAnimation(View v, int i) {
ValueAnimator bounceAnim = LauncherAnimUtils.ofPropertyValuesHolder(v,
PropertyValuesHolder.ofFloat("alpha", 1f),
PropertyValuesHolder.ofFloat("scaleX", 1f),
PropertyValuesHolder.ofFloat("scaleY", 1f));
bounceAnim.setDuration(InstallShortcutReceiver.NEW_SHORTCUT_BOUNCE_DURATION);
bounceAnim.setStartDelay(i * InstallShortcutReceiver.NEW_SHORTCUT_STAGGER_DELAY);
bounceAnim.setInterpolator(new SmoothPagedView.OvershootInterpolator());
return bounceAnim;
}
/**
* Runs a new animation that scales up icons that were added while Launcher was in the
* background.
*
* @param immediate whether to run the animation or show the results immediately
*/
private void runNewAppsAnimation(boolean immediate) {
AnimatorSet anim = LauncherAnimUtils.createAnimatorSet();
Collection<Animator> bounceAnims = new ArrayList<Animator>();
// Order these new views spatially so that they animate in order
Collections.sort(mNewShortcutAnimateViews, new Comparator<View>() {
@Override
public int compare(View a, View b) {
CellLayout.LayoutParams alp = (CellLayout.LayoutParams) a.getLayoutParams();
CellLayout.LayoutParams blp = (CellLayout.LayoutParams) b.getLayoutParams();
int cellCountX = LauncherModel.getCellCountX();
return (alp.cellY * cellCountX + alp.cellX) - (blp.cellY * cellCountX + blp.cellX);
}
});
// Animate each of the views in place (or show them immediately if requested)
if (immediate) {
for (View v : mNewShortcutAnimateViews) {
v.setAlpha(1f);
v.setScaleX(1f);
v.setScaleY(1f);
}
} else {
for (int i = 0; i < mNewShortcutAnimateViews.size(); ++i) {
View v = mNewShortcutAnimateViews.get(i);
bounceAnims.add(createNewAppBounceAnimation(v, i));
}
anim.playTogether(bounceAnims);
anim.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
if (mWorkspace != null) {
mWorkspace.postDelayed(mBuildLayersRunnable, 500);
}
}
});
anim.start();
}
// Clean up
mNewShortcutAnimateScreenId = -1;
mNewShortcutAnimateViews.clear();
new Thread("clearNewAppsThread") {
public void run() {
mSharedPrefs.edit()
.putInt(InstallShortcutReceiver.NEW_APPS_PAGE_KEY, -1)
.putStringSet(InstallShortcutReceiver.NEW_APPS_LIST_KEY, null)
.commit();
}
}.start();
}
@Override
public void bindSearchablesChanged() {
boolean searchVisible = updateGlobalSearchIcon();
boolean voiceVisible = updateVoiceSearchIcon(searchVisible);
if (mSearchDropTargetBar != null) {
mSearchDropTargetBar.onSearchPackagesChanged(searchVisible, voiceVisible);
}
}
/**
* Add the icons for all apps.
*
* Implementation of the method from LauncherModel.Callbacks.
*/
public void bindAllApplications(final ArrayList<ApplicationInfo> apps) {
if (mIntentsOnWorkspaceFromUpgradePath != null) {
getHotseat().addAllAppsFolder(mIconCache, apps,
mIntentsOnWorkspaceFromUpgradePath, Launcher.this, mWorkspace);
mIntentsOnWorkspaceFromUpgradePath = null;
}
}
/**
* A package was updated.
*
* Implementation of the method from LauncherModel.Callbacks.
*/
public void bindAppsUpdated(final ArrayList<ApplicationInfo> apps) {
if (waitUntilResume(new Runnable() {
public void run() {
bindAppsUpdated(apps);
}
})) {
return;
}
if (mWorkspace != null) {
mWorkspace.updateShortcuts(apps);
}
}
/**
* A package was uninstalled. We take both the super set of packageNames
* in addition to specific applications to remove, the reason being that
* this can be called when a package is updated as well. In that scenario,
* we only remove specific components from the workspace, where as
* package-removal should clear all items by package name.
*
* Implementation of the method from LauncherModel.Callbacks.
*/
public void bindComponentsRemoved(final ArrayList<String> packageNames,
final ArrayList<ApplicationInfo> appInfos,
final boolean packageRemoved) {
if (waitUntilResume(new Runnable() {
public void run() {
bindComponentsRemoved(packageNames, appInfos, packageRemoved);
}
})) {
return;
}
if (packageRemoved) {
mWorkspace.removeItemsByPackageName(packageNames);
} else {
mWorkspace.removeItemsByApplicationInfo(appInfos);
}
// Notify the drag controller
mDragController.onAppsRemoved(appInfos, this);
}
/**
* A number of packages were updated.
*/
private ArrayList<Object> mWidgetsAndShortcuts;
private Runnable mBindPackagesUpdatedRunnable = new Runnable() {
public void run() {
bindPackagesUpdated(mWidgetsAndShortcuts);
mWidgetsAndShortcuts = null;
}
};
public void bindPackagesUpdated(final ArrayList<Object> widgetsAndShortcuts) {
if (waitUntilResume(mBindPackagesUpdatedRunnable, true)) {
mWidgetsAndShortcuts = widgetsAndShortcuts;
return;
}
// Update the widgets pane
if (mAppsCustomizeContent != null) {
mAppsCustomizeContent.onPackagesUpdated(widgetsAndShortcuts);
}
}
private int mapConfigurationOriActivityInfoOri(int configOri) {
final Display d = getWindowManager().getDefaultDisplay();
int naturalOri = Configuration.ORIENTATION_LANDSCAPE;
switch (d.getRotation()) {
case Surface.ROTATION_0:
case Surface.ROTATION_180:
// We are currently in the same basic orientation as the natural orientation
naturalOri = configOri;
break;
case Surface.ROTATION_90:
case Surface.ROTATION_270:
// We are currently in the other basic orientation to the natural orientation
naturalOri = (configOri == Configuration.ORIENTATION_LANDSCAPE) ?
Configuration.ORIENTATION_PORTRAIT : Configuration.ORIENTATION_LANDSCAPE;
break;
}
int[] oriMap = {
ActivityInfo.SCREEN_ORIENTATION_PORTRAIT,
ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE,
ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT,
ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE
};
// Since the map starts at portrait, we need to offset if this device's natural orientation
// is landscape.
int indexOffset = 0;
if (naturalOri == Configuration.ORIENTATION_LANDSCAPE) {
indexOffset = 1;
}
return oriMap[(d.getRotation() + indexOffset) % 4];
}
public boolean isRotationEnabled() {
boolean enableRotation = sForceEnableRotation ||
getResources().getBoolean(R.bool.allow_rotation);
return enableRotation;
}
public void lockScreenOrientation() {
if (isRotationEnabled()) {
setRequestedOrientation(mapConfigurationOriActivityInfoOri(getResources()
.getConfiguration().orientation));
}
}
public void unlockScreenOrientation(boolean immediate) {
if (isRotationEnabled()) {
if (immediate) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
} else {
mHandler.postDelayed(new Runnable() {
public void run() {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
}
}, mRestoreScreenOrientationDelay);
}
}
}
/* Cling related */
private boolean isClingsEnabled() {
if (DISABLE_CLINGS) {
return false;
}
// disable clings when running in a test harness
if(ActivityManager.isRunningInTestHarness()) return false;
// Restricted secondary users (child mode) will potentially have very few apps
// seeded when they start up for the first time. Clings won't work well with that
// boolean supportsLimitedUsers =
// android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR2;
// Account[] accounts = AccountManager.get(this).getAccounts();
// if (supportsLimitedUsers && accounts.length == 0) {
// UserManager um = (UserManager) getSystemService(Context.USER_SERVICE);
// Bundle restrictions = um.getUserRestrictions();
// if (restrictions.getBoolean(UserManager.DISALLOW_MODIFY_ACCOUNTS, false)) {
// return false;
// }
// }
return true;
}
private Cling initCling(int clingId, int[] positionData, boolean animate, int delay) {
final Cling cling = (Cling) findViewById(clingId);
if (cling != null) {
cling.init(this, positionData);
cling.setVisibility(View.VISIBLE);
cling.setLayerType(View.LAYER_TYPE_HARDWARE, null);
if (animate) {
cling.buildLayer();
cling.setAlpha(0f);
cling.animate()
.alpha(1f)
.setInterpolator(new AccelerateInterpolator())
.setDuration(SHOW_CLING_DURATION)
.setStartDelay(delay)
.start();
} else {
cling.setAlpha(1f);
}
cling.setFocusableInTouchMode(true);
cling.post(new Runnable() {
public void run() {
cling.setFocusable(true);
cling.requestFocus();
}
});
mHideFromAccessibilityHelper.setImportantForAccessibilityToNo(
mDragLayer, clingId == R.id.all_apps_cling);
}
return cling;
}
private void dismissCling(final Cling cling, final String flag, int duration) {
// To catch cases where siblings of top-level views are made invisible, just check whether
// the cling is directly set to GONE before dismissing it.
if (cling != null && cling.getVisibility() != View.GONE) {
ObjectAnimator anim = LauncherAnimUtils.ofFloat(cling, "alpha", 0f);
anim.setDuration(duration);
anim.addListener(new AnimatorListenerAdapter() {
public void onAnimationEnd(Animator animation) {
cling.setVisibility(View.GONE);
cling.cleanup();
// We should update the shared preferences on a background thread
new Thread("dismissClingThread") {
public void run() {
SharedPreferences.Editor editor = mSharedPrefs.edit();
editor.putBoolean(flag, true);
editor.commit();
}
}.start();
};
});
anim.start();
mHideFromAccessibilityHelper.restoreImportantForAccessibility(mDragLayer);
}
}
private void removeCling(int id) {
final View cling = findViewById(id);
if (cling != null) {
final ViewGroup parent = (ViewGroup) cling.getParent();
parent.post(new Runnable() {
@Override
public void run() {
parent.removeView(cling);
}
});
mHideFromAccessibilityHelper.restoreImportantForAccessibility(mDragLayer);
}
}
private boolean skipCustomClingIfNoAccounts() {
Cling cling = (Cling) findViewById(R.id.workspace_cling);
boolean customCling = cling.getDrawIdentifier().equals("workspace_custom");
if (customCling) {
AccountManager am = AccountManager.get(this);
if (am == null) return false;
Account[] accounts = am.getAccountsByType("com.google");
return accounts.length == 0;
}
return false;
}
public void showFirstRunWorkspaceCling() {
// Enable the clings only if they have not been dismissed before
if (isClingsEnabled() &&
!mSharedPrefs.getBoolean(Cling.WORKSPACE_CLING_DISMISSED_KEY, false) &&
!skipCustomClingIfNoAccounts() ) {
// If we're not using the default workspace layout, replace workspace cling
// with a custom workspace cling (usually specified in an overlay)
// For now, only do this on tablets
if (mSharedPrefs.getInt(LauncherProvider.DEFAULT_WORKSPACE_RESOURCE_ID, 0) != 0 &&
getResources().getBoolean(R.bool.config_useCustomClings)) {
// Use a custom cling
View cling = findViewById(R.id.workspace_cling);
ViewGroup clingParent = (ViewGroup) cling.getParent();
int clingIndex = clingParent.indexOfChild(cling);
clingParent.removeViewAt(clingIndex);
View customCling = mInflater.inflate(R.layout.custom_workspace_cling, clingParent, false);
clingParent.addView(customCling, clingIndex);
customCling.setId(R.id.workspace_cling);
}
initCling(R.id.workspace_cling, null, false, 0);
} else {
removeCling(R.id.workspace_cling);
}
}
public void showFirstRunAllAppsCling(int[] position) {
// Enable the clings only if they have not been dismissed before
if (isClingsEnabled() &&
!mSharedPrefs.getBoolean(Cling.ALLAPPS_CLING_DISMISSED_KEY, false)) {
initCling(R.id.all_apps_cling, position, true, 0);
} else {
removeCling(R.id.all_apps_cling);
}
}
public Cling showFirstRunFoldersCling() {
// Enable the clings only if they have not been dismissed before
if (isClingsEnabled() &&
!mSharedPrefs.getBoolean(Cling.FOLDER_CLING_DISMISSED_KEY, false)) {
return initCling(R.id.folder_cling, null, true, 0);
} else {
removeCling(R.id.folder_cling);
return null;
}
}
public boolean isFolderClingVisible() {
Cling cling = (Cling) findViewById(R.id.folder_cling);
if (cling != null) {
return cling.getVisibility() == View.VISIBLE;
}
return false;
}
public void dismissWorkspaceCling(View v) {
Cling cling = (Cling) findViewById(R.id.workspace_cling);
dismissCling(cling, Cling.WORKSPACE_CLING_DISMISSED_KEY, DISMISS_CLING_DURATION);
}
public void dismissAllAppsCling(View v) {
Cling cling = (Cling) findViewById(R.id.all_apps_cling);
dismissCling(cling, Cling.ALLAPPS_CLING_DISMISSED_KEY, DISMISS_CLING_DURATION);
}
public void dismissFolderCling(View v) {
Cling cling = (Cling) findViewById(R.id.folder_cling);
dismissCling(cling, Cling.FOLDER_CLING_DISMISSED_KEY, DISMISS_CLING_DURATION);
}
/**
* Prints out out state for debugging.
*/
public void dumpState() {
Log.d(TAG, "BEGIN launcher3 dump state for launcher " + this);
Log.d(TAG, "mSavedState=" + mSavedState);
Log.d(TAG, "mWorkspaceLoading=" + mWorkspaceLoading);
Log.d(TAG, "mRestoring=" + mRestoring);
Log.d(TAG, "mWaitingForResult=" + mWaitingForResult);
Log.d(TAG, "mSavedInstanceState=" + mSavedInstanceState);
Log.d(TAG, "sFolders.size=" + sFolders.size());
mModel.dumpState();
if (mAppsCustomizeContent != null) {
mAppsCustomizeContent.dumpState();
}
Log.d(TAG, "END launcher3 dump state");
}
@Override
public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
super.dump(prefix, fd, writer, args);
writer.println(" ");
writer.println("Debug logs: ");
for (int i = 0; i < sDumpLogs.size(); i++) {
writer.println(" " + sDumpLogs.get(i));
}
}
public static void dumpDebugLogsToConsole() {
Log.d(TAG, "");
Log.d(TAG, "*********************");
Log.d(TAG, "Launcher debug logs: ");
for (int i = 0; i < sDumpLogs.size(); i++) {
Log.d(TAG, " " + sDumpLogs.get(i));
}
Log.d(TAG, "*********************");
Log.d(TAG, "");
}
}
interface LauncherTransitionable {
View getContent();
void onLauncherTransitionPrepare(Launcher l, boolean animated, boolean toWorkspace);
void onLauncherTransitionStart(Launcher l, boolean animated, boolean toWorkspace);
void onLauncherTransitionStep(Launcher l, float t);
void onLauncherTransitionEnd(Launcher l, boolean animated, boolean toWorkspace);
}
| false | false | null | null |
diff --git a/src/main/java/ch/bfh/bti7081/s2013/blue/service/PrescriptionService.java b/src/main/java/ch/bfh/bti7081/s2013/blue/service/PrescriptionService.java
index 3f7aed0..392f979 100644
--- a/src/main/java/ch/bfh/bti7081/s2013/blue/service/PrescriptionService.java
+++ b/src/main/java/ch/bfh/bti7081/s2013/blue/service/PrescriptionService.java
@@ -1,65 +1,70 @@
package ch.bfh.bti7081.s2013.blue.service;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import ch.bfh.bti7081.s2013.blue.entities.Patient;
import ch.bfh.bti7081.s2013.blue.entities.PrescriptionItem;
public class PrescriptionService {
private static PrescriptionService prescriptionService = null;
private PrescriptionService() {
}
public static PrescriptionService getInstance() {
if (prescriptionService == null) {
prescriptionService = new PrescriptionService();
}
return prescriptionService;
}
/*
* returns a list with DailyPrescirptions of the next 7 days
*/
public List<DailyPrescription> getDailyPrescriptions(Patient patient) {
EntityManager em = PatientService.getInstance().getEntityManager();
TypedQuery<PrescriptionItem> query = em.createQuery("SELECT item FROM PrescriptionItem item " +
"WHERE item.prescription.patient=:patient", PrescriptionItem.class);
query.setParameter("patient", patient);
List<PrescriptionItem> items = query.getResultList();
List<DailyPrescription> dailyPrescriptions = new ArrayList<DailyPrescription>();
Calendar calendar = Calendar.getInstance();
for (int i = 0; i < 7; i++) {
DailyPrescription dailyPrescription = new DailyPrescription();
dailyPrescription.setDate(calendar.getTime());
calendar.add(Calendar.DAY_OF_MONTH, 1);
// TODO: check start and end date
for (PrescriptionItem item : items) {
if (item.getMorning() > 0) {
dailyPrescription.getMorningDrugs().put(item.getMedicalDrug(), item.getMorning());
}
if (item.getNoon() > 0) {
dailyPrescription.getNoonDrugs().put(item.getMedicalDrug(), item.getNoon());
}
if (item.getEvening() > 0) {
dailyPrescription.getEveningDrugs().put(item.getMedicalDrug(), item.getEvening());
}
if (item.getNight() > 0) {
dailyPrescription.getNightDrugs().put(item.getMedicalDrug(), item.getNight());
}
}
dailyPrescriptions.add(dailyPrescription);
}
return dailyPrescriptions;
}
+
+ public List<PrescriptionItem> getPrescriptions(Patient patient) {
+ // TODO gassm9: implemented
+ return new ArrayList<PrescriptionItem>();
+ }
}
diff --git a/src/main/java/ch/bfh/bti7081/s2013/blue/ui/ReportCreateView.java b/src/main/java/ch/bfh/bti7081/s2013/blue/ui/ReportCreateView.java
index f898b96..b6c97de 100644
--- a/src/main/java/ch/bfh/bti7081/s2013/blue/ui/ReportCreateView.java
+++ b/src/main/java/ch/bfh/bti7081/s2013/blue/ui/ReportCreateView.java
@@ -1,88 +1,88 @@
package ch.bfh.bti7081.s2013.blue.ui;
import java.util.List;
import ch.bfh.bti7081.s2013.blue.entities.Patient;
import ch.bfh.bti7081.s2013.blue.entities.PrescriptionItem;
import ch.bfh.bti7081.s2013.blue.entities.Report;
import ch.bfh.bti7081.s2013.blue.service.PatientService;
import ch.bfh.bti7081.s2013.blue.service.PrescriptionService;
import ch.bfh.bti7081.s2013.blue.service.ReportService;
import com.vaadin.navigator.View;
import com.vaadin.navigator.ViewChangeListener.ViewChangeEvent;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.ComboBox;
import com.vaadin.ui.FormLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.RichTextArea;
-import com.vaadin.ui.Select;
import com.vaadin.ui.VerticalLayout;
+@SuppressWarnings("serial")
public class ReportCreateView extends VerticalLayout implements View, IBackButtonView {
private FormLayout formLayout;
private Label firstNameLabel;
private Label lastNameLabel;
private ComboBox comboboxDrug;
private RichTextArea rtReport;
private Long id;
public ReportCreateView() {
setSizeFull();
formLayout = new FormLayout();
firstNameLabel = new Label();
lastNameLabel = new Label();
- comboboxDrug = new Select();
+ comboboxDrug = new ComboBox();
rtReport = new RichTextArea();
firstNameLabel.setCaption("Vorname:");
lastNameLabel.setCaption("Nachname:");
rtReport.setCaption("Report: ");
comboboxDrug.setCaption("Medikament: ");
formLayout.addComponent(firstNameLabel);
formLayout.addComponent(lastNameLabel);
formLayout.addComponent(comboboxDrug);
formLayout.addComponent(rtReport);
addComponent(formLayout);
Button scanButton = new Button("Report speichern", new Button.ClickListener() {
@Override
public void buttonClick(ClickEvent event) {
//save report
Report report = new Report();
//report.setUser(user);
report.setText(rtReport.getValue());
report.setPrescriptionItem((PrescriptionItem) comboboxDrug.getValue());
ReportService.getInstance().createContainer().addEntity(report);
}
});
addComponent(scanButton);
}
@Override
public void enter(ViewChangeEvent event) {
this.id = Long.parseLong(event.getParameters());
Patient patient = PatientService.getInstance().createContainer().getItem(id).getEntity();
firstNameLabel.setValue(patient.getFirstName());
lastNameLabel.setValue(patient.getLastName());
List<PrescriptionItem> prescriptionItems = PrescriptionService.getInstance().getPrescriptions(patient);
for (PrescriptionItem prescriptionItem : prescriptionItems) {
comboboxDrug.addItem(prescriptionItem);
comboboxDrug.setItemCaption(prescriptionItem, prescriptionItem.getMedicalDrug().getName());
}
}
@Override
public String getBackView() {
return NavigatorUI.PATIENT_DETAIL_VIEW + "/" + this.id;
}
}
| false | false | null | null |
diff --git a/intro/assignment_5/Point.java b/intro/assignment_5/Point.java
index 1345f96..95fb137 100644
--- a/intro/assignment_5/Point.java
+++ b/intro/assignment_5/Point.java
@@ -1,76 +1,88 @@
/**
* Represents a 2D point coordinate.
*
* @author Ory Band
* @version 1.0
*/
public class Point {
/** X,Y coordinates. */
private double x,y;
/**
* @param x X coordinate.
* @param y Y coordinate.
*
* @return new initialized Point object.
*/
public Point(double x, double y) {
this.x = x;
this.y = y;
}
/**
* @param p Point object to deep copy.
*
* @return new initialized Point object.
*/
public Point(Point p) {
+ if (p == null) {
+ throw new RuntimeException("Point argument is null.");
+ }
+
this.x = p.getX();
this.y = p.getY();
}
/** @return Point's X coordinate. */
public double getX() {
return this.x;
}
/** @return Point's Y coordinate. */
public double getY() {
return this.y;
}
/**
* @param x X coordinate to add to Point's X coordinate.
* @param y Y coordinate to add to Point's Y coordinate.
*/
public void move(double x, double y) {
this.x += x;
this.y += y;
}
/**
* @param p Another Point object to add its coordinate's to the Point object in hand.
*/
public void move(Point p) {
+ if (p == null) {
+ throw new RuntimeException("Point argument is null.");
+ }
+
this.x += p.getX();
this.y += p.getY();
}
- /** @return True if object is of type Point, and if coordinates are equal to the Point object in hand. */
+ /** @return true if object is of type Point, and if coordinates are equal to the Point object in hand. */
public boolean equals(Object o) {
return o instanceof Point &&
this.x == ((Point) o).getX() &&
this.y == ((Point) o).getY();
}
/**
* @param p Point object to calculate distnace against.
*
* @return distance between points.
*/
public double distance(Point p) {
+ if (p == null) {
+ throw new RuntimeException("Point argument is null.");
+ }
+
return Math.sqrt(
Math.pow(p.getX() - this.x, 2) +
Math.pow(p.getY() - this.y, 2) );
}
}
diff --git a/intro/assignment_5/Polygon.java b/intro/assignment_5/Polygon.java
index 823f444..abdc6b0 100644
--- a/intro/assignment_5/Polygon.java
+++ b/intro/assignment_5/Polygon.java
@@ -1,89 +1,88 @@
/**
* Represents a generic polygon shape.
*
* @author Ory Band
* @version 1.0
*/
public abstract class Polygon implements Shape {
protected Point[] points;
/**
* @param p Coordinate list.
*
* @return a new initialized Polygon object.
*/
public Polygon(Point[] ps) {
// Validity tests.
if (ps == null) {
throw new RuntimeException("Point argument is null.");
} else if (ps.length < 3) {
throw new RuntimeException("Not enough points for Polygon (Minimum 3) - Point[] is too short.");
}
this.points = new Point[ps.length];
for (int i=0; i<ps.length; i++) {
if (ps[i] == null) {
throw new RuntimeException("Point[" + i + "] is null.");
} else {
this.points[i] = new Point(ps[i]);
}
}
}
/** @return amount of Polygon's coordinates. */
public int getNumOfPoints() {
return this.points.length;
}
/** @return sides' list. */
public double[] getSides() {
int l = this.points.length;
double[] sides = new double[l];
// Iterate over points and calculate sides.
for (int i=0; i<l; i++) {
if (i == l-1) {
// If we reached the last coord, calculate side against first point.
- sides[i] = this.points[i].distance(this.point[0]);
+ sides[i] = this.points[i].distance(this.points[0]);
} else {
- sides[i] = this.points[i].distance(this.point[i+1]);
+ sides[i] = this.points[i].distance(this.points[i+1]);
}
}
return sides;
}
/** @return Coordinate list. */
public Point[] getPoints() {
return this.points;
}
public double getPerimeter() {
- // Get sides length;
double[] sides = this.getSides();
// Sum sides.
double perimeter = 0.0;
for (int i=0; i<sides.length; i++) {
perimeter += sides[i];
}
return perimeter;
}
public void move(Point p) {
// Validity test.
if (p == null) {
throw new RuntimeException("Point argument is null.");
}
// Shift coordinates according to Point object, given as argument.
for (int i=0; i<this.points.length; i++) {
this.points[i].move(p.getX(), p.getY());
}
}
public double getArea();
public boolean contains(Point p);
}
| false | false | null | null |
diff --git a/src/main/java/net/stuxcrystal/configuration/annotations/Value.java b/src/main/java/net/stuxcrystal/configuration/annotations/Value.java
index 77256df..5912a76 100644
--- a/src/main/java/net/stuxcrystal/configuration/annotations/Value.java
+++ b/src/main/java/net/stuxcrystal/configuration/annotations/Value.java
@@ -1,40 +1,40 @@
/*
* Copyright 2013 StuxCrystal
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package net.stuxcrystal.configuration.annotations;
import java.lang.annotation.*;
/**
* Marks a value.<p />
- * If used on a class this will be the header of the entire file.
+ * Please note that this annotation can also be used on methods of Interfaces.
*
* @author StuxCrystal
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
-@Target({ElementType.FIELD, ElementType.TYPE})
+@Target({ElementType.FIELD, ElementType.METHOD})
public @interface Value {
/**
* The name of the value.<p />
* If not given, it uses the name of the field.
*/
public String name() default "";
/**
* The comment that is written above the value.
*/
public String[] comment() default {};
}
diff --git a/src/main/java/net/stuxcrystal/configuration/generators/yaml/YamlGenerator.java b/src/main/java/net/stuxcrystal/configuration/generators/yaml/YamlGenerator.java
index e9d49b5..39b5780 100644
--- a/src/main/java/net/stuxcrystal/configuration/generators/yaml/YamlGenerator.java
+++ b/src/main/java/net/stuxcrystal/configuration/generators/yaml/YamlGenerator.java
@@ -1,119 +1,128 @@
/*
* Copyright 2013 StuxCrystal
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package net.stuxcrystal.configuration.generators.yaml;
import net.stuxcrystal.configuration.ConfigurationLoader;
import net.stuxcrystal.configuration.NodeTreeGenerator;
import net.stuxcrystal.configuration.node.DataNode;
import net.stuxcrystal.configuration.node.MapNode;
import net.stuxcrystal.configuration.node.Node;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.Constructor;
+import org.yaml.snakeyaml.error.YAMLException;
import org.yaml.snakeyaml.representer.Representer;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
public class YamlGenerator implements NodeTreeGenerator {
private Yaml parser;
public YamlGenerator() {
DumperOptions options = new DumperOptions();
options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
options.setDefaultScalarStyle(DumperOptions.ScalarStyle.PLAIN);
parser = new Yaml(new Constructor(), new Representer(), options, new StringOnlyResolver());
}
public String getName() {
return "yaml";
}
@Override
public boolean isValidFile(File file) throws IOException {
return file.getName().endsWith(".yml") || file.getName().endsWith(".yaml");
}
@Override
public Node<?> parseFile(File file, ConfigurationLoader cparser) throws IOException {
- return parseNode(parser.load(new FileInputStream(file)));
+ try {
+ return parseNode(parser.load(new FileInputStream(file)));
+ } catch (YAMLException e) {
+ throw new IOException(e);
+ }
}
@Override
public Node<?> parse(InputStream stream, ConfigurationLoader cparser) throws IOException {
- return parseNode(parser.load(stream));
+ try {
+ return parseNode(parser.load(stream));
+ } catch (YAMLException e) {
+ throw new IOException(e);
+ }
}
@SuppressWarnings("unchecked")
private Node<?> parseNode(Object value) {
Node<?> n;
if (value instanceof Map) {
n = parseMap((Map<String, Object>) value);
} else if (value instanceof List) {
n = parseList((List<Object>) value);
} else {
n = new DataNode((String) value);
}
return n;
}
private Node<?> parseMap(Map<String, Object> data) {
MapNode node = new MapNode();
ArrayList<Node<?>> nodes = new ArrayList<>();
for (Entry<String, Object> entry : data.entrySet()) {
Node<?> n = parseNode(entry.getValue());
n.setName(entry.getKey());
n.setParent(node);
nodes.add(n);
}
node.setData(nodes.toArray(new Node<?>[nodes.size()]));
return node;
}
private Node<?> parseList(List<Object> data) {
MapNode node = new MapNode();
ArrayList<Node<?>> nodes = new ArrayList<>();
for (Object o : data) {
Node<?> n = parseNode(o);
n.setParent(node);
nodes.add(n);
}
node.setData(nodes.toArray(new Node<?>[nodes.size()]));
return node;
}
@Override
public void dumpFile(File file, Node<?> node, ConfigurationLoader parser) throws IOException {
dump(new FileWriter(file), node, parser);
}
@Override
public void dump(OutputStream stream, Node<?> node, ConfigurationLoader parser) throws IOException {
dump(new OutputStreamWriter(stream), node, parser);
}
private void dump(Writer writer, Node<?> node, ConfigurationLoader parser) throws IOException {
CommentAwareDumper dumper = new CommentAwareDumper(parser);
dumper.dump(writer, node);
writer.close();
}
}
| false | false | null | null |
diff --git a/src/main/java/uk/org/cowgill/james/jircd/ConfigBlock.java b/src/main/java/uk/org/cowgill/james/jircd/ConfigBlock.java
index a51e6d4..a12ddab 100644
--- a/src/main/java/uk/org/cowgill/james/jircd/ConfigBlock.java
+++ b/src/main/java/uk/org/cowgill/james/jircd/ConfigBlock.java
@@ -1,533 +1,531 @@
/*
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;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
import java.util.Collections;
import uk.org.cowgill.james.jircd.util.MultiHashMap;
import uk.org.cowgill.james.jircd.util.MultiMap;
import uk.org.cowgill.james.jircd.util.PushbackLineInputStream;
/**
* Represents a generic block in a configuration file
*
* Blocks have 0 or 1 parameter object and can contain
* any number of sub-blocks each with a referencing name
*
* @author James
*/
public class ConfigBlock
{
/**
* The blocks parameter
*/
public final String param;
/**
* The child blocks of this block
*/
public final MultiMap<String, ConfigBlock> subBlocks;
/**
* Creates a new config block
*
* Block parameters are converted to empty strings if null is passed
*
* @param param Parameter for block
* @param subBlocks The subblocks multimap for the block
*/
public ConfigBlock(String param, MultiMap<String, ConfigBlock> subBlocks)
{
if(param == null)
{
this.param = "";
}
else
{
this.param = param;
}
if(subBlocks == null)
{
subBlocks = new MultiHashMap<String, ConfigBlock>();
}
this.subBlocks = subBlocks;
}
/**
* Returns the block parameter as an integer
*
* @return The integer value
* @throws NumberFormatException If the parameter cannot be converted to an integer
*/
public int getParamAsInt() throws NumberFormatException
{
return Integer.parseInt(param);
}
/**
* Gets the parameter of the given sub block
*
* @param key The key of the sub-block
* @return The parameter or null if not found
*/
public String getSubBlockParamOptional(String key)
{
//Get collection
Collection<ConfigBlock> blocks = subBlocks.get(key);
if(blocks != null && blocks.size() == 1)
{
//Get block
ConfigBlock block = blocks.iterator().next();
//Return if param is not empty
if(block.param.length() > 0)
{
return block.param;
}
}
//Not found
return null;
}
/**
* Gets the parameter of the given sub block - requiring the block exists once
*
* @param key The key of the sub-block
* @return The parameter
* @throws ConfigException If the block does not exist exactly once or has no parameter
*/
public String getSubBlockParam(String key) throws ConfigException
{
String retVal = getSubBlockParamOptional(key);
if(retVal == null)
{
throw new ConfigException("Directive " + key + " must exist exactly once and have a parameter");
}
else
{
return retVal;
}
}
/**
* Gets the given sub-block but forces it to an empty block instead of null
*
* @param key key to lookup
* @return the non-null collection
*/
public Collection<ConfigBlock> getSubBlockNonNull(String key)
{
//Get sub block
Collection<ConfigBlock> block = subBlocks.get(key);
if(block == null)
{
return Collections.emptyList();
}
else
{
return block;
}
}
//-----------------------------------------------------
/**
* Skips any whitespace characters in the given stream
*
* This also handles single line comments at the start of lines
*/
private static void skipWhitespace(PushbackLineInputStream data) throws IOException
{
int c;
do
{
c = data.read();
}
while(Character.isWhitespace(c));
data.unread(c);
}
/**
* Called after a / has been read. Checks for c-style comments and skips them
*
* Returns true if a comment was skipped. False if no comment was found; data will be unchanged.
*/
private static boolean checkAndSkipComment(PushbackLineInputStream data) throws IOException, ConfigException
{
int c = data.read();
switch(c)
{
case -1:
//EOF
throw new ConfigException("Unexpected end of file", data);
case '/':
//Skip single line comment
skipComment(data);
return true;
case '*':
//Skip multi-line comment
for(;;)
{
switch(data.read())
{
case -1:
//EOF
throw new ConfigException("Unexpected end of file", data);
case '*':
//Could be beginning of end of comment
c = data.read();
if(c == '/')
{
//Yes
skipWhitespace(data);
return true;
}
else
{
//No, continue comment
data.unread(c);
break;
}
}
}
default:
//No comment
data.unread(c);
return false;
}
}
/**
* Skips a single line comment which has already begun
*/
private static void skipComment(PushbackLineInputStream data) throws IOException
{
int c;
for(;;)
{
c = data.read();
switch(c)
{
case -1:
case 10:
- case 13:
//End of comment
- data.unread(c);
skipWhitespace(data);
return;
}
}
}
/**
* Parses a directive parameter and returns it
*
* Will return on - ; { } EOF
*/
private static String parseParameter(PushbackLineInputStream data) throws IOException, ConfigException
{
//Terms can be separated with whitespace
// terms are concated with one space replacing any whitespace
StringBuilder outString = new StringBuilder();
int c;
boolean runLoop;
boolean lastWhite;
for(;;)
{
lastWhite = false;
c = data.read();
//Check whitespace
if(Character.isWhitespace(c))
{
//Insert space and skip other spaces
lastWhite = true;
outString.append(' ');
skipWhitespace(data);
c = data.read();
}
//Check special characters
switch(c)
{
case -1:
case '}':
case ';':
case '{':
//Termination characters
data.unread(c);
//Remove single whitespace at end
if(lastWhite)
{
outString.setLength(outString.length() - 1);
}
return outString.toString();
case '"':
//Begin quotes - handle specially
for(runLoop = true; runLoop;)
{
c = data.read();
switch(c)
{
case -1:
//EOF
throw new ConfigException("Unexpected end of file", data);
case '"':
//End of string
runLoop = false;
break;
default:
outString.append((char) c);
break;
}
}
break;
case '#':
//Skip single line comment
skipComment(data);
break;
case '/':
//Could be start of comment
if(checkAndSkipComment(data))
{
break;
}
//Or not, put back and fallthrough to write /
default:
//Copy verbatim to output
outString.append((char) c);
break;
}
}
}
/**
* Parses a list of directives and puts them in a multi-map
*
* If topLevel is true, will throw on }. Otherwise will throw on EOF
*
* Ends only on EOF or end brace
*/
private static MultiMap<String, ConfigBlock> parseDirectives(PushbackLineInputStream data, boolean topLevel)
throws ConfigException, IOException
{
//Loop until an EOF or } is found
MultiMap<String, ConfigBlock> map = new MultiHashMap<String, ConfigBlock>();
while(parseDirective(data, map))
;
//Check final char
switch(data.read())
{
case -1:
//EOF
if(!topLevel)
{
throw new ConfigException("Unexpected end of file", data);
}
break;
case '}':
//Closing brace
if(topLevel)
{
throw new ConfigException("Unexpected }", data);
}
break;
}
return map;
}
/**
* Parses a single directive from the config file
*
* Returns true if the map was updated
* false on EOF or end brace (use data.read to find out)
*/
private static boolean parseDirective(PushbackLineInputStream data,
MultiMap<String, ConfigBlock> map) throws ConfigException, IOException
{
int c;
boolean runLoop = true;
//Check for characters at the start
do
{
skipWhitespace(data);
//Check valid things at the start
c = data.read();
switch(c)
{
case -1:
case '}':
//EOF / end brace
data.unread(c);
return false;
case ';':
//Empty directive, ignore
break;
case '{':
//Empty block, parse sub directives and merge with map
map.putAll(parseDirectives(data, false));
//Expect end brace
skipWhitespace(data);
if(data.read() == -1)
{
throw new ConfigException("Unexpected end of file", data);
}
return true;
case '#':
//Single line comment
skipComment(data);
break;
case '/':
//Could be multi-line comment
if(checkAndSkipComment(data))
{
break;
}
else
{
//Not a comment. Put back and fallthough
data.unread('/');
}
default:
//No special characters
runLoop = false;
break;
}
}
while(runLoop);
data.unread(c);
//Loop around reading directive name
StringBuilder dName = new StringBuilder();
String param = null;
for(;;)
{
c = data.read();
//Check whitespace
if(Character.isWhitespace(c))
{
//End of directive name, parse parameter
skipWhitespace(data);
param = parseParameter(data);
//What data caused the end of the parameter
c = data.read();
// c = character after param and will be a special character
}
//Handle special chars
switch(c)
{
case -1:
//End of file???
throw new ConfigException("Unexpected end of file", data);
case ';':
//End of directive - name only
map.putValue(dName.toString(), new ConfigBlock(param, null));
return true;
case '{':
//Start subblock
map.putValue(dName.toString(), new ConfigBlock(param, parseDirectives(data, false)));
return true;
case '}':
//End of block???
throw new ConfigException("Unexpected }", data);
case '#':
//Single line comment
skipComment(data);
break;
case '/':
//Could be multi-line comment
if(checkAndSkipComment(data))
{
break;
}
//Or else fallthrough to write character
default:
//Add to name
dName.append((char) c);
break;
}
}
}
/**
* Parses the given string data into a heirachy of ConfigBlocks
*
* @param data The data stream to parse into blocks
* @return The config block
* @throws IOException Thrown when an IO error occurs in the input stream
* @throws ConfigException Thrown when an error occurs in parsing the config file
*/
public static ConfigBlock parse(InputStream data) throws IOException, ConfigException
{
return new ConfigBlock(null, parseDirectives(new PushbackLineInputStream(data), true));
}
}
diff --git a/src/main/java/uk/org/cowgill/james/jircd/util/PushbackLineInputStream.java b/src/main/java/uk/org/cowgill/james/jircd/util/PushbackLineInputStream.java
index 641426b..7230dab 100644
--- a/src/main/java/uk/org/cowgill/james/jircd/util/PushbackLineInputStream.java
+++ b/src/main/java/uk/org/cowgill/james/jircd/util/PushbackLineInputStream.java
@@ -1,168 +1,170 @@
/*
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.util;
import java.io.IOException;
import java.io.InputStream;
import java.io.PushbackInputStream;
public class PushbackLineInputStream extends PushbackInputStream
{
private int lineNo;
private int charNo;
/**
* Creates a new PushbackLineInputStream reading from the specified stream
*
* @param in stream which bytes will be read from
*/
public PushbackLineInputStream(InputStream in)
{
- super(in);
+ super(in, 2);
}
/**
* Creates a new PushbackLineInputStream reading from the specified stream with the specified pushback buffer size
*
* @param in stream which bytes will be read from
* @param size size of pushback buffer
*
* @throws IllegalArgumentException if size is <= 0
*/
public PushbackLineInputStream(InputStream in, int size)
{
super(in, size);
}
@Override
public int read() throws IOException
{
//Read character + determine if it's a newline
int c = super.read();
switch(c)
{
case 13:
- //Newline unless followed by a 10
+ //Check for windows style new lines before returning
c = super.read();
- if(c == 10)
+ if(c != 10)
{
- //Don't increase character number
+ //Undo this read and force current character to 10
super.unread(c);
- return c;
+ c = 10;
}
+ //Fallthrough to new line handler
+
case 10:
//Newline
lineNo++;
charNo = 1;
return c;
case -1:
//EOF
return c;
}
//Normal character
charNo++;
return c;
}
@Override
public long skip(long n) throws IOException
{
long skipped = 0;
while(skipped < n)
{
if(this.read() == -1)
{
break;
}
skipped++;
}
return skipped;
}
@Override
public void unread(int b) throws IOException
{
//Only pushback if not EOF
if(b != -1)
{
super.unread(b);
if(charNo == 1)
{
//Go up 1 row. Using 0 as character since we don't know!
lineNo--;
charNo = 0;
}
else
{
charNo--;
}
}
}
/**
* Returns the line number the stream is currently at
*/
public int getLineNo()
{
return lineNo;
}
/**
* Returns the character number the stream is currently at
*/
public int getCharNo()
{
return charNo;
}
/**
* This method is not implemented and throws UnsupportedOperationException
*/
@Override
public int read(byte[] b, int off, int len)
{
//Error - not allowed for this stream
throw new UnsupportedOperationException();
}
/**
* This method is not implemented and throws UnsupportedOperationException
*/
@Override
public void unread(byte[] b)
{
//Error - not allowed for this stream
throw new UnsupportedOperationException();
}
/**
* This method is not implemented and throws UnsupportedOperationException
*/
@Override
public void unread(byte[] b, int off, int len)
{
//Error - not allowed for this stream
throw new UnsupportedOperationException();
}
}
| false | false | null | null |
diff --git a/me.gladwell.eclipse.m2e.android/src/main/java/me/gladwell/eclipse/m2e/android/configuration/MavenAndroidClasspathConfigurer.java b/me.gladwell.eclipse.m2e.android/src/main/java/me/gladwell/eclipse/m2e/android/configuration/MavenAndroidClasspathConfigurer.java
index 04e6e6a..de2583a 100644
--- a/me.gladwell.eclipse.m2e.android/src/main/java/me/gladwell/eclipse/m2e/android/configuration/MavenAndroidClasspathConfigurer.java
+++ b/me.gladwell.eclipse.m2e.android/src/main/java/me/gladwell/eclipse/m2e/android/configuration/MavenAndroidClasspathConfigurer.java
@@ -1,70 +1,80 @@
/*******************************************************************************
* Copyright (c) 2012 Ricardo Gladwell
* 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
*******************************************************************************/
package me.gladwell.eclipse.m2e.android.configuration;
+import java.io.File;
import java.util.List;
import me.gladwell.eclipse.m2e.android.project.AndroidProject;
-import org.eclipse.core.runtime.IPath;
+import org.eclipse.core.resources.IFolder;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.NullProgressMonitor;
+import org.eclipse.core.runtime.Path;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.launching.JavaRuntime;
import org.eclipse.m2e.jdt.IClasspathDescriptor;
import org.eclipse.m2e.jdt.IClasspathDescriptor.EntryFilter;
import org.eclipse.m2e.jdt.IClasspathEntryDescriptor;
import org.eclipse.m2e.jdt.IClasspathManager;
-public class MavenAndroidClasspathConfigurer implements AndroidClasspathConfigurer {
+import com.android.sdklib.SdkConstants;
- private static final String ANDROID_GEN_PATH = "gen";
- private static final String ANDROID_CLASSES_FOLDER = "bin/classes";
+public class MavenAndroidClasspathConfigurer implements AndroidClasspathConfigurer {
public void addGenFolder(IJavaProject javaProject, AndroidProject project, IClasspathDescriptor classpath) {
- IPath gen = javaProject.getPath().append(ANDROID_GEN_PATH);
- if (!classpath.containsPath(gen)) {
- IPath classesOutput = javaProject.getPath().append(ANDROID_CLASSES_FOLDER);
- classpath.addSourceEntry(gen, classesOutput, true);
+ IFolder gen = javaProject.getProject().getFolder(SdkConstants.FD_GEN_SOURCES + File.separator);
+ if (!gen.exists()) {
+ try {
+ gen.create(true, true, new NullProgressMonitor());
+ } catch (CoreException e) {
+ throw new ProjectConfigurationException(e);
+ }
+ }
+
+ if (!classpath.containsPath(new Path(SdkConstants.FD_GEN_SOURCES))) {
+ classpath.addSourceEntry(gen.getFullPath(), null, false);
}
}
public void removeNonRuntimeDependencies(AndroidProject project, IClasspathDescriptor classpath) {
final List<String> providedDependencies = project.getProvidedDependencies();
classpath.removeEntry(new EntryFilter() {
public boolean accept(IClasspathEntryDescriptor descriptor) {
return providedDependencies.contains(descriptor.getPath().toOSString());
}
});
}
public void removeJreClasspathContainer(IClasspathDescriptor classpath) {
for(IClasspathEntry entry : classpath.getEntries()) {
if(entry.getEntryKind() == IClasspathEntry.CPE_CONTAINER) {
if(entry.getPath().toOSString().contains(JavaRuntime.JRE_CONTAINER)) {
classpath.removeEntry(entry.getPath());
}
}
}
}
public void markMavenContainerExported(IClasspathDescriptor classpath) {
for(IClasspathEntry entry : classpath.getEntries()) {
if(entry.getEntryKind() == IClasspathEntry.CPE_CONTAINER) {
if(entry.getPath().toOSString().equals(IClasspathManager.CONTAINER_ID)) {
IClasspathEntry newEntry = JavaCore.newContainerEntry(entry.getPath(), true);
classpath.removeEntry(entry.getPath());
classpath.addEntry(newEntry);
}
}
}
}
}
| false | false | null | null |
diff --git a/src/com/android/camera/FocusOverlayManager.java b/src/com/android/camera/FocusOverlayManager.java
index 24d47d6a..48eafa7d 100644
--- a/src/com/android/camera/FocusOverlayManager.java
+++ b/src/com/android/camera/FocusOverlayManager.java
@@ -1,542 +1,542 @@
/*
* Copyright (C) 2012 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.camera;
import android.annotation.TargetApi;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.graphics.RectF;
import android.hardware.Camera.Area;
import android.hardware.Camera.Parameters;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import com.android.camera.ui.FaceView;
import com.android.camera.ui.FocusIndicator;
import com.android.camera.ui.PieRenderer;
import com.android.gallery3d.common.ApiHelper;
import java.util.ArrayList;
import java.util.List;
/* A class that handles everything about focus in still picture mode.
* This also handles the metering area because it is the same as focus area.
*
* The test cases:
* (1) The camera has continuous autofocus. Move the camera. Take a picture when
* CAF is not in progress.
* (2) The camera has continuous autofocus. Move the camera. Take a picture when
* CAF is in progress.
* (3) The camera has face detection. Point the camera at some faces. Hold the
* shutter. Release to take a picture.
* (4) The camera has face detection. Point the camera at some faces. Single tap
* the shutter to take a picture.
* (5) The camera has autofocus. Single tap the shutter to take a picture.
* (6) The camera has autofocus. Hold the shutter. Release to take a picture.
* (7) The camera has no autofocus. Single tap the shutter and take a picture.
* (8) The camera has autofocus and supports focus area. Touch the screen to
* trigger autofocus. Take a picture.
* (9) The camera has autofocus and supports focus area. Touch the screen to
* trigger autofocus. Wait until it times out.
* (10) The camera has no autofocus and supports metering area. Touch the screen
* to change metering area.
*/
public class FocusOverlayManager {
private static final String TAG = "CAM_FocusManager";
private static final int RESET_TOUCH_FOCUS = 0;
private static final int RESET_TOUCH_FOCUS_DELAY = 3000;
private int mState = STATE_IDLE;
private static final int STATE_IDLE = 0; // Focus is not active.
private static final int STATE_FOCUSING = 1; // Focus is in progress.
// Focus is in progress and the camera should take a picture after focus finishes.
private static final int STATE_FOCUSING_SNAP_ON_FINISH = 2;
private static final int STATE_SUCCESS = 3; // Focus finishes and succeeds.
private static final int STATE_FAIL = 4; // Focus finishes and fails.
private boolean mInitialized;
private boolean mFocusAreaSupported;
private boolean mMeteringAreaSupported;
private boolean mLockAeAwbNeeded;
private boolean mAeAwbLock;
private Matrix mMatrix;
private PieRenderer mPieRenderer;
private int mPreviewWidth; // The width of the preview frame layout.
private int mPreviewHeight; // The height of the preview frame layout.
private boolean mMirror; // true if the camera is front-facing.
private int mDisplayOrientation;
private FaceView mFaceView;
private List<Object> mFocusArea; // focus area in driver format
private List<Object> mMeteringArea; // metering area in driver format
private String mFocusMode;
private String[] mDefaultFocusModes;
private String mOverrideFocusMode;
private Parameters mParameters;
private ComboPreferences mPreferences;
private Handler mHandler;
Listener mListener;
public interface Listener {
public void autoFocus();
public void cancelAutoFocus();
public boolean capture();
public void startFaceDetection();
public void stopFaceDetection();
public void setFocusParameters();
}
private class MainHandler extends Handler {
public MainHandler(Looper looper) {
super(looper);
}
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case RESET_TOUCH_FOCUS: {
cancelAutoFocus();
mListener.startFaceDetection();
break;
}
}
}
}
public FocusOverlayManager(ComboPreferences preferences, String[] defaultFocusModes,
Parameters parameters, Listener listener,
boolean mirror, Looper looper) {
mHandler = new MainHandler(looper);
mMatrix = new Matrix();
mPreferences = preferences;
mDefaultFocusModes = defaultFocusModes;
setParameters(parameters);
mListener = listener;
setMirror(mirror);
}
public void setFocusRenderer(PieRenderer renderer) {
mPieRenderer = renderer;
mInitialized = (mMatrix != null);
}
public void setParameters(Parameters parameters) {
mParameters = parameters;
mFocusAreaSupported = Util.isFocusAreaSupported(parameters);
mMeteringAreaSupported = Util.isMeteringAreaSupported(parameters);
mLockAeAwbNeeded = (Util.isAutoExposureLockSupported(mParameters) ||
Util.isAutoWhiteBalanceLockSupported(mParameters));
}
public void setPreviewSize(int previewWidth, int previewHeight) {
if (mPreviewWidth != previewWidth || mPreviewHeight != previewHeight) {
mPreviewWidth = previewWidth;
mPreviewHeight = previewHeight;
setMatrix();
}
}
public void setMirror(boolean mirror) {
mMirror = mirror;
setMatrix();
}
public void setDisplayOrientation(int displayOrientation) {
mDisplayOrientation = displayOrientation;
setMatrix();
}
public void setFaceView(FaceView faceView) {
mFaceView = faceView;
}
private void setMatrix() {
if (mPreviewWidth != 0 && mPreviewHeight != 0) {
Matrix matrix = new Matrix();
Util.prepareMatrix(matrix, mMirror, mDisplayOrientation,
mPreviewWidth, mPreviewHeight);
// In face detection, the matrix converts the driver coordinates to UI
// coordinates. In tap focus, the inverted matrix converts the UI
// coordinates to driver coordinates.
matrix.invert(mMatrix);
mInitialized = (mPieRenderer != null);
}
}
public void onShutterDown() {
if (!mInitialized) return;
// Lock AE and AWB so users can half-press shutter and recompose.
if (mLockAeAwbNeeded && !mAeAwbLock) {
mAeAwbLock = true;
mListener.setFocusParameters();
}
if (needAutoFocusCall()) {
// Do not focus if touch focus has been triggered.
if (mState != STATE_SUCCESS && mState != STATE_FAIL) {
autoFocus();
}
}
}
public void onShutterUp() {
if (!mInitialized) return;
if (needAutoFocusCall()) {
// User releases half-pressed focus key.
if (mState == STATE_FOCUSING || mState == STATE_SUCCESS
|| mState == STATE_FAIL) {
cancelAutoFocus();
}
}
// Unlock AE and AWB after cancelAutoFocus. Camera API does not
// guarantee setParameters can be called during autofocus.
if (mLockAeAwbNeeded && mAeAwbLock && (mState != STATE_FOCUSING_SNAP_ON_FINISH)) {
mAeAwbLock = false;
mListener.setFocusParameters();
}
}
public void doSnap() {
if (!mInitialized) return;
// If the user has half-pressed the shutter and focus is completed, we
// can take the photo right away. If the focus mode is infinity, we can
// also take the photo.
if (!needAutoFocusCall() || (mState == STATE_SUCCESS || mState == STATE_FAIL)) {
capture();
} else if (mState == STATE_FOCUSING) {
// Half pressing the shutter (i.e. the focus button event) will
// already have requested AF for us, so just request capture on
// focus here.
mState = STATE_FOCUSING_SNAP_ON_FINISH;
} else if (mState == STATE_IDLE) {
// We didn't do focus. This can happen if the user press focus key
// while the snapshot is still in progress. The user probably wants
// the next snapshot as soon as possible, so we just do a snapshot
// without focusing again.
capture();
}
}
public void onAutoFocus(boolean focused) {
if (mState == STATE_FOCUSING_SNAP_ON_FINISH) {
// Take the picture no matter focus succeeds or fails. No need
// to play the AF sound if we're about to play the shutter
// sound.
if (focused) {
mState = STATE_SUCCESS;
} else {
mState = STATE_FAIL;
}
updateFocusUI();
capture();
} else if (mState == STATE_FOCUSING) {
// This happens when (1) user is half-pressing the focus key or
// (2) touch focus is triggered. Play the focus tone. Do not
// take the picture now.
if (focused) {
mState = STATE_SUCCESS;
} else {
mState = STATE_FAIL;
}
updateFocusUI();
// If this is triggered by touch focus, cancel focus after a
// while.
if (mFocusArea != null) {
mHandler.sendEmptyMessageDelayed(RESET_TOUCH_FOCUS, RESET_TOUCH_FOCUS_DELAY);
}
} else if (mState == STATE_IDLE) {
// User has released the focus key before focus completes.
// Do nothing.
}
}
public void onAutoFocusMoving(boolean moving) {
if (!mInitialized) return;
// Ignore if the camera has detected some faces.
if (mFaceView != null && mFaceView.faceExists()) {
mPieRenderer.clear();
return;
}
// Ignore if we have requested autofocus. This method only handles
// continuous autofocus.
if (mState != STATE_IDLE) return;
if (moving) {
mPieRenderer.showStart();
} else {
mPieRenderer.showSuccess(true);
}
}
@TargetApi(ApiHelper.VERSION_CODES.ICE_CREAM_SANDWICH)
private void initializeFocusAreas(int focusWidth, int focusHeight,
int x, int y, int previewWidth, int previewHeight) {
if (mFocusArea == null) {
mFocusArea = new ArrayList<Object>();
mFocusArea.add(new Area(new Rect(), 1));
}
// Convert the coordinates to driver format.
calculateTapArea(focusWidth, focusHeight, 1f, x, y, previewWidth, previewHeight,
((Area) mFocusArea.get(0)).rect);
}
@TargetApi(ApiHelper.VERSION_CODES.ICE_CREAM_SANDWICH)
private void initializeMeteringAreas(int focusWidth, int focusHeight,
int x, int y, int previewWidth, int previewHeight) {
if (mMeteringArea == null) {
mMeteringArea = new ArrayList<Object>();
mMeteringArea.add(new Area(new Rect(), 1));
}
// Convert the coordinates to driver format.
// AE area is bigger because exposure is sensitive and
// easy to over- or underexposure if area is too small.
calculateTapArea(focusWidth, focusHeight, 1.5f, x, y, previewWidth, previewHeight,
((Area) mMeteringArea.get(0)).rect);
}
public void onSingleTapUp(int x, int y) {
if (!mInitialized || mState == STATE_FOCUSING_SNAP_ON_FINISH) return;
// Let users be able to cancel previous touch focus.
if ((mFocusArea != null) && (mState == STATE_FOCUSING ||
mState == STATE_SUCCESS || mState == STATE_FAIL)) {
cancelAutoFocus();
}
// Initialize variables.
int focusWidth = mPieRenderer.getSize();
int focusHeight = mPieRenderer.getSize();
if (focusWidth == 0 || mPieRenderer.getWidth() == 0
|| mPieRenderer.getHeight() == 0) return;
int previewWidth = mPreviewWidth;
int previewHeight = mPreviewHeight;
// Initialize mFocusArea.
if (mFocusAreaSupported) {
initializeFocusAreas(
focusWidth, focusHeight, x, y, previewWidth, previewHeight);
}
// Initialize mMeteringArea.
if (mMeteringAreaSupported) {
initializeMeteringAreas(
focusWidth, focusHeight, x, y, previewWidth, previewHeight);
}
// Use margin to set the focus indicator to the touched area.
mPieRenderer.setFocus(x, y, false);
// Stop face detection because we want to specify focus and metering area.
mListener.stopFaceDetection();
// Set the focus area and metering area.
mListener.setFocusParameters();
if (mFocusAreaSupported) {
autoFocus();
} else { // Just show the indicator in all other cases.
updateFocusUI();
// Reset the metering area in 3 seconds.
mHandler.removeMessages(RESET_TOUCH_FOCUS);
mHandler.sendEmptyMessageDelayed(RESET_TOUCH_FOCUS, RESET_TOUCH_FOCUS_DELAY);
}
}
public void onPreviewStarted() {
mState = STATE_IDLE;
}
public void onPreviewStopped() {
+ // If auto focus was in progress, it would have been stopped.
mState = STATE_IDLE;
resetTouchFocus();
- // If auto focus was in progress, it would have been canceled.
updateFocusUI();
}
public void onCameraReleased() {
onPreviewStopped();
}
private void autoFocus() {
Log.v(TAG, "Start autofocus.");
mListener.autoFocus();
mState = STATE_FOCUSING;
// Pause the face view because the driver will keep sending face
// callbacks after the focus completes.
if (mFaceView != null) mFaceView.pause();
updateFocusUI();
mHandler.removeMessages(RESET_TOUCH_FOCUS);
}
private void cancelAutoFocus() {
Log.v(TAG, "Cancel autofocus.");
// Reset the tap area before calling mListener.cancelAutofocus.
// Otherwise, focus mode stays at auto and the tap area passed to the
// driver is not reset.
resetTouchFocus();
mListener.cancelAutoFocus();
if (mFaceView != null) mFaceView.resume();
mState = STATE_IDLE;
updateFocusUI();
mHandler.removeMessages(RESET_TOUCH_FOCUS);
}
private void capture() {
if (mListener.capture()) {
mState = STATE_IDLE;
mHandler.removeMessages(RESET_TOUCH_FOCUS);
}
}
public String getFocusMode() {
if (mOverrideFocusMode != null) return mOverrideFocusMode;
List<String> supportedFocusModes = mParameters.getSupportedFocusModes();
if (mFocusAreaSupported && mFocusArea != null) {
// Always use autofocus in tap-to-focus.
mFocusMode = Parameters.FOCUS_MODE_AUTO;
} else {
// The default is continuous autofocus.
mFocusMode = mPreferences.getString(
CameraSettings.KEY_FOCUS_MODE, null);
// Try to find a supported focus mode from the default list.
if (mFocusMode == null) {
for (int i = 0; i < mDefaultFocusModes.length; i++) {
String mode = mDefaultFocusModes[i];
if (Util.isSupported(mode, supportedFocusModes)) {
mFocusMode = mode;
break;
}
}
}
}
if (!Util.isSupported(mFocusMode, supportedFocusModes)) {
// For some reasons, the driver does not support the current
// focus mode. Fall back to auto.
if (Util.isSupported(Parameters.FOCUS_MODE_AUTO,
mParameters.getSupportedFocusModes())) {
mFocusMode = Parameters.FOCUS_MODE_AUTO;
} else {
mFocusMode = mParameters.getFocusMode();
}
}
return mFocusMode;
}
public List getFocusAreas() {
return mFocusArea;
}
public List getMeteringAreas() {
return mMeteringArea;
}
public void updateFocusUI() {
if (!mInitialized) return;
// Show only focus indicator or face indicator.
boolean faceExists = (mFaceView != null && mFaceView.faceExists());
FocusIndicator focusIndicator = (faceExists) ? mFaceView : mPieRenderer;
if (mState == STATE_IDLE) {
if (mFocusArea == null) {
focusIndicator.clear();
} else {
// Users touch on the preview and the indicator represents the
// metering area. Either focus area is not supported or
// autoFocus call is not required.
focusIndicator.showStart();
}
} else if (mState == STATE_FOCUSING || mState == STATE_FOCUSING_SNAP_ON_FINISH) {
focusIndicator.showStart();
} else {
if (Util.FOCUS_MODE_CONTINUOUS_PICTURE.equals(mFocusMode)) {
// TODO: check HAL behavior and decide if this can be removed.
focusIndicator.showSuccess(false);
} else if (mState == STATE_SUCCESS) {
focusIndicator.showSuccess(false);
} else if (mState == STATE_FAIL) {
focusIndicator.showFail(false);
}
}
}
public void resetTouchFocus() {
if (!mInitialized) return;
// Put focus indicator to the center. clear reset position
mPieRenderer.clear();
mFocusArea = null;
mMeteringArea = null;
}
private void calculateTapArea(int focusWidth, int focusHeight, float areaMultiple,
int x, int y, int previewWidth, int previewHeight, Rect rect) {
int areaWidth = (int) (focusWidth * areaMultiple);
int areaHeight = (int) (focusHeight * areaMultiple);
int left = Util.clamp(x - areaWidth / 2, 0, previewWidth - areaWidth);
int top = Util.clamp(y - areaHeight / 2, 0, previewHeight - areaHeight);
RectF rectF = new RectF(left, top, left + areaWidth, top + areaHeight);
mMatrix.mapRect(rectF);
Util.rectFToRect(rectF, rect);
}
/* package */ int getFocusState() {
return mState;
}
public boolean isFocusCompleted() {
return mState == STATE_SUCCESS || mState == STATE_FAIL;
}
public boolean isFocusingSnapOnFinish() {
return mState == STATE_FOCUSING_SNAP_ON_FINISH;
}
public void removeMessages() {
mHandler.removeMessages(RESET_TOUCH_FOCUS);
}
public void overrideFocusMode(String focusMode) {
mOverrideFocusMode = focusMode;
}
public void setAeAwbLock(boolean lock) {
mAeAwbLock = lock;
}
public boolean getAeAwbLock() {
return mAeAwbLock;
}
private boolean needAutoFocusCall() {
String focusMode = getFocusMode();
return !(focusMode.equals(Parameters.FOCUS_MODE_INFINITY)
|| focusMode.equals(Parameters.FOCUS_MODE_FIXED)
|| focusMode.equals(Parameters.FOCUS_MODE_EDOF));
}
}
diff --git a/src/com/android/camera/PhotoModule.java b/src/com/android/camera/PhotoModule.java
index 86695ab4..9ece61aa 100644
--- a/src/com/android/camera/PhotoModule.java
+++ b/src/com/android/camera/PhotoModule.java
@@ -1,2564 +1,2569 @@
/*
* Copyright (C) 2012 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.camera;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentProviderClient;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences.Editor;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.SurfaceTexture;
import android.hardware.Camera.CameraInfo;
import android.hardware.Camera.Face;
import android.hardware.Camera.FaceDetectionListener;
import android.hardware.Camera.Parameters;
import android.hardware.Camera.PictureCallback;
import android.hardware.Camera.Size;
import android.location.Location;
import android.media.CameraProfile;
import android.net.Uri;
import android.os.Bundle;
import android.os.ConditionVariable;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.MessageQueue;
import android.os.SystemClock;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.OrientationEventListener;
import android.view.SurfaceHolder;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.FrameLayout.LayoutParams;
import android.widget.ImageView;
import android.widget.Toast;
import com.android.camera.CameraManager.CameraProxy;
import com.android.camera.ui.AbstractSettingPopup;
import com.android.camera.ui.FaceView;
import com.android.camera.ui.PieRenderer;
import com.android.camera.ui.PopupManager;
import com.android.camera.ui.PreviewSurfaceView;
import com.android.camera.ui.RenderOverlay;
import com.android.camera.ui.Rotatable;
import com.android.camera.ui.RotateLayout;
import com.android.camera.ui.RotateTextToast;
import com.android.camera.ui.TwoStateImageView;
import com.android.camera.ui.ZoomRenderer;
import com.android.gallery3d.app.CropImage;
import com.android.gallery3d.common.ApiHelper;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Formatter;
import java.util.List;
public class PhotoModule
implements CameraModule,
FocusOverlayManager.Listener,
CameraPreference.OnPreferenceChangedListener,
LocationManager.Listener,
PreviewFrameLayout.OnSizeChangedListener,
ShutterButton.OnShutterButtonListener,
SurfaceHolder.Callback,
PieRenderer.PieListener {
private static final String TAG = "CAM_PhotoModule";
// We number the request code from 1000 to avoid collision with Gallery.
private static final int REQUEST_CROP = 1000;
private static final int SETUP_PREVIEW = 1;
private static final int FIRST_TIME_INIT = 2;
private static final int CLEAR_SCREEN_DELAY = 3;
private static final int SET_CAMERA_PARAMETERS_WHEN_IDLE = 4;
private static final int CHECK_DISPLAY_ROTATION = 5;
private static final int SHOW_TAP_TO_FOCUS_TOAST = 6;
private static final int SWITCH_CAMERA = 7;
private static final int SWITCH_CAMERA_START_ANIMATION = 8;
private static final int CAMERA_OPEN_DONE = 9;
private static final int START_PREVIEW_DONE = 10;
private static final int OPEN_CAMERA_FAIL = 11;
private static final int CAMERA_DISABLED = 12;
// The subset of parameters we need to update in setCameraParameters().
private static final int UPDATE_PARAM_INITIALIZE = 1;
private static final int UPDATE_PARAM_ZOOM = 2;
private static final int UPDATE_PARAM_PREFERENCE = 4;
private static final int UPDATE_PARAM_ALL = -1;
// This is the timeout to keep the camera in onPause for the first time
// after screen on if the activity is started from secure lock screen.
private static final int KEEP_CAMERA_TIMEOUT = 1000; // ms
// copied from Camera hierarchy
private CameraActivity mActivity;
private View mRootView;
private CameraProxy mCameraDevice;
private int mCameraId;
private Parameters mParameters;
private boolean mPaused;
private AbstractSettingPopup mPopup;
// these are only used by Camera
// The activity is going to switch to the specified camera id. This is
// needed because texture copy is done in GL thread. -1 means camera is not
// switching.
protected int mPendingSwitchCameraId = -1;
private boolean mOpenCameraFail;
private boolean mCameraDisabled;
// When setCameraParametersWhenIdle() is called, we accumulate the subsets
// needed to be updated in mUpdateSet.
private int mUpdateSet;
private static final int SCREEN_DELAY = 2 * 60 * 1000;
private int mZoomValue; // The current zoom value.
private int mZoomMax;
private List<Integer> mZoomRatios;
private Parameters mInitialParams;
private boolean mFocusAreaSupported;
private boolean mMeteringAreaSupported;
private boolean mAeLockSupported;
private boolean mAwbLockSupported;
private boolean mContinousFocusSupported;
// The degrees of the device rotated clockwise from its natural orientation.
private int mOrientation = OrientationEventListener.ORIENTATION_UNKNOWN;
// The orientation compensation for icons and dialogs. Ex: if the value
// is 90, the UI components should be rotated 90 degrees counter-clockwise.
private int mOrientationCompensation = 0;
private ComboPreferences mPreferences;
private static final String sTempCropFilename = "crop-temp";
private ContentProviderClient mMediaProviderClient;
private ShutterButton mShutterButton;
private boolean mFaceDetectionStarted = false;
private PreviewFrameLayout mPreviewFrameLayout;
private Object mSurfaceTexture;
// for API level 10
private PreviewSurfaceView mPreviewSurfaceView;
private volatile SurfaceHolder mCameraSurfaceHolder;
private FaceView mFaceView;
private RenderOverlay mRenderOverlay;
private Rotatable mReviewCancelButton;
private Rotatable mReviewDoneButton;
// private View mReviewRetakeButton;
// mCropValue and mSaveUri are used only if isImageCaptureIntent() is true.
private String mCropValue;
private Uri mSaveUri;
private View mMenu;
private View mBlocker;
// Small indicators which show the camera settings in the viewfinder.
private ImageView mExposureIndicator;
private ImageView mFlashIndicator;
private ImageView mSceneIndicator;
private ImageView mHdrIndicator;
// A view group that contains all the small indicators.
private RotateLayout mOnScreenIndicators;
// We use a thread in ImageSaver to do the work of saving images. This
// reduces the shot-to-shot time.
private ImageSaver mImageSaver;
// Similarly, we use a thread to generate the name of the picture and insert
// it into MediaStore while picture taking is still in progress.
private ImageNamer mImageNamer;
private Runnable mDoSnapRunnable = new Runnable() {
@Override
public void run() {
onShutterButtonClick();
}
};
private final StringBuilder mBuilder = new StringBuilder();
private final Formatter mFormatter = new Formatter(mBuilder);
private final Object[] mFormatterArgs = new Object[1];
/**
* An unpublished intent flag requesting to return as soon as capturing
* is completed.
*
* TODO: consider publishing by moving into MediaStore.
*/
private static final String EXTRA_QUICK_CAPTURE =
"android.intent.extra.quickCapture";
// The display rotation in degrees. This is only valid when mCameraState is
// not PREVIEW_STOPPED.
private int mDisplayRotation;
// The value for android.hardware.Camera.setDisplayOrientation.
private int mCameraDisplayOrientation;
// The value for UI components like indicators.
private int mDisplayOrientation;
// The value for android.hardware.Camera.Parameters.setRotation.
private int mJpegRotation;
private boolean mFirstTimeInitialized;
private boolean mIsImageCaptureIntent;
private static final int PREVIEW_STOPPED = 0;
private static final int IDLE = 1; // preview is active
// Focus is in progress. The exact focus state is in Focus.java.
private static final int FOCUSING = 2;
private static final int SNAPSHOT_IN_PROGRESS = 3;
// Switching between cameras.
private static final int SWITCHING_CAMERA = 4;
private int mCameraState = PREVIEW_STOPPED;
private boolean mSnapshotOnIdle = false;
private ContentResolver mContentResolver;
private LocationManager mLocationManager;
private final ShutterCallback mShutterCallback = new ShutterCallback();
private final PostViewPictureCallback mPostViewPictureCallback =
new PostViewPictureCallback();
private final RawPictureCallback mRawPictureCallback =
new RawPictureCallback();
private final AutoFocusCallback mAutoFocusCallback =
new AutoFocusCallback();
private final Object mAutoFocusMoveCallback =
ApiHelper.HAS_AUTO_FOCUS_MOVE_CALLBACK
? new AutoFocusMoveCallback()
: null;
private final CameraErrorCallback mErrorCallback = new CameraErrorCallback();
private long mFocusStartTime;
private long mShutterCallbackTime;
private long mPostViewPictureCallbackTime;
private long mRawPictureCallbackTime;
private long mJpegPictureCallbackTime;
private long mOnResumeTime;
private byte[] mJpegImageData;
// These latency time are for the CameraLatency test.
public long mAutoFocusTime;
public long mShutterLag;
public long mShutterToPictureDisplayedTime;
public long mPictureDisplayedToJpegCallbackTime;
public long mJpegCallbackFinishTime;
public long mCaptureStartTime;
// This handles everything about focus.
private FocusOverlayManager mFocusManager;
private PieRenderer mPieRenderer;
private PhotoController mPhotoControl;
private ZoomRenderer mZoomRenderer;
private String mSceneMode;
private Toast mNotSelectableToast;
private final Handler mHandler = new MainHandler();
private PreferenceGroup mPreferenceGroup;
private boolean mQuickCapture;
CameraStartUpThread mCameraStartUpThread;
ConditionVariable mStartPreviewPrerequisiteReady = new ConditionVariable();
private PreviewGestures mGestures;
// The purpose is not to block the main thread in onCreate and onResume.
private class CameraStartUpThread extends Thread {
private volatile boolean mCancelled;
public void cancel() {
mCancelled = true;
}
@Override
public void run() {
try {
// We need to check whether the activity is paused before long
// operations to ensure that onPause() can be done ASAP.
if (mCancelled) return;
mCameraDevice = Util.openCamera(mActivity, mCameraId);
mParameters = mCameraDevice.getParameters();
// Wait until all the initialization needed by startPreview are
// done.
mStartPreviewPrerequisiteReady.block();
initializeCapabilities();
if (mFocusManager == null) initializeFocusManager();
if (mCancelled) return;
setCameraParameters(UPDATE_PARAM_ALL);
mHandler.sendEmptyMessage(CAMERA_OPEN_DONE);
if (mCancelled) return;
startPreview();
mHandler.sendEmptyMessage(START_PREVIEW_DONE);
mOnResumeTime = SystemClock.uptimeMillis();
mHandler.sendEmptyMessage(CHECK_DISPLAY_ROTATION);
} catch (CameraHardwareException e) {
mHandler.sendEmptyMessage(OPEN_CAMERA_FAIL);
} catch (CameraDisabledException e) {
mHandler.sendEmptyMessage(CAMERA_DISABLED);
}
}
}
/**
* This Handler is used to post message back onto the main thread of the
* application
*/
private class MainHandler extends Handler {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case SETUP_PREVIEW: {
setupPreview();
break;
}
case CLEAR_SCREEN_DELAY: {
mActivity.getWindow().clearFlags(
WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
break;
}
case FIRST_TIME_INIT: {
initializeFirstTime();
break;
}
case SET_CAMERA_PARAMETERS_WHEN_IDLE: {
setCameraParametersWhenIdle(0);
break;
}
case CHECK_DISPLAY_ROTATION: {
// Set the display orientation if display rotation has changed.
// Sometimes this happens when the device is held upside
// down and camera app is opened. Rotation animation will
// take some time and the rotation value we have got may be
// wrong. Framework does not have a callback for this now.
if (Util.getDisplayRotation(mActivity) != mDisplayRotation) {
setDisplayOrientation();
}
if (SystemClock.uptimeMillis() - mOnResumeTime < 5000) {
mHandler.sendEmptyMessageDelayed(CHECK_DISPLAY_ROTATION, 100);
}
break;
}
case SHOW_TAP_TO_FOCUS_TOAST: {
showTapToFocusToast();
break;
}
case SWITCH_CAMERA: {
switchCamera();
break;
}
case SWITCH_CAMERA_START_ANIMATION: {
((CameraScreenNail) mActivity.mCameraScreenNail).animateSwitchCamera();
break;
}
case CAMERA_OPEN_DONE: {
initializeAfterCameraOpen();
break;
}
case START_PREVIEW_DONE: {
mCameraStartUpThread = null;
setCameraState(IDLE);
if (!ApiHelper.HAS_SURFACE_TEXTURE) {
// This may happen if surfaceCreated has arrived.
mCameraDevice.setPreviewDisplayAsync(mCameraSurfaceHolder);
}
startFaceDetection();
locationFirstRun();
break;
}
case OPEN_CAMERA_FAIL: {
mCameraStartUpThread = null;
mOpenCameraFail = true;
Util.showErrorAndFinish(mActivity,
R.string.cannot_connect_camera);
break;
}
case CAMERA_DISABLED: {
mCameraStartUpThread = null;
mCameraDisabled = true;
Util.showErrorAndFinish(mActivity,
R.string.camera_disabled);
break;
}
}
}
}
@Override
public void init(CameraActivity activity, View parent, boolean reuseNail) {
mActivity = activity;
mRootView = parent;
mPreferences = new ComboPreferences(mActivity);
CameraSettings.upgradeGlobalPreferences(mPreferences.getGlobal());
mCameraId = getPreferredCameraId(mPreferences);
mContentResolver = mActivity.getContentResolver();
// To reduce startup time, open the camera and start the preview in
// another thread.
mCameraStartUpThread = new CameraStartUpThread();
mCameraStartUpThread.start();
mActivity.getLayoutInflater().inflate(R.layout.photo_module, (ViewGroup) mRootView);
// Surface texture is from camera screen nail and startPreview needs it.
// This must be done before startPreview.
mIsImageCaptureIntent = isImageCaptureIntent();
if (reuseNail) {
mActivity.reuseCameraScreenNail(!mIsImageCaptureIntent);
} else {
mActivity.createCameraScreenNail(!mIsImageCaptureIntent);
}
mPreferences.setLocalId(mActivity, mCameraId);
CameraSettings.upgradeLocalPreferences(mPreferences.getLocal());
// we need to reset exposure for the preview
resetExposureCompensation();
// Starting the preview needs preferences, camera screen nail, and
// focus area indicator.
mStartPreviewPrerequisiteReady.open();
initializeControlByIntent();
mQuickCapture = mActivity.getIntent().getBooleanExtra(EXTRA_QUICK_CAPTURE, false);
initializeMiscControls();
mLocationManager = new LocationManager(mActivity, this);
initOnScreenIndicator();
// Make sure all views are disabled before camera is open.
// enableCameraControls(false);
}
// Prompt the user to pick to record location for the very first run of
// camera only
private void locationFirstRun() {
if (RecordLocationPreference.isSet(mPreferences)) {
return;
}
new AlertDialog.Builder(mActivity)
.setTitle(R.string.remember_location_title)
.setMessage(R.string.remember_location_prompt)
.setPositiveButton(R.string.remember_location_yes, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int arg1) {
setLocationPreference(RecordLocationPreference.VALUE_ON);
}
})
.setNegativeButton(R.string.remember_location_no, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int arg1) {
dialog.cancel();
}
})
.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
setLocationPreference(RecordLocationPreference.VALUE_OFF);
}
})
.show();
}
private void setLocationPreference(String value) {
mPreferences.edit()
.putString(RecordLocationPreference.KEY, value)
.apply();
// TODO: Fix this to use the actual onSharedPreferencesChanged listener
// instead of invoking manually
onSharedPreferenceChanged();
}
private void initializeRenderOverlay() {
if (mPieRenderer != null) {
mRenderOverlay.addRenderer(mPieRenderer);
mFocusManager.setFocusRenderer(mPieRenderer);
}
if (mZoomRenderer != null) {
mRenderOverlay.addRenderer(mZoomRenderer);
}
if (mGestures != null) {
mGestures.clearTouchReceivers();
mGestures.setRenderOverlay(mRenderOverlay);
mGestures.addTouchReceiver(mBlocker);
mGestures.addTouchReceiver(mMenu);
if (isImageCaptureIntent()) {
if (mReviewCancelButton != null) {
mGestures.addTouchReceiver((View) mReviewCancelButton);
}
if (mReviewDoneButton != null) {
mGestures.addTouchReceiver((View) mReviewDoneButton);
}
}
}
mRenderOverlay.requestLayout();
}
private void initializeAfterCameraOpen() {
if (mPieRenderer == null) {
mPieRenderer = new PieRenderer(mActivity);
mPhotoControl = new PhotoController(mActivity, this, mPieRenderer);
mPhotoControl.setListener(this);
mPieRenderer.setPieListener(this);
}
if (mZoomRenderer == null) {
mZoomRenderer = new ZoomRenderer(mActivity);
}
if (mGestures == null) {
// this will handle gesture disambiguation and dispatching
mGestures = new PreviewGestures(mActivity, this, mZoomRenderer, mPieRenderer);
}
initializeRenderOverlay();
initializePhotoControl();
// These depend on camera parameters.
setPreviewFrameLayoutAspectRatio();
mFocusManager.setPreviewSize(mPreviewFrameLayout.getWidth(),
mPreviewFrameLayout.getHeight());
loadCameraPreferences();
initializeZoom();
updateOnScreenIndicators();
showTapToFocusToastIfNeeded();
}
private void initializePhotoControl() {
loadCameraPreferences();
if (mPhotoControl != null) {
mPhotoControl.initialize(mPreferenceGroup);
}
updateSceneModeUI();
// mIndicatorControlContainer.setListener(this);
}
private void resetExposureCompensation() {
String value = mPreferences.getString(CameraSettings.KEY_EXPOSURE,
CameraSettings.EXPOSURE_DEFAULT_VALUE);
if (!CameraSettings.EXPOSURE_DEFAULT_VALUE.equals(value)) {
Editor editor = mPreferences.edit();
editor.putString(CameraSettings.KEY_EXPOSURE, "0");
editor.apply();
}
}
private void keepMediaProviderInstance() {
// We want to keep a reference to MediaProvider in camera's lifecycle.
// TODO: Utilize mMediaProviderClient instance to replace
// ContentResolver calls.
if (mMediaProviderClient == null) {
mMediaProviderClient = mContentResolver
.acquireContentProviderClient(MediaStore.AUTHORITY);
}
}
// Snapshots can only be taken after this is called. It should be called
// once only. We could have done these things in onCreate() but we want to
// make preview screen appear as soon as possible.
private void initializeFirstTime() {
if (mFirstTimeInitialized) return;
// Initialize location service.
boolean recordLocation = RecordLocationPreference.get(
mPreferences, mContentResolver);
mLocationManager.recordLocation(recordLocation);
keepMediaProviderInstance();
// Initialize shutter button.
mShutterButton = mActivity.getShutterButton();
mShutterButton.setImageResource(R.drawable.btn_new_shutter);
mShutterButton.setOnShutterButtonListener(this);
mShutterButton.setVisibility(View.VISIBLE);
mImageSaver = new ImageSaver();
mImageNamer = new ImageNamer();
mFirstTimeInitialized = true;
addIdleHandler();
mActivity.updateStorageSpaceAndHint();
}
private void showTapToFocusToastIfNeeded() {
// Show the tap to focus toast if this is the first start.
if (mFocusAreaSupported &&
mPreferences.getBoolean(CameraSettings.KEY_CAMERA_FIRST_USE_HINT_SHOWN, true)) {
// Delay the toast for one second to wait for orientation.
mHandler.sendEmptyMessageDelayed(SHOW_TAP_TO_FOCUS_TOAST, 1000);
}
}
private void addIdleHandler() {
MessageQueue queue = Looper.myQueue();
queue.addIdleHandler(new MessageQueue.IdleHandler() {
@Override
public boolean queueIdle() {
Storage.ensureOSXCompatible();
return false;
}
});
}
// If the activity is paused and resumed, this method will be called in
// onResume.
private void initializeSecondTime() {
// Start location update if needed.
boolean recordLocation = RecordLocationPreference.get(
mPreferences, mContentResolver);
mLocationManager.recordLocation(recordLocation);
mImageSaver = new ImageSaver();
mImageNamer = new ImageNamer();
initializeZoom();
keepMediaProviderInstance();
hidePostCaptureAlert();
if (mPhotoControl != null) {
mPhotoControl.reloadPreferences();
}
}
private class ZoomChangeListener implements ZoomRenderer.OnZoomChangedListener {
@Override
public void onZoomValueChanged(int index) {
// Not useful to change zoom value when the activity is paused.
if (mPaused) return;
mZoomValue = index;
// Set zoom parameters asynchronously
mParameters.setZoom(mZoomValue);
mCameraDevice.setParametersAsync(mParameters);
if (mZoomRenderer != null) {
Parameters p = mCameraDevice.getParameters();
mZoomRenderer.setZoomValue(mZoomRatios.get(p.getZoom()));
}
}
@Override
public void onZoomStart() {
if (mPieRenderer != null) {
mPieRenderer.setBlockFocus(true);
}
}
@Override
public void onZoomEnd() {
if (mPieRenderer != null) {
mPieRenderer.setBlockFocus(false);
}
}
}
private void initializeZoom() {
if (!mParameters.isZoomSupported() || (mZoomRenderer == null)) return;
mZoomMax = mParameters.getMaxZoom();
mZoomRatios = mParameters.getZoomRatios();
// Currently we use immediate zoom for fast zooming to get better UX and
// there is no plan to take advantage of the smooth zoom.
if (mZoomRenderer != null) {
mZoomRenderer.setZoomMax(mZoomMax);
mZoomRenderer.setZoomValue(mZoomRatios.get(mParameters.getZoom()));
mZoomRenderer.setOnZoomChangeListener(new ZoomChangeListener());
}
}
@TargetApi(ApiHelper.VERSION_CODES.ICE_CREAM_SANDWICH)
@Override
public void startFaceDetection() {
if (!ApiHelper.HAS_FACE_DETECTION) return;
if (mFaceDetectionStarted) return;
if (mParameters.getMaxNumDetectedFaces() > 0) {
mFaceDetectionStarted = true;
mFaceView.clear();
mFaceView.setVisibility(View.VISIBLE);
mFaceView.setDisplayOrientation(mDisplayOrientation);
CameraInfo info = CameraHolder.instance().getCameraInfo()[mCameraId];
mFaceView.setMirror(info.facing == CameraInfo.CAMERA_FACING_FRONT);
mFaceView.resume();
mFocusManager.setFaceView(mFaceView);
mCameraDevice.setFaceDetectionListener(new FaceDetectionListener() {
@Override
public void onFaceDetection(Face[] faces, android.hardware.Camera camera) {
mFaceView.setFaces(faces);
}
});
mCameraDevice.startFaceDetection();
}
}
@TargetApi(ApiHelper.VERSION_CODES.ICE_CREAM_SANDWICH)
@Override
public void stopFaceDetection() {
if (!ApiHelper.HAS_FACE_DETECTION) return;
if (!mFaceDetectionStarted) return;
if (mParameters.getMaxNumDetectedFaces() > 0) {
mFaceDetectionStarted = false;
mCameraDevice.setFaceDetectionListener(null);
mCameraDevice.stopFaceDetection();
if (mFaceView != null) mFaceView.clear();
}
}
@Override
public boolean dispatchTouchEvent(MotionEvent m) {
if (mCameraState == SWITCHING_CAMERA) return true;
if (mPopup != null) {
return mActivity.superDispatchTouchEvent(m);
} else if (mGestures != null && mRenderOverlay != null) {
return mGestures.dispatchTouch(m);
}
return false;
}
private void initOnScreenIndicator() {
mOnScreenIndicators = (RotateLayout) mRootView.findViewById(R.id.on_screen_indicators);
mExposureIndicator = (ImageView) mOnScreenIndicators.findViewById(R.id.menu_exposure_indicator);
mFlashIndicator = (ImageView) mOnScreenIndicators.findViewById(R.id.menu_flash_indicator);
mSceneIndicator = (ImageView) mOnScreenIndicators.findViewById(R.id.menu_scenemode_indicator);
mHdrIndicator = (ImageView) mOnScreenIndicators.findViewById(R.id.menu_hdr_indicator);
}
@Override
public void showGpsOnScreenIndicator(boolean hasSignal) { }
@Override
public void hideGpsOnScreenIndicator() { }
private void updateExposureOnScreenIndicator(int value) {
if (mExposureIndicator == null) {
return;
}
int id = 0;
float step = mParameters.getExposureCompensationStep();
value = (int) Math.round(value * step);
switch(value) {
case -3:
id = R.drawable.ic_indicator_ev_n3;
break;
case -2:
id = R.drawable.ic_indicator_ev_n2;
break;
case -1:
id = R.drawable.ic_indicator_ev_n1;
break;
case 0:
id = R.drawable.ic_indicator_ev_0;
break;
case 1:
id = R.drawable.ic_indicator_ev_p1;
break;
case 2:
id = R.drawable.ic_indicator_ev_p2;
break;
case 3:
id = R.drawable.ic_indicator_ev_p3;
break;
}
mExposureIndicator.setImageResource(id);
}
private void updateFlashOnScreenIndicator(String value) {
if (mFlashIndicator == null) {
return;
}
if (value == null || Parameters.FLASH_MODE_OFF.equals(value)) {
mFlashIndicator.setImageResource(R.drawable.ic_indicator_flash_off);
} else {
if (Parameters.FLASH_MODE_AUTO.equals(value)) {
mFlashIndicator.setImageResource(R.drawable.ic_indicator_flash_auto);
} else if (Parameters.FLASH_MODE_ON.equals(value)) {
mFlashIndicator.setImageResource(R.drawable.ic_indicator_flash_on);
} else {
mFlashIndicator.setImageResource(R.drawable.ic_indicator_flash_off);
}
}
}
private void updateSceneOnScreenIndicator(String value) {
if (mSceneIndicator == null) {
return;
}
if ((value == null) || Parameters.SCENE_MODE_AUTO.equals(value)
|| Parameters.SCENE_MODE_HDR.equals(value)) {
mSceneIndicator.setImageResource(R.drawable.ic_indicator_sce_off);
} else {
mSceneIndicator.setImageResource(R.drawable.ic_indicator_sce_on);
}
}
private void updateHdrOnScreenIndicator(String value) {
if (mHdrIndicator == null) {
return;
}
if ((value != null) && Parameters.SCENE_MODE_HDR.equals(value)) {
mHdrIndicator.setImageResource(R.drawable.ic_indicator_hdr_on);
} else {
mHdrIndicator.setImageResource(R.drawable.ic_indicator_hdr_off);
}
}
private void updateOnScreenIndicators() {
updateSceneOnScreenIndicator(mParameters.getSceneMode());
updateExposureOnScreenIndicator(CameraSettings.readExposure(mPreferences));
updateFlashOnScreenIndicator(mParameters.getFlashMode());
updateHdrOnScreenIndicator(mParameters.getSceneMode());
}
private final class ShutterCallback
implements android.hardware.Camera.ShutterCallback {
@Override
public void onShutter() {
mShutterCallbackTime = System.currentTimeMillis();
mShutterLag = mShutterCallbackTime - mCaptureStartTime;
Log.v(TAG, "mShutterLag = " + mShutterLag + "ms");
}
}
private final class PostViewPictureCallback implements PictureCallback {
@Override
public void onPictureTaken(
byte [] data, android.hardware.Camera camera) {
mPostViewPictureCallbackTime = System.currentTimeMillis();
Log.v(TAG, "mShutterToPostViewCallbackTime = "
+ (mPostViewPictureCallbackTime - mShutterCallbackTime)
+ "ms");
}
}
private final class RawPictureCallback implements PictureCallback {
@Override
public void onPictureTaken(
byte [] rawData, android.hardware.Camera camera) {
mRawPictureCallbackTime = System.currentTimeMillis();
Log.v(TAG, "mShutterToRawCallbackTime = "
+ (mRawPictureCallbackTime - mShutterCallbackTime) + "ms");
}
}
private final class JpegPictureCallback implements PictureCallback {
Location mLocation;
public JpegPictureCallback(Location loc) {
mLocation = loc;
}
@Override
public void onPictureTaken(
final byte [] jpegData, final android.hardware.Camera camera) {
if (mPaused) {
return;
}
mJpegPictureCallbackTime = System.currentTimeMillis();
// If postview callback has arrived, the captured image is displayed
// in postview callback. If not, the captured image is displayed in
// raw picture callback.
if (mPostViewPictureCallbackTime != 0) {
mShutterToPictureDisplayedTime =
mPostViewPictureCallbackTime - mShutterCallbackTime;
mPictureDisplayedToJpegCallbackTime =
mJpegPictureCallbackTime - mPostViewPictureCallbackTime;
} else {
mShutterToPictureDisplayedTime =
mRawPictureCallbackTime - mShutterCallbackTime;
mPictureDisplayedToJpegCallbackTime =
mJpegPictureCallbackTime - mRawPictureCallbackTime;
}
Log.v(TAG, "mPictureDisplayedToJpegCallbackTime = "
+ mPictureDisplayedToJpegCallbackTime + "ms");
// Only animate when in full screen capture mode
// i.e. If monkey/a user swipes to the gallery during picture taking,
// don't show animation
if (ApiHelper.HAS_SURFACE_TEXTURE && !mIsImageCaptureIntent
&& mActivity.mShowCameraAppView) {
// Finish capture animation
((CameraScreenNail) mActivity.mCameraScreenNail).animateSlide();
}
mFocusManager.updateFocusUI(); // Ensure focus indicator is hidden.
if (!mIsImageCaptureIntent) {
if (ApiHelper.CAN_START_PREVIEW_IN_JPEG_CALLBACK) {
setupPreview();
} else {
// Camera HAL of some devices have a bug. Starting preview
// immediately after taking a picture will fail. Wait some
// time before starting the preview.
mHandler.sendEmptyMessageDelayed(SETUP_PREVIEW, 300);
}
}
if (!mIsImageCaptureIntent) {
// Calculate the width and the height of the jpeg.
Size s = mParameters.getPictureSize();
int orientation = Exif.getOrientation(jpegData);
int width, height;
if ((mJpegRotation + orientation) % 180 == 0) {
width = s.width;
height = s.height;
} else {
width = s.height;
height = s.width;
}
Uri uri = mImageNamer.getUri();
mActivity.addSecureAlbumItemIfNeeded(false, uri);
String title = mImageNamer.getTitle();
mImageSaver.addImage(jpegData, uri, title, mLocation,
width, height, orientation);
} else {
mJpegImageData = jpegData;
if (!mQuickCapture) {
showPostCaptureAlert();
} else {
doAttach();
}
}
// Check this in advance of each shot so we don't add to shutter
// latency. It's true that someone else could write to the SD card in
// the mean time and fill it, but that could have happened between the
// shutter press and saving the JPEG too.
mActivity.updateStorageSpaceAndHint();
long now = System.currentTimeMillis();
mJpegCallbackFinishTime = now - mJpegPictureCallbackTime;
Log.v(TAG, "mJpegCallbackFinishTime = "
+ mJpegCallbackFinishTime + "ms");
mJpegPictureCallbackTime = 0;
}
}
private final class AutoFocusCallback
implements android.hardware.Camera.AutoFocusCallback {
@Override
public void onAutoFocus(
boolean focused, android.hardware.Camera camera) {
if (mPaused) return;
mAutoFocusTime = System.currentTimeMillis() - mFocusStartTime;
Log.v(TAG, "mAutoFocusTime = " + mAutoFocusTime + "ms");
setCameraState(IDLE);
mFocusManager.onAutoFocus(focused);
}
}
@TargetApi(ApiHelper.VERSION_CODES.JELLY_BEAN)
private final class AutoFocusMoveCallback
implements android.hardware.Camera.AutoFocusMoveCallback {
@Override
public void onAutoFocusMoving(
boolean moving, android.hardware.Camera camera) {
mFocusManager.onAutoFocusMoving(moving);
}
}
// Each SaveRequest remembers the data needed to save an image.
private static class SaveRequest {
byte[] data;
Uri uri;
String title;
Location loc;
int width, height;
int orientation;
}
// We use a queue to store the SaveRequests that have not been completed
// yet. The main thread puts the request into the queue. The saver thread
// gets it from the queue, does the work, and removes it from the queue.
//
// The main thread needs to wait for the saver thread to finish all the work
// in the queue, when the activity's onPause() is called, we need to finish
// all the work, so other programs (like Gallery) can see all the images.
//
// If the queue becomes too long, adding a new request will block the main
// thread until the queue length drops below the threshold (QUEUE_LIMIT).
// If we don't do this, we may face several problems: (1) We may OOM
// because we are holding all the jpeg data in memory. (2) We may ANR
// when we need to wait for saver thread finishing all the work (in
// onPause() or gotoGallery()) because the time to finishing a long queue
// of work may be too long.
private class ImageSaver extends Thread {
private static final int QUEUE_LIMIT = 3;
private ArrayList<SaveRequest> mQueue;
private boolean mStop;
// Runs in main thread
public ImageSaver() {
mQueue = new ArrayList<SaveRequest>();
start();
}
// Runs in main thread
public void addImage(final byte[] data, Uri uri, String title,
Location loc, int width, int height, int orientation) {
SaveRequest r = new SaveRequest();
r.data = data;
r.uri = uri;
r.title = title;
r.loc = (loc == null) ? null : new Location(loc); // make a copy
r.width = width;
r.height = height;
r.orientation = orientation;
synchronized (this) {
while (mQueue.size() >= QUEUE_LIMIT) {
try {
wait();
} catch (InterruptedException ex) {
// ignore.
}
}
mQueue.add(r);
notifyAll(); // Tell saver thread there is new work to do.
}
}
// Runs in saver thread
@Override
public void run() {
while (true) {
SaveRequest r;
synchronized (this) {
if (mQueue.isEmpty()) {
notifyAll(); // notify main thread in waitDone
// Note that we can only stop after we saved all images
// in the queue.
if (mStop) break;
try {
wait();
} catch (InterruptedException ex) {
// ignore.
}
continue;
}
r = mQueue.get(0);
}
storeImage(r.data, r.uri, r.title, r.loc, r.width, r.height,
r.orientation);
synchronized (this) {
mQueue.remove(0);
notifyAll(); // the main thread may wait in addImage
}
}
}
// Runs in main thread
public void waitDone() {
synchronized (this) {
while (!mQueue.isEmpty()) {
try {
wait();
} catch (InterruptedException ex) {
// ignore.
}
}
}
}
// Runs in main thread
public void finish() {
waitDone();
synchronized (this) {
mStop = true;
notifyAll();
}
try {
join();
} catch (InterruptedException ex) {
// ignore.
}
}
// Runs in saver thread
private void storeImage(final byte[] data, Uri uri, String title,
Location loc, int width, int height, int orientation) {
boolean ok = Storage.updateImage(mContentResolver, uri, title, loc,
orientation, data, width, height);
if (ok) {
Util.broadcastNewPicture(mActivity, uri);
}
}
}
private static class ImageNamer extends Thread {
private boolean mRequestPending;
private ContentResolver mResolver;
private long mDateTaken;
private int mWidth, mHeight;
private boolean mStop;
private Uri mUri;
private String mTitle;
// Runs in main thread
public ImageNamer() {
start();
}
// Runs in main thread
public synchronized void prepareUri(ContentResolver resolver,
long dateTaken, int width, int height, int rotation) {
if (rotation % 180 != 0) {
int tmp = width;
width = height;
height = tmp;
}
mRequestPending = true;
mResolver = resolver;
mDateTaken = dateTaken;
mWidth = width;
mHeight = height;
notifyAll();
}
// Runs in main thread
public synchronized Uri getUri() {
// wait until the request is done.
while (mRequestPending) {
try {
wait();
} catch (InterruptedException ex) {
// ignore.
}
}
// return the uri generated
Uri uri = mUri;
mUri = null;
return uri;
}
// Runs in main thread, should be called after getUri().
public synchronized String getTitle() {
return mTitle;
}
// Runs in namer thread
@Override
public synchronized void run() {
while (true) {
if (mStop) break;
if (!mRequestPending) {
try {
wait();
} catch (InterruptedException ex) {
// ignore.
}
continue;
}
cleanOldUri();
generateUri();
mRequestPending = false;
notifyAll();
}
cleanOldUri();
}
// Runs in main thread
public synchronized void finish() {
mStop = true;
notifyAll();
}
// Runs in namer thread
private void generateUri() {
mTitle = Util.createJpegName(mDateTaken);
mUri = Storage.newImage(mResolver, mTitle, mDateTaken, mWidth, mHeight);
}
// Runs in namer thread
private void cleanOldUri() {
if (mUri == null) return;
Storage.deleteImage(mResolver, mUri);
mUri = null;
}
}
private void setCameraState(int state) {
mCameraState = state;
switch (state) {
case PREVIEW_STOPPED:
case SNAPSHOT_IN_PROGRESS:
case FOCUSING:
case SWITCHING_CAMERA:
if (mGestures != null) mGestures.setEnabled(false);
break;
case IDLE:
if (mGestures != null && mActivity.mShowCameraAppView) {
// Enable gestures only when the camera app view is visible
mGestures.setEnabled(true);
}
break;
}
}
@Override
public boolean capture() {
// If we are already in the middle of taking a snapshot then ignore.
if (mCameraDevice == null || mCameraState == SNAPSHOT_IN_PROGRESS
|| mCameraState == SWITCHING_CAMERA) {
return false;
}
mCaptureStartTime = System.currentTimeMillis();
mPostViewPictureCallbackTime = 0;
mJpegImageData = null;
// Only animate when in full screen capture mode
// i.e. If monkey/a user swipes to the gallery during picture taking,
// don't show animation
if (ApiHelper.HAS_SURFACE_TEXTURE && !mIsImageCaptureIntent
&& mActivity.mShowCameraAppView) {
// Start capture animation.
((CameraScreenNail) mActivity.mCameraScreenNail).animateFlash(getCameraRotation());
}
// Set rotation and gps data.
mJpegRotation = Util.getJpegRotation(mCameraId, mOrientation);
mParameters.setRotation(mJpegRotation);
Location loc = mLocationManager.getCurrentLocation();
Util.setGpsParameters(mParameters, loc);
mCameraDevice.setParameters(mParameters);
mCameraDevice.takePicture2(mShutterCallback, mRawPictureCallback,
mPostViewPictureCallback, new JpegPictureCallback(loc),
mCameraState, mFocusManager.getFocusState());
Size size = mParameters.getPictureSize();
mImageNamer.prepareUri(mContentResolver, mCaptureStartTime,
size.width, size.height, mJpegRotation);
mFaceDetectionStarted = false;
setCameraState(SNAPSHOT_IN_PROGRESS);
return true;
}
private int getCameraRotation() {
return (mOrientationCompensation - mDisplayRotation + 360) % 360;
}
@Override
public void setFocusParameters() {
setCameraParameters(UPDATE_PARAM_PREFERENCE);
}
private int getPreferredCameraId(ComboPreferences preferences) {
int intentCameraId = Util.getCameraFacingIntentExtras(mActivity);
if (intentCameraId != -1) {
// Testing purpose. Launch a specific camera through the intent
// extras.
return intentCameraId;
} else {
return CameraSettings.readPreferredCameraId(preferences);
}
}
@Override
public void onFullScreenChanged(boolean full) {
if (mFaceView != null) {
mFaceView.setBlockDraw(!full);
}
if (mPopup != null) {
dismissPopup(false, true);
}
if (mGestures != null) {
mGestures.setEnabled(full);
}
if (mRenderOverlay != null) {
// this can not happen in capture mode
mRenderOverlay.setVisibility(full ? View.VISIBLE : View.GONE);
}
if (mPieRenderer != null) {
mPieRenderer.setBlockFocus(!full);
}
if (mOnScreenIndicators != null) {
mOnScreenIndicators.setVisibility(full ? View.VISIBLE : View.GONE);
}
if (mMenu != null) {
mMenu.setVisibility(full ? View.VISIBLE : View.GONE);
}
if (mBlocker != null) {
mBlocker.setVisibility(full ? View.VISIBLE : View.GONE);
}
if (ApiHelper.HAS_SURFACE_TEXTURE) {
if (mActivity.mCameraScreenNail != null) {
((CameraScreenNail) mActivity.mCameraScreenNail).setFullScreen(full);
}
return;
}
if (full) {
mPreviewSurfaceView.expand();
} else {
mPreviewSurfaceView.shrink();
}
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
Log.v(TAG, "surfaceChanged:" + holder + " width=" + width + ". height="
+ height);
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
Log.v(TAG, "surfaceCreated: " + holder);
mCameraSurfaceHolder = holder;
// Do not access the camera if camera start up thread is not finished.
if (mCameraDevice == null || mCameraStartUpThread != null) return;
mCameraDevice.setPreviewDisplayAsync(holder);
// This happens when onConfigurationChanged arrives, surface has been
// destroyed, and there is no onFullScreenChanged.
if (mCameraState == PREVIEW_STOPPED) {
setupPreview();
}
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
Log.v(TAG, "surfaceDestroyed: " + holder);
mCameraSurfaceHolder = null;
stopPreview();
}
private void updateSceneModeUI() {
// If scene mode is set, we cannot set flash mode, white balance, and
// focus mode, instead, we read it from driver
if (!Parameters.SCENE_MODE_AUTO.equals(mSceneMode)) {
overrideCameraSettings(mParameters.getFlashMode(),
mParameters.getWhiteBalance(), mParameters.getFocusMode());
} else {
overrideCameraSettings(null, null, null);
}
}
private void overrideCameraSettings(final String flashMode,
final String whiteBalance, final String focusMode) {
if (mPhotoControl != null) {
// mPieControl.enableFilter(true);
mPhotoControl.overrideSettings(
CameraSettings.KEY_FLASH_MODE, flashMode,
CameraSettings.KEY_WHITE_BALANCE, whiteBalance,
CameraSettings.KEY_FOCUS_MODE, focusMode);
// mPieControl.enableFilter(false);
}
}
private void loadCameraPreferences() {
CameraSettings settings = new CameraSettings(mActivity, mInitialParams,
mCameraId, CameraHolder.instance().getCameraInfo());
mPreferenceGroup = settings.getPreferenceGroup(R.xml.camera_preferences);
}
@Override
public boolean collapseCameraControls() {
// Remove all the popups/dialog boxes
boolean ret = false;
if (mPopup != null) {
dismissPopup(false);
ret = true;
}
return ret;
}
public boolean removeTopLevelPopup() {
// Remove the top level popup or dialog box and return true if there's any
if (mPopup != null) {
dismissPopup(true);
return true;
}
return false;
}
@Override
public void onOrientationChanged(int orientation) {
// We keep the last known orientation. So if the user first orient
// the camera then point the camera to floor or sky, we still have
// the correct orientation.
if (orientation == OrientationEventListener.ORIENTATION_UNKNOWN) return;
mOrientation = Util.roundOrientation(orientation, mOrientation);
// When the screen is unlocked, display rotation may change. Always
// calculate the up-to-date orientationCompensation.
int orientationCompensation =
(mOrientation + Util.getDisplayRotation(mActivity)) % 360;
if (mOrientationCompensation != orientationCompensation) {
mOrientationCompensation = orientationCompensation;
if (mFaceView != null) {
mFaceView.setOrientation(mOrientationCompensation, true);
}
setDisplayOrientation();
}
// Show the toast after getting the first orientation changed.
if (mHandler.hasMessages(SHOW_TAP_TO_FOCUS_TOAST)) {
mHandler.removeMessages(SHOW_TAP_TO_FOCUS_TOAST);
showTapToFocusToast();
}
}
@Override
public void onStop() {
if (mMediaProviderClient != null) {
mMediaProviderClient.release();
mMediaProviderClient = null;
}
}
// onClick handler for R.id.btn_retake
@OnClickAttr
public void onReviewRetakeClicked(View v) {
if (mPaused) return;
hidePostCaptureAlert();
setupPreview();
}
// onClick handler for R.id.btn_done
@OnClickAttr
public void onReviewDoneClicked(View v) {
doAttach();
}
// onClick handler for R.id.btn_cancel
@OnClickAttr
public void onReviewCancelClicked(View v) {
doCancel();
}
private void doAttach() {
if (mPaused) {
return;
}
byte[] data = mJpegImageData;
if (mCropValue == null) {
// First handle the no crop case -- just return the value. If the
// caller specifies a "save uri" then write the data to its
// stream. Otherwise, pass back a scaled down version of the bitmap
// directly in the extras.
if (mSaveUri != null) {
OutputStream outputStream = null;
try {
outputStream = mContentResolver.openOutputStream(mSaveUri);
outputStream.write(data);
outputStream.close();
mActivity.setResultEx(Activity.RESULT_OK);
mActivity.finish();
} catch (IOException ex) {
// ignore exception
} finally {
Util.closeSilently(outputStream);
}
} else {
int orientation = Exif.getOrientation(data);
Bitmap bitmap = Util.makeBitmap(data, 50 * 1024);
bitmap = Util.rotate(bitmap, orientation);
mActivity.setResultEx(Activity.RESULT_OK,
new Intent("inline-data").putExtra("data", bitmap));
mActivity.finish();
}
} else {
// Save the image to a temp file and invoke the cropper
Uri tempUri = null;
FileOutputStream tempStream = null;
try {
File path = mActivity.getFileStreamPath(sTempCropFilename);
path.delete();
tempStream = mActivity.openFileOutput(sTempCropFilename, 0);
tempStream.write(data);
tempStream.close();
tempUri = Uri.fromFile(path);
} catch (FileNotFoundException ex) {
mActivity.setResultEx(Activity.RESULT_CANCELED);
mActivity.finish();
return;
} catch (IOException ex) {
mActivity.setResultEx(Activity.RESULT_CANCELED);
mActivity.finish();
return;
} finally {
Util.closeSilently(tempStream);
}
Bundle newExtras = new Bundle();
if (mCropValue.equals("circle")) {
newExtras.putString("circleCrop", "true");
}
if (mSaveUri != null) {
newExtras.putParcelable(MediaStore.EXTRA_OUTPUT, mSaveUri);
} else {
newExtras.putBoolean("return-data", true);
}
if (mActivity.isSecureCamera()) {
newExtras.putBoolean(CropImage.KEY_SHOW_WHEN_LOCKED, true);
}
Intent cropIntent = new Intent("com.android.camera.action.CROP");
cropIntent.setData(tempUri);
cropIntent.putExtras(newExtras);
mActivity.startActivityForResult(cropIntent, REQUEST_CROP);
}
}
private void doCancel() {
mActivity.setResultEx(Activity.RESULT_CANCELED, new Intent());
mActivity.finish();
}
@Override
public void onShutterButtonFocus(boolean pressed) {
if (mPaused || collapseCameraControls()
|| (mCameraState == SNAPSHOT_IN_PROGRESS)
|| (mCameraState == PREVIEW_STOPPED)) return;
// Do not do focus if there is not enough storage.
if (pressed && !canTakePicture()) return;
if (pressed) {
mFocusManager.onShutterDown();
} else {
mFocusManager.onShutterUp();
}
}
@Override
public void onShutterButtonClick() {
if (mPaused || collapseCameraControls()
|| (mCameraState == SWITCHING_CAMERA)
|| (mCameraState == PREVIEW_STOPPED)) return;
// Do not take the picture if there is not enough storage.
if (mActivity.getStorageSpace() <= Storage.LOW_STORAGE_THRESHOLD) {
Log.i(TAG, "Not enough space or storage not ready. remaining="
+ mActivity.getStorageSpace());
return;
}
Log.v(TAG, "onShutterButtonClick: mCameraState=" + mCameraState);
// If the user wants to do a snapshot while the previous one is still
// in progress, remember the fact and do it after we finish the previous
// one and re-start the preview. Snapshot in progress also includes the
// state that autofocus is focusing and a picture will be taken when
// focus callback arrives.
if ((mFocusManager.isFocusingSnapOnFinish() || mCameraState == SNAPSHOT_IN_PROGRESS)
&& !mIsImageCaptureIntent) {
mSnapshotOnIdle = true;
return;
}
mSnapshotOnIdle = false;
mFocusManager.doSnap();
}
@Override
public void installIntentFilter() {
}
@Override
public boolean updateStorageHintOnResume() {
return mFirstTimeInitialized;
}
@Override
public void updateCameraAppView() {
}
@Override
public void onResumeBeforeSuper() {
mPaused = false;
}
@Override
public void onResumeAfterSuper() {
if (mOpenCameraFail || mCameraDisabled) return;
mJpegPictureCallbackTime = 0;
mZoomValue = 0;
// Start the preview if it is not started.
if (mCameraState == PREVIEW_STOPPED && mCameraStartUpThread == null) {
resetExposureCompensation();
mCameraStartUpThread = new CameraStartUpThread();
mCameraStartUpThread.start();
}
// If first time initialization is not finished, put it in the
// message queue.
if (!mFirstTimeInitialized) {
mHandler.sendEmptyMessage(FIRST_TIME_INIT);
} else {
initializeSecondTime();
}
keepScreenOnAwhile();
// Dismiss open menu if exists.
PopupManager.getInstance(mActivity).notifyShowPopup(null);
}
void waitCameraStartUpThread() {
try {
if (mCameraStartUpThread != null) {
mCameraStartUpThread.cancel();
mCameraStartUpThread.join();
mCameraStartUpThread = null;
setCameraState(IDLE);
}
} catch (InterruptedException e) {
// ignore
}
}
@Override
public void onPauseBeforeSuper() {
mPaused = true;
}
@Override
public void onPauseAfterSuper() {
// Wait the camera start up thread to finish.
waitCameraStartUpThread();
// When camera is started from secure lock screen for the first time
// after screen on, the activity gets onCreate->onResume->onPause->onResume.
// To reduce the latency, keep the camera for a short time so it does
// not need to be opened again.
if (mCameraDevice != null && mActivity.isSecureCamera()
&& ActivityBase.isFirstStartAfterScreenOn()) {
ActivityBase.resetFirstStartAfterScreenOn();
CameraHolder.instance().keep(KEEP_CAMERA_TIMEOUT);
}
+ // Reset the focus first. Camera CTS does not guarantee that
+ // cancelAutoFocus is allowed after preview stops.
+ if (mCameraDevice != null && mCameraState != PREVIEW_STOPPED) {
+ mCameraDevice.cancelAutoFocus();
+ }
stopPreview();
// Close the camera now because other activities may need to use it.
closeCamera();
if (mSurfaceTexture != null) {
((CameraScreenNail) mActivity.mCameraScreenNail).releaseSurfaceTexture();
mSurfaceTexture = null;
}
resetScreenOn();
// Clear UI.
collapseCameraControls();
if (mFaceView != null) mFaceView.clear();
if (mFirstTimeInitialized) {
if (mImageSaver != null) {
mImageSaver.finish();
mImageSaver = null;
mImageNamer.finish();
mImageNamer = null;
}
}
if (mLocationManager != null) mLocationManager.recordLocation(false);
updateExposureOnScreenIndicator(0);
// If we are in an image capture intent and has taken
// a picture, we just clear it in onPause.
mJpegImageData = null;
// Remove the messages in the event queue.
mHandler.removeMessages(SETUP_PREVIEW);
mHandler.removeMessages(FIRST_TIME_INIT);
mHandler.removeMessages(CHECK_DISPLAY_ROTATION);
mHandler.removeMessages(SWITCH_CAMERA);
mHandler.removeMessages(SWITCH_CAMERA_START_ANIMATION);
mHandler.removeMessages(CAMERA_OPEN_DONE);
mHandler.removeMessages(START_PREVIEW_DONE);
mHandler.removeMessages(OPEN_CAMERA_FAIL);
mHandler.removeMessages(CAMERA_DISABLED);
mPendingSwitchCameraId = -1;
if (mFocusManager != null) mFocusManager.removeMessages();
}
private void initializeControlByIntent() {
mBlocker = mRootView.findViewById(R.id.blocker);
mMenu = mRootView.findViewById(R.id.menu);
mMenu.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (mPieRenderer != null) {
mPieRenderer.showInCenter();
}
}
});
if (mIsImageCaptureIntent) {
mActivity.hideSwitcher();
// Cannot use RotateImageView for "done" and "cancel" button because
// the tablet layout uses RotateLayout, which cannot be cast to
// RotateImageView.
mReviewDoneButton = (Rotatable) mRootView.findViewById(R.id.btn_done);
mReviewCancelButton = (Rotatable) mRootView.findViewById(R.id.btn_cancel);
((View) mReviewCancelButton).setVisibility(View.VISIBLE);
((View) mReviewDoneButton).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
onReviewDoneClicked(v);
}
});
((View) mReviewCancelButton).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
onReviewCancelClicked(v);
}
});
// Not grayed out upon disabled, to make the follow-up fade-out
// effect look smooth. Note that the review done button in tablet
// layout is not a TwoStateImageView.
if (mReviewDoneButton instanceof TwoStateImageView) {
((TwoStateImageView) mReviewDoneButton).enableFilter(false);
}
setupCaptureParams();
}
}
/**
* The focus manager is the first UI related element to get initialized,
* and it requires the RenderOverlay, so initialize it here
*/
private void initializeFocusManager() {
// Create FocusManager object. startPreview needs it.
mRenderOverlay = (RenderOverlay) mRootView.findViewById(R.id.render_overlay);
// if mFocusManager not null, reuse it
// otherwise create a new instance
if (mFocusManager != null) {
mFocusManager.removeMessages();
} else {
CameraInfo info = CameraHolder.instance().getCameraInfo()[mCameraId];
boolean mirror = (info.facing == CameraInfo.CAMERA_FACING_FRONT);
String[] defaultFocusModes = mActivity.getResources().getStringArray(
R.array.pref_camera_focusmode_default_array);
mFocusManager = new FocusOverlayManager(mPreferences, defaultFocusModes,
mInitialParams, this, mirror,
mActivity.getMainLooper());
}
}
private void initializeMiscControls() {
// startPreview needs this.
mPreviewFrameLayout = (PreviewFrameLayout) mRootView.findViewById(R.id.frame);
// Set touch focus listener.
mActivity.setSingleTapUpListener(mPreviewFrameLayout);
mFaceView = (FaceView) mRootView.findViewById(R.id.face_view);
mPreviewFrameLayout.setOnSizeChangedListener(this);
mPreviewFrameLayout.setOnLayoutChangeListener(mActivity);
if (!ApiHelper.HAS_SURFACE_TEXTURE) {
mPreviewSurfaceView =
(PreviewSurfaceView) mRootView.findViewById(R.id.preview_surface_view);
mPreviewSurfaceView.setVisibility(View.VISIBLE);
mPreviewSurfaceView.getHolder().addCallback(this);
}
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
Log.v(TAG, "onConfigurationChanged");
setDisplayOrientation();
((ViewGroup) mRootView).removeAllViews();
LayoutInflater inflater = mActivity.getLayoutInflater();
inflater.inflate(R.layout.photo_module, (ViewGroup) mRootView);
// from onCreate()
initializeControlByIntent();
initializeFocusManager();
initializeMiscControls();
loadCameraPreferences();
// from initializeFirstTime()
mShutterButton = mActivity.getShutterButton();
mShutterButton.setOnShutterButtonListener(this);
initializeZoom();
initOnScreenIndicator();
updateOnScreenIndicators();
if (mFaceView != null) {
mFaceView.clear();
mFaceView.setVisibility(View.VISIBLE);
mFaceView.setDisplayOrientation(mDisplayOrientation);
CameraInfo info = CameraHolder.instance().getCameraInfo()[mCameraId];
mFaceView.setMirror(info.facing == CameraInfo.CAMERA_FACING_FRONT);
mFaceView.resume();
mFocusManager.setFaceView(mFaceView);
}
initializeRenderOverlay();
onFullScreenChanged(mActivity.isInCameraApp());
if (mJpegImageData != null) { // Jpeg data found, picture has been taken.
showPostCaptureAlert();
}
}
@Override
public void onActivityResult(
int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_CROP: {
Intent intent = new Intent();
if (data != null) {
Bundle extras = data.getExtras();
if (extras != null) {
intent.putExtras(extras);
}
}
mActivity.setResultEx(resultCode, intent);
mActivity.finish();
File path = mActivity.getFileStreamPath(sTempCropFilename);
path.delete();
break;
}
}
}
private boolean canTakePicture() {
return isCameraIdle() && (mActivity.getStorageSpace() > Storage.LOW_STORAGE_THRESHOLD);
}
@Override
public void autoFocus() {
mFocusStartTime = System.currentTimeMillis();
mCameraDevice.autoFocus(mAutoFocusCallback);
setCameraState(FOCUSING);
}
@Override
public void cancelAutoFocus() {
mCameraDevice.cancelAutoFocus();
setCameraState(IDLE);
setCameraParameters(UPDATE_PARAM_PREFERENCE);
}
// Preview area is touched. Handle touch focus.
@Override
public void onSingleTapUp(View view, int x, int y) {
if (mPaused || mCameraDevice == null || !mFirstTimeInitialized
|| mCameraState == SNAPSHOT_IN_PROGRESS
|| mCameraState == SWITCHING_CAMERA
|| mCameraState == PREVIEW_STOPPED) {
return;
}
// Do not trigger touch focus if popup window is opened.
if (removeTopLevelPopup()) return;
// Check if metering area or focus area is supported.
if (!mFocusAreaSupported && !mMeteringAreaSupported) {
if (mPieRenderer != null) {
mPieRenderer.setFocus(x, y, true);
}
} else {
mFocusManager.onSingleTapUp(x, y);
}
}
@Override
public boolean onBackPressed() {
if (mPieRenderer != null && mPieRenderer.showsItems()) {
mPieRenderer.hide();
return true;
}
// In image capture mode, back button should:
// 1) if there is any popup, dismiss them, 2) otherwise, get out of image capture
if (mIsImageCaptureIntent) {
if (!removeTopLevelPopup()) {
// no popup to dismiss, cancel image capture
doCancel();
}
return true;
} else if (!isCameraIdle()) {
// ignore backs while we're taking a picture
return true;
} else {
return removeTopLevelPopup();
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_FOCUS:
if (mFirstTimeInitialized && event.getRepeatCount() == 0) {
onShutterButtonFocus(true);
}
return true;
case KeyEvent.KEYCODE_CAMERA:
if (mFirstTimeInitialized && event.getRepeatCount() == 0) {
onShutterButtonClick();
}
return true;
case KeyEvent.KEYCODE_DPAD_CENTER:
// If we get a dpad center event without any focused view, move
// the focus to the shutter button and press it.
if (mFirstTimeInitialized && event.getRepeatCount() == 0) {
// Start auto-focus immediately to reduce shutter lag. After
// the shutter button gets the focus, onShutterButtonFocus()
// will be called again but it is fine.
if (removeTopLevelPopup()) return true;
onShutterButtonFocus(true);
if (mShutterButton.isInTouchMode()) {
mShutterButton.requestFocusFromTouch();
} else {
mShutterButton.requestFocus();
}
mShutterButton.setPressed(true);
}
return true;
}
return false;
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_FOCUS:
if (mFirstTimeInitialized) {
onShutterButtonFocus(false);
}
return true;
}
return false;
}
@TargetApi(ApiHelper.VERSION_CODES.ICE_CREAM_SANDWICH)
private void closeCamera() {
if (mCameraDevice != null) {
mCameraDevice.setZoomChangeListener(null);
if(ApiHelper.HAS_FACE_DETECTION) {
mCameraDevice.setFaceDetectionListener(null);
}
mCameraDevice.setErrorCallback(null);
CameraHolder.instance().release();
mFaceDetectionStarted = false;
mCameraDevice = null;
setCameraState(PREVIEW_STOPPED);
mFocusManager.onCameraReleased();
}
}
private void setDisplayOrientation() {
mDisplayRotation = Util.getDisplayRotation(mActivity);
mDisplayOrientation = Util.getDisplayOrientation(mDisplayRotation, mCameraId);
mCameraDisplayOrientation = Util.getDisplayOrientation(0, mCameraId);
if (mFaceView != null) {
mFaceView.setDisplayOrientation(mDisplayOrientation);
}
if (mFocusManager != null) {
mFocusManager.setDisplayOrientation(mDisplayOrientation);
}
// GLRoot also uses the DisplayRotation, and needs to be told to layout to update
mActivity.getGLRoot().requestLayoutContentPane();
}
// Only called by UI thread.
private void setupPreview() {
mFocusManager.resetTouchFocus();
startPreview();
setCameraState(IDLE);
startFaceDetection();
}
// This can be called by UI Thread or CameraStartUpThread. So this should
// not modify the views.
private void startPreview() {
mCameraDevice.setErrorCallback(mErrorCallback);
- // If we're previewing already, stop the preview first (this will blank
- // the screen).
+ // ICS camera frameworks has a bug. Face detection state is not cleared
+ // after taking a picture. Stop the preview to work around it. The bug
+ // was fixed in JB.
if (mCameraState != PREVIEW_STOPPED) stopPreview();
setDisplayOrientation();
if (!mSnapshotOnIdle) {
// If the focus mode is continuous autofocus, call cancelAutoFocus to
// resume it because it may have been paused by autoFocus call.
if (Util.FOCUS_MODE_CONTINUOUS_PICTURE.equals(mFocusManager.getFocusMode())) {
mCameraDevice.cancelAutoFocus();
}
mFocusManager.setAeAwbLock(false); // Unlock AE and AWB.
}
setCameraParameters(UPDATE_PARAM_ALL);
if (ApiHelper.HAS_SURFACE_TEXTURE) {
CameraScreenNail screenNail = (CameraScreenNail) mActivity.mCameraScreenNail;
if (mSurfaceTexture == null) {
Size size = mParameters.getPreviewSize();
if (mCameraDisplayOrientation % 180 == 0) {
screenNail.setSize(size.width, size.height);
} else {
screenNail.setSize(size.height, size.width);
}
mActivity.notifyScreenNailChanged();
screenNail.acquireSurfaceTexture();
mSurfaceTexture = screenNail.getSurfaceTexture();
}
mCameraDevice.setDisplayOrientation(mCameraDisplayOrientation);
mCameraDevice.setPreviewTextureAsync((SurfaceTexture) mSurfaceTexture);
} else {
mCameraDevice.setDisplayOrientation(mDisplayOrientation);
mCameraDevice.setPreviewDisplayAsync(mCameraSurfaceHolder);
}
Log.v(TAG, "startPreview");
mCameraDevice.startPreviewAsync();
mFocusManager.onPreviewStarted();
if (mSnapshotOnIdle) {
mHandler.post(mDoSnapRunnable);
}
}
private void stopPreview() {
if (mCameraDevice != null && mCameraState != PREVIEW_STOPPED) {
Log.v(TAG, "stopPreview");
- mCameraDevice.cancelAutoFocus(); // Reset the focus.
mCameraDevice.stopPreview();
mFaceDetectionStarted = false;
}
setCameraState(PREVIEW_STOPPED);
if (mFocusManager != null) mFocusManager.onPreviewStopped();
}
@SuppressWarnings("deprecation")
private void updateCameraParametersInitialize() {
// Reset preview frame rate to the maximum because it may be lowered by
// video camera application.
List<Integer> frameRates = mParameters.getSupportedPreviewFrameRates();
if (frameRates != null) {
Integer max = Collections.max(frameRates);
mParameters.setPreviewFrameRate(max);
}
mParameters.set(Util.RECORDING_HINT, Util.FALSE);
// Disable video stabilization. Convenience methods not available in API
// level <= 14
String vstabSupported = mParameters.get("video-stabilization-supported");
if ("true".equals(vstabSupported)) {
mParameters.set("video-stabilization", "false");
}
}
private void updateCameraParametersZoom() {
// Set zoom.
if (mParameters.isZoomSupported()) {
mParameters.setZoom(mZoomValue);
}
}
@TargetApi(ApiHelper.VERSION_CODES.JELLY_BEAN)
private void setAutoExposureLockIfSupported() {
if (mAeLockSupported) {
mParameters.setAutoExposureLock(mFocusManager.getAeAwbLock());
}
}
@TargetApi(ApiHelper.VERSION_CODES.JELLY_BEAN)
private void setAutoWhiteBalanceLockIfSupported() {
if (mAwbLockSupported) {
mParameters.setAutoWhiteBalanceLock(mFocusManager.getAeAwbLock());
}
}
@TargetApi(ApiHelper.VERSION_CODES.ICE_CREAM_SANDWICH)
private void setFocusAreasIfSupported() {
if (mFocusAreaSupported) {
mParameters.setFocusAreas(mFocusManager.getFocusAreas());
}
}
@TargetApi(ApiHelper.VERSION_CODES.ICE_CREAM_SANDWICH)
private void setMeteringAreasIfSupported() {
if (mMeteringAreaSupported) {
// Use the same area for focus and metering.
mParameters.setMeteringAreas(mFocusManager.getMeteringAreas());
}
}
private void updateCameraParametersPreference() {
setAutoExposureLockIfSupported();
setAutoWhiteBalanceLockIfSupported();
setFocusAreasIfSupported();
setMeteringAreasIfSupported();
// Set picture size.
String pictureSize = mPreferences.getString(
CameraSettings.KEY_PICTURE_SIZE, null);
if (pictureSize == null) {
CameraSettings.initialCameraPictureSize(mActivity, mParameters);
} else {
List<Size> supported = mParameters.getSupportedPictureSizes();
CameraSettings.setCameraPictureSize(
pictureSize, supported, mParameters);
}
Size size = mParameters.getPictureSize();
// Set a preview size that is closest to the viewfinder height and has
// the right aspect ratio.
List<Size> sizes = mParameters.getSupportedPreviewSizes();
Size optimalSize = Util.getOptimalPreviewSize(mActivity, sizes,
(double) size.width / size.height);
Size original = mParameters.getPreviewSize();
if (!original.equals(optimalSize)) {
mParameters.setPreviewSize(optimalSize.width, optimalSize.height);
// Zoom related settings will be changed for different preview
// sizes, so set and read the parameters to get latest values
mCameraDevice.setParameters(mParameters);
mParameters = mCameraDevice.getParameters();
}
Log.v(TAG, "Preview size is " + optimalSize.width + "x" + optimalSize.height);
// Since changing scene mode may change supported values, set scene mode
// first. HDR is a scene mode. To promote it in UI, it is stored in a
// separate preference.
String hdr = mPreferences.getString(CameraSettings.KEY_CAMERA_HDR,
mActivity.getString(R.string.pref_camera_hdr_default));
if (mActivity.getString(R.string.setting_on_value).equals(hdr)) {
mSceneMode = Util.SCENE_MODE_HDR;
} else {
mSceneMode = mPreferences.getString(
CameraSettings.KEY_SCENE_MODE,
mActivity.getString(R.string.pref_camera_scenemode_default));
}
if (Util.isSupported(mSceneMode, mParameters.getSupportedSceneModes())) {
if (!mParameters.getSceneMode().equals(mSceneMode)) {
mParameters.setSceneMode(mSceneMode);
// Setting scene mode will change the settings of flash mode,
// white balance, and focus mode. Here we read back the
// parameters, so we can know those settings.
mCameraDevice.setParameters(mParameters);
mParameters = mCameraDevice.getParameters();
}
} else {
mSceneMode = mParameters.getSceneMode();
if (mSceneMode == null) {
mSceneMode = Parameters.SCENE_MODE_AUTO;
}
}
// Set JPEG quality.
int jpegQuality = CameraProfile.getJpegEncodingQualityParameter(mCameraId,
CameraProfile.QUALITY_HIGH);
mParameters.setJpegQuality(jpegQuality);
// For the following settings, we need to check if the settings are
// still supported by latest driver, if not, ignore the settings.
// Set exposure compensation
int value = CameraSettings.readExposure(mPreferences);
int max = mParameters.getMaxExposureCompensation();
int min = mParameters.getMinExposureCompensation();
if (value >= min && value <= max) {
mParameters.setExposureCompensation(value);
} else {
Log.w(TAG, "invalid exposure range: " + value);
}
if (Parameters.SCENE_MODE_AUTO.equals(mSceneMode)) {
// Set flash mode.
String flashMode = mPreferences.getString(
CameraSettings.KEY_FLASH_MODE,
mActivity.getString(R.string.pref_camera_flashmode_default));
List<String> supportedFlash = mParameters.getSupportedFlashModes();
if (Util.isSupported(flashMode, supportedFlash)) {
mParameters.setFlashMode(flashMode);
} else {
flashMode = mParameters.getFlashMode();
if (flashMode == null) {
flashMode = mActivity.getString(
R.string.pref_camera_flashmode_no_flash);
}
}
// Set white balance parameter.
String whiteBalance = mPreferences.getString(
CameraSettings.KEY_WHITE_BALANCE,
mActivity.getString(R.string.pref_camera_whitebalance_default));
if (Util.isSupported(whiteBalance,
mParameters.getSupportedWhiteBalance())) {
mParameters.setWhiteBalance(whiteBalance);
} else {
whiteBalance = mParameters.getWhiteBalance();
if (whiteBalance == null) {
whiteBalance = Parameters.WHITE_BALANCE_AUTO;
}
}
// Set focus mode.
mFocusManager.overrideFocusMode(null);
mParameters.setFocusMode(mFocusManager.getFocusMode());
} else {
mFocusManager.overrideFocusMode(mParameters.getFocusMode());
}
if (mContinousFocusSupported && ApiHelper.HAS_AUTO_FOCUS_MOVE_CALLBACK) {
updateAutoFocusMoveCallback();
}
}
@TargetApi(ApiHelper.VERSION_CODES.JELLY_BEAN)
private void updateAutoFocusMoveCallback() {
if (mParameters.getFocusMode().equals(Util.FOCUS_MODE_CONTINUOUS_PICTURE)) {
mCameraDevice.setAutoFocusMoveCallback(
(AutoFocusMoveCallback) mAutoFocusMoveCallback);
} else {
mCameraDevice.setAutoFocusMoveCallback(null);
}
}
// We separate the parameters into several subsets, so we can update only
// the subsets actually need updating. The PREFERENCE set needs extra
// locking because the preference can be changed from GLThread as well.
private void setCameraParameters(int updateSet) {
if ((updateSet & UPDATE_PARAM_INITIALIZE) != 0) {
updateCameraParametersInitialize();
}
if ((updateSet & UPDATE_PARAM_ZOOM) != 0) {
updateCameraParametersZoom();
}
if ((updateSet & UPDATE_PARAM_PREFERENCE) != 0) {
updateCameraParametersPreference();
}
mCameraDevice.setParameters(mParameters);
}
// If the Camera is idle, update the parameters immediately, otherwise
// accumulate them in mUpdateSet and update later.
private void setCameraParametersWhenIdle(int additionalUpdateSet) {
mUpdateSet |= additionalUpdateSet;
if (mCameraDevice == null) {
// We will update all the parameters when we open the device, so
// we don't need to do anything now.
mUpdateSet = 0;
return;
} else if (isCameraIdle()) {
setCameraParameters(mUpdateSet);
updateSceneModeUI();
mUpdateSet = 0;
} else {
if (!mHandler.hasMessages(SET_CAMERA_PARAMETERS_WHEN_IDLE)) {
mHandler.sendEmptyMessageDelayed(
SET_CAMERA_PARAMETERS_WHEN_IDLE, 1000);
}
}
}
private boolean isCameraIdle() {
return (mCameraState == IDLE) ||
((mFocusManager != null) && mFocusManager.isFocusCompleted()
&& (mCameraState != SWITCHING_CAMERA));
}
private boolean isImageCaptureIntent() {
String action = mActivity.getIntent().getAction();
return (MediaStore.ACTION_IMAGE_CAPTURE.equals(action)
|| ActivityBase.ACTION_IMAGE_CAPTURE_SECURE.equals(action));
}
private void setupCaptureParams() {
Bundle myExtras = mActivity.getIntent().getExtras();
if (myExtras != null) {
mSaveUri = (Uri) myExtras.getParcelable(MediaStore.EXTRA_OUTPUT);
mCropValue = myExtras.getString("crop");
}
}
private void showPostCaptureAlert() {
if (mIsImageCaptureIntent) {
Util.fadeOut(mShutterButton);
mOnScreenIndicators.setVisibility(View.GONE);
mMenu.setVisibility(View.GONE);
// Util.fadeIn(mReviewRetakeButton);
Util.fadeIn((View) mReviewDoneButton);
}
}
private void hidePostCaptureAlert() {
if (mIsImageCaptureIntent) {
mOnScreenIndicators.setVisibility(View.VISIBLE);
mMenu.setVisibility(View.VISIBLE);
// Util.fadeOut(mReviewRetakeButton);
Util.fadeOut((View) mReviewDoneButton);
Util.fadeIn(mShutterButton);
}
}
@Override
public void onSharedPreferenceChanged() {
// ignore the events after "onPause()"
if (mPaused) return;
boolean recordLocation = RecordLocationPreference.get(
mPreferences, mContentResolver);
mLocationManager.recordLocation(recordLocation);
setCameraParametersWhenIdle(UPDATE_PARAM_PREFERENCE);
setPreviewFrameLayoutAspectRatio();
updateOnScreenIndicators();
}
@Override
public void onCameraPickerClicked(int cameraId) {
if (mPaused || mPendingSwitchCameraId != -1) return;
mPendingSwitchCameraId = cameraId;
if (ApiHelper.HAS_SURFACE_TEXTURE) {
Log.v(TAG, "Start to copy texture. cameraId=" + cameraId);
// We need to keep a preview frame for the animation before
// releasing the camera. This will trigger onPreviewTextureCopied.
((CameraScreenNail) mActivity.mCameraScreenNail).copyTexture();
// Disable all camera controls.
setCameraState(SWITCHING_CAMERA);
} else {
switchCamera();
}
}
private void switchCamera() {
if (mPaused) return;
Log.v(TAG, "Start to switch camera. id=" + mPendingSwitchCameraId);
mCameraId = mPendingSwitchCameraId;
mPendingSwitchCameraId = -1;
mPhotoControl.setCameraId(mCameraId);
// from onPause
closeCamera();
collapseCameraControls();
if (mFaceView != null) mFaceView.clear();
if (mFocusManager != null) mFocusManager.removeMessages();
// Restart the camera and initialize the UI. From onCreate.
mPreferences.setLocalId(mActivity, mCameraId);
CameraSettings.upgradeLocalPreferences(mPreferences.getLocal());
try {
mCameraDevice = Util.openCamera(mActivity, mCameraId);
mParameters = mCameraDevice.getParameters();
} catch (CameraHardwareException e) {
Util.showErrorAndFinish(mActivity, R.string.cannot_connect_camera);
return;
} catch (CameraDisabledException e) {
Util.showErrorAndFinish(mActivity, R.string.camera_disabled);
return;
}
initializeCapabilities();
CameraInfo info = CameraHolder.instance().getCameraInfo()[mCameraId];
boolean mirror = (info.facing == CameraInfo.CAMERA_FACING_FRONT);
mFocusManager.setMirror(mirror);
mFocusManager.setParameters(mInitialParams);
setupPreview();
loadCameraPreferences();
initializePhotoControl();
// from initializeFirstTime
initializeZoom();
updateOnScreenIndicators();
showTapToFocusToastIfNeeded();
if (ApiHelper.HAS_SURFACE_TEXTURE) {
// Start switch camera animation. Post a message because
// onFrameAvailable from the old camera may already exist.
mHandler.sendEmptyMessage(SWITCH_CAMERA_START_ANIMATION);
}
}
@Override
public void onPieOpened(int centerX, int centerY) {
mActivity.cancelActivityTouchHandling();
mActivity.setSwipingEnabled(false);
if (mFaceView != null) {
mFaceView.setBlockDraw(true);
}
}
@Override
public void onPieClosed() {
mActivity.setSwipingEnabled(true);
if (mFaceView != null) {
mFaceView.setBlockDraw(false);
}
}
// Preview texture has been copied. Now camera can be released and the
// animation can be started.
@Override
public void onPreviewTextureCopied() {
mHandler.sendEmptyMessage(SWITCH_CAMERA);
}
@Override
public void onCaptureTextureCopied() {
}
@Override
public void onUserInteraction() {
if (!mActivity.isFinishing()) keepScreenOnAwhile();
}
private void resetScreenOn() {
mHandler.removeMessages(CLEAR_SCREEN_DELAY);
mActivity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
private void keepScreenOnAwhile() {
mHandler.removeMessages(CLEAR_SCREEN_DELAY);
mActivity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
mHandler.sendEmptyMessageDelayed(CLEAR_SCREEN_DELAY, SCREEN_DELAY);
}
// TODO: Delete this function after old camera code is removed
@Override
public void onRestorePreferencesClicked() {
}
@Override
public void onOverriddenPreferencesClicked() {
if (mPaused) return;
if (mNotSelectableToast == null) {
String str = mActivity.getResources().getString(R.string.not_selectable_in_scene_mode);
mNotSelectableToast = Toast.makeText(mActivity, str, Toast.LENGTH_SHORT);
}
mNotSelectableToast.show();
}
private void showTapToFocusToast() {
new RotateTextToast(mActivity, R.string.tap_to_focus, mOrientationCompensation).show();
// Clear the preference.
Editor editor = mPreferences.edit();
editor.putBoolean(CameraSettings.KEY_CAMERA_FIRST_USE_HINT_SHOWN, false);
editor.apply();
}
private void initializeCapabilities() {
mInitialParams = mCameraDevice.getParameters();
mFocusAreaSupported = Util.isFocusAreaSupported(mInitialParams);
mMeteringAreaSupported = Util.isMeteringAreaSupported(mInitialParams);
mAeLockSupported = Util.isAutoExposureLockSupported(mInitialParams);
mAwbLockSupported = Util.isAutoWhiteBalanceLockSupported(mInitialParams);
mContinousFocusSupported = mInitialParams.getSupportedFocusModes().contains(
Util.FOCUS_MODE_CONTINUOUS_PICTURE);
}
// PreviewFrameLayout size has changed.
@Override
public void onSizeChanged(int width, int height) {
if (mFocusManager != null) mFocusManager.setPreviewSize(width, height);
}
void setPreviewFrameLayoutAspectRatio() {
// Set the preview frame aspect ratio according to the picture size.
Size size = mParameters.getPictureSize();
mPreviewFrameLayout.setAspectRatio((double) size.width / size.height);
}
@Override
public boolean needsSwitcher() {
return !mIsImageCaptureIntent;
}
public void showPopup(AbstractSettingPopup popup) {
mActivity.hideUI();
mPopup = popup;
// Make sure popup is brought up with the right orientation
mPopup.setOrientation(mOrientationCompensation, false);
mPopup.setVisibility(View.VISIBLE);
FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
lp.gravity = Gravity.CENTER;
((FrameLayout) mRootView).addView(mPopup, lp);
}
public void dismissPopup(boolean topPopupOnly) {
dismissPopup(topPopupOnly, false);
}
private void dismissPopup(boolean topOnly, boolean fullScreen) {
if (!fullScreen) {
mActivity.showUI();
}
if (mPopup != null) {
((FrameLayout) mRootView).removeView(mPopup);
mPopup = null;
}
mPhotoControl.popupDismissed(topOnly);
}
@Override
public void onShowSwitcherPopup() {
if (mPieRenderer.showsItems()) {
mPieRenderer.hide();
}
}
}
| false | false | null | null |
diff --git a/activemq-core/src/main/java/org/apache/activemq/store/jdbc/JDBCIOExceptionHandler.java b/activemq-core/src/main/java/org/apache/activemq/store/jdbc/JDBCIOExceptionHandler.java
index a1e12a108..b6ba1a6ec 100644
--- a/activemq-core/src/main/java/org/apache/activemq/store/jdbc/JDBCIOExceptionHandler.java
+++ b/activemq-core/src/main/java/org/apache/activemq/store/jdbc/JDBCIOExceptionHandler.java
@@ -1,56 +1,56 @@
/**
* 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.store.jdbc;
import java.io.IOException;
import org.apache.activemq.broker.Locker;
import org.apache.activemq.util.DefaultIOExceptionHandler;
/**
* @org.apache.xbean.XBean
*/
public class JDBCIOExceptionHandler extends DefaultIOExceptionHandler {
public JDBCIOExceptionHandler() {
setIgnoreSQLExceptions(false);
setStopStartConnectors(true);
}
@Override
protected boolean hasLockOwnership() throws IOException {
boolean hasLock = true;
if (broker.getPersistenceAdapter() instanceof JDBCPersistenceAdapter) {
JDBCPersistenceAdapter jdbcPersistenceAdapter = (JDBCPersistenceAdapter) broker.getPersistenceAdapter();
- Locker locker = jdbcPersistenceAdapter.getDatabaseLocker();
+ Locker locker = jdbcPersistenceAdapter.getLocker();
if (locker != null) {
try {
if (!locker.keepAlive()) {
hasLock = false;
}
} catch (IOException ignored) {
}
if (!hasLock) {
throw new IOException("PersistenceAdapter lock no longer valid using: " + locker);
}
}
}
return hasLock;
}
}
diff --git a/activemq-core/src/main/java/org/apache/activemq/store/jdbc/JDBCPersistenceAdapter.java b/activemq-core/src/main/java/org/apache/activemq/store/jdbc/JDBCPersistenceAdapter.java
index d2fb03c7a..b2d9c26ae 100755
--- a/activemq-core/src/main/java/org/apache/activemq/store/jdbc/JDBCPersistenceAdapter.java
+++ b/activemq-core/src/main/java/org/apache/activemq/store/jdbc/JDBCPersistenceAdapter.java
@@ -1,884 +1,884 @@
/**
* 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.store.jdbc;
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Collections;
import java.util.Locale;
import java.util.Set;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import javax.sql.DataSource;
import org.apache.activemq.ActiveMQMessageAudit;
import org.apache.activemq.broker.BrokerService;
import org.apache.activemq.broker.BrokerServiceAware;
import org.apache.activemq.broker.ConnectionContext;
import org.apache.activemq.command.ActiveMQDestination;
import org.apache.activemq.command.ActiveMQQueue;
import org.apache.activemq.command.ActiveMQTopic;
import org.apache.activemq.command.Message;
import org.apache.activemq.command.MessageAck;
import org.apache.activemq.command.MessageId;
import org.apache.activemq.command.ProducerId;
import org.apache.activemq.openwire.OpenWireFormat;
import org.apache.activemq.broker.Locker;
import org.apache.activemq.store.MessageStore;
import org.apache.activemq.store.PersistenceAdapter;
import org.apache.activemq.store.TopicMessageStore;
import org.apache.activemq.store.TransactionStore;
import org.apache.activemq.store.jdbc.adapter.DefaultJDBCAdapter;
import org.apache.activemq.store.memory.MemoryTransactionStore;
import org.apache.activemq.usage.SystemUsage;
import org.apache.activemq.util.ByteSequence;
import org.apache.activemq.util.FactoryFinder;
import org.apache.activemq.util.IOExceptionSupport;
import org.apache.activemq.util.LongSequenceGenerator;
import org.apache.activemq.wireformat.WireFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A {@link PersistenceAdapter} implementation using JDBC for persistence
* storage.
*
* This persistence adapter will correctly remember prepared XA transactions,
* but it will not keep track of local transaction commits so that operations
* performed against the Message store are done as a single uow.
*
* @org.apache.xbean.XBean element="jdbcPersistenceAdapter"
*
*
*/
public class JDBCPersistenceAdapter extends DataSourceSupport implements PersistenceAdapter,
BrokerServiceAware {
private static final Logger LOG = LoggerFactory.getLogger(JDBCPersistenceAdapter.class);
private static FactoryFinder adapterFactoryFinder = new FactoryFinder(
"META-INF/services/org/apache/activemq/store/jdbc/");
private static FactoryFinder lockFactoryFinder = new FactoryFinder(
"META-INF/services/org/apache/activemq/store/jdbc/lock/");
private WireFormat wireFormat = new OpenWireFormat();
private BrokerService brokerService;
private Statements statements;
private JDBCAdapter adapter;
private MemoryTransactionStore transactionStore;
private ScheduledThreadPoolExecutor clockDaemon;
private ScheduledFuture<?> cleanupTicket, keepAliveTicket;
private int cleanupPeriod = 1000 * 60 * 5;
private boolean useExternalMessageReferences;
private boolean useDatabaseLock = true;
private long lockKeepAlivePeriod = 1000*30;
private long lockAcquireSleepInterval = DefaultDatabaseLocker.DEFAULT_LOCK_ACQUIRE_SLEEP_INTERVAL;
private Locker locker;
private boolean createTablesOnStartup = true;
private DataSource lockDataSource;
private int transactionIsolation;
private File directory;
protected int maxProducersToAudit=1024;
protected int maxAuditDepth=1000;
protected boolean enableAudit=false;
protected int auditRecoveryDepth = 1024;
protected ActiveMQMessageAudit audit;
protected LongSequenceGenerator sequenceGenerator = new LongSequenceGenerator();
protected int maxRows = DefaultJDBCAdapter.MAX_ROWS;
public JDBCPersistenceAdapter() {
}
public JDBCPersistenceAdapter(DataSource ds, WireFormat wireFormat) {
super(ds);
this.wireFormat = wireFormat;
}
public Set<ActiveMQDestination> getDestinations() {
TransactionContext c = null;
try {
c = getTransactionContext();
return getAdapter().doGetDestinations(c);
} catch (IOException e) {
return emptyDestinationSet();
} catch (SQLException e) {
JDBCPersistenceAdapter.log("JDBC Failure: ", e);
return emptyDestinationSet();
} finally {
if (c != null) {
try {
c.close();
} catch (Throwable e) {
}
}
}
}
@SuppressWarnings("unchecked")
private Set<ActiveMQDestination> emptyDestinationSet() {
return Collections.EMPTY_SET;
}
protected void createMessageAudit() {
if (enableAudit && audit == null) {
audit = new ActiveMQMessageAudit(maxAuditDepth,maxProducersToAudit);
TransactionContext c = null;
try {
c = getTransactionContext();
getAdapter().doMessageIdScan(c, auditRecoveryDepth, new JDBCMessageIdScanListener() {
public void messageId(MessageId id) {
audit.isDuplicate(id);
}
});
} catch (Exception e) {
LOG.error("Failed to reload store message audit for JDBC persistence adapter", e);
} finally {
if (c != null) {
try {
c.close();
} catch (Throwable e) {
}
}
}
}
}
public void initSequenceIdGenerator() {
TransactionContext c = null;
try {
c = getTransactionContext();
getAdapter().doMessageIdScan(c, auditRecoveryDepth, new JDBCMessageIdScanListener() {
public void messageId(MessageId id) {
audit.isDuplicate(id);
}
});
} catch (Exception e) {
LOG.error("Failed to reload store message audit for JDBC persistence adapter", e);
} finally {
if (c != null) {
try {
c.close();
} catch (Throwable e) {
}
}
}
}
public MessageStore createQueueMessageStore(ActiveMQQueue destination) throws IOException {
MessageStore rc = new JDBCMessageStore(this, getAdapter(), wireFormat, destination, audit);
if (transactionStore != null) {
rc = transactionStore.proxy(rc);
}
return rc;
}
public TopicMessageStore createTopicMessageStore(ActiveMQTopic destination) throws IOException {
TopicMessageStore rc = new JDBCTopicMessageStore(this, getAdapter(), wireFormat, destination, audit);
if (transactionStore != null) {
rc = transactionStore.proxy(rc);
}
return rc;
}
/**
* Cleanup method to remove any state associated with the given destination
* @param destination Destination to forget
*/
public void removeQueueMessageStore(ActiveMQQueue destination) {
if (destination.isQueue() && getBrokerService().shouldRecordVirtualDestination(destination)) {
try {
removeConsumerDestination(destination);
} catch (IOException ioe) {
LOG.error("Failed to remove consumer destination: " + destination, ioe);
}
}
}
private void removeConsumerDestination(ActiveMQQueue destination) throws IOException {
TransactionContext c = getTransactionContext();
try {
String id = destination.getQualifiedName();
getAdapter().doDeleteSubscription(c, destination, id, id);
} catch (SQLException e) {
JDBCPersistenceAdapter.log("JDBC Failure: ", e);
throw IOExceptionSupport.create("Failed to remove consumer destination: " + destination, e);
} finally {
c.close();
}
}
/**
* Cleanup method to remove any state associated with the given destination
* No state retained.... nothing to do
*
* @param destination Destination to forget
*/
public void removeTopicMessageStore(ActiveMQTopic destination) {
}
public TransactionStore createTransactionStore() throws IOException {
if (transactionStore == null) {
transactionStore = new JdbcMemoryTransactionStore(this);
}
return this.transactionStore;
}
public long getLastMessageBrokerSequenceId() throws IOException {
TransactionContext c = getTransactionContext();
try {
long seq = getAdapter().doGetLastMessageStoreSequenceId(c);
sequenceGenerator.setLastSequenceId(seq);
long brokerSeq = 0;
if (seq != 0) {
byte[] msg = getAdapter().doGetMessageById(c, seq);
if (msg != null) {
Message last = (Message)wireFormat.unmarshal(new ByteSequence(msg));
brokerSeq = last.getMessageId().getBrokerSequenceId();
} else {
LOG.warn("Broker sequence id wasn't recovered properly, possible duplicates!");
}
}
return brokerSeq;
} catch (SQLException e) {
JDBCPersistenceAdapter.log("JDBC Failure: ", e);
throw IOExceptionSupport.create("Failed to get last broker message id: " + e, e);
} finally {
c.close();
}
}
public long getLastProducerSequenceId(ProducerId id) throws IOException {
TransactionContext c = getTransactionContext();
try {
return getAdapter().doGetLastProducerSequenceId(c, id);
} catch (SQLException e) {
JDBCPersistenceAdapter.log("JDBC Failure: ", e);
throw IOExceptionSupport.create("Failed to get last broker message id: " + e, e);
} finally {
c.close();
}
}
public void start() throws Exception {
getAdapter().setUseExternalMessageReferences(isUseExternalMessageReferences());
if (isCreateTablesOnStartup()) {
TransactionContext transactionContext = getTransactionContext();
transactionContext.begin();
try {
try {
getAdapter().doCreateTables(transactionContext);
} catch (SQLException e) {
LOG.warn("Cannot create tables due to: " + e);
JDBCPersistenceAdapter.log("Failure Details: ", e);
}
} finally {
transactionContext.commit();
}
}
if (isUseDatabaseLock()) {
- Locker service = getDatabaseLocker();
+ Locker service = getLocker();
if (service == null) {
LOG.warn("No databaseLocker configured for the JDBC Persistence Adapter");
} else {
service.start();
if (lockKeepAlivePeriod > 0) {
keepAliveTicket = getScheduledThreadPoolExecutor().scheduleAtFixedRate(new Runnable() {
public void run() {
databaseLockKeepAlive();
}
}, lockKeepAlivePeriod, lockKeepAlivePeriod, TimeUnit.MILLISECONDS);
}
if (brokerService != null) {
brokerService.getBroker().nowMasterBroker();
}
}
}
// Cleanup the db periodically.
if (cleanupPeriod > 0) {
cleanupTicket = getScheduledThreadPoolExecutor().scheduleWithFixedDelay(new Runnable() {
public void run() {
cleanup();
}
}, 0, cleanupPeriod, TimeUnit.MILLISECONDS);
}
createMessageAudit();
}
public synchronized void stop() throws Exception {
if (cleanupTicket != null) {
cleanupTicket.cancel(true);
cleanupTicket = null;
}
if (keepAliveTicket != null) {
keepAliveTicket.cancel(false);
keepAliveTicket = null;
}
// do not shutdown clockDaemon as it may kill the thread initiating shutdown
Locker service = getDatabaseLocker();
if (service != null) {
service.stop();
}
}
public void cleanup() {
TransactionContext c = null;
try {
LOG.debug("Cleaning up old messages.");
c = getTransactionContext();
getAdapter().doDeleteOldMessages(c);
} catch (IOException e) {
LOG.warn("Old message cleanup failed due to: " + e, e);
} catch (SQLException e) {
LOG.warn("Old message cleanup failed due to: " + e);
JDBCPersistenceAdapter.log("Failure Details: ", e);
} finally {
if (c != null) {
try {
c.close();
} catch (Throwable e) {
}
}
LOG.debug("Cleanup done.");
}
}
public void setScheduledThreadPoolExecutor(ScheduledThreadPoolExecutor clockDaemon) {
this.clockDaemon = clockDaemon;
}
public ScheduledThreadPoolExecutor getScheduledThreadPoolExecutor() {
if (clockDaemon == null) {
clockDaemon = new ScheduledThreadPoolExecutor(5, new ThreadFactory() {
public Thread newThread(Runnable runnable) {
Thread thread = new Thread(runnable, "ActiveMQ Cleanup Timer");
thread.setDaemon(true);
return thread;
}
});
}
return clockDaemon;
}
public JDBCAdapter getAdapter() throws IOException {
if (adapter == null) {
setAdapter(createAdapter());
}
return adapter;
}
/**
*
* @deprecated as of 5.7.0, replaced by {@link #getLocker()}
*/
@Deprecated
public Locker getDatabaseLocker() throws IOException {
return getLocker();
}
public Locker getLocker() throws IOException {
if (locker == null && isUseDatabaseLock()) {
setLocker(loadDataBaseLocker());
}
return locker;
}
/**
* Sets the database locker strategy to use to lock the database on startup
* @throws IOException
*
* @deprecated as of 5.7.0, replaced by {@link #setLocker(org.apache.activemq.broker.Locker)}
*/
public void setDatabaseLocker(Locker locker) throws IOException {
setLocker(locker);
}
/**
* Sets the database locker strategy to use to lock the database on startup
* @throws IOException
*/
public void setLocker(Locker locker) throws IOException {
this.locker = locker;
locker.configure(this);
locker.setLockAcquireSleepInterval(getLockAcquireSleepInterval());
}
public DataSource getLockDataSource() throws IOException {
if (lockDataSource == null) {
lockDataSource = getDataSource();
if (lockDataSource == null) {
throw new IllegalArgumentException(
"No dataSource property has been configured");
}
} else {
LOG.info("Using a separate dataSource for locking: "
+ lockDataSource);
}
return lockDataSource;
}
public void setLockDataSource(DataSource dataSource) {
this.lockDataSource = dataSource;
}
public BrokerService getBrokerService() {
return brokerService;
}
public void setBrokerService(BrokerService brokerService) {
this.brokerService = brokerService;
}
/**
* @throws IOException
*/
protected JDBCAdapter createAdapter() throws IOException {
adapter = (JDBCAdapter) loadAdapter(adapterFactoryFinder, "adapter");
// Use the default JDBC adapter if the
// Database type is not recognized.
if (adapter == null) {
adapter = new DefaultJDBCAdapter();
LOG.debug("Using default JDBC Adapter: " + adapter);
}
return adapter;
}
private Object loadAdapter(FactoryFinder finder, String kind) throws IOException {
Object adapter = null;
TransactionContext c = getTransactionContext();
try {
try {
// Make the filename file system safe.
String dirverName = c.getConnection().getMetaData().getDriverName();
dirverName = dirverName.replaceAll("[^a-zA-Z0-9\\-]", "_").toLowerCase(Locale.ENGLISH);
try {
adapter = finder.newInstance(dirverName);
LOG.info("Database " + kind + " driver override recognized for : [" + dirverName + "] - adapter: " + adapter.getClass());
} catch (Throwable e) {
LOG.info("Database " + kind + " driver override not found for : [" + dirverName
+ "]. Will use default implementation.");
}
} catch (SQLException e) {
LOG.warn("JDBC error occurred while trying to detect database type for overrides. Will use default implementations: "
+ e.getMessage());
JDBCPersistenceAdapter.log("Failure Details: ", e);
}
} finally {
c.close();
}
return adapter;
}
public void setAdapter(JDBCAdapter adapter) {
this.adapter = adapter;
this.adapter.setStatements(getStatements());
this.adapter.setMaxRows(getMaxRows());
}
public WireFormat getWireFormat() {
return wireFormat;
}
public void setWireFormat(WireFormat wireFormat) {
this.wireFormat = wireFormat;
}
public TransactionContext getTransactionContext(ConnectionContext context) throws IOException {
if (context == null) {
return getTransactionContext();
} else {
TransactionContext answer = (TransactionContext)context.getLongTermStoreContext();
if (answer == null) {
answer = getTransactionContext();
context.setLongTermStoreContext(answer);
}
return answer;
}
}
public TransactionContext getTransactionContext() throws IOException {
TransactionContext answer = new TransactionContext(this);
if (transactionIsolation > 0) {
answer.setTransactionIsolation(transactionIsolation);
}
return answer;
}
public void beginTransaction(ConnectionContext context) throws IOException {
TransactionContext transactionContext = getTransactionContext(context);
transactionContext.begin();
}
public void commitTransaction(ConnectionContext context) throws IOException {
TransactionContext transactionContext = getTransactionContext(context);
transactionContext.commit();
}
public void rollbackTransaction(ConnectionContext context) throws IOException {
TransactionContext transactionContext = getTransactionContext(context);
transactionContext.rollback();
}
public int getCleanupPeriod() {
return cleanupPeriod;
}
/**
* Sets the number of milliseconds until the database is attempted to be
* cleaned up for durable topics
*/
public void setCleanupPeriod(int cleanupPeriod) {
this.cleanupPeriod = cleanupPeriod;
}
public void deleteAllMessages() throws IOException {
TransactionContext c = getTransactionContext();
try {
getAdapter().doDropTables(c);
getAdapter().setUseExternalMessageReferences(isUseExternalMessageReferences());
getAdapter().doCreateTables(c);
LOG.info("Persistence store purged.");
} catch (SQLException e) {
JDBCPersistenceAdapter.log("JDBC Failure: ", e);
throw IOExceptionSupport.create(e);
} finally {
c.close();
}
}
public boolean isUseExternalMessageReferences() {
return useExternalMessageReferences;
}
public void setUseExternalMessageReferences(boolean useExternalMessageReferences) {
this.useExternalMessageReferences = useExternalMessageReferences;
}
public boolean isCreateTablesOnStartup() {
return createTablesOnStartup;
}
/**
* Sets whether or not tables are created on startup
*/
public void setCreateTablesOnStartup(boolean createTablesOnStartup) {
this.createTablesOnStartup = createTablesOnStartup;
}
public boolean isUseDatabaseLock() {
return useDatabaseLock;
}
/**
* Sets whether or not an exclusive database lock should be used to enable
* JDBC Master/Slave. Enabled by default.
*/
public void setUseDatabaseLock(boolean useDatabaseLock) {
this.useDatabaseLock = useDatabaseLock;
}
public static void log(String msg, SQLException e) {
String s = msg + e.getMessage();
while (e.getNextException() != null) {
e = e.getNextException();
s += ", due to: " + e.getMessage();
}
LOG.warn(s, e);
}
public Statements getStatements() {
if (statements == null) {
statements = new Statements();
}
return statements;
}
public void setStatements(Statements statements) {
this.statements = statements;
}
/**
* @param usageManager The UsageManager that is controlling the
* destination's memory usage.
*/
public void setUsageManager(SystemUsage usageManager) {
}
protected void databaseLockKeepAlive() {
boolean stop = false;
try {
Locker locker = getDatabaseLocker();
if (locker != null) {
if (!locker.keepAlive()) {
stop = true;
}
}
} catch (IOException e) {
LOG.warn("databaselocker keepalive resulted in: " + e, e);
}
if (stop) {
stopBroker();
}
}
protected void stopBroker() {
// we can no longer keep the lock so lets fail
LOG.info(brokerService.getBrokerName() + ", no longer able to keep the exclusive lock so giving up being a master");
try {
brokerService.stop();
} catch (Exception e) {
LOG.warn("Failure occurred while stopping broker");
}
}
protected Locker loadDataBaseLocker() throws IOException {
DefaultDatabaseLocker locker = (DefaultDatabaseLocker) loadAdapter(lockFactoryFinder, "lock");
if (locker == null) {
locker = new DefaultDatabaseLocker();
LOG.debug("Using default JDBC Locker: " + locker);
}
return locker;
}
public void setBrokerName(String brokerName) {
}
public String toString() {
return "JDBCPersistenceAdapter(" + super.toString() + ")";
}
public void setDirectory(File dir) {
this.directory=dir;
}
public File getDirectory(){
if (this.directory==null && brokerService != null){
this.directory=brokerService.getBrokerDataDirectory();
}
return this.directory;
}
// interesting bit here is proof that DB is ok
public void checkpoint(boolean sync) throws IOException {
// by pass TransactionContext to avoid IO Exception handler
Connection connection = null;
try {
connection = getDataSource().getConnection();
} catch (SQLException e) {
LOG.debug("Could not get JDBC connection for checkpoint: " + e);
throw IOExceptionSupport.create(e);
} finally {
if (connection != null) {
try {
connection.close();
} catch (Throwable ignored) {
}
}
}
}
public long size(){
return 0;
}
public long getLockKeepAlivePeriod() {
return lockKeepAlivePeriod;
}
public void setLockKeepAlivePeriod(long lockKeepAlivePeriod) {
this.lockKeepAlivePeriod = lockKeepAlivePeriod;
}
public long getLockAcquireSleepInterval() {
return lockAcquireSleepInterval;
}
/**
* millisecond interval between lock acquire attempts, applied to newly created DefaultDatabaseLocker
* not applied if DataBaseLocker is injected.
*/
public void setLockAcquireSleepInterval(long lockAcquireSleepInterval) {
this.lockAcquireSleepInterval = lockAcquireSleepInterval;
}
/**
* set the Transaction isolation level to something other that TRANSACTION_READ_UNCOMMITTED
* This allowable dirty isolation level may not be achievable in clustered DB environments
* so a more restrictive and expensive option may be needed like TRANSACTION_REPEATABLE_READ
* see isolation level constants in {@link java.sql.Connection}
* @param transactionIsolation the isolation level to use
*/
public void setTransactionIsolation(int transactionIsolation) {
this.transactionIsolation = transactionIsolation;
}
public int getMaxProducersToAudit() {
return maxProducersToAudit;
}
public void setMaxProducersToAudit(int maxProducersToAudit) {
this.maxProducersToAudit = maxProducersToAudit;
}
public int getMaxAuditDepth() {
return maxAuditDepth;
}
public void setMaxAuditDepth(int maxAuditDepth) {
this.maxAuditDepth = maxAuditDepth;
}
public boolean isEnableAudit() {
return enableAudit;
}
public void setEnableAudit(boolean enableAudit) {
this.enableAudit = enableAudit;
}
public int getAuditRecoveryDepth() {
return auditRecoveryDepth;
}
public void setAuditRecoveryDepth(int auditRecoveryDepth) {
this.auditRecoveryDepth = auditRecoveryDepth;
}
public long getNextSequenceId() {
synchronized(sequenceGenerator) {
return sequenceGenerator.getNextSequenceId();
}
}
public int getMaxRows() {
return maxRows;
}
/*
* the max rows return from queries, with sparse selectors this may need to be increased
*/
public void setMaxRows(int maxRows) {
this.maxRows = maxRows;
}
public void recover(JdbcMemoryTransactionStore jdbcMemoryTransactionStore) throws IOException {
TransactionContext c = getTransactionContext();
try {
getAdapter().doRecoverPreparedOps(c, jdbcMemoryTransactionStore);
} catch (SQLException e) {
JDBCPersistenceAdapter.log("JDBC Failure: ", e);
throw IOExceptionSupport.create("Failed to recover from: " + jdbcMemoryTransactionStore + ". Reason: " + e,e);
} finally {
c.close();
}
}
public void commitAdd(ConnectionContext context, MessageId messageId) throws IOException {
TransactionContext c = getTransactionContext(context);
try {
long sequence = (Long)messageId.getDataLocator();
getAdapter().doCommitAddOp(c, sequence);
} catch (SQLException e) {
JDBCPersistenceAdapter.log("JDBC Failure: ", e);
throw IOExceptionSupport.create("Failed to commit add: " + messageId + ". Reason: " + e, e);
} finally {
c.close();
}
}
public void commitRemove(ConnectionContext context, MessageAck ack) throws IOException {
TransactionContext c = getTransactionContext(context);
try {
getAdapter().doRemoveMessage(c, (Long)ack.getLastMessageId().getDataLocator(), null);
} catch (SQLException e) {
JDBCPersistenceAdapter.log("JDBC Failure: ", e);
throw IOExceptionSupport.create("Failed to commit last ack: " + ack + ". Reason: " + e,e);
} finally {
c.close();
}
}
public void commitLastAck(ConnectionContext context, long xidLastAck, long priority, ActiveMQDestination destination, String subName, String clientId) throws IOException {
TransactionContext c = getTransactionContext(context);
try {
getAdapter().doSetLastAck(c, destination, null, clientId, subName, xidLastAck, priority);
} catch (SQLException e) {
JDBCPersistenceAdapter.log("JDBC Failure: ", e);
throw IOExceptionSupport.create("Failed to commit last ack with priority: " + priority + " on " + destination + " for " + subName + ":" + clientId + ". Reason: " + e,e);
} finally {
c.close();
}
}
public void rollbackLastAck(ConnectionContext context, JDBCTopicMessageStore store, MessageAck ack, String subName, String clientId) throws IOException {
TransactionContext c = getTransactionContext(context);
try {
byte priority = (byte) store.getCachedStoreSequenceId(c, store.getDestination(), ack.getLastMessageId())[1];
getAdapter().doClearLastAck(c, store.getDestination(), priority, clientId, subName);
} catch (SQLException e) {
JDBCPersistenceAdapter.log("JDBC Failure: ", e);
throw IOExceptionSupport.create("Failed to rollback last ack: " + ack + " on " + store.getDestination() + " for " + subName + ":" + clientId + ". Reason: " + e,e);
} finally {
c.close();
}
}
// after recovery there is no record of the original messageId for the ack
public void rollbackLastAck(ConnectionContext context, byte priority, ActiveMQDestination destination, String subName, String clientId) throws IOException {
TransactionContext c = getTransactionContext(context);
try {
getAdapter().doClearLastAck(c, destination, priority, clientId, subName);
} catch (SQLException e) {
JDBCPersistenceAdapter.log("JDBC Failure: ", e);
throw IOExceptionSupport.create("Failed to rollback last ack with priority: " + priority + " on " + destination + " for " + subName + ":" + clientId + ". Reason: " + e, e);
} finally {
c.close();
}
}
long[] getStoreSequenceIdForMessageId(MessageId messageId, ActiveMQDestination destination) throws IOException {
long[] result = new long[]{-1, Byte.MAX_VALUE -1};
TransactionContext c = getTransactionContext();
try {
result = adapter.getStoreSequenceId(c, destination, messageId);
} catch (SQLException e) {
JDBCPersistenceAdapter.log("JDBC Failure: ", e);
throw IOExceptionSupport.create("Failed to get store sequenceId for messageId: " + messageId +", on: " + destination + ". Reason: " + e, e);
} finally {
c.close();
}
return result;
}
}
| false | false | null | null |
diff --git a/src/biz/bokhorst/xprivacy/ActivityApp.java b/src/biz/bokhorst/xprivacy/ActivityApp.java
index 79def979..9c3b2820 100644
--- a/src/biz/bokhorst/xprivacy/ActivityApp.java
+++ b/src/biz/bokhorst/xprivacy/ActivityApp.java
@@ -1,1314 +1,1314 @@
package biz.bokhorst.xprivacy;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
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 org.json.JSONArray;
import org.json.JSONObject;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.NotificationManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.Settings.Secure;
import android.support.v4.app.NavUtils;
import android.support.v4.app.TaskStackBuilder;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
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.view.ViewParent;
import android.view.Window;
import android.widget.BaseExpandableListAdapter;
import android.widget.Button;
import android.widget.CheckedTextView;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
public class ActivityApp extends Activity {
private int mThemeId;
private ApplicationInfoEx mAppInfo = null;
private RestrictionAdapter mPrivacyListAdapter = null;
private Bitmap[] mCheck;
public static final String cUid = "Uid";
public static final String cRestrictionName = "RestrictionName";
public static final String cMethodName = "MethodName";
public static final String cActionClear = "Clear";
private static final int ACTIVITY_FETCH = 1;
private static ExecutorService mExecutor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors(),
new PriorityThreadFactory());
private static class PriorityThreadFactory implements ThreadFactory {
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread(r);
t.setPriority(Thread.NORM_PRIORITY);
return t;
}
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set theme
String themeName = PrivacyManager.getSetting(null, this, 0, PrivacyManager.cSettingTheme, "", false);
mThemeId = (themeName.equals("Dark") ? R.style.CustomTheme : R.style.CustomTheme_Light);
setTheme(mThemeId);
// Set layout
setContentView(R.layout.restrictionlist);
// Get arguments
Bundle extras = getIntent().getExtras();
int uid = extras.getInt(cUid);
String restrictionName = (extras.containsKey(cRestrictionName) ? extras.getString(cRestrictionName) : null);
String methodName = (extras.containsKey(cMethodName) ? extras.getString(cMethodName) : null);
// Get app info
try {
mAppInfo = new ApplicationInfoEx(this, uid);
} catch (NameNotFoundException ignored) {
finish();
return;
}
// Set title
setTitle(String.format("%s - %s", getString(R.string.app_name),
TextUtils.join(", ", mAppInfo.getApplicationName())));
// Handle info click
ImageView imgInfo = (ImageView) findViewById(R.id.imgInfo);
imgInfo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent infoIntent = new Intent(Intent.ACTION_VIEW);
- infoIntent.setData(Uri.parse(String.format(ActivityShare.BASE_URL + "?package_name=%s",
- mAppInfo.getPackageName())));
+ infoIntent.setData(Uri.parse(String.format(ActivityShare.BASE_URL + "?package_name=%s", mAppInfo
+ .getPackageName().get(0))));
startActivity(infoIntent);
}
});
// Display app name
TextView tvAppName = (TextView) findViewById(R.id.tvApp);
tvAppName.setText(mAppInfo.toString());
// Background color
if (mAppInfo.isSystem()) {
LinearLayout llInfo = (LinearLayout) findViewById(R.id.llInfo);
llInfo.setBackgroundColor(getResources().getColor(Util.getThemed(this, R.attr.color_dangerous)));
}
// Display app icon
final ImageView imgIcon = (ImageView) findViewById(R.id.imgIcon);
imgIcon.setImageDrawable(mAppInfo.getIcon(this));
// Handle icon click
imgIcon.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
openContextMenu(imgIcon);
}
});
// Add context menu to icon
registerForContextMenu(imgIcon);
// Check if internet access
if (!mAppInfo.hasInternet(this)) {
ImageView imgInternet = (ImageView) findViewById(R.id.imgInternet);
imgInternet.setVisibility(View.INVISIBLE);
}
// Check if frozen
if (!mAppInfo.isFrozen(this)) {
ImageView imgFrozen = (ImageView) findViewById(R.id.imgFrozen);
imgFrozen.setVisibility(View.INVISIBLE);
}
// Display version
TextView tvVersion = (TextView) findViewById(R.id.tvVersion);
tvVersion.setText(mAppInfo.getVersion(this));
// Display package name
TextView tvPackageName = (TextView) findViewById(R.id.tvPackageName);
tvPackageName.setText(TextUtils.join(", ", mAppInfo.getPackageName()));
// Fill privacy list view adapter
final ExpandableListView lvRestriction = (ExpandableListView) findViewById(R.id.elvRestriction);
lvRestriction.setGroupIndicator(null);
mPrivacyListAdapter = new RestrictionAdapter(R.layout.restrictionentry, mAppInfo, restrictionName, methodName);
lvRestriction.setAdapter(mPrivacyListAdapter);
if (restrictionName != null) {
int groupPosition = PrivacyManager.getRestrictions().indexOf(restrictionName);
lvRestriction.expandGroup(groupPosition);
lvRestriction.setSelectedGroup(groupPosition);
if (methodName != null) {
int childPosition = PrivacyManager.getMethods(restrictionName).indexOf(
new PrivacyManager.MethodDescription(methodName));
lvRestriction.setSelectedChild(groupPosition, childPosition, true);
}
}
// Up navigation
getActionBar().setDisplayHomeAsUpEnabled(true);
mCheck = Util.getTriStateCheckBox(this);
// Tutorial
if (!PrivacyManager.getSettingBool(null, this, 0, PrivacyManager.cSettingTutorialDetails, false, false)) {
((RelativeLayout) findViewById(R.id.rlTutorialHeader)).setVisibility(View.VISIBLE);
((RelativeLayout) findViewById(R.id.rlTutorialDetails)).setVisibility(View.VISIBLE);
}
View.OnClickListener listener = new View.OnClickListener() {
@Override
public void onClick(View view) {
ViewParent parent = view.getParent();
while (!parent.getClass().equals(RelativeLayout.class))
parent = parent.getParent();
((View) parent).setVisibility(View.GONE);
PrivacyManager.setSetting(null, ActivityApp.this, 0, PrivacyManager.cSettingTutorialDetails,
Boolean.TRUE.toString());
}
};
((Button) findViewById(R.id.btnTutorialHeader)).setOnClickListener(listener);
((Button) findViewById(R.id.btnTutorialDetails)).setOnClickListener(listener);
// Clear
if (extras.containsKey(cActionClear)) {
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(mAppInfo.getUid());
optionClear();
}
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
}
@Override
protected void onResume() {
super.onResume();
if (mPrivacyListAdapter != null)
mPrivacyListAdapter.notifyDataSetChanged();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.app, menu);
return true;
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.app_icon, menu);
// Launch
PackageManager pm = getPackageManager();
if (pm.getLaunchIntentForPackage(mAppInfo.getPackageName().get(0)) == null)
menu.findItem(R.id.menu_app_launch).setEnabled(false);
// Play
boolean hasMarketLink = Util.hasMarketLink(this, mAppInfo.getPackageName().get(0));
menu.findItem(R.id.menu_app_store).setEnabled(hasMarketLink);
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
// Accounts
boolean accountsRestricted = PrivacyManager.getRestricted(null, this, mAppInfo.getUid(),
PrivacyManager.cAccounts, null, false, false);
boolean appsRestricted = PrivacyManager.getRestricted(null, this, mAppInfo.getUid(), PrivacyManager.cSystem,
null, false, false);
boolean contactsRestricted = PrivacyManager.getRestricted(null, this, mAppInfo.getUid(),
PrivacyManager.cContacts, null, false, false);
menu.findItem(R.id.menu_accounts).setEnabled(accountsRestricted);
menu.findItem(R.id.menu_applications).setEnabled(appsRestricted);
menu.findItem(R.id.menu_contacts).setEnabled(contactsRestricted);
return super.onPrepareOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
Intent upIntent = NavUtils.getParentActivityIntent(this);
if (upIntent != null)
if (NavUtils.shouldUpRecreateTask(this, upIntent))
TaskStackBuilder.create(this).addNextIntentWithParentStack(upIntent).startActivities();
else
NavUtils.navigateUpTo(this, upIntent);
return true;
case R.id.menu_help:
optionHelp();
return true;
case R.id.menu_tutorial:
optionTutorial();
return true;
case R.id.menu_apply:
optionApply();
return true;
case R.id.menu_clear:
optionClear();
return true;
case R.id.menu_usage:
optionUsage();
return true;
case R.id.menu_submit:
optionSubmit();
return true;
case R.id.menu_fetch:
optionFetch();
return true;
case R.id.menu_app_launch:
optionLaunch();
return true;
case R.id.menu_app_settings:
optionSettings();
return true;
case R.id.menu_app_store:
optionStore();
return true;
case R.id.menu_accounts:
optionAccounts();
return true;
case R.id.menu_applications:
optionApplications();
return true;
case R.id.menu_contacts:
optionContacts();
return true;
case R.id.menu_settings:
SettingsDialog.edit(ActivityApp.this, mAppInfo);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_app_launch:
optionLaunch();
return true;
case R.id.menu_app_settings:
optionSettings();
return true;
case R.id.menu_app_store:
optionStore();
return true;
default:
return super.onContextItemSelected(item);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent dataIntent) {
super.onActivityResult(requestCode, resultCode, dataIntent);
if (requestCode == ACTIVITY_FETCH) {
if (mPrivacyListAdapter != null)
mPrivacyListAdapter.notifyDataSetChanged();
String errorMessage = null;
if (dataIntent != null && dataIntent.hasExtra(ActivityShare.cErrorMessage))
errorMessage = dataIntent.getStringExtra(ActivityShare.cErrorMessage);
String text = String.format("%s: %s", getString(R.string.menu_fetch),
errorMessage == null ? getString(R.string.msg_done) : errorMessage);
Toast toast = Toast.makeText(this, text, Toast.LENGTH_LONG);
toast.show();
}
}
// Options
private void optionHelp() {
// Show help
Dialog dialog = new Dialog(ActivityApp.this);
dialog.requestWindowFeature(Window.FEATURE_LEFT_ICON);
dialog.setTitle(getString(R.string.menu_help));
dialog.setContentView(R.layout.help);
dialog.setFeatureDrawableResource(Window.FEATURE_LEFT_ICON, Util.getThemed(this, R.attr.icon_launcher));
ImageView imgHelpHalf = (ImageView) dialog.findViewById(R.id.imgHelpHalf);
imgHelpHalf.setImageBitmap(mCheck[1]);
dialog.setCancelable(true);
dialog.show();
}
private void optionTutorial() {
((RelativeLayout) findViewById(R.id.rlTutorialHeader)).setVisibility(View.VISIBLE);
((RelativeLayout) findViewById(R.id.rlTutorialDetails)).setVisibility(View.VISIBLE);
PrivacyManager.setSetting(null, this, 0, PrivacyManager.cSettingTutorialDetails, Boolean.FALSE.toString());
}
private void optionApply() {
// Get toggle
boolean some = false;
final List<String> listRestriction = PrivacyManager.getRestrictions();
for (String restrictionName : listRestriction) {
String templateName = PrivacyManager.cSettingTemplate + "." + restrictionName;
if (PrivacyManager.getSettingBool(null, ActivityApp.this, 0, templateName, true, false))
if (PrivacyManager.getRestricted(null, ActivityApp.this, mAppInfo.getUid(), restrictionName, null,
false, false)) {
some = true;
break;
}
}
final boolean restricted = !some;
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(ActivityApp.this);
alertDialogBuilder.setTitle(getString(restricted ? R.string.menu_apply : R.string.menu_clear_all));
alertDialogBuilder.setMessage(getString(R.string.msg_sure));
alertDialogBuilder.setIcon(Util.getThemed(this, R.attr.icon_launcher));
alertDialogBuilder.setPositiveButton(getString(android.R.string.ok), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// Do toggle
boolean restart = false;
for (String restrictionName : listRestriction) {
String templateName = PrivacyManager.cSettingTemplate + "." + restrictionName;
if (PrivacyManager.getSettingBool(null, ActivityApp.this, 0, templateName, true, false))
restart = PrivacyManager.setRestricted(null, ActivityApp.this, mAppInfo.getUid(),
restrictionName, null, restricted) || restart;
}
// Refresh display
if (mPrivacyListAdapter != null)
mPrivacyListAdapter.notifyDataSetChanged();
// Notify restart
if (restart)
Toast.makeText(ActivityApp.this, getString(R.string.msg_restart), Toast.LENGTH_SHORT).show();
}
});
alertDialogBuilder.setNegativeButton(getString(android.R.string.cancel), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
private void optionClear() {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(ActivityApp.this);
alertDialogBuilder.setTitle(getString(R.string.menu_clear_all));
alertDialogBuilder.setMessage(getString(R.string.msg_sure));
alertDialogBuilder.setIcon(Util.getThemed(this, R.attr.icon_launcher));
alertDialogBuilder.setPositiveButton(getString(android.R.string.ok), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
boolean restart = PrivacyManager.deleteRestrictions(ActivityApp.this, mAppInfo.getUid());
// Refresh display
if (mPrivacyListAdapter != null)
mPrivacyListAdapter.notifyDataSetChanged();
// Notify restart
if (restart)
Toast.makeText(ActivityApp.this, getString(R.string.msg_restart), Toast.LENGTH_SHORT).show();
}
});
alertDialogBuilder.setNegativeButton(getString(android.R.string.cancel), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
private void optionUsage() {
Intent intent = new Intent(this, ActivityUsage.class);
intent.putExtra(ActivityUsage.cUid, mAppInfo.getUid());
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
private void optionSubmit() {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setTitle(getString(R.string.menu_submit));
alertDialogBuilder.setMessage(getString(R.string.msg_sure));
alertDialogBuilder.setIcon(Util.getThemed(this, R.attr.icon_launcher));
alertDialogBuilder.setPositiveButton(getString(android.R.string.ok), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
SubmitTask submitTask = new SubmitTask();
submitTask.executeOnExecutor(mExecutor, mAppInfo);
}
});
alertDialogBuilder.setNegativeButton(getString(android.R.string.cancel), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
private void optionFetch() {
if (Util.getProLicense() == null) {
// Redirect to pro page
Intent browserIntent = new Intent(Intent.ACTION_VIEW, ActivityMain.cProUri);
startActivity(browserIntent);
} else {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setTitle(getString(R.string.menu_fetch));
alertDialogBuilder.setMessage(getString(R.string.msg_sure));
alertDialogBuilder.setIcon(Util.getThemed(this, R.attr.icon_launcher));
alertDialogBuilder.setPositiveButton(getString(android.R.string.ok), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent("biz.bokhorst.xprivacy.action.FETCH");
intent.putExtra(ActivityShare.cUid, mAppInfo.getUid());
startActivityForResult(intent, ACTIVITY_FETCH);
}
});
alertDialogBuilder.setNegativeButton(getString(android.R.string.cancel),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
}
private void optionAccounts() {
AccountsTask accountsTask = new AccountsTask();
accountsTask.executeOnExecutor(mExecutor, (Object) null);
}
private void optionApplications() {
if (Util.getProLicense() == null) {
// Redirect to pro page
Intent browserIntent = new Intent(Intent.ACTION_VIEW, ActivityMain.cProUri);
startActivity(browserIntent);
} else {
ApplicationsTask appsTask = new ApplicationsTask();
appsTask.executeOnExecutor(mExecutor, (Object) null);
}
}
private void optionContacts() {
if (Util.getProLicense() == null) {
// Redirect to pro page
Intent browserIntent = new Intent(Intent.ACTION_VIEW, ActivityMain.cProUri);
startActivity(browserIntent);
} else {
ContactsTask contactsTask = new ContactsTask();
contactsTask.executeOnExecutor(mExecutor, (Object) null);
}
}
private void optionLaunch() {
Intent intentLaunch = getPackageManager().getLaunchIntentForPackage(mAppInfo.getPackageName().get(0));
startActivity(intentLaunch);
}
private void optionSettings() {
Intent intentSettings = new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
- Uri.parse("package:" + mAppInfo.getPackageName()));
+ Uri.parse("package:" + mAppInfo.getPackageName().get(0)));
startActivity(intentSettings);
}
private void optionStore() {
Intent intentStore = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id="
- + mAppInfo.getPackageName()));
+ + mAppInfo.getPackageName().get(0)));
startActivity(intentStore);
}
// Tasks
private class AccountsTask extends AsyncTask<Object, Object, Object> {
private List<CharSequence> mListAccount;
private Account[] mAccounts;
private boolean[] mSelection;
@Override
protected Object doInBackground(Object... params) {
// Get accounts
mListAccount = new ArrayList<CharSequence>();
AccountManager accountManager = AccountManager.get(ActivityApp.this);
mAccounts = accountManager.getAccounts();
mSelection = new boolean[mAccounts.length];
for (int i = 0; i < mAccounts.length; i++)
try {
mListAccount.add(String.format("%s (%s)", mAccounts[i].name, mAccounts[i].type));
String sha1 = Util.sha1(mAccounts[i].name + mAccounts[i].type);
mSelection[i] = PrivacyManager.getSettingBool(null, ActivityApp.this, 0,
String.format("Account.%d.%s", mAppInfo.getUid(), sha1), false, false);
} catch (Throwable ex) {
Util.bug(null, ex);
}
return null;
}
@Override
protected void onPostExecute(Object result) {
// Build dialog
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(ActivityApp.this);
alertDialogBuilder.setTitle(getString(R.string.menu_accounts));
alertDialogBuilder.setIcon(Util.getThemed(ActivityApp.this, R.attr.icon_launcher));
alertDialogBuilder.setMultiChoiceItems(mListAccount.toArray(new CharSequence[0]), mSelection,
new DialogInterface.OnMultiChoiceClickListener() {
public void onClick(DialogInterface dialog, int whichButton, boolean isChecked) {
try {
Account account = mAccounts[whichButton];
String sha1 = Util.sha1(account.name + account.type);
PrivacyManager.setSetting(null, ActivityApp.this, 0,
String.format("Account.%d.%s", mAppInfo.getUid(), sha1),
Boolean.toString(isChecked));
} catch (Throwable ex) {
Util.bug(null, ex);
Toast toast = Toast.makeText(ActivityApp.this, ex.toString(), Toast.LENGTH_LONG);
toast.show();
}
}
});
alertDialogBuilder.setPositiveButton(getString(R.string.msg_done), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// Do nothing
}
});
// Show dialog
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
super.onPostExecute(result);
}
}
private class ApplicationsTask extends AsyncTask<Object, Object, Object> {
private List<ApplicationInfo> mListInfo;
private List<CharSequence> mListApp;
private boolean[] mSelection;
@Override
protected Object doInBackground(Object... params) {
// Get applications
final PackageManager pm = ActivityApp.this.getPackageManager();
mListInfo = pm.getInstalledApplications(PackageManager.GET_META_DATA);
Collections.sort(mListInfo, new Comparator<ApplicationInfo>() {
public int compare(ApplicationInfo info1, ApplicationInfo info2) {
return ((String) pm.getApplicationLabel(info1)).compareTo(((String) pm.getApplicationLabel(info2)));
}
});
// Build selection list
mListApp = new ArrayList<CharSequence>();
mSelection = new boolean[mListInfo.size()];
for (int i = 0; i < mListInfo.size(); i++)
try {
mListApp.add(String.format("%s (%s)", pm.getApplicationLabel(mListInfo.get(i)),
mListInfo.get(i).packageName));
mSelection[i] = PrivacyManager.getSettingBool(null, ActivityApp.this, 0,
String.format("Application.%d.%s", mAppInfo.getUid(), mListInfo.get(i).packageName), false,
false);
} catch (Throwable ex) {
Util.bug(null, ex);
}
return null;
}
@Override
protected void onPostExecute(Object result) {
// Build dialog
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(ActivityApp.this);
alertDialogBuilder.setTitle(getString(R.string.menu_applications));
alertDialogBuilder.setIcon(Util.getThemed(ActivityApp.this, R.attr.icon_launcher));
alertDialogBuilder.setMultiChoiceItems(mListApp.toArray(new CharSequence[0]), mSelection,
new DialogInterface.OnMultiChoiceClickListener() {
public void onClick(DialogInterface dialog, int whichButton, boolean isChecked) {
try {
PrivacyManager.setSetting(
null,
ActivityApp.this,
0,
String.format("Application.%d.%s", mAppInfo.getUid(),
mListInfo.get(whichButton).packageName), Boolean.toString(isChecked));
} catch (Throwable ex) {
Util.bug(null, ex);
Toast toast = Toast.makeText(ActivityApp.this, ex.toString(), Toast.LENGTH_LONG);
toast.show();
}
}
});
alertDialogBuilder.setPositiveButton(getString(R.string.msg_done), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// Do nothing
}
});
// Show dialog
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
super.onPostExecute(result);
}
}
private class ContactsTask extends AsyncTask<Object, Object, Object> {
private List<CharSequence> mListContact;
private long[] mIds;
private boolean[] mSelection;
@Override
protected Object doInBackground(Object... params) {
// Map contacts
Map<Long, String> mapContact = new LinkedHashMap<Long, String>();
Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,
new String[] { ContactsContract.Contacts._ID, Phone.DISPLAY_NAME }, null, null, Phone.DISPLAY_NAME);
if (cursor != null)
try {
while (cursor.moveToNext()) {
long id = cursor.getLong(cursor.getColumnIndex(ContactsContract.Contacts._ID));
String contact = cursor.getString(cursor.getColumnIndex(Phone.DISPLAY_NAME));
if (contact == null)
contact = "-";
mapContact.put(id, contact);
}
} finally {
cursor.close();
}
// Build dialog data
mListContact = new ArrayList<CharSequence>();
mIds = new long[mapContact.size()];
mSelection = new boolean[mapContact.size()];
int i = 0;
for (Long id : mapContact.keySet()) {
mListContact.add(mapContact.get(id));
mIds[i] = id;
mSelection[i++] = PrivacyManager.getSettingBool(null, ActivityApp.this, 0,
String.format("Contact.%d.%d", mAppInfo.getUid(), id), false, false);
}
return null;
}
@Override
protected void onPostExecute(Object result) {
// Build dialog
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(ActivityApp.this);
alertDialogBuilder.setTitle(getString(R.string.menu_contacts));
alertDialogBuilder.setIcon(Util.getThemed(ActivityApp.this, R.attr.icon_launcher));
alertDialogBuilder.setMultiChoiceItems(mListContact.toArray(new CharSequence[0]), mSelection,
new DialogInterface.OnMultiChoiceClickListener() {
public void onClick(DialogInterface dialog, int whichButton, boolean isChecked) {
// Contact
PrivacyManager.setSetting(null, ActivityApp.this, 0,
String.format("Contact.%d.%d", mAppInfo.getUid(), mIds[whichButton]),
Boolean.toString(isChecked));
// Raw contacts
Cursor cursor = getContentResolver().query(ContactsContract.RawContacts.CONTENT_URI,
new String[] { ContactsContract.RawContacts._ID },
ContactsContract.RawContacts.CONTACT_ID + "=?",
new String[] { String.valueOf(mIds[whichButton]) }, null);
try {
while (cursor.moveToNext()) {
PrivacyManager.setSetting(null, ActivityApp.this, 0,
String.format("RawContact.%d.%d", mAppInfo.getUid(), cursor.getLong(0)),
Boolean.toString(isChecked));
}
} finally {
cursor.close();
}
}
});
alertDialogBuilder.setPositiveButton(getString(R.string.msg_done), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// Do nothing
}
});
// Show dialog
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
super.onPostExecute(result);
}
}
@SuppressLint("DefaultLocale")
private class SubmitTask extends AsyncTask<ApplicationInfoEx, Object, String> {
@Override
protected String doInBackground(ApplicationInfoEx... params) {
try {
// Encode restrictions
int uid = params[0].getUid();
JSONArray jSettings = new JSONArray();
for (String restrictionName : PrivacyManager.getRestrictions()) {
boolean restricted = PrivacyManager.getRestricted(null, ActivityApp.this, uid, restrictionName,
null, false, false);
// Category
long used = PrivacyManager.getUsed(ActivityApp.this, uid, restrictionName, null);
JSONObject jRestriction = new JSONObject();
jRestriction.put("restriction", restrictionName);
jRestriction.put("restricted", restricted);
jRestriction.put("used", used);
jSettings.put(jRestriction);
// Methods
for (PrivacyManager.MethodDescription md : PrivacyManager.getMethods(restrictionName)) {
boolean mRestricted = restricted
&& PrivacyManager.getRestricted(null, ActivityApp.this, uid, restrictionName,
md.getName(), false, false);
long mUsed = PrivacyManager.getUsed(ActivityApp.this, uid, restrictionName, md.getName());
JSONObject jMethod = new JSONObject();
jMethod.put("restriction", restrictionName);
jMethod.put("method", md.getName());
jMethod.put("restricted", mRestricted);
jMethod.put("used", mUsed);
jSettings.put(jMethod);
}
}
// Get data
PackageInfo pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
String android_id = Secure.getString(ActivityApp.this.getContentResolver(), Secure.ANDROID_ID);
JSONArray appName = new JSONArray();
for (String name : params[0].getApplicationName())
appName.put(name);
JSONArray pkgName = new JSONArray();
for (String name : params[0].getPackageName())
pkgName.put(name);
JSONArray pkgVersion = new JSONArray();
for (String version : params[0].getPackageVersion(ActivityApp.this))
pkgVersion.put(version);
// Encode package
JSONObject jRoot = new JSONObject();
jRoot.put("protocol_version", 4);
jRoot.put("android_id", Util.md5(android_id).toLowerCase());
jRoot.put("android_sdk", Build.VERSION.SDK_INT);
jRoot.put("xprivacy_version", pInfo.versionCode);
jRoot.put("application_name", appName);
jRoot.put("package_name", pkgName);
jRoot.put("package_version", pkgVersion);
jRoot.put("settings", jSettings);
// Submit
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, ActivityShare.TIMEOUT_MILLISEC);
HttpConnectionParams.setSoTimeout(httpParams, ActivityShare.TIMEOUT_MILLISEC);
HttpClient httpclient = new DefaultHttpClient(httpParams);
HttpPost httpost = new HttpPost(ActivityShare.BASE_URL + "?format=json&action=submit");
httpost.setEntity(new ByteArrayEntity(jRoot.toString().getBytes("UTF-8")));
httpost.setHeader("Accept", "application/json");
httpost.setHeader("Content-type", "application/json");
HttpResponse response = httpclient.execute(httpost);
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
// Succeeded
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
JSONObject status = new JSONObject(out.toString("UTF-8"));
if (status.getBoolean("ok")) {
// Mark as shared
PrivacyManager.setSetting(null, ActivityApp.this, mAppInfo.getUid(),
PrivacyManager.cSettingState, Integer.toString(ActivityMain.STATE_SHARED));
return getString(R.string.msg_done);
} else
return status.getString("error");
} else {
// Failed
response.getEntity().getContent().close();
return statusLine.getReasonPhrase();
}
} catch (Throwable ex) {
Util.bug(null, ex);
return ex.toString();
}
}
@Override
protected void onPostExecute(String result) {
Toast toast = Toast.makeText(ActivityApp.this,
String.format("%s: %s", getString(R.string.menu_submit), result), Toast.LENGTH_LONG);
toast.show();
super.onPostExecute(result);
}
}
// Adapters
private class RestrictionAdapter extends BaseExpandableListAdapter {
private ApplicationInfoEx mAppInfo;
private String mSelectedRestrictionName;
private String mSelectedMethodName;
private List<String> mRestrictions;
private HashMap<Integer, List<PrivacyManager.MethodDescription>> mMethodDescription;
private LayoutInflater mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
public RestrictionAdapter(int resource, ApplicationInfoEx appInfo, String selectedRestrictionName,
String selectedMethodName) {
mAppInfo = appInfo;
mSelectedRestrictionName = selectedRestrictionName;
mSelectedMethodName = selectedMethodName;
mRestrictions = new ArrayList<String>();
mMethodDescription = new LinkedHashMap<Integer, List<PrivacyManager.MethodDescription>>();
boolean fUsed = PrivacyManager.getSettingBool(null, ActivityApp.this, 0, PrivacyManager.cSettingFUsed,
false, false);
boolean fPermission = PrivacyManager.getSettingBool(null, ActivityApp.this, 0,
PrivacyManager.cSettingFPermission, false, false);
for (String rRestrictionName : PrivacyManager.getRestrictions()) {
boolean isUsed = (PrivacyManager.getUsed(ActivityApp.this, mAppInfo.getUid(), rRestrictionName, null) > 0);
boolean hasPermission = PrivacyManager.hasPermission(ActivityApp.this,
mAppInfo.getPackageName().get(0), rRestrictionName);
if (mSelectedRestrictionName != null
|| ((fUsed ? isUsed : true) && (fPermission ? isUsed || hasPermission : true)))
mRestrictions.add(rRestrictionName);
}
}
@Override
public Object getGroup(int groupPosition) {
return mRestrictions.get(groupPosition);
}
@Override
public int getGroupCount() {
return mRestrictions.size();
}
@Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
private class GroupViewHolder {
private View row;
private int position;
public ImageView imgIndicator;
public ImageView imgUsed;
public ImageView imgGranted;
public ImageView imgInfo;
public TextView tvName;
public ImageView imgCBName;
public RelativeLayout rlName;
public GroupViewHolder(View theRow, int thePosition) {
row = theRow;
position = thePosition;
imgIndicator = (ImageView) row.findViewById(R.id.imgIndicator);
imgUsed = (ImageView) row.findViewById(R.id.imgUsed);
imgGranted = (ImageView) row.findViewById(R.id.imgGranted);
imgInfo = (ImageView) row.findViewById(R.id.imgInfo);
tvName = (TextView) row.findViewById(R.id.tvName);
imgCBName = (ImageView) row.findViewById(R.id.imgCBName);
rlName = (RelativeLayout) row.findViewById(R.id.rlName);
}
}
private class GroupHolderTask extends AsyncTask<Object, Object, Object> {
private int position;
private GroupViewHolder holder;
private String restrictionName;
private boolean used;
private boolean permission;
private boolean allRestricted = true;
private boolean someRestricted = false;
public GroupHolderTask(int thePosition, GroupViewHolder theHolder, String theRestrictionName) {
position = thePosition;
holder = theHolder;
restrictionName = theRestrictionName;
}
@Override
protected Object doInBackground(Object... params) {
if (holder.position == position && restrictionName != null) {
// Get info
used = (PrivacyManager.getUsed(holder.row.getContext(), mAppInfo.getUid(), restrictionName, null) != 0);
permission = PrivacyManager.hasPermission(holder.row.getContext(),
mAppInfo.getPackageName().get(0), restrictionName);
for (boolean restricted : PrivacyManager.getRestricted(holder.row.getContext(), mAppInfo.getUid(),
restrictionName)) {
allRestricted = (allRestricted && restricted);
someRestricted = (someRestricted || restricted);
}
}
return null;
}
@Override
protected void onPostExecute(Object result) {
if (holder.position == position && restrictionName != null) {
// Set data
holder.tvName.setTypeface(null, used ? Typeface.BOLD_ITALIC : Typeface.NORMAL);
holder.imgUsed.setVisibility(used ? View.VISIBLE : View.INVISIBLE);
holder.imgGranted.setVisibility(permission ? View.VISIBLE : View.INVISIBLE);
// Display restriction
if (allRestricted)
holder.imgCBName.setImageBitmap(mCheck[2]); // Full
else if (someRestricted)
holder.imgCBName.setImageBitmap(mCheck[1]); // Half
else
holder.imgCBName.setImageBitmap(mCheck[0]); // Off
holder.imgCBName.setVisibility(View.VISIBLE);
// Listen for restriction changes
holder.rlName.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Get all/some restricted
boolean allRestricted = true;
boolean someRestricted = false;
for (boolean restricted : PrivacyManager.getRestricted(view.getContext(),
mAppInfo.getUid(), restrictionName)) {
allRestricted = (allRestricted && restricted);
someRestricted = (someRestricted || restricted);
}
boolean restart = PrivacyManager.setRestricted(null, view.getContext(), mAppInfo.getUid(),
restrictionName, null, !someRestricted);
// Update all/some restricted
allRestricted = true;
someRestricted = false;
for (boolean restricted : PrivacyManager.getRestricted(holder.row.getContext(),
mAppInfo.getUid(), restrictionName)) {
allRestricted = (allRestricted && restricted);
someRestricted = (someRestricted || restricted);
}
// Display restriction
if (allRestricted)
holder.imgCBName.setImageBitmap(mCheck[2]); // Full
else if (someRestricted)
holder.imgCBName.setImageBitmap(mCheck[1]); // Half
else
holder.imgCBName.setImageBitmap(mCheck[0]); // Off
// Refresh display
notifyDataSetChanged(); // Needed to update childs
// Notify restart
if (restart)
Toast.makeText(view.getContext(), getString(R.string.msg_restart), Toast.LENGTH_SHORT)
.show();
}
});
}
}
}
@Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
GroupViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.restrictionentry, null);
holder = new GroupViewHolder(convertView, groupPosition);
convertView.setTag(holder);
} else {
holder = (GroupViewHolder) convertView.getTag();
holder.position = groupPosition;
}
// Get entry
final String restrictionName = (String) getGroup(groupPosition);
// Indicator state
holder.imgIndicator.setImageResource(Util.getThemed(ActivityApp.this,
isExpanded ? R.attr.icon_expander_maximized : R.attr.icon_expander_minimized));
// Disable indicator for empty groups
if (getChildrenCount(groupPosition) == 0)
holder.imgIndicator.setVisibility(View.INVISIBLE);
else
holder.imgIndicator.setVisibility(View.VISIBLE);
// Display if used
holder.tvName.setTypeface(null, Typeface.NORMAL);
holder.imgUsed.setVisibility(View.INVISIBLE);
// Check if permission
holder.imgGranted.setVisibility(View.INVISIBLE);
// Handle info
holder.imgInfo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent infoIntent = new Intent(Intent.ACTION_VIEW);
infoIntent.setData(Uri.parse(ActivityMain.cXUrl + "#" + restrictionName));
startActivity(infoIntent);
}
});
// Display localized name
holder.tvName.setText(PrivacyManager.getLocalizedName(holder.row.getContext(), restrictionName));
// Display restriction
holder.imgCBName.setVisibility(View.INVISIBLE);
// Async update
new GroupHolderTask(groupPosition, holder, restrictionName).executeOnExecutor(mExecutor, (Object) null);
return convertView;
}
private List<PrivacyManager.MethodDescription> getMethodDescriptions(int groupPosition) {
if (!mMethodDescription.containsKey(groupPosition)) {
boolean fUsed = PrivacyManager.getSettingBool(null, ActivityApp.this, 0, PrivacyManager.cSettingFUsed,
false, false);
boolean fPermission = PrivacyManager.getSettingBool(null, ActivityApp.this, 0,
PrivacyManager.cSettingFPermission, false, false);
List<PrivacyManager.MethodDescription> listMethod = new ArrayList<PrivacyManager.MethodDescription>();
String restrictionName = mRestrictions.get(groupPosition);
for (PrivacyManager.MethodDescription md : PrivacyManager.getMethods((String) getGroup(groupPosition))) {
boolean isUsed = (PrivacyManager.getUsed(ActivityApp.this, mAppInfo.getUid(), restrictionName,
md.getName()) > 0);
boolean hasPermission = PrivacyManager.hasPermission(ActivityApp.this, mAppInfo.getPackageName()
.get(0), md);
if (mSelectedMethodName != null
|| ((fUsed ? isUsed : true) && (fPermission ? isUsed || hasPermission : true)))
listMethod.add(md);
}
mMethodDescription.put(groupPosition, listMethod);
}
return mMethodDescription.get(groupPosition);
}
@Override
public Object getChild(int groupPosition, int childPosition) {
return getMethodDescriptions(groupPosition).get(childPosition);
}
@Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
@Override
public int getChildrenCount(int groupPosition) {
return getMethodDescriptions(groupPosition).size();
}
@Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return false;
}
private class ChildViewHolder {
private View row;
private int groupPosition;
private int childPosition;
public ImageView imgUsed;
public ImageView imgGranted;
public CheckedTextView ctvMethodName;
private ChildViewHolder(View theRow, int gPosition, int cPosition) {
row = theRow;
groupPosition = gPosition;
childPosition = cPosition;
imgUsed = (ImageView) row.findViewById(R.id.imgUsed);
imgGranted = (ImageView) row.findViewById(R.id.imgGranted);
ctvMethodName = (CheckedTextView) row.findViewById(R.id.ctvMethodName);
}
}
private class ChildHolderTask extends AsyncTask<Object, Object, Object> {
private int groupPosition;
private int childPosition;
private ChildViewHolder holder;
private String restrictionName;
private PrivacyManager.MethodDescription md;
private long lastUsage;
private boolean parentRestricted;
private boolean permission;
private boolean restricted;
public ChildHolderTask(int gPosition, int cPosition, ChildViewHolder theHolder, String theRestrictionName) {
groupPosition = gPosition;
childPosition = cPosition;
holder = theHolder;
restrictionName = theRestrictionName;
}
@Override
protected Object doInBackground(Object... params) {
if (holder.groupPosition == groupPosition && holder.childPosition == childPosition
&& restrictionName != null) {
// Get info
md = (PrivacyManager.MethodDescription) getChild(groupPosition, childPosition);
lastUsage = PrivacyManager.getUsed(holder.row.getContext(), mAppInfo.getUid(), restrictionName,
md.getName());
parentRestricted = PrivacyManager.getRestricted(null, holder.row.getContext(), mAppInfo.getUid(),
restrictionName, null, false, false);
permission = PrivacyManager.hasPermission(holder.row.getContext(),
mAppInfo.getPackageName().get(0), md);
restricted = PrivacyManager.getRestricted(null, holder.row.getContext(), mAppInfo.getUid(),
restrictionName, md.getName(), false, false);
}
return null;
}
@Override
protected void onPostExecute(Object result) {
if (holder.groupPosition == groupPosition && holder.childPosition == childPosition
&& restrictionName != null) {
// Set data
if (lastUsage > 0) {
CharSequence sLastUsage = DateUtils.getRelativeTimeSpanString(lastUsage, new Date().getTime(),
DateUtils.SECOND_IN_MILLIS, 0);
holder.ctvMethodName.setText(String.format("%s (%s)", md.getName(), sLastUsage));
}
holder.ctvMethodName.setEnabled(parentRestricted);
holder.imgUsed.setVisibility(lastUsage == 0 ? View.INVISIBLE : View.VISIBLE);
holder.ctvMethodName.setTypeface(null, lastUsage == 0 ? Typeface.NORMAL : Typeface.BOLD_ITALIC);
holder.imgGranted.setVisibility(permission ? View.VISIBLE : View.INVISIBLE);
holder.ctvMethodName.setChecked(restricted);
// Listen for restriction changes
holder.ctvMethodName.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
boolean restricted = PrivacyManager.getRestricted(null, view.getContext(),
mAppInfo.getUid(), restrictionName, md.getName(), false, false);
restricted = !restricted;
holder.ctvMethodName.setChecked(restricted);
boolean restart = PrivacyManager.setRestricted(null, view.getContext(), mAppInfo.getUid(),
restrictionName, md.getName(), restricted);
// Refresh display
notifyDataSetChanged(); // Needed to update parent
// Notify restart
if (restart)
Toast.makeText(view.getContext(), getString(R.string.msg_restart), Toast.LENGTH_SHORT)
.show();
}
});
}
}
}
@Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView,
ViewGroup parent) {
ChildViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.restrictionchild, null);
holder = new ChildViewHolder(convertView, groupPosition, childPosition);
convertView.setTag(holder);
} else {
holder = (ChildViewHolder) convertView.getTag();
holder.groupPosition = groupPosition;
holder.childPosition = childPosition;
}
// Get entry
final String restrictionName = (String) getGroup(groupPosition);
final PrivacyManager.MethodDescription md = (PrivacyManager.MethodDescription) getChild(groupPosition,
childPosition);
// Set background color
if (md.isDangerous())
holder.row.setBackgroundColor(getResources().getColor(
Util.getThemed(ActivityApp.this, R.attr.color_dangerous)));
else
holder.row.setBackgroundColor(Color.TRANSPARENT);
// Display method name
holder.ctvMethodName.setText(md.getName());
holder.ctvMethodName.setEnabled(false);
holder.ctvMethodName.setTypeface(null, Typeface.NORMAL);
// Display if used
holder.imgUsed.setVisibility(View.INVISIBLE);
// Display if permissions
holder.imgGranted.setVisibility(View.INVISIBLE);
// Display restriction
holder.ctvMethodName.setChecked(false);
holder.ctvMethodName.setClickable(false);
// Async update
new ChildHolderTask(groupPosition, childPosition, holder, restrictionName).executeOnExecutor(mExecutor,
(Object) null);
return convertView;
}
@Override
public boolean hasStableIds() {
return true;
}
}
}
| false | false | null | null |
diff --git a/src/bzb/se/update/DumpData.java b/src/bzb/se/update/DumpData.java
index b3ffb6e..cdbe3a9 100644
--- a/src/bzb/se/update/DumpData.java
+++ b/src/bzb/se/update/DumpData.java
@@ -1,170 +1,170 @@
package bzb.se.update;
import java.io.*;
import java.sql.*;
import java.util.*;
import java.net.URL;
/*
* Gets data from Darryn's MySQL database and dumps it to a local XML file
*/
public class DumpData {
public static void main(String[] args) {
if (args[0].equals("0")) {
System.out.println("Getting data from MySQL DB");
grabByMySQL();
} else if (args[0].equals("1")) {
System.out.println("Getting data from DB via PHP");
grabByPHP();
}
}
public static void grabByMySQL() {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
String dbURL = "jdbc:mysql://mysql.mitussis.net:3306/mitussis_earth";
String username = "bedwell";
String password = "growlingflythrough";
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Connecting to database");
conn =
DriverManager.getConnection(dbURL, username, password);
System.out.println("Connected");
stmt = conn.createStatement();
System.out.println("Reading database structure");
ArrayList columns = new ArrayList();
if (stmt.execute("select column_name,data_type from information_schema.columns where table_name like 'bedwell_flythrough';")) {
rs = stmt.getResultSet();
} else {
System.err.println("select failed");
}
while (rs.next()) {
String columnName = rs.getString("column_name");
columns.add(columnName);
System.out.println("Found column " + columnName);
}
Collections.sort(columns);
stmt = conn.createStatement();
System.out.println("Reading data");
if (stmt.execute("select * from bedwell_flythrough;")) {
rs = stmt.getResultSet();
} else {
System.err.println("select failed");
}
ArrayList records = new ArrayList();
while (rs.next()) {
Record r = new Record();
Iterator j = columns.iterator();
while (j.hasNext()) {
String columnName = (String) j.next();
String data = rs.getString(columnName);
if (data != null) {
r.addData(columnName, rs.getString(columnName));
}
}
records.add(r);
}
Iterator i = records.iterator();
String xml = "<?xml version=\"1.0\"?>\n<markers>\n";
while (i.hasNext()) {
Record r = (Record) i.next();
xml += "\t<marker>\n";
Set thisColumns = r.getColumns();
Iterator k = thisColumns.iterator();
while (k.hasNext()) {
String columnName = (String) k.next();
columnName = "marker" + columnName.substring(0,0).toUpperCase() + columnName.substring(1);
try {
xml += "\t\t<" + columnName + ">" + r.getData(columnName) + "</" + columnName + ">\n";
} catch (Exception e) {
e.printStackTrace();
}
}
xml += "\t</marker>\n";
}
xml += "</records>\n";
writeToFile(xml);
} catch (ClassNotFoundException ex) {
System.err.println("Failed to load mysql driver");
System.err.println(ex);
} catch (SQLException ex) {
System.out.println("SQLException: " + ex.getMessage());
System.out.println("SQLState: " + ex.getSQLState());
System.out.println("VendorError: " + ex.getErrorCode());
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException ex) { /* ignore */ }
rs = null;
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException ex) { /* ignore */ }
stmt = null;
}
if (conn != null) {
try {
conn.close();
} catch (SQLException ex) { /* ignore */ }
conn = null;
}
}
}
public static void grabByPHP () {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(new URL("http://mitussis.net/earth/china/xml.php").openStream()));
String line = reader.readLine();
String xml = line;
while (line != null) {
line = reader.readLine();
if (line != null) {
xml += line + "\n";
}
}
writeToFile(xml);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void writeToFile (String xml) {
try {
System.out.println("Writing data to file");
- BufferedWriter out = new BufferedWriter(new FileWriter("markers.xml"));
+ BufferedWriter out = new BufferedWriter(new FileWriter("res/markers.xml"));
out.write(xml);
out.close();
System.out.println("Written");
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
diff --git a/src/bzb/se/update/Screenshots.java b/src/bzb/se/update/Screenshots.java
index fabfddf..5e6ce2f 100644
--- a/src/bzb/se/update/Screenshots.java
+++ b/src/bzb/se/update/Screenshots.java
@@ -1,72 +1,72 @@
package bzb.se.update;
import java.io.File;
import org.w3c.dom.Document;
import org.w3c.dom.*;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import net.dapper.scrender.Scrender;
/*
* Looks up web content and creates screenshots
*/
public class Screenshots {
public static void main(String[] args) {
try {
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
- Document doc = docBuilder.parse (new File("markers.xml"));
+ Document doc = docBuilder.parse (new File("res/markers.xml"));
// normalize text representation
doc.getDocumentElement ().normalize ();
NodeList markers = doc.getElementsByTagName("marker");
int total = markers.getLength();
System.out.println("Total markers: " + total);
for(int s = 0; s < markers.getLength(); s++){
Node firstNode = markers.item(s);
if(firstNode.getNodeType() == Node.ELEMENT_NODE){
Element firstElement = (Element)firstNode;
if (firstElement.hasAttribute("markerSiteURL")) {
String mediaURL = firstElement.getAttribute("markerSiteURL").trim();
if (mediaURL.length() > 0) {
System.out.println("Media URL: " + mediaURL);
try {
Scrender scrender = new Scrender();
scrender.init();
scrender.render(mediaURL, new File("./screenshots/" + firstElement.getAttribute("markerRecord").trim() + ".jpg"));
} catch (Exception e) {
e.printStackTrace();
}
} else {
System.out.println("No media URL");
}
} else {
System.out.println("No media URL");
}
}//end of if clause
}//end of for loop with s var
}catch (SAXParseException err) {
System.out.println ("** Parsing error" + ", line " + err.getLineNumber () + ", uri " + err.getSystemId ());
System.out.println(" " + err.getMessage ());
}catch (SAXException e) {
Exception x = e.getException ();
((x == null) ? e : x).printStackTrace ();
}catch (Throwable t) {
t.printStackTrace ();
}
}
}
| false | false | null | null |
diff --git a/fog.routing.hrm/src/de/tuilmenau/ics/fog/routing/hierarchical/RoutingEntry.java b/fog.routing.hrm/src/de/tuilmenau/ics/fog/routing/hierarchical/RoutingEntry.java
index ce544743..6c36862b 100644
--- a/fog.routing.hrm/src/de/tuilmenau/ics/fog/routing/hierarchical/RoutingEntry.java
+++ b/fog.routing.hrm/src/de/tuilmenau/ics/fog/routing/hierarchical/RoutingEntry.java
@@ -1,898 +1,913 @@
/*******************************************************************************
* Forwarding on Gates Simulator/Emulator - Hierarchical Routing Management
* Copyright (c) 2012, Integrated Communication Systems Group, TU Ilmenau.
*
* 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.
******************************************************************************/
package de.tuilmenau.ics.fog.routing.hierarchical;
import java.util.LinkedList;
import java.util.List;
import de.tuilmenau.ics.fog.routing.RouteSegment;
import de.tuilmenau.ics.fog.routing.hierarchical.management.AbstractRoutingGraph;
import de.tuilmenau.ics.fog.routing.hierarchical.management.AbstractRoutingGraphLink;
import de.tuilmenau.ics.fog.routing.naming.hierarchical.HRMID;
import de.tuilmenau.ics.fog.routing.naming.hierarchical.L2Address;
import de.tuilmenau.ics.fog.ui.Logging;
/**
* HRM Routing: The class describes a routing entry consisting of
* 1.) Destination: either a node or an aggregated address (a cluster)
* 2.) Next hop: either a node or an aggregated address (a cluster)
* 3.) Hop count: the hop costs this route causes
* 4.) Utilization: the route usage, e.g., 0.59 for 59%
* 5.) Min. delay [ms]: the additional delay, which is caused minimal from this route
* 6.) Max. data rate [Kb/s]: the data rate, which is possible via this route under optimal circumstances
*/
public class RoutingEntry implements RouteSegment
{
private static final long serialVersionUID = 1328799038900154655L;
private static boolean RECORD_CAUSES = true;
/**
* Defines a constant value for "no hop costs".
*/
public static final int NO_HOP_COSTS = 0;
/**
* Defines a constant value for "no utilization".
*/
public static final float NO_UTILIZATION = 0;
/**
* Defines a constant value for "no delay".
*/
public static final long NO_DELAY = 0;
/**
* Defines a constant value for "infinite data rate".
*/
public static final long INFINITE_DATARATE = Long.MAX_VALUE;
/**
* Stores the destination of this route entry.
*/
private HRMID mDestination = null;
/**
* Stores the source of this route entry.
*/
private HRMID mSource = null;
/**
* Stores the next hop of this route entry.
*/
private HRMID mNextHop = null;
/**
* Stores the last next hop of a route entry which was determined by combining multiple routing entries and this instance is the result.
*/
private HRMID mLastNextHop = null;
/**
* Stores the hop costs (physical hop count) the described route causes.
*/
private int mHopCount = NO_HOP_COSTS;
/**
* Stores the utilization[%] of the described route.
*/
private float mUtilization = NO_UTILIZATION;
/**
* Stores the minimum additional delay[ms] the described route causes.
*/
private long mMinDelay = NO_DELAY;
/**
* Stores the maximum data rate[Kb/s] the described route might provide.
*/
private long mMaxDataRate = INFINITE_DATARATE;
/**
* Stores if the route describes a local loop.
*/
private boolean mLocalLoop = false;
/**
* Stores if the route describes a link to a neighbor node.
* ONLY FOR GUI: This value is not part of the concept. It is only used for debugging purposes.
*/
private boolean mRouteToDirectNeighbor = false;
/**
* Stores of the route describes a route for traversing a cluster
*/
private boolean mRouteForClusterTraversal = false;
/**
* Stores the L2 address of the next hop if known
*/
private L2Address mNextHopL2Address = null;
/**
* Stores the cause for this entry.
* This variable is not part of the concept. It is only for GUI/debugging use.
*/
private LinkedList<String> mCause = new LinkedList<String>();
/**
* Stores if this entry belongs to an HRG instance.
* This variable is not part of the concept. It is only used to simplify the implementation. Otherwise, the same class has to be duplicated with very minor differences in order to be used within a HRG
*/
private boolean mBelongstoHRG = false;
/**
* Stores the timeout value of this route entry
*/
private double mTimeout = 0;
/**
* Stores if the link was reported
* ONLY FOR GUI: This value is not part of the concept. It is only used for debugging purposes.
*/
private boolean mReportedLink = false;
/**
* Stores the sender of this shared link
* ONLY FOR GUI: This value is not part of the concept. It is only used for debugging purposes.
*/
private HRMID mReporter = null;
/**
* Stores if the link was shared
* ONLY FOR GUI: This value is not part of the concept. It is only used for debugging purposes.
*/
private boolean mSharedLink = false;
/**
* Stores the sender of this shared link
* ONLY FOR GUI: This value is not part of the concept. It is only used for debugging purposes.
*/
private HRMID mSharer = null;
/**
* Constructor
*
* @param pSource the source of this route
* @param pDestination the destination of this route
* @param pNextHop the next hop for this route
* @param pHopCount the hop costs
* @param pUtilization the utilization of the described route
* @param pMinDelay the minimum additional delay the described route causes
* @param pMaxDataRate the maximum data rate the described route might provide
* @param pCause the cause for this routing table entry
*/
@SuppressWarnings("unchecked")
private RoutingEntry(HRMID pSource, HRMID pDestination, HRMID pNextHop, int pHopCount, float pUtilization, long pMinDelay, long pMaxDataRate, LinkedList<String> pCause)
{
setDest(pDestination);
setSource(pSource);
setNextHop(pNextHop);
mHopCount = pHopCount;
mUtilization = pUtilization;
mMinDelay = pMinDelay;
mMaxDataRate = pMaxDataRate;
mLocalLoop = false;
mRouteToDirectNeighbor = false;
if((pCause != null) && (!pCause.isEmpty())){
mCause = (LinkedList<String>) pCause.clone();
}
}
/**
* Constructor
*
* @param pSource the source of this route
* @param pDestination the destination of this route
* @param pNextHop the next hop for this route
* @param pHopCount the hop costs
* @param pUtilization the utilization of the described route
* @param pMinDelay the minimum additional delay the described route causes
* @param pMaxDataRate the maximum data rate the described route might provide
* @param pCause the cause for this routing table entry
*/
private RoutingEntry(HRMID pSource, HRMID pDestination, HRMID pNextHop, int pHopCount, float pUtilization, long pMinDelay, long pMaxDataRate, String pCause)
{
this(pSource, pDestination, pNextHop, pHopCount, pUtilization, pMinDelay, pMaxDataRate, (LinkedList<String>)null);
if(pCause != null){
extendCause(pCause);
}
}
/**
* Constructor
*
* @param pDestination the destination of this route
* @param pNextHop the next hop for this route
* @param pHopCount the hop costs
* @param pUtilization the utilization of the described route
* @param pMinDelay the minimum additional delay the described route causes
* @param pMaxDataRate the maximum data rate the described route might provide
* @param pCause the cause for this routing table entry
*/
private RoutingEntry(HRMID pDestination, HRMID pNextHop, int pHopCount, float pUtilization, long pMinDelay, long pMaxDataRate, String pCause)
{
this(null, pDestination, pNextHop, pHopCount, pUtilization, pMinDelay, pMaxDataRate, pCause);
}
/**
* Factory function: creates a routing loop, which is used for routing traffic on the local host.
*
* @param pLoopAddress the address which defines the destination and next hop of this route
* @param pCause the cause for this routing table entry
*/
public static RoutingEntry createLocalhostEntry(HRMID pLoopAddress, String pCause)
{
// create instance
RoutingEntry tEntry = new RoutingEntry(null, pLoopAddress, pLoopAddress, NO_HOP_COSTS, NO_UTILIZATION, NO_DELAY, INFINITE_DATARATE, pCause);
// mark as local loop
tEntry.mLocalLoop = true;
// set the source of this route
tEntry.mSource = pLoopAddress;
// return with the entry
return tEntry;
}
/**
* Factory function: creates a general route
*
* @param pSource the source of the route
* @param pDestination the direct neighbor
* @param pNextHop the next hop for the route
* @param pHopCount the hop costs
* @param pUtilization the utilization of the described route
* @param pMinDelay the minimum additional delay the described route causes
* @param pMaxDataRate the maximum data rate the described route might provide
* @param pCause the cause for this routing table entry
*/
public static RoutingEntry create(HRMID pSource, HRMID pDestination, HRMID pNextHop, int pHopCount, float pUtilization, long pMinDelay, long pMaxDataRate, LinkedList<String> pCause)
{
// create instance
RoutingEntry tEntry = new RoutingEntry(pSource, pDestination, pNextHop, pHopCount, pUtilization, pMinDelay, pMaxDataRate, pCause);
// return with the entry
return tEntry;
}
/**
* Factory function: creates a general route
*
* @param pSource the source of the route
* @param pDestination the direct neighbor
* @param pNextHop the next hop for the route
* @param pHopCount the hop costs
* @param pUtilization the utilization of the described route
* @param pMinDelay the minimum additional delay the described route causes
* @param pMaxDataRate the maximum data rate the described route might provide
* @param pCause the cause for this routing table entry
*/
public static RoutingEntry create(HRMID pSource, HRMID pDestination, HRMID pNextHop, int pHopCount, float pUtilization, long pMinDelay, long pMaxDataRate, String pCause)
{
// create instance
RoutingEntry tEntry = new RoutingEntry(pSource, pDestination, pNextHop, pHopCount, pUtilization, pMinDelay, pMaxDataRate, pCause);
// return with the entry
return tEntry;
}
/**
* Factory function: creates an aggregated route from a given path
*
* @param pPath the path of route parts
*
* @return the aggregated route
*/
public static RoutingEntry create(List<AbstractRoutingGraphLink> pPath)
{
RoutingEntry tResult = null;
+ // is the given path valid?
if(pPath != null){
+ // has the given path any data?
if(!pPath.isEmpty()){
+ // iterate over all path parts
for(AbstractRoutingGraphLink tLink : pPath){
+ // is the RoutingEntry for the current link valid?
if((tLink.getRoute() != null) && (tLink.getRoute().size() == 1)){
+ // get the routing entry of the current link
RoutingEntry tNextRoutePart = (RoutingEntry) tLink.getRoute().getFirst();
+ // do we have the first path part?
if(tResult != null){
- if(tResult.getNextHop().equals(tNextRoutePart.getSource())){
+ if(tResult.getLastNextHop().equals(tNextRoutePart.getSource())){
tResult.append(tNextRoutePart, "RT::create()_1");
- // aggregate the next hop
- tResult.setNextHop(tNextRoutePart.getNextHop());
+ /**
+ * auto-learn the next physical hop
+ */
+ if(tResult.getHopCount() == NO_HOP_COSTS){
+ // aggregate the next hop
+ tResult.setNextHop(tNextRoutePart.getNextHop());
+ }
}else{
- Logging.err(null, "Cannot create an aggregated routing entry..");
- Logging.err(null, " ..current result: " + tResult);
- Logging.err(null, " ..faulty next part: " + tNextRoutePart);
+// Logging.err(null, "Cannot create an aggregated routing entry..");
+// Logging.err(null, " ..current result: " + tResult);
+// Logging.err(null, " ..faulty next part: " + tNextRoutePart);
+// Logging.err(null, " ..overall path is:");
+// for(AbstractRoutingGraphLink tLink2 : pPath){
+// Logging.err(null, " .." + tLink2);
+// }
// reset the result
tResult = null;
// immediate return
break;
}
}else{
// start with first path fragment
tResult = tNextRoutePart.clone();
tResult.extendCause("RT::create()_2");
}
}else{
// reset the result
tResult = null;
- // imediate return
+ // immediate return
break;
}
}
}
}
return tResult;
}
/**
* Factory function: creates a route to a direct neighbor.
*
* @param pSource the source of the route
* @param pDestination the direct neighbor
* @param pNextHop the next hop for the route
* @param pUtilization the utilization of the described route
* @param pMinDelay the minimum additional delay the described route causes
* @param pMaxDataRate the maximum data rate the described route might provide
* @param pCause the cause for this routing table entry
*/
public static RoutingEntry createRouteToDirectNeighbor(HRMID pSource, HRMID pDestination, HRMID pNextHop, float pUtilization, long pMinDelay, long pMaxDataRate, String pCause)
{
// create instance
RoutingEntry tEntry = create(pSource, pDestination, pNextHop, HRMConfig.Routing.HOP_COSTS_TO_A_DIRECT_NEIGHBOR, pUtilization, pMinDelay, pMaxDataRate, pCause);
// mark as local loop
tEntry.mRouteToDirectNeighbor = true;
// return with the entry
return tEntry;
}
/**
* Factory function: creates a route to a direct neighbor.
*
* @param pSource the source of the route
* @param pDirectNeighbor the direct neighbor
* @param pUtilization the utilization of the described route
* @param pMinDelay the minimum additional delay the described route causes
* @param pMaxDataRate the maximum data rate the described route might provide
* @param pCause the cause for this routing table entry
*/
private static RoutingEntry createRouteToDirectNeighbor(HRMID pSource, HRMID pDirectNeighbor, float pUtilization, long pMinDelay, long pMaxDataRate, String pCause)
{
// return with the entry
return createRouteToDirectNeighbor(pSource, pDirectNeighbor, pDirectNeighbor, pUtilization, pMinDelay, pMaxDataRate, pCause);
}
/**
* Factory function: creates a route to a direct neighbor.
*
* @param pDirectNeighbor the destination of the direct neighbor
* @param pUtilization the utilization of the described route
* @param pMinDelay the minimum additional delay the described route causes
* @param pMaxDataRate the maximum data rate the described route might provide
* @param pCause the cause for this routing table entry
*/
public static RoutingEntry createRouteToDirectNeighbor(HRMID pDirectNeighbor, float pUtilization, long pMinDelay, long pMaxDataRate, String pCause)
{
// return with the entry
return createRouteToDirectNeighbor(null, pDirectNeighbor, pUtilization, pMinDelay, pMaxDataRate, pCause);
}
/**
* Assigns the entry to an HRG instance
*/
public void assignToHRG(AbstractRoutingGraph<HRMID, AbstractRoutingGraphLink> pMHierarchicalRoutingGraph)
{
mBelongstoHRG = true;
}
/**
* Extends the cause string
*
* @param pCause the additional cause string
*/
public void extendCause(String pCause)
{
if(RECORD_CAUSES){
mCause.add(pCause);
}
}
/**
* Returns the cause for this entry
*
* @return the cause
*/
public LinkedList<String> getCause()
{
return mCause;
}
/**
* Sets a new timeout for this route entry
*
* @param pTimeout the new timeout
*/
public void setTimeout(double pTimeout)
{
mTimeout = pTimeout;
}
/**
* Returns the timeout for this route entry
*
* @return the new timeout
*/
public double getTimeout()
{
return mTimeout;
}
/**
* Defines the L2 address of the next hop
*
* @param pDestL2Address the L2 address of the next hop
*/
public void setNextHopL2Address(L2Address pNextHopL2Address)
{
mNextHopL2Address = pNextHopL2Address;
}
/**
* Returns the L2 address of the next hop of this route (if known)
*
* @return the L2 address of the next hop, returns null if none is known
*/
public L2Address getNextHopL2Address()
{
return (mNextHopL2Address != null ? mNextHopL2Address.clone() : null);
}
/**
* Returns the source of the route
*
* @return the source
*/
public HRMID getSource()
{
return mSource.clone();
}
/**
* Returns the destination of the route
*
* @return the destination
*/
public HRMID getDest()
{
return mDestination.clone();
}
/**
* Sets a new destination
*
* @param pDestination the new destination
*/
public void setDest(HRMID pDestination)
{
mDestination = (pDestination != null ? pDestination.clone() : null);
}
/**
* Sets a new source
*
* @param pSource the new source
*/
public void setSource(HRMID pSource)
{
mSource = (pSource != null ? pSource.clone() : null);
}
/**
* Returns the last next hop of this route
*
* @return the last next hop
*/
public HRMID getLastNextHop()
{
return mLastNextHop.clone();
}
/**
* Sets a new last next hop
*
* @param pNextHop the new last next hop
*/
public void setLastNextHop(HRMID pLastNextHop)
{
mLastNextHop = (pLastNextHop != null ? pLastNextHop.clone() : null);
}
/**
* Returns the next hop of this route
*
* @return the next hop
*/
public HRMID getNextHop()
{
return mNextHop.clone();
}
/**
* Sets a new next hop
*
* @param pNextHop the new next hop
*/
public void setNextHop(HRMID pNextHop)
{
mNextHop = (pNextHop != null ? pNextHop.clone() : null);
setLastNextHop(mNextHop);
}
/**
* Sets a new cause description
*
* @param pCause the new description
*/
public void setCause(LinkedList<String> pCause)
{
mCause = pCause;
}
/**
* Returns the hop costs of this route
*
* @return the hop costs
*/
public int getHopCount()
{
return mHopCount;
}
/**
* Returns the utilization of this route
*
* @return the utilization
*/
public float getUtilization()
{
return mUtilization;
}
/**
* Returns the minimum additional delay this route causes.
*
* @return the minimum additional delay
*/
public long getMinDelay()
{
return mMinDelay;
}
/**
* Returns the maximum data rate this route might provide.
*
* @return the maximum data rate
*/
public long getMaxDataRate()
{
return mMaxDataRate;
}
/**
* Determines if the route describes a local loop.
* (for GUI only)
*
* @return true if the route is a local loop, otherwise false
*/
public boolean isLocalLoop()
{
return mLocalLoop;
}
/**
* Determines if the route ends at a direct neighbor.
* (for GUI only)
*
* @return true if the route is such a route, otherwise false
*/
public boolean isRouteToDirectNeighbor()
{
return mRouteToDirectNeighbor;
}
/**
* Determines if the route ends at a direct neighbor.
*
* @return true if the route is such a route, otherwise false
*/
public boolean isRouteForClusterTraversal()
{
return mRouteForClusterTraversal;
}
/**
* Marks this routing entry as being used for cluster traversal
*/
public void setRouteForClusterTraversal()
{
mRouteForClusterTraversal = true;
}
/**
* Marks this link as reported from an inferior entity
*
* @param pSender the sender of this reported link
*/
public void setReportedLink(HRMID pSender)
{
mReportedLink = true;
mReporter = pSender;
}
/**
* Marks this link as reported from an inferior entity
*
* @param pSender the sender of this shared link
*/
public void setSharedLink(HRMID pSender)
{
mSharedLink = true;
mSharer = pSender;
}
/**
* Returns the sender of this shared link
*
* @return the sender
*/
public HRMID getShareSender()
{
return mSharer;
}
/**
* Returns the sender of this reported link
*
* @return the sender
*/
public HRMID getReportSender()
{
return mReporter;
}
/**
* Returns if this link was shared
*
* @return true or false
*/
public boolean isSharedLink()
{
return mSharedLink;
}
/**
* Returns if this link was reported
*
* @return true or false
*/
public boolean isReportedLink()
{
return mReportedLink;
}
/**
* Combines this entry with another one
*
* @param pOtherEntry the other routing entry
*/
public void chain(RoutingEntry pOtherEntry)
{
RoutingEntry tOldThis = clone();
// HOP COUNT -> add both
mHopCount += pOtherEntry.mHopCount;
// MIN DELAY -> add both
mMinDelay += pOtherEntry.mMinDelay;
// MAX DATA RATE -> find the minimum
mMaxDataRate = (mMaxDataRate < pOtherEntry.mMaxDataRate ? mMaxDataRate : pOtherEntry.mMaxDataRate);
// UTILIZATION -> find the maximum
mUtilization = (mUtilization > pOtherEntry.mUtilization ? mUtilization : pOtherEntry.mUtilization);
// how should we combine both route entries?
if(mSource.equals(pOtherEntry.mNextHop)){
/**
* we have "other ==> this"
*/
mSource = pOtherEntry.mSource;
mNextHop = pOtherEntry.mNextHop;
mNextHopL2Address = pOtherEntry.mNextHopL2Address;
}else if(mNextHop.equals(pOtherEntry.mSource)){
/**
* we have "this == other"
*/
mDestination = pOtherEntry.mDestination;
}else{
throw new RuntimeException("Cannot chain these two routing entries: \n ..entry 1: " + tOldThis + "\n ..entry 2: " + pOtherEntry);
}
// deactivate loopback flag
mLocalLoop = false;
// deactivate neighbor flag
mRouteToDirectNeighbor = false;
extendCause(" ");
extendCause("RoutingEntry::CHAINING()_start with these two entries:");
extendCause(" this: " + tOldThis);
extendCause(" other: " + pOtherEntry);
for(String tCauseString : pOtherEntry.getCause()){
extendCause("CHAINED ENTRY: " + tCauseString);
}
extendCause("RoutingEntry::CHAINING()_end as: " + this);
extendCause(" ");
}
/**
* Appends another entry to this one
*
* @param pOtherEntry the other routing entry
* @param pCause the cause for this call
*/
public void append(RoutingEntry pOtherEntry, String pCause)
{
RoutingEntry tOldThis = clone();
if(pOtherEntry == null){
Logging.err(this, "append() got a null pointer");
return;
}
// set the next hop of the other entry as last next hop of the resulting routing entry
setLastNextHop(pOtherEntry.mNextHop);
/**
* auto-learn the next physical hop
*/
if(mHopCount == NO_HOP_COSTS){
setNextHop(pOtherEntry.mNextHop);
}
// HOP COUNT -> add both
mHopCount += pOtherEntry.mHopCount;
// MIN DELAY -> add both
mMinDelay += pOtherEntry.mMinDelay;
// MAX DATA RATE -> find the minimum
mMaxDataRate = (mMaxDataRate < pOtherEntry.mMaxDataRate ? mMaxDataRate : pOtherEntry.mMaxDataRate);
// UTILIZATION -> find the maximum
mUtilization = (mUtilization > pOtherEntry.mUtilization ? mUtilization : pOtherEntry.mUtilization);
mDestination = pOtherEntry.mDestination;
// deactivate loopback flag
mLocalLoop = false;
// deactivate neighbor flag
mRouteToDirectNeighbor = false;
extendCause(" ");
extendCause("RoutingEntry::APPENDING()_start, cause=" + pCause);
extendCause(" this: " + tOldThis);
extendCause(" other: " + pOtherEntry);
for(String tCauseString : pOtherEntry.getCause()){
extendCause("APPENDED ENTRY: " + tCauseString);
}
extendCause("RoutingEntry::APPENDING()_end as: " + this);
extendCause(" ");
}
/**
* Creates an identical duplicate
*
* @return the identical duplicate
*/
public RoutingEntry clone()
{
// create object copy
RoutingEntry tResult = new RoutingEntry(mSource, mDestination, mNextHop, mHopCount, mUtilization, mMinDelay, mMaxDataRate, mCause);
// update the last next hop
tResult.setLastNextHop(mLastNextHop);
// update the flag "route to direct neighbor"
tResult.mRouteToDirectNeighbor = mRouteToDirectNeighbor;
// update flag "route to local host"
tResult.mLocalLoop = mLocalLoop;
// update next hop L2 address
tResult.mNextHopL2Address = mNextHopL2Address;
// update timeout
tResult.mTimeout = mTimeout;
tResult.mSharedLink = mSharedLink;
tResult. mReportedLink = mReportedLink;
tResult.mSharer = mSharer;
tResult.mReporter = mReporter;
return tResult;
}
/**
* Returns if both objects address the same cluster/coordinator
*
* @return true or false
*/
@Override
public boolean equals(Object pObj)
{
//Logging.trace(this, "Comparing routing entry with: " + pObj);
if(pObj instanceof RoutingEntry){
RoutingEntry tOther = (RoutingEntry)pObj;
if(((getDest() == null) || (tOther.getDest() == null) || (getDest().equals(tOther.getDest()))) &&
((getNextHop() == null) || (tOther.getNextHop() == null) || (getNextHop().equals(tOther.getNextHop()))) &&
((getSource() == null) || (tOther.getSource() == null) || (getSource().equals(tOther.getSource()))) //&&
/*((getNextHopL2Address() == null) || (tOther.getNextHopL2Address() == null) || (getNextHopL2Address().equals(tOther.getNextHopL2Address())))*/){
//Logging.trace(this, " ..true");
return true;
}
}
//Logging.trace(this, " ..false");
return false;
}
/**
* Returns the size of a serialized representation
*
* @return the size
*/
@Override
public int getSerialisedSize()
{
// TODO: implement me
return 0;
}
/**
* Returns an object describing string
*
* @return the describing string
*/
@Override
public String toString()
{
String tResult = (mReportedLink ? "REP: " : "") + (mSharedLink ? "SHA: " : "");
if(!mBelongstoHRG){
tResult += "(" + (getSource() != null ? "Source=" + getSource() + ", " : "") + "Dest.=" + getDest() + ", Next=" + getNextHop() + (getLastNextHop() != null ? ", LastNext=" + getLastNextHop() : "") + (getNextHopL2Address() != null ? ", NextL2=" + getNextHopL2Address() : "") + ", Hops=" + (getHopCount() > 0 ? getHopCount() : "none") + (HRMConfig.QoS.REPORT_QOS_ATTRIBUTES_AUTOMATICALLY ? ", Util=" + (getUtilization() > 0 ? getUtilization() : "none") + ", MinDel=" + (getMinDelay() > 0 ? getMinDelay() : "none") + ", MaxDR=" + (getMaxDataRate() != INFINITE_DATARATE ? getMaxDataRate() : "inf.") : "") + ")";
}else{
tResult += getSource() + " <=" + (mRouteForClusterTraversal ? "TRAV" : "") + "=> " + getNextHop() + ", Dest.=" + getDest() + (mTimeout > 0 ? ", TO: " + mTimeout : "") + (getNextHopL2Address() != null ? ", NextL2=" + getNextHopL2Address() : "") + ", Hops=" + (getHopCount() > 0 ? getHopCount() : "none") + (HRMConfig.QoS.REPORT_QOS_ATTRIBUTES_AUTOMATICALLY ? ", Util=" + (getUtilization() > 0 ? getUtilization() : "none") + ", MinDel=" + (getMinDelay() > 0 ? getMinDelay() : "none") + ", MaxDR=" + (getMaxDataRate() != INFINITE_DATARATE ? getMaxDataRate() : "inf.") : "");
}
return tResult;
}
}
| false | false | null | null |
diff --git a/JodaTime/src/java/org/joda/time/format/DateTimeFormatter.java b/JodaTime/src/java/org/joda/time/format/DateTimeFormatter.java
index 3ab9eb25..e841eae0 100644
--- a/JodaTime/src/java/org/joda/time/format/DateTimeFormatter.java
+++ b/JodaTime/src/java/org/joda/time/format/DateTimeFormatter.java
@@ -1,650 +1,649 @@
/*
* Copyright 2001-2005 Stephen Colebourne
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.joda.time.format;
import java.io.IOException;
import java.io.Writer;
import java.util.Locale;
import org.joda.time.Chronology;
import org.joda.time.DateTime;
import org.joda.time.DateTimeUtils;
import org.joda.time.DateTimeZone;
import org.joda.time.MutableDateTime;
import org.joda.time.ReadWritableInstant;
import org.joda.time.ReadableInstant;
import org.joda.time.ReadablePartial;
/**
* Controls the printing and parsing of a datetime to and from a string.
* <p>
* This class is the main API for printing and parsing used by most applications.
* Instances of this class are created via one of three factory classes:
* <ul>
* <li>{@link DateTimeFormat} - formats by pattern and style</li>
* <li>{@link ISODateTimeFormat} - ISO8601 formats</li>
* <li>{@link DateTimeFormatterBuilder} - complex formats created via method calls</li>
* </ul>
* <p>
* An instance of this class holds a reference internally to one printer and
* one parser. It is possible that one of these may be null, in which case the
* formatter cannot print/parse. This can be checked via the {@link #isPrinter()}
* and {@link #isParser()} methods.
* <p>
* The underlying printer/parser can be altered to behave exactly as required
* by using one of the decorator modifiers:
* <ul>
* <li>{@link #withLocale(Locale)} - returns a new formatter that uses the specified locale</li>
* <li>{@link #withZone(DateTimeZone)} - returns a new formatter that uses the specified time zone</li>
* <li>{@link #withChronology(Chronology)} - returns a new formatter that uses the specified chronology</li>
* <li>{@link #withOffsetParsed()} - returns a new formatter that returns the parsed time zone offset</li>
* </ul>
* Each of these returns a new formatter (instances of this class are immutable).
* <p>
* The main methods of the class are the <code>printXxx</code> and
* <code>parseXxx</code> methods. These are used as follows:
* <pre>
* // print using the defaults (default locale, chronology/zone of the datetime)
* String dateStr = formatter.print(dt);
* // print using the French locale
* String dateStr = formatter.withLocale(Locale.FRENCH).print(dt);
* // print using the UTC zone
* String dateStr = formatter.withZone(DateTimeZone.UTC).print(dt);
*
* // parse using the Paris zone
* DateTime date = formatter.withZone(DateTimeZone.forID("Europe/Paris")).parseDateTime(str);
* </pre>
*
* @author Brian S O'Neill
* @author Stephen Colebourne
* @since 1.0
*/
public class DateTimeFormatter {
/** The internal printer used to output the datetime. */
private final DateTimePrinter iPrinter;
/** The internal parser used to output the datetime. */
private final DateTimeParser iParser;
/** The locale to use for printing and parsing. */
private final Locale iLocale;
/** Whether the offset is parsed. */
private final boolean iOffsetParsed;
/** The chronology to use as an override. */
private final Chronology iChrono;
/** The zone to use as an override. */
private final DateTimeZone iZone;
/**
* Creates a new formatter, however you will normally use the factory
* or the builder.
*
* @param printer the internal printer, null if cannot print
* @param parser the internal parser, null if cannot parse
*/
public DateTimeFormatter(
DateTimePrinter printer, DateTimeParser parser) {
super();
iPrinter = printer;
iParser = parser;
iLocale = null;
iOffsetParsed = false;
iChrono = null;
iZone = null;
}
/**
* Constructor.
*/
private DateTimeFormatter(
DateTimePrinter printer, DateTimeParser parser,
Locale locale, boolean offsetParsed,
Chronology chrono, DateTimeZone zone) {
super();
iPrinter = printer;
iParser = parser;
iLocale = locale;
iOffsetParsed = offsetParsed;
iChrono = chrono;
iZone = zone;
}
//-----------------------------------------------------------------------
/**
* Is this formatter capable of printing.
*
* @return true if this is a printer
*/
public boolean isPrinter() {
return (iPrinter != null);
}
/**
* Gets the internal printer object that performs the real printing work.
*
* @return the internal printer
*/
public DateTimePrinter getPrinter() {
return iPrinter;
}
/**
* Is this formatter capable of parsing.
*
* @return true if this is a parser
*/
public boolean isParser() {
return (iParser != null);
}
/**
* Gets the internal parser object that performs the real parsing work.
*
* @return the internal parser
*/
public DateTimeParser getParser() {
return iParser;
}
//-----------------------------------------------------------------------
/**
* Returns a new formatter with a different locale that will be used
* for printing and parsing.
* <p>
* A DateTimeFormatter is immutable, so a new instance is returned,
* and the original is unaltered and still usable.
*
* @param locale the locale to use
* @return the new formatter
*/
public DateTimeFormatter withLocale(Locale locale) {
locale = (locale == null ? Locale.getDefault() : locale);
if (locale.equals(getLocale())) {
return this;
}
return new DateTimeFormatter(iPrinter, iParser, locale, iOffsetParsed, iChrono, iZone);
}
/**
* Gets the locale that will be used for printing and parsing.
*
* @return the locale to use
*/
public Locale getLocale() {
return iLocale;
}
//-----------------------------------------------------------------------
/**
* Returns a new formatter that will create a datetime with a time zone
* equal to that of the offset of the parsed string.
* <p>
* After calling this method, a string '2004-06-09T10:20:30-08:00' will
* create a datetime with a zone of -08:00 (a fixed zone, with no daylight
* savings rules). If the parsed string represents a local time (no zone
* offset) the parsed datetime will be in the default zone.
* <p>
* Calling this method sets the override zone to null.
* Calling the override zone method sets this flag off.
*
- * @param locale the locale to use
* @return the new formatter
*/
public DateTimeFormatter withOffsetParsed() {
if (iOffsetParsed == true) {
return this;
}
return new DateTimeFormatter(iPrinter, iParser, iLocale, true, iChrono, null);
}
/**
* Checks whether the offset from the string is used as the zone of
* the parsed datetime.
*
* @return true if the offset from the string is used as the zone
*/
public boolean isOffsetParsed() {
return iOffsetParsed;
}
//-----------------------------------------------------------------------
/**
* Returns a new formatter that will use the specified chronology in
* preference to that of the printed object, or ISO on a parse.
* <p>
* When printing, this chronolgy will be used in preference to the chronology
* from the datetime that would otherwise be used.
* <p>
* When parsing, this chronology will be set on the parsed datetime.
* <p>
- * A null zone means of no-override.
+ * A null chronology means of no-override.
* If both an override chronology and an override zone are set, the
* override zone will take precedence over the zone in the chronology.
*
- * @param zone the zone to use as an override
+ * @param chrono the chronology to use as an override
* @return the new formatter
*/
public DateTimeFormatter withChronology(Chronology chrono) {
if (iChrono == chrono) {
return this;
}
return new DateTimeFormatter(iPrinter, iParser, iLocale, iOffsetParsed, chrono, iZone);
}
/**
* Gets the chronology to use as an override.
*
* @return the chronology to use as an override
*/
public Chronology getChronolgy() {
return iChrono;
}
//-----------------------------------------------------------------------
/**
* Returns a new formatter that will use the specified zone in preference
* to the zone of the printed object, or default zone on a parse.
* <p>
* When printing, this zone will be used in preference to the zone
* from the datetime that would otherwise be used.
* <p>
* When parsing, this zone will be set on the parsed datetime.
* <p>
* A null zone means of no-override.
* If both an override chronology and an override zone are set, the
* override zone will take precedence over the zone in the chronology.
*
* @param zone the zone to use as an override
* @return the new formatter
*/
public DateTimeFormatter withZone(DateTimeZone zone) {
if (iZone == zone) {
return this;
}
return new DateTimeFormatter(iPrinter, iParser, iLocale, false, iChrono, zone);
}
/**
* Gets the zone to use as an override.
*
* @return the zone to use as an override
*/
public DateTimeZone getZone() {
return iZone;
}
//-----------------------------------------------------------------------
/**
* Prints a ReadableInstant, using the chronology supplied by the instant.
*
* @param buf formatted instant is appended to this buffer
* @param instant instant to format, null means now
*/
public void printTo(StringBuffer buf, ReadableInstant instant) {
checkPrinter();
long millis = DateTimeUtils.getInstantMillis(instant);
Chronology chrono = DateTimeUtils.getInstantChronology(instant);
printTo(buf, millis, chrono);
}
/**
* Prints a ReadableInstant, using the chronology supplied by the instant.
*
* @param out formatted instant is written out
* @param instant instant to format, null means now
*/
public void printTo(Writer out, ReadableInstant instant) throws IOException {
checkPrinter();
long millis = DateTimeUtils.getInstantMillis(instant);
Chronology chrono = DateTimeUtils.getInstantChronology(instant);
printTo(out, millis, chrono);
}
//-----------------------------------------------------------------------
/**
* Prints an instant from milliseconds since 1970-01-01T00:00:00Z,
* using ISO chronology in the default DateTimeZone.
*
* @param buf formatted instant is appended to this buffer
* @param instant millis since 1970-01-01T00:00:00Z
*/
public void printTo(StringBuffer buf, long instant) {
checkPrinter();
printTo(buf, instant, null);
}
/**
* Prints an instant from milliseconds since 1970-01-01T00:00:00Z,
* using ISO chronology in the default DateTimeZone.
*
* @param out formatted instant is written out
* @param instant millis since 1970-01-01T00:00:00Z
*/
public void printTo(Writer out, long instant) throws IOException {
checkPrinter();
printTo(out, instant, null);
}
//-----------------------------------------------------------------------
/**
* Prints a ReadablePartial.
* <p>
* Neither the override chronology nor the override zone are used
* by this method.
*
* @param buf formatted partial is appended to this buffer
* @param partial partial to format
*/
public void printTo(StringBuffer buf, ReadablePartial partial) {
checkPrinter();
if (partial == null) {
throw new IllegalArgumentException("The partial must not be null");
}
iPrinter.printTo(buf, partial, iLocale);
}
/**
* Prints a ReadablePartial.
* <p>
* Neither the override chronology nor the override zone are used
* by this method.
*
* @param out formatted partial is written out
* @param partial partial to format
*/
public void printTo(Writer out, ReadablePartial partial) throws IOException {
checkPrinter();
if (partial == null) {
throw new IllegalArgumentException("The partial must not be null");
}
iPrinter.printTo(out, partial, iLocale);
}
//-----------------------------------------------------------------------
/**
* Prints a ReadableInstant to a String.
* <p>
* This method will use the override zone and the override chronololgy if
* they are set. Otherwise it will use the chronology and zone of the instant.
*
* @param instant instant to format, null means now
* @return the printed result
*/
public String print(ReadableInstant instant) {
checkPrinter();
StringBuffer buf = new StringBuffer(iPrinter.estimatePrintedLength());
printTo(buf, instant);
return buf.toString();
}
/**
* Prints a millisecond instant to a String.
* <p>
* This method will use the override zone and the override chronololgy if
* they are set. Otherwise it will use the ISO chronology and default zone.
*
* @param instant millis since 1970-01-01T00:00:00Z
* @return the printed result
*/
public String print(long instant) {
checkPrinter();
StringBuffer buf = new StringBuffer(iPrinter.estimatePrintedLength());
printTo(buf, instant);
return buf.toString();
}
/**
* Prints a ReadablePartial to a new String.
* <p>
* Neither the override chronology nor the override zone are used
* by this method.
*
* @param partial partial to format
* @return the printed result
*/
public String print(ReadablePartial partial) {
checkPrinter();
StringBuffer buf = new StringBuffer(iPrinter.estimatePrintedLength());
printTo(buf, partial);
return buf.toString();
}
private void printTo(StringBuffer buf, long instant, Chronology chrono) {
chrono = selectChronology(chrono);
// Shift instant into local time (UTC) to avoid excessive offset
// calculations when printing multiple fields in a composite printer.
DateTimeZone zone = chrono.getZone();
int offset = zone.getOffset(instant);
iPrinter.printTo(buf, instant + offset, chrono.withUTC(), offset, zone, iLocale);
}
private void printTo(Writer buf, long instant, Chronology chrono) throws IOException {
chrono = selectChronology(chrono);
// Shift instant into local time (UTC) to avoid excessive offset
// calculations when printing multiple fields in a composite printer.
DateTimeZone zone = chrono.getZone();
int offset = zone.getOffset(instant);
iPrinter.printTo(buf, instant + offset, chrono.withUTC(), offset, zone, iLocale);
}
/**
* Method called when there is nothing to parse.
*
* @return the exception
*/
private void checkPrinter() {
if (iPrinter == null) {
throw new UnsupportedOperationException("Printing not supported");
}
}
//-----------------------------------------------------------------------
/**
* Parses a datetime from the given text, at the given position, saving the
* result into the fields of the given ReadWritableInstant. If the parse
* succeeds, the return value is the new text position. Note that the parse
* may succeed without fully reading the text and in this case those fields
* that were read will be set.
* <p>
* Only those fields present in the string will be changed in the specified
* instant. All other fields will remain unaltered. Thus if the string only
* contains a year and a month, then the day and time will be retained from
* the input instant. If this is not the behaviour you want, then reset the
* fields before calling this method, or use {@link #parseDateTime(String)}
* or {@link #parseMutableDateTime(String)}.
* <p>
* If it fails, the return value is negative, but the instant may still be
* modified. To determine the position where the parse failed, apply the
* one's complement operator (~) on the return value.
* <p>
* The parse will use the chronology of the instant.
*
* @param instant an instant that will be modified, not null
* @param text the text to parse
* @param position position to start parsing from
* @return new position, negative value means parse failed -
* apply complement operator (~) to get position of failure
* @throws UnsupportedOperationException if parsing is not supported
* @throws IllegalArgumentException if the instant is null
* @throws IllegalArgumentException if any field is out of range
*/
public int parseInto(ReadWritableInstant instant, String text, int position) {
checkParser();
if (instant == null) {
throw new IllegalArgumentException("Instant must not be null");
}
long instantMillis = instant.getMillis();
Chronology chrono = instant.getChronology();
long instantLocal = instantMillis + chrono.getZone().getOffset(instantMillis);
chrono = selectChronology(chrono);
DateTimeParserBucket bucket = new DateTimeParserBucket(instantLocal, chrono, iLocale);
int newPos = iParser.parseInto(bucket, text, position);
instant.setMillis(bucket.computeMillis());
if (iOffsetParsed && bucket.getZone() == null) {
int parsedOffset = bucket.getOffset();
DateTimeZone parsedZone = DateTimeZone.forOffsetMillis(parsedOffset);
chrono = chrono.withZone(parsedZone);
}
instant.setChronology(chrono);
return newPos;
}
/**
* Parses a datetime from the given text, returning the number of
* milliseconds since the epoch, 1970-01-01T00:00:00Z.
* <p>
* The parse will use the ISO chronology, and the default time zone.
* If the text contains a time zone string then that will be taken into account.
*
* @param text text to parse
* @return parsed value expressed in milliseconds since the epoch
* @throws UnsupportedOperationException if parsing is not supported
* @throws IllegalArgumentException if the text to parse is invalid
*/
public long parseMillis(String text) {
checkParser();
Chronology chrono = selectChronology(iChrono);
DateTimeParserBucket bucket = new DateTimeParserBucket(0, chrono, iLocale);
int newPos = iParser.parseInto(bucket, text, 0);
if (newPos >= 0) {
if (newPos >= text.length()) {
return bucket.computeMillis(true);
}
} else {
newPos = ~newPos;
}
throw new IllegalArgumentException(FormatUtils.createErrorMessage(text, newPos));
}
/**
* Parses a datetime from the given text, returning a new DateTime.
* <p>
* The parse will use the zone and chronology specified on this formatter.
* <p>
* If the text contains a time zone string then that will be taken into
* account in adjusting the time of day as follows.
* If the {@link #withOffsetParsed()} has been called, then the resulting
* DateTime will have a fixed offset based on the parsed time zone.
* Otherwise the resulting DateTime will have the zone of this formatter,
* but the parsed zone may have caused the time to be adjusted.
*
* @param text the text to parse
* @return parsed value in a DateTime object
* @throws UnsupportedOperationException if parsing is not supported
* @throws IllegalArgumentException if the text to parse is invalid
*/
public DateTime parseDateTime(String text) {
checkParser();
Chronology chrono = selectChronology(null);
DateTimeParserBucket bucket = new DateTimeParserBucket(0, chrono, iLocale);
int newPos = iParser.parseInto(bucket, text, 0);
if (newPos >= 0) {
if (newPos >= text.length()) {
long millis = bucket.computeMillis(true);
if (iOffsetParsed && bucket.getZone() == null) {
int parsedOffset = bucket.getOffset();
DateTimeZone parsedZone = DateTimeZone.forOffsetMillis(parsedOffset);
chrono = chrono.withZone(parsedZone);
}
return new DateTime(millis, chrono);
}
} else {
newPos = ~newPos;
}
throw new IllegalArgumentException(FormatUtils.createErrorMessage(text, newPos));
}
/**
* Parses a datetime from the given text, returning a new MutableDateTime.
* <p>
* The parse will use the zone and chronology specified on this formatter.
* <p>
* If the text contains a time zone string then that will be taken into
* account in adjusting the time of day as follows.
* If the {@link #withOffsetParsed()} has been called, then the resulting
* DateTime will have a fixed offset based on the parsed time zone.
* Otherwise the resulting DateTime will have the zone of this formatter,
* but the parsed zone may have caused the time to be adjusted.
*
* @param text the text to parse
* @return parsed value in a MutableDateTime object
* @throws UnsupportedOperationException if parsing is not supported
* @throws IllegalArgumentException if the text to parse is invalid
*/
public MutableDateTime parseMutableDateTime(String text) {
checkParser();
Chronology chrono = selectChronology(null);
DateTimeParserBucket bucket = new DateTimeParserBucket(0, chrono, iLocale);
int newPos = iParser.parseInto(bucket, text, 0);
if (newPos >= 0) {
if (newPos >= text.length()) {
long millis = bucket.computeMillis(true);
if (iOffsetParsed && bucket.getZone() == null) {
int parsedOffset = bucket.getOffset();
DateTimeZone parsedZone = DateTimeZone.forOffsetMillis(parsedOffset);
chrono = chrono.withZone(parsedZone);
}
return new MutableDateTime(millis, chrono);
}
} else {
newPos = ~newPos;
}
throw new IllegalArgumentException(FormatUtils.createErrorMessage(text, newPos));
}
/**
* Method called when there is nothing to parse.
*
* @return the exception
*/
private void checkParser() {
if (iParser == null) {
throw new UnsupportedOperationException("Parsing not supported");
}
}
//-----------------------------------------------------------------------
/**
* Determines the correct chronology to use.
*
* @param chrono the proposed chronology
* @return the actual chronology
*/
private Chronology selectChronology(Chronology chrono) {
chrono = DateTimeUtils.getChronology(chrono);
if (iChrono != null) {
chrono = iChrono;
}
if (iZone != null) {
chrono = chrono.withZone(iZone);
}
return chrono;
}
}
diff --git a/JodaTime/src/java/org/joda/time/format/DateTimeFormatterBuilder.java b/JodaTime/src/java/org/joda/time/format/DateTimeFormatterBuilder.java
index 2bb8bff1..aaa8556b 100644
--- a/JodaTime/src/java/org/joda/time/format/DateTimeFormatterBuilder.java
+++ b/JodaTime/src/java/org/joda/time/format/DateTimeFormatterBuilder.java
@@ -1,2359 +1,2359 @@
/*
* Copyright 2001-2005 Stephen Colebourne
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.joda.time.format;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import org.joda.time.Chronology;
import org.joda.time.DateTimeConstants;
import org.joda.time.DateTimeField;
import org.joda.time.DateTimeFieldType;
import org.joda.time.DateTimeZone;
import org.joda.time.ReadablePartial;
import org.joda.time.field.MillisDurationField;
import org.joda.time.field.PreciseDateTimeField;
/**
* Factory that creates complex instances of DateTimeFormatter via method calls.
* <p>
* Datetime formatting is performed by the {@link DateTimeFormatter} class.
* Three classes provide factory methods to create formatters, and this is one.
* The others are {@link DateTimeFormat} and {@link ISODateTimeFormat}.
* <p>
* DateTimeFormatterBuilder is used for constructing formatters which are then
* used to print or parse. The formatters are built by appending specific fields
* or other formatters to an instanece of this builder.
* <p>
* For example, a formatter that prints month and year, like "January 1970",
* can be constructed as follows:
* <p>
* <pre>
* DateTimeFormatter monthAndYear = new DateTimeFormatterBuilder()
* .appendMonthOfYearText()
* .appendLiteral(' ')
* .appendYear(4, 4)
* .toFormatter();
* </pre>
* <p>
* DateTimeFormatterBuilder itself is mutable and not thread-safe, but the
* formatters that it builds are thread-safe and immutable.
*
* @author Brian S O'Neill
* @author Stephen Colebourne
* @since 1.0
* @see DateTimeFormat
* @see ISODateTimeFormat
*/
public class DateTimeFormatterBuilder {
/** Array of printers and parsers (alternating). */
private ArrayList iElementPairs;
/** Cache of the last returned formatter. */
private Object iFormatter;
//-----------------------------------------------------------------------
/**
* Creates a DateTimeFormatterBuilder.
*/
public DateTimeFormatterBuilder() {
super();
iElementPairs = new ArrayList();
}
//-----------------------------------------------------------------------
/**
* Converts to a DateTimePrinter that can only print, using all the
* appended elements.
* <p>
* Subsequent changes to this builder do not affect the returned formatter.
*
* @throws UnsupportedOperationException if printing is not supported
*/
public DateTimePrinter toPrinter() {
Object f = getFormatter();
if (isPrinter(f)) {
return (DateTimePrinter) f;
}
throw new UnsupportedOperationException("Printing is not supported");
}
/**
* Converts to a DateTimeFormatter that can only parse, using all the
* appended elements.
* <p>
* Subsequent changes to this builder do not affect the returned formatter.
*
* @throws UnsupportedOperationException if parsing is not supported
*/
public DateTimeParser toParser() {
Object f = getFormatter();
if (isParser(f)) {
return (DateTimeParser) f;
}
throw new UnsupportedOperationException("Parsing is not supported");
}
/**
* Converts to a DateTimeFormatter that using all the appended elements.
* <p>
* Subsequent changes to this builder do not affect the returned formatter.
* <p>
* The returned formatter may not support both printing and parsing.
* The methods {@link DateTimeFormatter#isPrinter()} and
* {@link DateTimeFormatter#isParser()} will help you determine the state
* of the formatter.
*
* @throws UnsupportedOperationException if neither printing nor parsing is supported
*/
public DateTimeFormatter toFormatter() {
Object f = getFormatter();
DateTimePrinter printer = null;
if (isPrinter(f)) {
printer = (DateTimePrinter) f;
}
DateTimeParser parser = null;
if (isParser(f)) {
parser = (DateTimeParser) f;
}
if (printer != null || parser != null) {
return new DateTimeFormatter(printer, parser);
}
throw new UnsupportedOperationException("Both printing and parsing not supported");
}
//-----------------------------------------------------------------------
/**
* Returns true if toPrinter can be called without throwing an
* UnsupportedOperationException.
*
* @return true if a printer can be built
*/
public boolean canBuildPrinter() {
return isPrinter(getFormatter());
}
/**
* Returns true if toParser can be called without throwing an
* UnsupportedOperationException.
*
* @return true if a parser can be built
*/
public boolean canBuildParser() {
return isParser(getFormatter());
}
/**
* Returns true if toFormatter can be called without throwing an
* UnsupportedOperationException.
*
* @return true if a formatter can be built
*/
public boolean canBuildFormatter() {
return isFormatter(getFormatter());
}
//-----------------------------------------------------------------------
/**
* Clears out all the appended elements, allowing this builder to be
* reused.
*/
public void clear() {
iFormatter = null;
iElementPairs.clear();
}
//-----------------------------------------------------------------------
/**
* Appends another formatter.
*
* @param formatter the formatter to add
* @return this DateTimeFormatterBuilder
* @throws IllegalArgumentException if formatter is null or of an invalid type
*/
public DateTimeFormatterBuilder append(DateTimeFormatter formatter) {
if (formatter == null) {
throw new IllegalArgumentException("No formatter supplied");
}
return append0(formatter.getPrinter(), formatter.getParser());
}
/**
* Appends just a printer. With no matching parser, a parser cannot be
* built from this DateTimeFormatterBuilder.
*
* @param printer the printer to add
* @return this DateTimeFormatterBuilder
* @throws IllegalArgumentException if printer is null or of an invalid type
*/
public DateTimeFormatterBuilder append(DateTimePrinter printer) {
checkPrinter(printer);
return append0(printer, null);
}
/**
* Appends just a parser. With no matching printer, a printer cannot be
* built from this builder.
*
* @param parser the parser to add
* @return this DateTimeFormatterBuilder
* @throws IllegalArgumentException if parser is null or of an invalid type
*/
public DateTimeFormatterBuilder append(DateTimeParser parser) {
checkParser(parser);
return append0(null, parser);
}
/**
* Appends a printer/parser pair.
*
* @param printer the printer to add
* @param parser the parser to add
* @return this DateTimeFormatterBuilder
* @throws IllegalArgumentException if printer or parser is null or of an invalid type
*/
public DateTimeFormatterBuilder append(DateTimePrinter printer, DateTimeParser parser) {
checkPrinter(printer);
checkParser(parser);
return append0(printer, parser);
}
/**
* Appends a printer and a set of matching parsers. When parsing, the first
* parser in the list is selected for parsing. If it fails, the next is
* chosen, and so on. If none of these parsers succeeds, then the failed
* position of the parser that made the greatest progress is returned.
* <p>
* Only the printer is optional. In addtion, it is illegal for any but the
* last of the parser array elements to be null. If the last element is
* null, this represents the empty parser. The presence of an empty parser
* indicates that the entire array of parse formats is optional.
*
* @param printer the printer to add
* @param parsers the parsers to add
* @return this DateTimeFormatterBuilder
* @throws IllegalArgumentException if any printer or parser is of an invalid type
* @throws IllegalArgumentException if any parser element but the last is null
*/
public DateTimeFormatterBuilder append(DateTimePrinter printer, DateTimeParser[] parsers) {
if (printer != null) {
checkPrinter(printer);
}
if (parsers == null) {
throw new IllegalArgumentException("No parsers supplied");
}
int length = parsers.length;
if (length == 1) {
if (parsers[0] == null) {
throw new IllegalArgumentException("No parser supplied");
}
return append0(printer, parsers[0]);
}
DateTimeParser[] copyOfParsers = new DateTimeParser[length];
int i;
for (i = 0; i < length - 1; i++) {
if ((copyOfParsers[i] = parsers[i]) == null) {
throw new IllegalArgumentException("Incomplete parser array");
}
}
copyOfParsers[i] = parsers[i];
return append0(printer, new MatchingParser(copyOfParsers));
}
/**
* Appends just a parser element which is optional. With no matching
* printer, a printer cannot be built from this DateTimeFormatterBuilder.
*
* @return this DateTimeFormatterBuilder
* @throws IllegalArgumentException if parser is null or of an invalid type
*/
public DateTimeFormatterBuilder appendOptional(DateTimeParser parser) {
checkParser(parser);
DateTimeParser[] parsers = new DateTimeParser[] {parser, null};
return append0(null, new MatchingParser(parsers));
}
//-----------------------------------------------------------------------
/**
* Checks if the parser is non null and a provider.
*
* @param parser the parser to check
*/
private void checkParser(DateTimeParser parser) {
if (parser == null) {
throw new IllegalArgumentException("No parser supplied");
}
}
/**
* Checks if the printer is non null and a provider.
*
* @param printer the printer to check
*/
private void checkPrinter(DateTimePrinter printer) {
if (printer == null) {
throw new IllegalArgumentException("No printer supplied");
}
}
private DateTimeFormatterBuilder append0(Object element) {
iFormatter = null;
// Add the element as both a printer and parser.
iElementPairs.add(element);
iElementPairs.add(element);
return this;
}
private DateTimeFormatterBuilder append0(
DateTimePrinter printer, DateTimeParser parser) {
iFormatter = null;
iElementPairs.add(printer);
iElementPairs.add(parser);
return this;
}
//-----------------------------------------------------------------------
/**
* Instructs the printer to emit a specific character, and the parser to
* expect it. The parser is case-insensitive.
*
* @return this DateTimeFormatterBuilder
*/
public DateTimeFormatterBuilder appendLiteral(char c) {
return append0(new CharacterLiteral(c));
}
/**
* Instructs the printer to emit specific text, and the parser to expect
* it. The parser is case-insensitive.
*
* @return this DateTimeFormatterBuilder
* @throws IllegalArgumentException if text is null
*/
public DateTimeFormatterBuilder appendLiteral(String text) {
if (text == null) {
throw new IllegalArgumentException("Literal must not be null");
}
switch (text.length()) {
case 0:
return this;
case 1:
return append0(new CharacterLiteral(text.charAt(0)));
default:
return append0(new StringLiteral(text));
}
}
/**
* Instructs the printer to emit a field value as a decimal number, and the
* parser to expect an unsigned decimal number.
*
* @param fieldType type of field to append
* @param minDigits minumum number of digits to <i>print</i>
* @param maxDigits maximum number of digits to <i>parse</i>, or the estimated
* maximum number of digits to print
* @return this DateTimeFormatterBuilder
* @throws IllegalArgumentException if field type is null
*/
public DateTimeFormatterBuilder appendDecimal(
DateTimeFieldType fieldType, int minDigits, int maxDigits) {
if (fieldType == null) {
throw new IllegalArgumentException("Field type must not be null");
}
if (maxDigits < minDigits) {
maxDigits = minDigits;
}
if (minDigits < 0 || maxDigits <= 0) {
throw new IllegalArgumentException();
}
if (minDigits <= 1) {
return append0(new UnpaddedNumber(fieldType, maxDigits, false));
} else {
return append0(new PaddedNumber(fieldType, maxDigits, false, minDigits));
}
}
/**
* Instructs the printer to emit a field value as a decimal number, and the
* parser to expect a signed decimal number.
*
* @param fieldType type of field to append
* @param minDigits minumum number of digits to <i>print</i>
* @param maxDigits maximum number of digits to <i>parse</i>, or the estimated
* maximum number of digits to print
* @return this DateTimeFormatterBuilder
* @throws IllegalArgumentException if field type is null
*/
public DateTimeFormatterBuilder appendSignedDecimal(
DateTimeFieldType fieldType, int minDigits, int maxDigits) {
if (fieldType == null) {
throw new IllegalArgumentException("Field type must not be null");
}
if (maxDigits < minDigits) {
maxDigits = minDigits;
}
if (minDigits < 0 || maxDigits <= 0) {
throw new IllegalArgumentException();
}
if (minDigits <= 1) {
return append0(new UnpaddedNumber(fieldType, maxDigits, true));
} else {
return append0(new PaddedNumber(fieldType, maxDigits, true, minDigits));
}
}
/**
* Instructs the printer to emit a field value as text, and the
* parser to expect text.
*
* @param fieldType type of field to append
* @return this DateTimeFormatterBuilder
* @throws IllegalArgumentException if field type is null
*/
public DateTimeFormatterBuilder appendText(DateTimeFieldType fieldType) {
if (fieldType == null) {
throw new IllegalArgumentException("Field type must not be null");
}
return append0(new TextField(fieldType, false));
}
/**
* Instructs the printer to emit a field value as short text, and the
* parser to expect text.
*
* @param fieldType type of field to append
* @return this DateTimeFormatterBuilder
* @throws IllegalArgumentException if field type is null
*/
public DateTimeFormatterBuilder appendShortText(DateTimeFieldType fieldType) {
if (fieldType == null) {
throw new IllegalArgumentException("Field type must not be null");
}
return append0(new TextField(fieldType, true));
}
/**
* Instructs the printer to emit a remainder of time as a decimal fraction,
* sans decimal point. For example, if the field is specified as
* minuteOfHour and the time is 12:30:45, the value printed is 75. A
* decimal point is implied, so the fraction is 0.75, or three-quarters of
* a minute.
*
* @param fieldType type of field to append
* @param minDigits minumum number of digits to print.
* @param maxDigits maximum number of digits to print or parse.
* @return this DateTimeFormatterBuilder
* @throws IllegalArgumentException if field type is null
*/
public DateTimeFormatterBuilder appendFraction(
DateTimeFieldType fieldType, int minDigits, int maxDigits) {
if (fieldType == null) {
throw new IllegalArgumentException("Field type must not be null");
}
if (maxDigits < minDigits) {
maxDigits = minDigits;
}
if (minDigits < 0 || maxDigits <= 0) {
throw new IllegalArgumentException();
}
return append0(new Fraction(fieldType, minDigits, maxDigits));
}
/**
* @param minDigits minumum number of digits to print
* @param maxDigits maximum number of digits to print or parse
* @return this DateTimeFormatterBuilder
*/
public DateTimeFormatterBuilder appendFractionOfSecond(int minDigits, int maxDigits) {
return appendFraction(DateTimeFieldType.secondOfDay(), minDigits, maxDigits);
}
/**
* @param minDigits minumum number of digits to print
* @param maxDigits maximum number of digits to print or parse
* @return this DateTimeFormatterBuilder
*/
public DateTimeFormatterBuilder appendFractionOfMinute(int minDigits, int maxDigits) {
return appendFraction(DateTimeFieldType.minuteOfDay(), minDigits, maxDigits);
}
/**
* @param minDigits minumum number of digits to print
* @param maxDigits maximum number of digits to print or parse
* @return this DateTimeFormatterBuilder
*/
public DateTimeFormatterBuilder appendFractionOfHour(int minDigits, int maxDigits) {
return appendFraction(DateTimeFieldType.hourOfDay(), minDigits, maxDigits);
}
/**
* @param minDigits minumum number of digits to print
* @param maxDigits maximum number of digits to print or parse
* @return this DateTimeFormatterBuilder
*/
public DateTimeFormatterBuilder appendFractionOfDay(int minDigits, int maxDigits) {
return appendFraction(DateTimeFieldType.dayOfYear(), minDigits, maxDigits);
}
/**
* Instructs the printer to emit a numeric millisOfSecond field.
*
* @param minDigits minumum number of digits to print
* @return this DateTimeFormatterBuilder
*/
public DateTimeFormatterBuilder appendMillisOfSecond(int minDigits) {
return appendDecimal(DateTimeFieldType.millisOfSecond(), minDigits, 3);
}
/**
* Instructs the printer to emit a numeric millisOfDay field.
*
* @param minDigits minumum number of digits to print
* @return this DateTimeFormatterBuilder
*/
public DateTimeFormatterBuilder appendMillisOfDay(int minDigits) {
return appendDecimal(DateTimeFieldType.millisOfDay(), minDigits, 8);
}
/**
* Instructs the printer to emit a numeric secondOfMinute field.
*
* @param minDigits minumum number of digits to print
* @return this DateTimeFormatterBuilder
*/
public DateTimeFormatterBuilder appendSecondOfMinute(int minDigits) {
return appendDecimal(DateTimeFieldType.secondOfMinute(), minDigits, 2);
}
/**
* Instructs the printer to emit a numeric secondOfDay field.
*
* @param minDigits minumum number of digits to print
* @return this DateTimeFormatterBuilder
*/
public DateTimeFormatterBuilder appendSecondOfDay(int minDigits) {
return appendDecimal(DateTimeFieldType.secondOfDay(), minDigits, 5);
}
/**
* Instructs the printer to emit a numeric minuteOfHour field.
*
* @param minDigits minumum number of digits to print
* @return this DateTimeFormatterBuilder
*/
public DateTimeFormatterBuilder appendMinuteOfHour(int minDigits) {
return appendDecimal(DateTimeFieldType.minuteOfHour(), minDigits, 2);
}
/**
* Instructs the printer to emit a numeric minuteOfDay field.
*
* @param minDigits minumum number of digits to print
* @return this DateTimeFormatterBuilder
*/
public DateTimeFormatterBuilder appendMinuteOfDay(int minDigits) {
return appendDecimal(DateTimeFieldType.minuteOfDay(), minDigits, 4);
}
/**
* Instructs the printer to emit a numeric hourOfDay field.
*
* @param minDigits minumum number of digits to print
* @return this DateTimeFormatterBuilder
*/
public DateTimeFormatterBuilder appendHourOfDay(int minDigits) {
return appendDecimal(DateTimeFieldType.hourOfDay(), minDigits, 2);
}
/**
* Instructs the printer to emit a numeric clockhourOfDay field.
*
* @param minDigits minumum number of digits to print
* @return this DateTimeFormatterBuilder
*/
public DateTimeFormatterBuilder appendClockhourOfDay(int minDigits) {
return appendDecimal(DateTimeFieldType.clockhourOfDay(), minDigits, 2);
}
/**
* Instructs the printer to emit a numeric hourOfHalfday field.
*
* @param minDigits minumum number of digits to print
* @return this DateTimeFormatterBuilder
*/
public DateTimeFormatterBuilder appendHourOfHalfday(int minDigits) {
return appendDecimal(DateTimeFieldType.hourOfHalfday(), minDigits, 2);
}
/**
* Instructs the printer to emit a numeric clockhourOfHalfday field.
*
* @param minDigits minumum number of digits to print
* @return this DateTimeFormatterBuilder
*/
public DateTimeFormatterBuilder appendClockhourOfHalfday(int minDigits) {
return appendDecimal(DateTimeFieldType.clockhourOfHalfday(), minDigits, 2);
}
/**
* Instructs the printer to emit a numeric dayOfWeek field.
*
* @param minDigits minumum number of digits to print
* @return this DateTimeFormatterBuilder
*/
public DateTimeFormatterBuilder appendDayOfWeek(int minDigits) {
return appendDecimal(DateTimeFieldType.dayOfWeek(), minDigits, 1);
}
/**
* Instructs the printer to emit a numeric dayOfMonth field.
*
* @param minDigits minumum number of digits to print
* @return this DateTimeFormatterBuilder
*/
public DateTimeFormatterBuilder appendDayOfMonth(int minDigits) {
return appendDecimal(DateTimeFieldType.dayOfMonth(), minDigits, 2);
}
/**
* Instructs the printer to emit a numeric dayOfYear field.
*
* @param minDigits minumum number of digits to print
* @return this DateTimeFormatterBuilder
*/
public DateTimeFormatterBuilder appendDayOfYear(int minDigits) {
return appendDecimal(DateTimeFieldType.dayOfYear(), minDigits, 3);
}
/**
* Instructs the printer to emit a numeric weekOfWeekyear field.
*
* @param minDigits minumum number of digits to print
* @return this DateTimeFormatterBuilder
*/
public DateTimeFormatterBuilder appendWeekOfWeekyear(int minDigits) {
return appendDecimal(DateTimeFieldType.weekOfWeekyear(), minDigits, 2);
}
/**
* Instructs the printer to emit a numeric weekyear field.
*
* @param minDigits minumum number of digits to <i>print</i>
* @param maxDigits maximum number of digits to <i>parse</i>, or the estimated
* maximum number of digits to print
* @return this DateTimeFormatterBuilder
*/
public DateTimeFormatterBuilder appendWeekyear(int minDigits, int maxDigits) {
return appendSignedDecimal(DateTimeFieldType.weekyear(), minDigits, maxDigits);
}
/**
* Instructs the printer to emit a numeric monthOfYear field.
*
* @param minDigits minumum number of digits to print
* @return this DateTimeFormatterBuilder
*/
public DateTimeFormatterBuilder appendMonthOfYear(int minDigits) {
return appendDecimal(DateTimeFieldType.monthOfYear(), minDigits, 2);
}
/**
* Instructs the printer to emit a numeric year field.
*
* @param minDigits minumum number of digits to <i>print</i>
* @param maxDigits maximum number of digits to <i>parse</i>, or the estimated
* maximum number of digits to print
* @return this DateTimeFormatterBuilder
*/
public DateTimeFormatterBuilder appendYear(int minDigits, int maxDigits) {
return appendSignedDecimal(DateTimeFieldType.year(), minDigits, maxDigits);
}
/**
* Instructs the printer to emit a numeric year field which always prints
* and parses two digits. A pivot year is used during parsing to determine
* the range of supported years as <code>(pivot - 50) .. (pivot + 49)</code>.
*
* <pre>
* pivot supported range 00 is 20 is 40 is 60 is 80 is
* ---------------------------------------------------------------
* 1950 1900..1999 1900 1920 1940 1960 1980
* 1975 1925..2024 2000 2020 1940 1960 1980
* 2000 1950..2049 2000 2020 2040 1960 1980
* 2025 1975..2074 2000 2020 2040 2060 1980
* 2050 2000..2099 2000 2020 2040 2060 2080
* </pre>
*
* @param pivot pivot year to use when parsing
* @return this DateTimeFormatterBuilder
*/
public DateTimeFormatterBuilder appendTwoDigitYear(int pivot) {
return append0(new TwoDigitYear(pivot));
}
/**
* Instructs the printer to emit a numeric yearOfEra field.
*
* @param minDigits minumum number of digits to <i>print</i>
* @param maxDigits maximum number of digits to <i>parse</i>, or the estimated
* maximum number of digits to print
* @return this DateTimeFormatterBuilder
*/
public DateTimeFormatterBuilder appendYearOfEra(int minDigits, int maxDigits) {
return appendDecimal(DateTimeFieldType.yearOfEra(), minDigits, maxDigits);
}
/**
* Instructs the printer to emit a numeric year of century field.
*
* @param minDigits minumum number of digits to print
* @param maxDigits maximum number of digits to <i>parse</i>, or the estimated
* maximum number of digits to print
* @return this DateTimeFormatterBuilder
*/
public DateTimeFormatterBuilder appendYearOfCentury(int minDigits, int maxDigits) {
return appendDecimal(DateTimeFieldType.yearOfCentury(), minDigits, maxDigits);
}
/**
* Instructs the printer to emit a numeric century of era field.
*
* @param minDigits minumum number of digits to print
* @param maxDigits maximum number of digits to <i>parse</i>, or the estimated
* maximum number of digits to print
* @return this DateTimeFormatterBuilder
*/
public DateTimeFormatterBuilder appendCenturyOfEra(int minDigits, int maxDigits) {
return appendSignedDecimal(DateTimeFieldType.centuryOfEra(), minDigits, maxDigits);
}
/**
* Instructs the printer to emit a locale-specific AM/PM text, and the
* parser to expect it. The parser is case-insensitive.
*
* @return this DateTimeFormatterBuilder
*/
public DateTimeFormatterBuilder appendHalfdayOfDayText() {
return appendText(DateTimeFieldType.halfdayOfDay());
}
/**
* Instructs the printer to emit a locale-specific dayOfWeek text. The
* parser will accept a long or short dayOfWeek text, case-insensitive.
*
* @return this DateTimeFormatterBuilder
*/
public DateTimeFormatterBuilder appendDayOfWeekText() {
return appendText(DateTimeFieldType.dayOfWeek());
}
/**
* Instructs the printer to emit a short locale-specific dayOfWeek
* text. The parser will accept a long or short dayOfWeek text,
* case-insensitive.
*
* @return this DateTimeFormatterBuilder
*/
public DateTimeFormatterBuilder appendDayOfWeekShortText() {
return appendShortText(DateTimeFieldType.dayOfWeek());
}
/**
* Instructs the printer to emit a short locale-specific monthOfYear
* text. The parser will accept a long or short monthOfYear text,
* case-insensitive.
*
* @return this DateTimeFormatterBuilder
*/
public DateTimeFormatterBuilder appendMonthOfYearText() {
return appendText(DateTimeFieldType.monthOfYear());
}
/**
* Instructs the printer to emit a locale-specific monthOfYear text. The
* parser will accept a long or short monthOfYear text, case-insensitive.
*
* @return this DateTimeFormatterBuilder
*/
public DateTimeFormatterBuilder appendMonthOfYearShortText() {
return appendShortText(DateTimeFieldType.monthOfYear());
}
/**
* Instructs the printer to emit a locale-specific era text (BC/AD), and
* the parser to expect it. The parser is case-insensitive.
*
* @return this DateTimeFormatterBuilder
*/
public DateTimeFormatterBuilder appendEraText() {
return appendText(DateTimeFieldType.era());
}
/**
* Instructs the printer to emit a locale-specific time zone name. A
* parser cannot be created from this builder if a time zone name is
* appended.
*
* @return this DateTimeFormatterBuilder
*/
public DateTimeFormatterBuilder appendTimeZoneName() {
return append0(new TimeZonePrinter(false), null);
}
/**
* Instructs the printer to emit a short locale-specific time zone
* name. A parser cannot be created from this builder if time zone
* name is appended.
*
* @return this DateTimeFormatterBuilder
*/
public DateTimeFormatterBuilder appendTimeZoneShortName() {
return append0(new TimeZonePrinter(true), null);
}
/**
* Instructs the printer to emit text and numbers to display time zone
* offset from UTC. A parser will use the parsed time zone offset to adjust
* the datetime.
*
* @param zeroOffsetText Text to use if time zone offset is zero. If
* null, offset is always shown.
* @param showSeparators If true, prints ':' separator before minute and
* second field and prints '.' separator before fraction field.
* @param minFields minimum number of fields to print, stopping when no
* more precision is required. 1=hours, 2=minutes, 3=seconds, 4=fraction
* @param maxFields maximum number of fields to print
* @return this DateTimeFormatterBuilder
*/
public DateTimeFormatterBuilder appendTimeZoneOffset(
String zeroOffsetText, boolean showSeparators,
int minFields, int maxFields) {
return append0(new TimeZoneOffset
(zeroOffsetText, showSeparators, minFields, maxFields));
}
//-----------------------------------------------------------------------
/**
* Calls upon {@link DateTimeFormat} to parse the pattern and append the
* results into this builder.
*
* @param pattern pattern specification
* @throws IllegalArgumentException if the pattern is invalid
- * @see DateTimeFormat#appendPatternTo(DateTimeFormatterBuilder,String)
+ * @see DateTimeFormat
*/
public DateTimeFormatterBuilder appendPattern(String pattern) {
DateTimeFormat.appendPatternTo(this, pattern);
return this;
}
//-----------------------------------------------------------------------
private Object getFormatter() {
Object f = iFormatter;
if (f == null) {
if (iElementPairs.size() == 2) {
Object printer = iElementPairs.get(0);
Object parser = iElementPairs.get(1);
if (printer != null) {
if (printer == parser || parser == null) {
f = printer;
}
} else {
f = parser;
}
}
if (f == null) {
f = new Composite(iElementPairs);
}
iFormatter = f;
}
return f;
}
private boolean isPrinter(Object f) {
if (f instanceof DateTimePrinter) {
if (f instanceof Composite) {
return ((Composite)f).isPrinter();
}
return true;
}
return false;
}
private boolean isParser(Object f) {
if (f instanceof DateTimeParser) {
if (f instanceof Composite) {
return ((Composite)f).isParser();
}
return true;
}
return false;
}
private boolean isFormatter(Object f) {
if (f instanceof DateTimeFormatter) {
if (f instanceof Composite) {
return ((Composite)f).isPrinter()
|| ((Composite)f).isParser();
}
return true;
}
return false;
}
static void appendUnknownString(StringBuffer buf, int len) {
for (int i = len; --i >= 0;) {
buf.append('\ufffd');
}
}
static void printUnknownString(Writer out, int len) throws IOException {
for (int i = len; --i >= 0;) {
out.write('\ufffd');
}
}
//-----------------------------------------------------------------------
static class CharacterLiteral
implements DateTimePrinter, DateTimeParser {
private final char iValue;
CharacterLiteral(char value) {
super();
iValue = value;
}
public int estimatePrintedLength() {
return 1;
}
public void printTo(
StringBuffer buf, long instant, Chronology chrono,
int displayOffset, DateTimeZone displayZone, Locale locale) {
buf.append(iValue);
}
public void printTo(
Writer out, long instant, Chronology chrono,
int displayOffset, DateTimeZone displayZone, Locale locale) throws IOException {
out.write(iValue);
}
public void printTo(StringBuffer buf, ReadablePartial partial, Locale locale) {
buf.append(iValue);
}
public void printTo(Writer out, ReadablePartial partial, Locale locale) throws IOException {
out.write(iValue);
}
public int estimateParsedLength() {
return 1;
}
public int parseInto(DateTimeParserBucket bucket, String text, int position) {
if (position >= text.length()) {
return ~position;
}
char a = text.charAt(position);
char b = iValue;
if (a != b) {
a = Character.toUpperCase(a);
b = Character.toUpperCase(b);
if (a != b) {
a = Character.toLowerCase(a);
b = Character.toLowerCase(b);
if (a != b) {
return ~position;
}
}
}
return position + 1;
}
}
//-----------------------------------------------------------------------
static class StringLiteral
implements DateTimePrinter, DateTimeParser {
private final String iValue;
StringLiteral(String value) {
super();
iValue = value;
}
public int estimatePrintedLength() {
return iValue.length();
}
public void printTo(
StringBuffer buf, long instant, Chronology chrono,
int displayOffset, DateTimeZone displayZone, Locale locale) {
buf.append(iValue);
}
public void printTo(
Writer out, long instant, Chronology chrono,
int displayOffset, DateTimeZone displayZone, Locale locale) throws IOException {
out.write(iValue);
}
public void printTo(StringBuffer buf, ReadablePartial partial, Locale locale) {
buf.append(iValue);
}
public void printTo(Writer out, ReadablePartial partial, Locale locale) throws IOException {
out.write(iValue);
}
public int estimateParsedLength() {
return iValue.length();
}
public int parseInto(DateTimeParserBucket bucket, String text, int position) {
if (text.regionMatches(true, position, iValue, 0, iValue.length())) {
return position + iValue.length();
}
return ~position;
}
}
//-----------------------------------------------------------------------
static abstract class NumberFormatter
implements DateTimePrinter, DateTimeParser {
protected final DateTimeFieldType iFieldType;
protected final int iMaxParsedDigits;
protected final boolean iSigned;
NumberFormatter(DateTimeFieldType fieldType,
int maxParsedDigits, boolean signed) {
super();
iFieldType = fieldType;
iMaxParsedDigits = maxParsedDigits;
iSigned = signed;
}
public int estimateParsedLength() {
return iMaxParsedDigits;
}
public int parseInto(DateTimeParserBucket bucket, String text, int position) {
int limit = Math.min(iMaxParsedDigits, text.length() - position);
boolean negative = false;
int length = 0;
while (length < limit) {
char c = text.charAt(position + length);
if (length == 0 && (c == '-' || c == '+') && iSigned) {
negative = c == '-';
if (negative) {
length++;
} else {
// Skip the '+' for parseInt to succeed.
position++;
}
// Expand the limit to disregard the sign character.
limit = Math.min(limit + 1, text.length() - position);
continue;
}
if (c < '0' || c > '9') {
break;
}
length++;
}
if (length == 0) {
return ~position;
}
int value;
if (length >= 9) {
// Since value may exceed integer limits, use stock parser
// which checks for this.
value = Integer.parseInt
(text.substring(position, position += length));
} else {
int i = position;
if (negative) {
i++;
}
value = text.charAt(i++) - '0';
position += length;
while (i < position) {
value = ((value << 3) + (value << 1)) + text.charAt(i++) - '0';
}
if (negative) {
value = -value;
}
}
bucket.saveField(iFieldType, value);
return position;
}
}
//-----------------------------------------------------------------------
static class UnpaddedNumber extends NumberFormatter {
protected UnpaddedNumber(DateTimeFieldType fieldType,
int maxParsedDigits, boolean signed)
{
super(fieldType, maxParsedDigits, signed);
}
public int estimatePrintedLength() {
return iMaxParsedDigits;
}
public void printTo(
StringBuffer buf, long instant, Chronology chrono,
int displayOffset, DateTimeZone displayZone, Locale locale) {
try {
DateTimeField field = iFieldType.getField(chrono);
FormatUtils.appendUnpaddedInteger(buf, field.get(instant));
} catch (RuntimeException e) {
buf.append('\ufffd');
}
}
public void printTo(
Writer out, long instant, Chronology chrono,
int displayOffset, DateTimeZone displayZone, Locale locale) throws IOException {
try {
DateTimeField field = iFieldType.getField(chrono);
FormatUtils.writeUnpaddedInteger(out, field.get(instant));
} catch (RuntimeException e) {
out.write('\ufffd');
}
}
public void printTo(StringBuffer buf, ReadablePartial partial, Locale locale) {
if (partial.isSupported(iFieldType)) {
try {
FormatUtils.appendUnpaddedInteger(buf, partial.get(iFieldType));
} catch (RuntimeException e) {
buf.append('\ufffd');
}
} else {
buf.append('\ufffd');
}
}
public void printTo(Writer out, ReadablePartial partial, Locale locale) throws IOException {
if (partial.isSupported(iFieldType)) {
try {
FormatUtils.writeUnpaddedInteger(out, partial.get(iFieldType));
} catch (RuntimeException e) {
out.write('\ufffd');
}
} else {
out.write('\ufffd');
}
}
}
//-----------------------------------------------------------------------
static class PaddedNumber extends NumberFormatter {
protected final int iMinPrintedDigits;
protected PaddedNumber(DateTimeFieldType fieldType, int maxParsedDigits,
boolean signed, int minPrintedDigits)
{
super(fieldType, maxParsedDigits, signed);
iMinPrintedDigits = minPrintedDigits;
}
public int estimatePrintedLength() {
return iMaxParsedDigits;
}
public void printTo(
StringBuffer buf, long instant, Chronology chrono,
int displayOffset, DateTimeZone displayZone, Locale locale) {
try {
DateTimeField field = iFieldType.getField(chrono);
FormatUtils.appendPaddedInteger(buf, field.get(instant), iMinPrintedDigits);
} catch (RuntimeException e) {
appendUnknownString(buf, iMinPrintedDigits);
}
}
public void printTo(
Writer out, long instant, Chronology chrono,
int displayOffset, DateTimeZone displayZone, Locale locale) throws IOException {
try {
DateTimeField field = iFieldType.getField(chrono);
FormatUtils.writePaddedInteger(out, field.get(instant), iMinPrintedDigits);
} catch (RuntimeException e) {
printUnknownString(out, iMinPrintedDigits);
}
}
public void printTo(StringBuffer buf, ReadablePartial partial, Locale locale) {
if (partial.isSupported(iFieldType)) {
try {
FormatUtils.appendPaddedInteger(buf, partial.get(iFieldType), iMinPrintedDigits);
} catch (RuntimeException e) {
appendUnknownString(buf, iMinPrintedDigits);
}
} else {
appendUnknownString(buf, iMinPrintedDigits);
}
}
public void printTo(Writer out, ReadablePartial partial, Locale locale) throws IOException {
if (partial.isSupported(iFieldType)) {
try {
FormatUtils.writePaddedInteger(out, partial.get(iFieldType), iMinPrintedDigits);
} catch (RuntimeException e) {
printUnknownString(out, iMinPrintedDigits);
}
} else {
printUnknownString(out, iMinPrintedDigits);
}
}
}
//-----------------------------------------------------------------------
static class TwoDigitYear
implements DateTimePrinter, DateTimeParser {
private final int iPivot;
TwoDigitYear(int pivot) {
super();
iPivot = pivot;
}
public int estimateParsedLength() {
return 2;
}
public int parseInto(DateTimeParserBucket bucket, String text, int position) {
int limit = Math.min(2, text.length() - position);
if (limit < 2) {
return ~position;
}
int year;
char c = text.charAt(position);
if (c < '0' || c > '9') {
return ~position;
}
year = c - '0';
c = text.charAt(position + 1);
if (c < '0' || c > '9') {
return ~position;
}
year = ((year << 3) + (year << 1)) + c - '0';
int low = iPivot - 50;
int t;
if (low >= 0) {
t = low % 100;
} else {
t = 99 + ((low + 1) % 100);
}
year += low + ((year < t) ? 100 : 0) - t;
bucket.saveField(DateTimeFieldType.year(), year);
return position + 2;
}
public int estimatePrintedLength() {
return 2;
}
public void printTo(
StringBuffer buf, long instant, Chronology chrono,
int displayOffset, DateTimeZone displayZone, Locale locale) {
int year = getTwoDigitYear(instant, chrono);
if (year < 0) {
buf.append('\ufffd');
buf.append('\ufffd');
} else {
FormatUtils.appendPaddedInteger(buf, year, 2);
}
}
public void printTo(
Writer out, long instant, Chronology chrono,
int displayOffset, DateTimeZone displayZone, Locale locale) throws IOException {
int year = getTwoDigitYear(instant, chrono);
if (year < 0) {
out.write('\ufffd');
out.write('\ufffd');
} else {
FormatUtils.writePaddedInteger(out, year, 2);
}
}
private int getTwoDigitYear(long instant, Chronology chrono) {
try {
int year = chrono.year().get(instant);
if (year < 0) {
year = -year;
}
return year % 100;
} catch (RuntimeException e) {
return -1;
}
}
public void printTo(StringBuffer buf, ReadablePartial partial, Locale locale) {
int year = getTwoDigitYear(partial);
if (year < 0) {
buf.append('\ufffd');
buf.append('\ufffd');
} else {
FormatUtils.appendPaddedInteger(buf, year, 2);
}
}
public void printTo(Writer out, ReadablePartial partial, Locale locale) throws IOException {
int year = getTwoDigitYear(partial);
if (year < 0) {
out.write('\ufffd');
out.write('\ufffd');
} else {
FormatUtils.writePaddedInteger(out, year, 2);
}
}
private int getTwoDigitYear(ReadablePartial partial) {
if (partial.isSupported(DateTimeFieldType.year())) {
try {
int year = partial.get(DateTimeFieldType.year());
if (year < 0) {
year = -year;
}
return year % 100;
} catch (RuntimeException e) {}
}
return -1;
}
}
//-----------------------------------------------------------------------
static class TextField
implements DateTimePrinter, DateTimeParser {
private final DateTimeFieldType iFieldType;
private final boolean iShort;
TextField(DateTimeFieldType fieldType, boolean isShort) {
super();
iFieldType = fieldType;
iShort = isShort;
}
public int estimatePrintedLength() {
return iShort ? 6 : 20;
}
public void printTo(
StringBuffer buf, long instant, Chronology chrono,
int displayOffset, DateTimeZone displayZone, Locale locale) {
try {
buf.append(print(instant, chrono, locale));
} catch (RuntimeException e) {
buf.append('\ufffd');
}
}
public void printTo(
Writer out, long instant, Chronology chrono,
int displayOffset, DateTimeZone displayZone, Locale locale) throws IOException {
try {
out.write(print(instant, chrono, locale));
} catch (RuntimeException e) {
out.write('\ufffd');
}
}
public void printTo(StringBuffer buf, ReadablePartial partial, Locale locale) {
try {
buf.append(print(partial, locale));
} catch (RuntimeException e) {
buf.append('\ufffd');
}
}
public void printTo(Writer out, ReadablePartial partial, Locale locale) throws IOException {
try {
out.write(print(partial, locale));
} catch (RuntimeException e) {
out.write('\ufffd');
}
}
private String print(long instant, Chronology chrono, Locale locale) {
DateTimeField field = iFieldType.getField(chrono);
if (iShort) {
return field.getAsShortText(instant, locale);
} else {
return field.getAsText(instant, locale);
}
}
private String print(ReadablePartial partial, Locale locale) {
if (partial.isSupported(iFieldType)) {
DateTimeField field = iFieldType.getField(partial.getChronology());
if (iShort) {
return field.getAsShortText(partial, locale);
} else {
return field.getAsText(partial, locale);
}
} else {
return "\ufffd";
}
}
public int estimateParsedLength() {
return estimatePrintedLength();
}
public int parseInto(DateTimeParserBucket bucket, String text, int position) {
int limit = text.length();
int i = position;
for (; i<limit; i++) {
char c = text.charAt(i);
if (c < 'A') {
break;
}
if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || Character.isLetter(c)) {
continue;
}
break;
}
if (i == position) {
return ~position;
}
Locale locale = bucket.getLocale();
bucket.saveField(iFieldType, text.substring(position, i), locale);
return i;
}
}
//-----------------------------------------------------------------------
static class Fraction
implements DateTimePrinter, DateTimeParser {
private final DateTimeFieldType iFieldType;
protected int iMinDigits;
protected int iMaxDigits;
protected Fraction(DateTimeFieldType fieldType, int minDigits, int maxDigits) {
super();
iFieldType = fieldType;
// Limit the precision requirements.
if (maxDigits > 18) {
maxDigits = 18;
}
iMinDigits = minDigits;
iMaxDigits = maxDigits;
}
public int estimatePrintedLength() {
return iMaxDigits;
}
public void printTo(
StringBuffer buf, long instant, Chronology chrono,
int displayOffset, DateTimeZone displayZone, Locale locale) {
try {
printTo(buf, null, instant, chrono);
} catch (IOException e) {
// Not gonna happen.
}
}
public void printTo(
Writer out, long instant, Chronology chrono,
int displayOffset, DateTimeZone displayZone, Locale locale) throws IOException {
printTo(null, out, instant, chrono);
}
public void printTo(StringBuffer buf, ReadablePartial partial, Locale locale) {
if (partial.isSupported(iFieldType)) {
long millis = partial.getChronology().set(partial, 0L);
try {
printTo(buf, null, millis, partial.getChronology());
} catch (IOException e) {
// Not gonna happen.
}
} else {
buf.append('\ufffd');
}
}
public void printTo(Writer out, ReadablePartial partial, Locale locale) throws IOException {
if (partial.isSupported(iFieldType)) {
long millis = partial.getChronology().set(partial, 0L);
printTo(null, out, millis, partial.getChronology());
} else {
out.write('\ufffd');
}
}
protected void printTo(StringBuffer buf, Writer out, long instant, Chronology chrono)
throws IOException
{
DateTimeField field = iFieldType.getField(chrono);
int minDigits = iMinDigits;
long fraction;
try {
fraction = field.remainder(instant);
} catch (RuntimeException e) {
if (buf != null) {
appendUnknownString(buf, minDigits);
} else {
printUnknownString(out, minDigits);
}
return;
}
if (fraction == 0) {
if (buf != null) {
while (--minDigits >= 0) {
buf.append('0');
}
} else {
while (--minDigits >= 0) {
out.write('0');
}
}
return;
}
String str;
long[] fractionData = getFractionData(fraction, field);
long scaled = fractionData[0];
int maxDigits = (int) fractionData[1];
if ((scaled & 0x7fffffff) == scaled) {
str = Integer.toString((int) scaled);
} else {
str = Long.toString(scaled);
}
int length = str.length();
int digits = maxDigits;
while (length < digits) {
if (buf != null) {
buf.append('0');
} else {
out.write('0');
}
minDigits--;
digits--;
}
if (minDigits < digits) {
// Chop off as many trailing zero digits as necessary.
while (minDigits < digits) {
if (length <= 1 || str.charAt(length - 1) != '0') {
break;
}
digits--;
length--;
}
if (length < str.length()) {
if (buf != null) {
for (int i=0; i<length; i++) {
buf.append(str.charAt(i));
}
} else {
for (int i=0; i<length; i++) {
out.write(str.charAt(i));
}
}
return;
}
}
if (buf != null) {
buf.append(str);
} else {
out.write(str);
}
}
private long[] getFractionData(long fraction, DateTimeField field) {
long rangeMillis = field.getDurationField().getUnitMillis();
long scalar;
int maxDigits = iMaxDigits;
while (true) {
switch (maxDigits) {
default: scalar = 1L; break;
case 1: scalar = 10L; break;
case 2: scalar = 100L; break;
case 3: scalar = 1000L; break;
case 4: scalar = 10000L; break;
case 5: scalar = 100000L; break;
case 6: scalar = 1000000L; break;
case 7: scalar = 10000000L; break;
case 8: scalar = 100000000L; break;
case 9: scalar = 1000000000L; break;
case 10: scalar = 10000000000L; break;
case 11: scalar = 100000000000L; break;
case 12: scalar = 1000000000000L; break;
case 13: scalar = 10000000000000L; break;
case 14: scalar = 100000000000000L; break;
case 15: scalar = 1000000000000000L; break;
case 16: scalar = 10000000000000000L; break;
case 17: scalar = 100000000000000000L; break;
case 18: scalar = 1000000000000000000L; break;
}
if (((rangeMillis * scalar) / scalar) == rangeMillis) {
break;
}
// Overflowed: scale down.
maxDigits--;
}
return new long[] {fraction * scalar / rangeMillis, maxDigits};
}
public int estimateParsedLength() {
return iMaxDigits;
}
public int parseInto(DateTimeParserBucket bucket, String text, int position) {
DateTimeField field = iFieldType.getField(bucket.getChronology());
int limit = Math.min(iMaxDigits, text.length() - position);
long value = 0;
long n = field.getDurationField().getUnitMillis() * 10;
int length = 0;
while (length < limit) {
char c = text.charAt(position + length);
if (c < '0' || c > '9') {
break;
}
length++;
long nn = n / 10;
value += (c - '0') * nn;
n = nn;
}
value /= 10;
if (length == 0) {
return ~position;
}
if (value > Integer.MAX_VALUE) {
return ~position;
}
DateTimeField parseField = new PreciseDateTimeField(
DateTimeFieldType.millisOfSecond(),
MillisDurationField.INSTANCE,
field.getDurationField());
bucket.saveField(parseField, (int) value);
return position + length;
}
}
//-----------------------------------------------------------------------
static class TimeZoneOffset
implements DateTimePrinter, DateTimeParser {
private final String iZeroOffsetText;
private final boolean iShowSeparators;
private final int iMinFields;
private final int iMaxFields;
TimeZoneOffset(String zeroOffsetText,
boolean showSeparators,
int minFields, int maxFields)
{
super();
iZeroOffsetText = zeroOffsetText;
iShowSeparators = showSeparators;
if (minFields <= 0 || maxFields < minFields) {
throw new IllegalArgumentException();
}
if (minFields > 4) {
minFields = 4;
maxFields = 4;
}
iMinFields = minFields;
iMaxFields = maxFields;
}
public int estimatePrintedLength() {
int est = 1 + iMinFields << 1;
if (iShowSeparators) {
est += iMinFields - 1;
}
if (iZeroOffsetText != null && iZeroOffsetText.length() > est) {
est = iZeroOffsetText.length();
}
return est;
}
public void printTo(
StringBuffer buf, long instant, Chronology chrono,
int displayOffset, DateTimeZone displayZone, Locale locale) {
if (displayZone == null) {
return; // no zone
}
if (displayOffset == 0 && iZeroOffsetText != null) {
buf.append(iZeroOffsetText);
return;
}
if (displayOffset >= 0) {
buf.append('+');
} else {
buf.append('-');
displayOffset = -displayOffset;
}
int hours = displayOffset / DateTimeConstants.MILLIS_PER_HOUR;
FormatUtils.appendPaddedInteger(buf, hours, 2);
if (iMaxFields == 1) {
return;
}
displayOffset -= hours * (int)DateTimeConstants.MILLIS_PER_HOUR;
if (displayOffset == 0 && iMinFields <= 1) {
return;
}
int minutes = displayOffset / DateTimeConstants.MILLIS_PER_MINUTE;
if (iShowSeparators) {
buf.append(':');
}
FormatUtils.appendPaddedInteger(buf, minutes, 2);
if (iMaxFields == 2) {
return;
}
displayOffset -= minutes * DateTimeConstants.MILLIS_PER_MINUTE;
if (displayOffset == 0 && iMinFields <= 2) {
return;
}
int seconds = displayOffset / DateTimeConstants.MILLIS_PER_SECOND;
if (iShowSeparators) {
buf.append(':');
}
FormatUtils.appendPaddedInteger(buf, seconds, 2);
if (iMaxFields == 3) {
return;
}
displayOffset -= seconds * DateTimeConstants.MILLIS_PER_SECOND;
if (displayOffset == 0 && iMinFields <= 3) {
return;
}
if (iShowSeparators) {
buf.append('.');
}
FormatUtils.appendPaddedInteger(buf, displayOffset, 3);
}
public void printTo(
Writer out, long instant, Chronology chrono,
int displayOffset, DateTimeZone displayZone, Locale locale) throws IOException {
if (displayZone == null) {
return; // no zone
}
if (displayOffset == 0 && iZeroOffsetText != null) {
out.write(iZeroOffsetText);
return;
}
if (displayOffset >= 0) {
out.write('+');
} else {
out.write('-');
displayOffset = -displayOffset;
}
int hours = displayOffset / DateTimeConstants.MILLIS_PER_HOUR;
FormatUtils.writePaddedInteger(out, hours, 2);
if (iMaxFields == 1) {
return;
}
displayOffset -= hours * (int)DateTimeConstants.MILLIS_PER_HOUR;
if (displayOffset == 0 && iMinFields == 1) {
return;
}
int minutes = displayOffset / DateTimeConstants.MILLIS_PER_MINUTE;
if (iShowSeparators) {
out.write(':');
}
FormatUtils.writePaddedInteger(out, minutes, 2);
if (iMaxFields == 2) {
return;
}
displayOffset -= minutes * DateTimeConstants.MILLIS_PER_MINUTE;
if (displayOffset == 0 && iMinFields == 2) {
return;
}
int seconds = displayOffset / DateTimeConstants.MILLIS_PER_SECOND;
if (iShowSeparators) {
out.write(':');
}
FormatUtils.writePaddedInteger(out, seconds, 2);
if (iMaxFields == 3) {
return;
}
displayOffset -= seconds * DateTimeConstants.MILLIS_PER_SECOND;
if (displayOffset == 0 && iMinFields == 3) {
return;
}
if (iShowSeparators) {
out.write('.');
}
FormatUtils.writePaddedInteger(out, displayOffset, 3);
}
public void printTo(StringBuffer buf, ReadablePartial partial, Locale locale) {
// no zone info
}
public void printTo(Writer out, ReadablePartial partial, Locale locale) throws IOException {
// no zone info
}
public int estimateParsedLength() {
return estimatePrintedLength();
}
public int parseInto(DateTimeParserBucket bucket, String text, int position) {
int limit = text.length() - position;
zeroOffset:
if (iZeroOffsetText != null) {
if (iZeroOffsetText.length() == 0) {
// Peek ahead, looking for sign character.
if (limit > 0) {
char c = text.charAt(position);
if (c == '-' || c == '+') {
break zeroOffset;
}
}
bucket.setOffset(0);
return position;
}
if (text.regionMatches(true, position, iZeroOffsetText, 0,
iZeroOffsetText.length())) {
bucket.setOffset(0);
return position + iZeroOffsetText.length();
}
}
// Format to expect is sign character followed by at least one digit.
if (limit <= 1) {
return ~position;
}
boolean negative;
char c = text.charAt(position);
if (c == '-') {
negative = true;
} else if (c == '+') {
negative = false;
} else {
return ~position;
}
limit--;
position++;
// Format following sign is one of:
//
// hh
// hhmm
// hhmmss
// hhmmssSSS
// hh:mm
// hh:mm:ss
// hh:mm:ss.SSS
// First parse hours.
if (digitCount(text, position, 2) < 2) {
// Need two digits for hour.
return ~position;
}
int offset;
int hours = FormatUtils.parseTwoDigits(text, position);
if (hours > 23) {
return ~position;
}
offset = hours * DateTimeConstants.MILLIS_PER_HOUR;
limit -= 2;
position += 2;
parse: {
// Need to decide now if separators are expected or parsing
// stops at hour field.
if (limit <= 0) {
break parse;
}
boolean expectSeparators;
c = text.charAt(position);
if (c == ':') {
expectSeparators = true;
limit--;
position++;
} else if (c >= '0' && c <= '9') {
expectSeparators = false;
} else {
break parse;
}
// Proceed to parse minutes.
int count = digitCount(text, position, 2);
if (count == 0 && !expectSeparators) {
break parse;
} else if (count < 2) {
// Need two digits for minute.
return ~position;
}
int minutes = FormatUtils.parseTwoDigits(text, position);
if (minutes > 59) {
return ~position;
}
offset += minutes * DateTimeConstants.MILLIS_PER_MINUTE;
limit -= 2;
position += 2;
// Proceed to parse seconds.
if (limit <= 0) {
break parse;
}
if (expectSeparators) {
if (text.charAt(position) != ':') {
break parse;
}
limit--;
position++;
}
count = digitCount(text, position, 2);
if (count == 0 && !expectSeparators) {
break parse;
} else if (count < 2) {
// Need two digits for second.
return ~position;
}
int seconds = FormatUtils.parseTwoDigits(text, position);
if (seconds > 59) {
return ~position;
}
offset += seconds * DateTimeConstants.MILLIS_PER_SECOND;
limit -= 2;
position += 2;
// Proceed to parse fraction of second.
if (limit <= 0) {
break parse;
}
if (expectSeparators) {
if (text.charAt(position) != '.' && text.charAt(position) != ',') {
break parse;
}
limit--;
position++;
}
count = digitCount(text, position, 3);
if (count == 0 && !expectSeparators) {
break parse;
} else if (count < 1) {
// Need at least one digit for fraction of second.
return ~position;
}
offset += (text.charAt(position++) - '0') * 100;
if (count > 1) {
offset += (text.charAt(position++) - '0') * 10;
if (count > 2) {
offset += text.charAt(position++) - '0';
}
}
}
bucket.setOffset(negative ? -offset : offset);
return position;
}
/**
* Returns actual amount of digits to parse, but no more than original
* 'amount' parameter.
*/
private int digitCount(String text, int position, int amount) {
int limit = Math.min(text.length() - position, amount);
amount = 0;
for (; limit > 0; limit--) {
char c = text.charAt(position + amount);
if (c < '0' || c > '9') {
break;
}
amount++;
}
return amount;
}
}
//-----------------------------------------------------------------------
static class TimeZonePrinter
implements DateTimePrinter {
private final boolean iShortFormat;
TimeZonePrinter(boolean shortFormat) {
super();
iShortFormat = shortFormat;
}
public int estimatePrintedLength() {
return iShortFormat ? 4 : 20;
}
public void printTo(
StringBuffer buf, long instant, Chronology chrono,
int displayOffset, DateTimeZone displayZone, Locale locale) {
buf.append(print(instant, displayZone, locale));
}
public void printTo(
Writer out, long instant, Chronology chrono,
int displayOffset, DateTimeZone displayZone, Locale locale) throws IOException {
out.write(print(instant, displayZone, locale));
}
private String print(long instant, DateTimeZone displayZone, Locale locale) {
if (displayZone == null) {
return ""; // no zone
}
if (iShortFormat) {
return displayZone.getShortName(instant, locale);
} else {
return displayZone.getName(instant, locale);
}
}
public void printTo(StringBuffer buf, ReadablePartial partial, Locale locale) {
// no zone info
}
public void printTo(Writer out, ReadablePartial partial, Locale locale) throws IOException {
// no zone info
}
}
//-----------------------------------------------------------------------
static class Composite
implements DateTimePrinter, DateTimeParser {
private final DateTimePrinter[] iPrinters;
private final DateTimeParser[] iParsers;
private final int iPrintedLengthEstimate;
private final int iParsedLengthEstimate;
Composite(List elementPairs) {
super();
List printerList = new ArrayList();
List parserList = new ArrayList();
decompose(elementPairs, printerList, parserList);
if (printerList.size() <= 0) {
iPrinters = null;
iPrintedLengthEstimate = 0;
} else {
int size = printerList.size();
iPrinters = new DateTimePrinter[size];
int printEst = 0;
for (int i=0; i<size; i++) {
DateTimePrinter printer = (DateTimePrinter) printerList.get(i);
printEst += printer.estimatePrintedLength();
iPrinters[i] = printer;
}
iPrintedLengthEstimate = printEst;
}
if (parserList.size() <= 0) {
iParsers = null;
iParsedLengthEstimate = 0;
} else {
int size = parserList.size();
iParsers = new DateTimeParser[size];
int parseEst = 0;
for (int i=0; i<size; i++) {
DateTimeParser parser = (DateTimeParser) parserList.get(i);
parseEst += parser.estimateParsedLength();
iParsers[i] = parser;
}
iParsedLengthEstimate = parseEst;
}
}
private Composite(Composite base, DateTimePrinter[] printers) {
iPrinters = printers;
iParsers = base.iParsers;
iPrintedLengthEstimate = base.iPrintedLengthEstimate;
iParsedLengthEstimate = base.iParsedLengthEstimate;
}
public int estimatePrintedLength() {
return iPrintedLengthEstimate;
}
public void printTo(
StringBuffer buf, long instant, Chronology chrono,
int displayOffset, DateTimeZone displayZone, Locale locale) {
DateTimePrinter[] elements = iPrinters;
if (elements == null) {
throw new UnsupportedOperationException();
}
int len = elements.length;
for (int i = 0; i < len; i++) {
elements[i].printTo(buf, instant, chrono, displayOffset, displayZone, locale);
}
}
public void printTo(
Writer out, long instant, Chronology chrono,
int displayOffset, DateTimeZone displayZone, Locale locale) throws IOException {
DateTimePrinter[] elements = iPrinters;
if (elements == null) {
throw new UnsupportedOperationException();
}
int len = elements.length;
for (int i = 0; i < len; i++) {
elements[i].printTo(out, instant, chrono, displayOffset, displayZone, locale);
}
}
public void printTo(StringBuffer buf, ReadablePartial partial, Locale locale) {
DateTimePrinter[] elements = iPrinters;
if (elements == null) {
throw new UnsupportedOperationException();
}
int len = elements.length;
for (int i=0; i<len; i++) {
elements[i].printTo(buf, partial, locale);
}
}
public void printTo(Writer out, ReadablePartial partial, Locale locale) throws IOException {
DateTimePrinter[] elements = iPrinters;
if (elements == null) {
throw new UnsupportedOperationException();
}
int len = elements.length;
for (int i=0; i<len; i++) {
elements[i].printTo(out, partial, locale);
}
}
public int estimateParsedLength() {
return iParsedLengthEstimate;
}
public int parseInto(DateTimeParserBucket bucket, String text, int position) {
DateTimeParser[] elements = iParsers;
if (elements == null) {
throw new UnsupportedOperationException();
}
int len = elements.length;
for (int i=0; i<len && position >= 0; i++) {
position = elements[i].parseInto(bucket, text, position);
}
return position;
}
boolean isPrinter() {
return iPrinters != null;
}
boolean isParser() {
return iParsers != null;
}
/**
* Processes the element pairs, putting results into the given printer
* and parser lists.
*/
private void decompose(List elementPairs, List printerList, List parserList) {
int size = elementPairs.size();
for (int i=0; i<size; i+=2) {
Object element = elementPairs.get(i);
if (element != null && element instanceof DateTimePrinter) {
if (element instanceof Composite) {
addArrayToList(printerList, ((Composite)element).iPrinters);
} else {
printerList.add(element);
}
}
element = elementPairs.get(i + 1);
if (element != null && element instanceof DateTimeParser) {
if (element instanceof Composite) {
addArrayToList(parserList, ((Composite)element).iParsers);
} else {
parserList.add(element);
}
}
}
}
private void addArrayToList(List list, Object[] array) {
if (array != null) {
for (int i=0; i<array.length; i++) {
list.add(array[i]);
}
}
}
}
//-----------------------------------------------------------------------
static class MatchingParser
implements DateTimeParser {
private final DateTimeParser[] iParsers;
private final int iParsedLengthEstimate;
MatchingParser(DateTimeParser[] parsers) {
super();
iParsers = parsers;
int est = 0;
for (int i=parsers.length; --i>=0 ;) {
DateTimeParser parser = parsers[i];
if (parser != null) {
int len = parser.estimateParsedLength();
if (len > est) {
len = est;
}
}
}
iParsedLengthEstimate = est;
}
public int estimateParsedLength() {
return iParsedLengthEstimate;
}
public int parseInto(DateTimeParserBucket bucket, String text, int position) {
DateTimeParser[] parsers = iParsers;
int length = parsers.length;
final Object originalState = bucket.saveState();
boolean isOptional = false;
int bestValidPos = position;
Object bestValidState = null;
int bestInvalidPos = position;
for (int i=0; i<length; i++) {
DateTimeParser parser = parsers[i];
if (parser == null) {
// The empty parser wins only if nothing is better.
if (bestValidPos <= position) {
return position;
}
isOptional = true;
break;
}
int parsePos = parser.parseInto(bucket, text, position);
if (parsePos >= position) {
if (parsePos > bestValidPos) {
if (parsePos >= text.length() ||
(i + 1) >= length || parsers[i + 1] == null) {
// Completely parsed text or no more parsers to
// check. Skip the rest.
return parsePos;
}
bestValidPos = parsePos;
bestValidState = bucket.saveState();
}
} else {
if (parsePos < 0) {
parsePos = ~parsePos;
if (parsePos > bestInvalidPos) {
bestInvalidPos = parsePos;
}
}
}
bucket.restoreState(originalState);
}
if (bestValidPos > position || (bestValidPos == position && isOptional)) {
// Restore the state to the best valid parse.
if (bestValidState != null) {
bucket.restoreState(bestValidState);
}
return bestValidPos;
}
return ~bestInvalidPos;
}
}
}
| false | false | null | null |
diff --git a/plugin/src/net/sf/orcc/ir/parser/IrParser.java b/plugin/src/net/sf/orcc/ir/parser/IrParser.java
index 677fb77b0..53ebf2553 100644
--- a/plugin/src/net/sf/orcc/ir/parser/IrParser.java
+++ b/plugin/src/net/sf/orcc/ir/parser/IrParser.java
@@ -1,888 +1,901 @@
/*
* Copyright (c) 2009, IETR/INSA of Rennes
* 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 the IETR/INSA of Rennes 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 net.sf.orcc.ir.parser;
import static net.sf.orcc.ir.IrConstants.BINARY_EXPR;
import static net.sf.orcc.ir.IrConstants.BOP_BAND;
import static net.sf.orcc.ir.IrConstants.BOP_BOR;
import static net.sf.orcc.ir.IrConstants.BOP_BXOR;
import static net.sf.orcc.ir.IrConstants.BOP_DIV;
import static net.sf.orcc.ir.IrConstants.BOP_DIV_INT;
import static net.sf.orcc.ir.IrConstants.BOP_EQ;
import static net.sf.orcc.ir.IrConstants.BOP_EXP;
import static net.sf.orcc.ir.IrConstants.BOP_GE;
import static net.sf.orcc.ir.IrConstants.BOP_GT;
import static net.sf.orcc.ir.IrConstants.BOP_LAND;
import static net.sf.orcc.ir.IrConstants.BOP_LE;
import static net.sf.orcc.ir.IrConstants.BOP_LOR;
import static net.sf.orcc.ir.IrConstants.BOP_LT;
import static net.sf.orcc.ir.IrConstants.BOP_MINUS;
import static net.sf.orcc.ir.IrConstants.BOP_MOD;
import static net.sf.orcc.ir.IrConstants.BOP_NE;
import static net.sf.orcc.ir.IrConstants.BOP_PLUS;
import static net.sf.orcc.ir.IrConstants.BOP_SHIFT_LEFT;
import static net.sf.orcc.ir.IrConstants.BOP_SHIFT_RIGHT;
import static net.sf.orcc.ir.IrConstants.BOP_TIMES;
import static net.sf.orcc.ir.IrConstants.KEY_ACTIONS;
import static net.sf.orcc.ir.IrConstants.KEY_ACTION_SCHED;
import static net.sf.orcc.ir.IrConstants.KEY_INITIALIZES;
import static net.sf.orcc.ir.IrConstants.KEY_INPUTS;
import static net.sf.orcc.ir.IrConstants.KEY_NAME;
import static net.sf.orcc.ir.IrConstants.KEY_OUTPUTS;
import static net.sf.orcc.ir.IrConstants.KEY_PROCEDURES;
import static net.sf.orcc.ir.IrConstants.KEY_SOURCE_FILE;
import static net.sf.orcc.ir.IrConstants.KEY_STATE_VARS;
import static net.sf.orcc.ir.IrConstants.NAME_ASSIGN;
import static net.sf.orcc.ir.IrConstants.NAME_CALL;
import static net.sf.orcc.ir.IrConstants.NAME_EMPTY;
import static net.sf.orcc.ir.IrConstants.NAME_HAS_TOKENS;
import static net.sf.orcc.ir.IrConstants.NAME_IF;
import static net.sf.orcc.ir.IrConstants.NAME_JOIN;
import static net.sf.orcc.ir.IrConstants.NAME_LOAD;
import static net.sf.orcc.ir.IrConstants.NAME_PEEK;
import static net.sf.orcc.ir.IrConstants.NAME_READ;
import static net.sf.orcc.ir.IrConstants.NAME_RETURN;
import static net.sf.orcc.ir.IrConstants.NAME_STORE;
import static net.sf.orcc.ir.IrConstants.NAME_WHILE;
import static net.sf.orcc.ir.IrConstants.NAME_WRITE;
import static net.sf.orcc.ir.IrConstants.UNARY_EXPR;
import static net.sf.orcc.ir.IrConstants.UOP_BNOT;
import static net.sf.orcc.ir.IrConstants.UOP_LNOT;
import static net.sf.orcc.ir.IrConstants.UOP_MINUS;
import static net.sf.orcc.ir.IrConstants.UOP_NUM_ELTS;
import static net.sf.orcc.ir.IrConstants.VAR_EXPR;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.sf.orcc.OrccException;
import net.sf.orcc.common.LocalUse;
import net.sf.orcc.common.LocalVariable;
import net.sf.orcc.common.Location;
import net.sf.orcc.common.Port;
import net.sf.orcc.ir.actor.Action;
import net.sf.orcc.ir.actor.ActionScheduler;
import net.sf.orcc.ir.actor.Actor;
import net.sf.orcc.ir.actor.FSM;
import net.sf.orcc.ir.actor.Procedure;
import net.sf.orcc.ir.actor.StateVar;
import net.sf.orcc.ir.actor.Tag;
import net.sf.orcc.ir.consts.AbstractConst;
import net.sf.orcc.ir.consts.BoolConst;
import net.sf.orcc.ir.consts.IConst;
import net.sf.orcc.ir.consts.IntConst;
import net.sf.orcc.ir.consts.ListConst;
import net.sf.orcc.ir.consts.StringConst;
import net.sf.orcc.ir.expr.BinaryExpr;
import net.sf.orcc.ir.expr.BinaryOp;
import net.sf.orcc.ir.expr.BooleanExpr;
import net.sf.orcc.ir.expr.IExpr;
import net.sf.orcc.ir.expr.IntExpr;
import net.sf.orcc.ir.expr.StringExpr;
import net.sf.orcc.ir.expr.UnaryExpr;
import net.sf.orcc.ir.expr.UnaryOp;
import net.sf.orcc.ir.expr.VarExpr;
import net.sf.orcc.ir.nodes.AbstractNode;
import net.sf.orcc.ir.nodes.AssignVarNode;
import net.sf.orcc.ir.nodes.CallNode;
import net.sf.orcc.ir.nodes.EmptyNode;
import net.sf.orcc.ir.nodes.HasTokensNode;
import net.sf.orcc.ir.nodes.IfNode;
import net.sf.orcc.ir.nodes.JoinNode;
import net.sf.orcc.ir.nodes.LoadNode;
import net.sf.orcc.ir.nodes.PeekNode;
import net.sf.orcc.ir.nodes.PhiAssignment;
import net.sf.orcc.ir.nodes.ReadNode;
import net.sf.orcc.ir.nodes.ReturnNode;
import net.sf.orcc.ir.nodes.StoreNode;
import net.sf.orcc.ir.nodes.WhileNode;
import net.sf.orcc.ir.nodes.WriteNode;
import net.sf.orcc.ir.type.BoolType;
import net.sf.orcc.ir.type.IType;
import net.sf.orcc.ir.type.IntType;
import net.sf.orcc.ir.type.ListType;
import net.sf.orcc.ir.type.StringType;
import net.sf.orcc.ir.type.UintType;
import net.sf.orcc.ir.type.VoidType;
import net.sf.orcc.util.OrderedMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
/**
* This class provides a parser for orcc's IR.
*
* @author Matthieu Wipliez
*
*/
public class IrParser {
private Map<Tag, Action> actions;
private String file;
private OrderedMap<Port> inputs;
private boolean isInitialize;
private OrderedMap<Port> outputs;
private AbstractNode previousNode;
private OrderedMap<Procedure> procs;
private List<Action> untaggedActions;
private Map<String, LocalVariable> varDefs;
private Action getAction(JSONArray array) throws JSONException {
if (array.length() == 0) {
// removes the first untagged action found
return untaggedActions.remove(0);
} else {
- List<String> tagList = new ArrayList<String>();
+ Tag tag = new Tag();
for (int i = 0; i < array.length(); i++) {
- tagList.add(array.getString(i));
+ tag.add(array.getString(i));
}
- return actions.get(tagList);
+ return actions.get(tag);
}
}
private LocalVariable getVarDef(JSONArray array) throws JSONException,
OrccException {
String name = array.getString(0);
Integer suffix = array.isNull(1) ? null : array.getInt(1);
int index = array.getInt(2);
// retrieve the variable definition
LocalVariable varDef = varDefs.get(stringOfVar(name, suffix, index));
if (varDef == null) {
throw new OrccException("unknown variable: " + name + suffix + "_"
+ index);
}
return varDef;
}
private Action parseAction(JSONArray array) throws JSONException,
OrccException {
JSONArray tagArray = array.getJSONArray(0);
Tag tag = new Tag();
for (int i = 0; i < tagArray.length(); i++) {
tag.add(tagArray.getString(i));
}
Map<Port, Integer> ip = parsePattern(inputs, array.getJSONArray(1));
Map<Port, Integer> op = parsePattern(outputs, array.getJSONArray(2));
- Procedure scheduler = parseProc(array.getJSONArray(3));
- Procedure body = parseProc(array.getJSONArray(4));
+ Procedure scheduler = parseProc(array.getJSONArray(3), false);
+ Procedure body = parseProc(array.getJSONArray(4), false);
Action action = new Action(body.getLocation(), tag, ip, op, scheduler,
body);
putAction(tag, action);
return action;
}
private List<Action> parseActions(JSONArray array) throws JSONException,
OrccException {
List<Action> actions = new ArrayList<Action>();
for (int i = 0; i < array.length(); i++) {
actions.add(parseAction(array.getJSONArray(i)));
}
return actions;
}
private ActionScheduler parseActionScheduler(JSONArray array)
throws JSONException, OrccException {
JSONArray actionArray = array.getJSONArray(0);
List<Action> actions = new ArrayList<Action>();
for (int i = 0; i < actionArray.length(); i++) {
actions.add(getAction(actionArray.getJSONArray(i)));
}
FSM fsm = null;
if (!array.isNull(1)) {
fsm = parseFSM(array.getJSONArray(1));
}
return new ActionScheduler(actions, fsm);
}
/**
* Parses the input stream that this parser's constructor was given as YAML,
* and returns an actor from it.
*
* @return An {@link Actor}.
* @throws JSONException
*/
public Actor parseActor(InputStream in) throws OrccException {
try {
actions = new HashMap<Tag, Action>();
procs = new OrderedMap<Procedure>();
untaggedActions = new ArrayList<Action>();
varDefs = new HashMap<String, LocalVariable>();
JSONTokener tokener = new JSONTokener(new InputStreamReader(in));
JSONObject obj = new JSONObject(tokener);
file = obj.getString(KEY_SOURCE_FILE);
String name = obj.getString(KEY_NAME);
inputs = parsePorts(obj.getJSONArray(KEY_INPUTS));
outputs = parsePorts(obj.getJSONArray(KEY_OUTPUTS));
JSONArray array = obj.getJSONArray(KEY_STATE_VARS);
List<StateVar> stateVars = parseStateVars(array);
array = obj.getJSONArray(KEY_PROCEDURES);
for (int i = 0; i < array.length(); i++) {
- parseProc(array.getJSONArray(i));
+ parseProc(array.getJSONArray(i), true);
}
array = obj.getJSONArray(KEY_ACTIONS);
List<Action> actions = parseActions(array);
// a bit dirty, this one...
// when isInitialize is true, don't put actions in hash tables.
isInitialize = true;
array = obj.getJSONArray(KEY_INITIALIZES);
List<Action> initializes = parseActions(array);
array = obj.getJSONArray(KEY_ACTION_SCHED);
ActionScheduler sched = parseActionScheduler(array);
// no parameters at this point.
List<LocalVariable> parameters = new ArrayList<LocalVariable>();
Actor actor = new Actor(name, file, parameters, inputs, outputs,
stateVars, procs, actions, initializes, sched, null);
in.close();
return actor;
} catch (JSONException e) {
throw new OrccException("JSON error", e);
} catch (IOException e) {
throw new OrccException("I/O error", e);
}
}
private AssignVarNode parseAssignVarNode(int id, Location loc,
JSONArray array) throws JSONException, OrccException {
LocalVariable var = getVarDef(array.getJSONArray(0));
IExpr value = parseExpr(array.getJSONArray(1));
return new AssignVarNode(id, loc, var, value);
}
private BinaryExpr parseBinaryExpr(Location location, JSONArray array)
throws JSONException, OrccException {
String name = array.getString(0);
IExpr e1 = parseExpr(array.getJSONArray(1));
IExpr e2 = parseExpr(array.getJSONArray(2));
IType type = parseType(array.get(3));
BinaryOp op = null;
if (name.equals(BOP_BAND)) {
op = BinaryOp.BAND;
} else if (name.equals(BOP_BOR)) {
op = BinaryOp.BOR;
} else if (name.equals(BOP_BXOR)) {
op = BinaryOp.BXOR;
} else if (name.equals(BOP_DIV)) {
op = BinaryOp.DIV;
} else if (name.equals(BOP_DIV_INT)) {
op = BinaryOp.DIV_INT;
} else if (name.equals(BOP_EQ)) {
op = BinaryOp.EQ;
} else if (name.equals(BOP_EXP)) {
op = BinaryOp.EXP;
} else if (name.equals(BOP_GE)) {
op = BinaryOp.GE;
} else if (name.equals(BOP_GT)) {
op = BinaryOp.GT;
} else if (name.equals(BOP_LAND)) {
op = BinaryOp.LAND;
} else if (name.equals(BOP_LE)) {
op = BinaryOp.LE;
} else if (name.equals(BOP_LOR)) {
op = BinaryOp.LOR;
} else if (name.equals(BOP_LT)) {
op = BinaryOp.LT;
} else if (name.equals(BOP_MINUS)) {
op = BinaryOp.MINUS;
} else if (name.equals(BOP_MOD)) {
op = BinaryOp.MOD;
} else if (name.equals(BOP_NE)) {
op = BinaryOp.NE;
} else if (name.equals(BOP_PLUS)) {
op = BinaryOp.PLUS;
} else if (name.equals(BOP_SHIFT_LEFT)) {
op = BinaryOp.SHIFT_LEFT;
} else if (name.equals(BOP_SHIFT_RIGHT)) {
op = BinaryOp.SHIFT_RIGHT;
} else if (name.equals(BOP_TIMES)) {
op = BinaryOp.TIMES;
} else {
throw new OrccException("Invalid binary operator: " + name);
}
return new BinaryExpr(location, e1, op, e2, type);
}
private CallNode parseCallNode(int id, Location loc, JSONArray array)
throws JSONException, OrccException {
LocalVariable res = null;
String procName = array.getString(0);
if (!array.isNull(1)) {
res = getVarDef(array.getJSONArray(1));
}
List<IExpr> parameters = parseExprs(array.getJSONArray(2));
return new CallNode(id, loc, res, procs.get(procName), parameters);
}
/**
* Parses the given object as a constant.
*
* @param obj
* A YAML-encoded constant that may be a {@link Boolean}, an
* {@link Integer}, a {@link List} or a {@link String}.
* @return An {@link AbstractConst} created from the given object.
* @throws JSONException
*/
private IConst parseConstant(Object obj) throws JSONException,
OrccException {
IConst constant = null;
if (obj instanceof Boolean) {
constant = new BoolConst((Boolean) obj);
} else if (obj instanceof Integer) {
constant = new IntConst((Integer) obj);
} else if (obj instanceof JSONArray) {
JSONArray array = (JSONArray) obj;
List<IConst> cstList = new ArrayList<IConst>();
for (int i = 0; i < array.length(); i++) {
cstList.add(parseConstant(array.get(i)));
}
constant = new ListConst(cstList);
} else if (obj instanceof String) {
constant = new StringConst((String) obj);
} else {
throw new OrccException("Unknown constant: " + obj);
}
return constant;
}
private EmptyNode parseEmptyNode(int nodeId, Location location) {
return new EmptyNode(nodeId, location);
}
private IExpr parseExpr(JSONArray array) throws JSONException,
OrccException {
Location location = parseLocation(array.getJSONArray(0));
Object obj = array.get(1);
IExpr expr = null;
if (obj instanceof Boolean) {
expr = new BooleanExpr(location, (Boolean) obj);
} else if (obj instanceof Integer) {
expr = new IntExpr(location, (Integer) obj);
} else if (obj instanceof String) {
expr = new StringExpr(location, (String) obj);
} else if (obj instanceof JSONArray) {
array = (JSONArray) obj;
String name = array.getString(0);
if (name.equals(VAR_EXPR)) {
LocalUse var = parseVarUse(array.getJSONArray(1));
expr = new VarExpr(location, var);
} else if (name.equals(UNARY_EXPR)) {
return parseUnaryExpr(location, array.getJSONArray(1));
} else if (name.equals(BINARY_EXPR)) {
return parseBinaryExpr(location, array.getJSONArray(1));
} else {
throw new OrccException("Invalid expression kind: " + name);
}
} else {
throw new OrccException("Invalid expression: " + obj);
}
return expr;
}
private List<IExpr> parseExprs(JSONArray array) throws JSONException,
OrccException {
List<IExpr> exprs = new ArrayList<IExpr>();
for (int i = 0; i < array.length(); i++) {
exprs.add(parseExpr(array.getJSONArray(i)));
}
return exprs;
}
private FSM parseFSM(JSONArray array) throws JSONException, OrccException {
String initialState = array.getString(0);
FSM fsm = new FSM();
JSONArray stateArray = array.getJSONArray(1);
for (int i = 0; i < stateArray.length(); i++) {
fsm.addState(stateArray.getString(i));
}
// set the initial state *after* initializing the states to get a
// prettier order
fsm.setInitialState(initialState);
JSONArray transitionsArray = array.getJSONArray(2);
for (int i = 0; i < transitionsArray.length(); i++) {
JSONArray transitionArray = transitionsArray.getJSONArray(i);
String source = transitionArray.getString(0);
JSONArray targetsArray = transitionArray.getJSONArray(1);
for (int j = 0; j < targetsArray.length(); j++) {
JSONArray targetArray = targetsArray.getJSONArray(j);
Action action = getAction(targetArray.getJSONArray(0));
String target = targetArray.getString(1);
fsm.addTransition(source, target, action);
}
}
return fsm;
}
private HasTokensNode parseHasTokensNode(int id, Location loc,
JSONArray array) throws JSONException, OrccException {
LocalVariable varDef = getVarDef(array.getJSONArray(0));
String fifoName = array.getString(1);
int numTokens = array.getInt(2);
return new HasTokensNode(id, loc, fifoName, numTokens, varDef);
}
private IfNode parseIfNode(int id, Location loc, JSONArray array)
throws JSONException, OrccException {
IExpr condition = parseExpr(array.getJSONArray(0));
List<AbstractNode> thenNodes = parseNodes(array.getJSONArray(1));
List<AbstractNode> elseNodes = parseNodes(array.getJSONArray(2));
return new IfNode(id, loc, condition, thenNodes, elseNodes, null);
}
private JoinNode parseJoinNode(int id, Location loc, JSONArray array)
throws JSONException, OrccException {
List<PhiAssignment> phis = new ArrayList<PhiAssignment>();
for (int i = 0; i < array.length(); i++) {
phis.add(parsePhiNode(array.getJSONArray(i)));
}
return new JoinNode(id, loc, phis);
}
private LoadNode parseLoadNode(int id, Location loc, JSONArray array)
throws JSONException, OrccException {
LocalVariable target = getVarDef(array.getJSONArray(0));
LocalUse source = parseVarUse(array.getJSONArray(1));
List<IExpr> indexes = parseExprs(array.getJSONArray(2));
return new LoadNode(id, loc, target, source, indexes);
}
private Location parseLocation(JSONArray array) throws JSONException {
if (array.length() == 4) {
int startLine = array.getInt(0);
int startCol = array.getInt(1);
// TODO to be removed when Java frontend done.
// int endLine = array.getInt(2);
int endCol = array.getInt(3);
return new Location(startLine, startCol, endCol);
} else {
return new Location();
}
}
private AbstractNode parseNode(JSONArray array) throws JSONException,
OrccException {
String name = array.getString(0);
int id = array.getInt(1);
Location loc = parseLocation(array.getJSONArray(2));
AbstractNode node = null;
if (name.equals(NAME_ASSIGN)) {
node = parseAssignVarNode(id, loc, array.getJSONArray(3));
} else if (name.equals(NAME_CALL)) {
node = parseCallNode(id, loc, array.getJSONArray(3));
} else if (name.equals(NAME_EMPTY)) {
node = parseEmptyNode(id, loc);
} else if (name.equals(NAME_HAS_TOKENS)) {
node = parseHasTokensNode(id, loc, array.getJSONArray(3));
} else if (name.equals(NAME_IF)) {
node = parseIfNode(id, loc, array.getJSONArray(3));
} else if (name.equals(NAME_JOIN)) {
node = parseJoinNode(id, loc, array.getJSONArray(3));
// if the previous node is an If, then the join node we just parsed
// is the If's join node.
// We set it, and just pretend we didn't parse anything (otherwise
// the join would be referenced once in the if, and once in the node
// list)
if (previousNode instanceof IfNode) {
((IfNode) previousNode).setJoinNode((JoinNode) node);
node = null;
}
} else if (name.equals(NAME_LOAD)) {
node = parseLoadNode(id, loc, array.getJSONArray(3));
} else if (name.equals(NAME_PEEK)) {
node = parsePeekNode(id, loc, array.getJSONArray(3));
} else if (name.equals(NAME_READ)) {
node = parseReadNode(id, loc, array.getJSONArray(3));
} else if (name.equals(NAME_RETURN)) {
node = parseReturnNode(id, loc, array.getJSONArray(3));
} else if (name.equals(NAME_STORE)) {
node = parseStoreNode(id, loc, array.getJSONArray(3));
} else if (name.equals(NAME_WHILE)) {
node = parseWhileNode(id, loc, array.getJSONArray(3));
} else if (name.equals(NAME_WRITE)) {
node = parseWriteNode(id, loc, array.getJSONArray(3));
} else {
throw new OrccException("Invalid node definition: " + name);
}
previousNode = node;
return node;
}
private List<AbstractNode> parseNodes(JSONArray array)
throws JSONException, OrccException {
List<AbstractNode> nodes = new ArrayList<AbstractNode>();
for (int i = 0; i < array.length(); i++) {
AbstractNode node = parseNode(array.getJSONArray(i));
if (node != null) {
nodes.add(node);
}
}
return nodes;
}
private Map<Port, Integer> parsePattern(OrderedMap<Port> ports,
JSONArray array) throws JSONException, OrccException {
Map<Port, Integer> pattern = new HashMap<Port, Integer>();
for (int i = 0; i < array.length(); i++) {
JSONArray patternArray = array.getJSONArray(i);
Port port = ports.get(patternArray.getString(0));
int numTokens = patternArray.getInt(1);
pattern.put(port, numTokens);
}
return pattern;
}
private PeekNode parsePeekNode(int id, Location loc, JSONArray array)
throws JSONException, OrccException {
String fifoName = array.getString(0);
int numTokens = array.getInt(1);
LocalVariable varDef = getVarDef(array.getJSONArray(2));
return new PeekNode(id, loc, fifoName, numTokens, varDef);
}
private PhiAssignment parsePhiNode(JSONArray array) throws JSONException,
OrccException {
LocalVariable varDef = getVarDef(array.getJSONArray(0));
List<LocalUse> vars = new ArrayList<LocalUse>();
array = array.getJSONArray(1);
for (int i = 0; i < array.length(); i++) {
vars.add(parseVarUse(array.getJSONArray(i)));
}
return new PhiAssignment(varDef, vars);
}
/**
* Parses the given list as a list of ports.
*
* @param list
* A list of YAML-encoded {@link LocalVariable}s.
* @return A {@link List}<{@link LocalVariable}>.
* @throws JSONException
*/
private OrderedMap<Port> parsePorts(JSONArray array) throws JSONException,
OrccException {
OrderedMap<Port> ports = new OrderedMap<Port>();
for (int i = 0; i < array.length(); i++) {
JSONArray port = array.getJSONArray(i);
Location location = parseLocation(port.getJSONArray(0));
IType type = parseType(port.get(1));
String name = port.getString(2);
Port po = new Port(location, type, name);
ports.register(file, location, name, po);
}
return ports;
}
- private Procedure parseProc(JSONArray array) throws JSONException,
- OrccException {
+ /**
+ * Parses a procedure and optionally adds it to the {@link #procs} map.
+ *
+ * @param array
+ * a JSON array
+ * @param register
+ * if true, add this procedure to the {@link #procs} map.
+ * @return the procedure parsed
+ * @throws JSONException
+ * @throws OrccException
+ */
+ private Procedure parseProc(JSONArray array, boolean register)
+ throws JSONException, OrccException {
JSONArray array1 = array.getJSONArray(0);
String name = array1.getString(0);
boolean external = array1.getBoolean(1);
Location location = parseLocation(array.getJSONArray(1));
IType returnType = parseType(array.get(2));
List<LocalVariable> parameters = parseVarDefs(array.getJSONArray(3));
List<LocalVariable> locals = parseVarDefs(array.getJSONArray(4));
List<AbstractNode> nodes = parseNodes(array.getJSONArray(5));
Procedure proc = new Procedure(name, external, location, returnType,
parameters, locals, nodes);
- procs.register(file, location, name, proc);
+ if (register) {
+ procs.register(file, location, name, proc);
+ }
return proc;
}
private ReadNode parseReadNode(int id, Location loc, JSONArray array)
throws JSONException, OrccException {
String fifoName = array.getString(0);
int numTokens = array.getInt(1);
LocalVariable varDef = getVarDef(array.getJSONArray(2));
return new ReadNode(id, loc, fifoName, numTokens, varDef);
}
private List<LocalUse> parseRefs(JSONArray array) {
// TODO parse references
List<LocalUse> refs = new ArrayList<LocalUse>();
return refs;
}
private ReturnNode parseReturnNode(int id, Location loc, JSONArray array)
throws JSONException, OrccException {
IExpr expr = parseExpr(array);
return new ReturnNode(id, loc, expr);
}
/**
* Parses the given list as a list of state variables. A {@link StateVar} is
* a {@link LocalVariable} with an optional reference to an
* {@link AbstractConst} that contain the variable's initial value.
*
* @param list
* A list of YAML-encoded {@link LocalVariable}.
* @return A {@link List}<{@link StateVar}>.
* @throws JSONException
*/
private List<StateVar> parseStateVars(JSONArray array)
throws JSONException, OrccException {
List<StateVar> stateVars = new ArrayList<StateVar>();
for (int i = 0; i < array.length(); i++) {
JSONArray varDefArray = array.getJSONArray(i);
LocalVariable def = parseVarDef(varDefArray.getJSONArray(0));
IConst init = null;
if (!varDefArray.isNull(1)) {
init = parseConstant(varDefArray.get(1));
}
StateVar stateVar = new StateVar(def, init);
stateVars.add(stateVar);
}
return stateVars;
}
private StoreNode parseStoreNode(int id, Location loc, JSONArray array)
throws JSONException, OrccException {
LocalUse target = parseVarUse(array.getJSONArray(0));
List<IExpr> indexes = parseExprs(array.getJSONArray(1));
IExpr value = parseExpr(array.getJSONArray(2));
return new StoreNode(id, loc, target, indexes, value);
}
/**
* Parses the given object as a type definition.
*
* @param obj
* A YAML-encoded type definition. This is either a
* {@link String} for simple types (bool, String, void) or a
* {@link List} for types with parameters (int, uint, List).
* @return An {@link IType}.
* @throws JSONException
*/
private IType parseType(Object obj) throws JSONException, OrccException {
IType type = null;
if (obj instanceof String) {
String name = (String) obj;
if (name.equals(BoolType.NAME)) {
type = new BoolType();
} else if (name.equals(StringType.NAME)) {
type = new StringType();
} else if (name.equals(VoidType.NAME)) {
type = new VoidType();
} else {
throw new OrccException("Unknown type: " + name);
}
} else if (obj instanceof JSONArray) {
JSONArray array = (JSONArray) obj;
String name = array.getString(0);
if (name.equals(IntType.NAME)) {
IExpr expr = parseExpr(array.getJSONArray(1));
type = new IntType(expr);
} else if (name.equals(UintType.NAME)) {
IExpr expr = parseExpr(array.getJSONArray(1));
type = new UintType(expr);
} else if (name.equals(ListType.NAME)) {
IExpr expr = parseExpr(array.getJSONArray(1));
IType subType = parseType(array.get(2));
type = new ListType(expr, subType);
} else {
throw new OrccException("Unknown type: " + name);
}
} else {
throw new OrccException("Invalid type definition: "
+ obj.toString());
}
return type;
}
private UnaryExpr parseUnaryExpr(Location location, JSONArray array)
throws JSONException, OrccException {
String name = array.getString(0);
IExpr expr = parseExpr(array.getJSONArray(1));
IType type = parseType(array.get(2));
UnaryOp op = null;
if (name.equals(UOP_BNOT)) {
op = UnaryOp.BNOT;
} else if (name.equals(UOP_LNOT)) {
op = UnaryOp.LNOT;
} else if (name.equals(UOP_MINUS)) {
op = UnaryOp.MINUS;
} else if (name.equals(UOP_NUM_ELTS)) {
op = UnaryOp.NUM_ELTS;
} else {
throw new OrccException("Invalid unary operator: " + name);
}
return new UnaryExpr(location, op, expr, type);
}
/**
* Returns a variable definition using objects returned by the given
* iterator.
*
* @param it
* An iterator on YAML-encoded objects that hold information
* about a variable definition.
* @return A {@link LocalVariable}.
* @throws JSONException
*/
private LocalVariable parseVarDef(JSONArray array) throws JSONException,
OrccException {
JSONArray details = array.getJSONArray(0);
String name = details.getString(0);
boolean assignable = details.getBoolean(1);
boolean global = details.getBoolean(2);
Integer suffix = details.isNull(3) ? null : details.getInt(3);
int index = details.getInt(4);
// TODO parse node in VarDef
// int nodeId =
details.getInt(5);
Location loc = parseLocation(array.getJSONArray(1));
IType type = parseType(array.get(2));
AbstractNode node = null;
List<LocalUse> refs = parseRefs(array.getJSONArray(3));
LocalVariable varDef = new LocalVariable(assignable, global, index,
loc, name, node, refs, suffix, type);
// register the variable definition
varDefs.put(stringOfVar(name, suffix, index), varDef);
return varDef;
}
private List<LocalVariable> parseVarDefs(JSONArray array)
throws JSONException, OrccException {
List<LocalVariable> variables = new ArrayList<LocalVariable>();
for (int i = 0; i < array.length(); i++) {
variables.add(parseVarDef(array.getJSONArray(i)));
}
return variables;
}
private LocalUse parseVarUse(JSONArray array) throws JSONException,
OrccException {
LocalVariable varDef = getVarDef(array.getJSONArray(0));
// TODO parse node in VarUse
// int nodeId =
array.getInt(1);
return new LocalUse(varDef, null);
}
private WhileNode parseWhileNode(int id, Location loc, JSONArray array)
throws JSONException, OrccException {
IExpr condition = parseExpr(array.getJSONArray(0));
List<AbstractNode> nodes = parseNodes(array.getJSONArray(1));
JoinNode joinNode = (JoinNode) nodes.remove(0);
return new WhileNode(id, loc, condition, nodes, joinNode);
}
private WriteNode parseWriteNode(int id, Location loc, JSONArray array)
throws JSONException, OrccException {
String fifoName = array.getString(0);
int numTokens = array.getInt(1);
LocalVariable varDef = getVarDef(array.getJSONArray(2));
return new WriteNode(id, loc, fifoName, numTokens, varDef);
}
private void putAction(Tag tag, Action action) {
if (!isInitialize) {
if (tag.isEmpty()) {
untaggedActions.add(action);
} else {
actions.put(tag, action);
}
}
}
private String stringOfVar(String name, Integer suffix, int index) {
return name + (suffix == null ? "" : suffix) + "_" + index;
}
}
| false | false | null | null |
diff --git a/src/net/sf/freecol/client/control/InGameController.java b/src/net/sf/freecol/client/control/InGameController.java
index 4e4aa9b97..cc43f4798 100644
--- a/src/net/sf/freecol/client/control/InGameController.java
+++ b/src/net/sf/freecol/client/control/InGameController.java
@@ -1,4233 +1,4233 @@
/**
* 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.client.control;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import net.sf.freecol.FreeCol;
import net.sf.freecol.client.ClientOptions;
import net.sf.freecol.client.FreeColClient;
import net.sf.freecol.client.gui.Canvas;
import net.sf.freecol.client.gui.GUI;
import net.sf.freecol.client.gui.InGameMenuBar;
import net.sf.freecol.client.gui.Canvas.MissionaryAction;
import net.sf.freecol.client.gui.Canvas.ScoutAction;
import net.sf.freecol.client.gui.Canvas.TradeAction;
import net.sf.freecol.client.gui.action.BuildColonyAction;
import net.sf.freecol.client.gui.animation.Animations;
import net.sf.freecol.client.gui.i18n.Messages;
import net.sf.freecol.client.gui.option.FreeColActionUI;
import net.sf.freecol.client.gui.panel.ChoiceItem;
import net.sf.freecol.client.gui.panel.DeclarationDialog;
import net.sf.freecol.client.gui.panel.EventPanel;
import net.sf.freecol.client.gui.panel.PreCombatDialog;
import net.sf.freecol.client.gui.panel.ReportTurnPanel;
import net.sf.freecol.client.gui.panel.TradeRouteDialog;
import net.sf.freecol.client.gui.sound.SoundLibrary.SoundEffect;
import net.sf.freecol.client.networking.Client;
import net.sf.freecol.common.model.AbstractGoods;
import net.sf.freecol.common.model.AbstractUnit;
import net.sf.freecol.common.model.BuildableType;
import net.sf.freecol.common.model.Building;
import net.sf.freecol.common.model.Colony;
import net.sf.freecol.common.model.ColonyTile;
import net.sf.freecol.common.model.DiplomaticTrade;
import net.sf.freecol.common.model.EquipmentType;
import net.sf.freecol.common.model.Europe;
import net.sf.freecol.common.model.ExportData;
import net.sf.freecol.common.model.FreeColGameObject;
import net.sf.freecol.common.model.Game;
import net.sf.freecol.common.model.GameOptions;
import net.sf.freecol.common.model.GoalDecider;
import net.sf.freecol.common.model.Goods;
import net.sf.freecol.common.model.GoodsContainer;
import net.sf.freecol.common.model.GoodsType;
import net.sf.freecol.common.model.HistoryEvent;
import net.sf.freecol.common.model.IndianSettlement;
import net.sf.freecol.common.model.Location;
import net.sf.freecol.common.model.Map;
import net.sf.freecol.common.model.ModelMessage;
import net.sf.freecol.common.model.Nameable;
import net.sf.freecol.common.model.Ownable;
import net.sf.freecol.common.model.PathNode;
import net.sf.freecol.common.model.Player;
import net.sf.freecol.common.model.Region;
import net.sf.freecol.common.model.Settlement;
import net.sf.freecol.common.model.Tension;
import net.sf.freecol.common.model.Tile;
import net.sf.freecol.common.model.TileImprovement;
import net.sf.freecol.common.model.TileImprovementType;
import net.sf.freecol.common.model.TileItemContainer;
import net.sf.freecol.common.model.TradeRoute;
import net.sf.freecol.common.model.Unit;
import net.sf.freecol.common.model.UnitType;
import net.sf.freecol.common.model.WorkLocation;
import net.sf.freecol.common.model.CombatModel.CombatResult;
import net.sf.freecol.common.model.CombatModel.CombatResultType;
import net.sf.freecol.common.model.Map.Direction;
import net.sf.freecol.common.model.Map.Position;
import net.sf.freecol.common.model.Player.Stance;
import net.sf.freecol.common.model.TradeRoute.Stop;
import net.sf.freecol.common.model.Unit.MoveType;
import net.sf.freecol.common.model.Unit.UnitState;
import net.sf.freecol.common.networking.BuildColonyMessage;
import net.sf.freecol.common.networking.BuyLandMessage;
import net.sf.freecol.common.networking.ChatMessage;
import net.sf.freecol.common.networking.CloseTransactionMessage;
import net.sf.freecol.common.networking.DeclareIndependenceMessage;
import net.sf.freecol.common.networking.DiplomaticTradeMessage;
import net.sf.freecol.common.networking.GetTransactionMessage;
import net.sf.freecol.common.networking.GoodsForSaleMessage;
import net.sf.freecol.common.networking.Message;
import net.sf.freecol.common.networking.NetworkConstants;
import net.sf.freecol.common.networking.RenameMessage;
import net.sf.freecol.common.networking.SetDestinationMessage;
import net.sf.freecol.common.networking.SpySettlementMessage;
import net.sf.freecol.common.networking.StatisticsMessage;
import net.sf.freecol.common.networking.StealLandMessage;
import net.sf.freecol.common.networking.UpdateCurrentStopMessage;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
/**
* The controller that will be used while the game is played.
*/
public final class InGameController implements NetworkConstants {
private static final Logger logger = Logger.getLogger(InGameController.class.getName());
private final FreeColClient freeColClient;
/**
* Sets that the turn will be ended when all going-to units have been moved.
*/
private boolean endingTurn = false;
/**
* If true, then at least one unit has been active and the turn may automatically be ended.
*/
private boolean canAutoEndTurn = false;
/**
* Sets that all going-to orders should be executed.
*/
private boolean executeGoto = false;
/**
* A hash map of messages to be ignored.
*/
private HashMap<String, Integer> messagesToIgnore = new HashMap<String, Integer>();
/**
* A list of save game files.
*/
private ArrayList<File> allSaveGames = new ArrayList<File>();
/**
* The constructor to use.
*
* @param freeColClient The main controller.
*/
public InGameController(FreeColClient freeColClient) {
this.freeColClient = freeColClient;
}
/**
* Opens a dialog where the user should specify the filename and saves the
* game.
*/
public void saveGame() {
final Canvas canvas = freeColClient.getCanvas();
String fileName = freeColClient.getMyPlayer().getName() + "_" + freeColClient.getMyPlayer().getNationAsString()
+ "_" + freeColClient.getGame().getTurn().toSaveGameString();
fileName = fileName.replaceAll(" ", "_");
if (freeColClient.getMyPlayer().isAdmin() && freeColClient.getFreeColServer() != null) {
final File file = canvas.showSaveDialog(FreeCol.getSaveDirectory(), fileName);
if (file != null) {
FreeCol.setSaveDirectory(file.getParentFile());
saveGame(file);
}
}
}
/**
* Saves the game to the given file.
*
* @param file The <code>File</code>.
*/
public void saveGame(final File file) {
final Canvas canvas = freeColClient.getCanvas();
canvas.showStatusPanel(Messages.message("status.savingGame"));
try {
freeColClient.getFreeColServer().saveGame(file, freeColClient.getMyPlayer().getName());
canvas.closeStatusPanel();
} catch (IOException e) {
canvas.errorMessage("couldNotSaveGame");
}
canvas.requestFocusInWindow();
}
/**
* Opens a dialog where the user should specify the filename and loads the
* game.
*/
public void loadGame() {
Canvas canvas = freeColClient.getCanvas();
File file = canvas.showLoadDialog(FreeCol.getSaveDirectory());
if (file == null) {
return;
}
if (!file.isFile()) {
canvas.errorMessage("fileNotFound");
return;
}
if (!canvas.showConfirmDialog("stopCurrentGame.text", "stopCurrentGame.yes", "stopCurrentGame.no")) {
return;
}
freeColClient.getConnectController().quitGame(true);
canvas.removeInGameComponents();
freeColClient.getConnectController().loadGame(file);
}
/**
* Sets the "debug mode" to be active or not. Calls
* {@link FreeCol#setInDebugMode(boolean)} and reinitialize the
* <code>FreeColMenuBar</code>.
*
* @param debug Should be set to <code>true</code> in order to enable
* debug mode.
*/
public void setInDebugMode(boolean debug) {
FreeCol.setInDebugMode(debug);
freeColClient.getCanvas().setJMenuBar(new InGameMenuBar(freeColClient));
freeColClient.getCanvas().updateJMenuBar();
}
/**
* Declares independence for the home country.
*/
public void declareIndependence() {
Game game = freeColClient.getGame();
Player player = freeColClient.getMyPlayer();
if (game.getCurrentPlayer() != player) {
freeColClient.getCanvas().showInformationMessage("notYourTurn");
return;
}
Canvas canvas = freeColClient.getCanvas();
if (player.getSoL() < 50) {
canvas.showInformationMessage("declareIndependence.notMajority",
FreeCol.getSpecification().getGoodsType("model.goods.bells"),
"%percentage%",
Integer.toString(player.getSoL()));
return;
}
if (!canvas.showConfirmDialog("declareIndependence.areYouSure.text",
"declareIndependence.areYouSure.yes",
"declareIndependence.areYouSure.no")) {
return;
}
String nationName = Messages.message("declareIndependence.defaultNation",
"%nation%", player.getNewLandName());
nationName = canvas.showInputDialog("declareIndependence.enterNation", nationName,
Messages.message("ok"), Messages.message("cancel"));
player.setIndependentNationName(nationName);
Element reply = freeColClient.getClient().ask(new DeclareIndependenceMessage(nationName).toXMLElement());
if (reply == null) {
throw new NullPointerException("Failed to receive reply to \"declareIndependence\" message");
}
NodeList childNodes = reply.getChildNodes();
Element playerElement = (Element) childNodes.item(0);
Player refPlayer = (Player) game.getFreeColGameObject(playerElement.getAttribute("ID"));
if (refPlayer == null) {
refPlayer = new Player(game, playerElement);
}
for (int index = 1; index < childNodes.getLength(); index++) {
final Element unitElement = (Element) childNodes.item(index);
if (game.getFreeColGameObject(unitElement.getAttribute("ID")) == null) {
new Unit(game, (Element) childNodes.item(index));
} // Else: This unit has already been updated since it's on a carrier.
}
game.addPlayer(refPlayer);
freeColClient.getMyPlayer().declareIndependence();
freeColClient.getActionManager().update();
canvas.showFreeColDialog(new DeclarationDialog(canvas, freeColClient));
nextModelMessage();
}
/**
* Sends a public chat message.
*
* @param message The text of the message.
*/
public void sendChat(String message) {
ChatMessage chatMessage = new ChatMessage(freeColClient.getMyPlayer(),
message,
Boolean.FALSE);
freeColClient.getClient().sendAndWait(chatMessage.toXMLElement());
}
/**
* Sets <code>player</code> as the new <code>currentPlayer</code> of the
* game.
*
* @param currentPlayer The player.
*/
public void setCurrentPlayer(Player currentPlayer) {
logger.finest("Setting current player " + currentPlayer.getName());
Game game = freeColClient.getGame();
game.setCurrentPlayer(currentPlayer);
if (freeColClient.getMyPlayer().equals(currentPlayer)) {
// Autosave the game:
if (freeColClient.getFreeColServer() != null) {
final int turnNumber = freeColClient.getGame().getTurn().getNumber();
final int savegamePeriod = freeColClient.getClientOptions().getInteger(ClientOptions.AUTOSAVE_PERIOD);
if (savegamePeriod == 1 || (savegamePeriod != 0 && turnNumber % savegamePeriod == 0)) {
final String filename = Messages.message("clientOptions.savegames.autosave.fileprefix") + '-'
+ freeColClient.getGame().getTurn().toSaveGameString() + ".fsg";
File saveGameFile = new File(FreeCol.getAutosaveDirectory(), filename);
saveGame(saveGameFile);
int generations = freeColClient.getClientOptions().getInteger(ClientOptions.AUTOSAVE_GENERATIONS);
if (generations > 0) {
allSaveGames.add(saveGameFile);
if (allSaveGames.size() > generations) {
File fileToDelete = allSaveGames.remove(0);
fileToDelete.delete();
}
}
}
}
removeUnitsOutsideLOS();
if (currentPlayer.checkEmigrate()) {
if (currentPlayer.hasAbility("model.ability.selectRecruit") &&
currentPlayer.getEurope().recruitablesDiffer()) {
emigrateUnitInEurope(freeColClient.getCanvas().showEmigrationPanel());
} else {
emigrateUnitInEurope(0);
}
}
if (!freeColClient.isSingleplayer()) {
freeColClient.playSound(currentPlayer.getNation().getAnthem());
}
checkTradeRoutesInEurope();
displayModelMessages(true);
nextActiveUnit();
}
logger.finest("Exiting method setCurrentPlayer()");
}
/**
* Renames a <code>Nameable</code>.
*
* @param object The object to rename.
*/
public void rename(Nameable object) {
if (!(object instanceof Ownable) || ((Ownable) object).getOwner() != freeColClient.getMyPlayer()) {
return;
}
String name = null;
if (object instanceof Colony) {
name = freeColClient.getCanvas().showInputDialog("renameColony.text",
object.getName(),
"renameColony.yes",
"renameColony.no");
if (name == null || name.length() == 0) {
return; // user cancelled
}
if (freeColClient.getMyPlayer().getSettlement(name) != null) {
// colony name must be unique (per Player)
freeColClient.getCanvas().showInformationMessage("nameColony.notUnique",
"%name%", name);
return;
}
} else if (object instanceof Unit) {
name = freeColClient.getCanvas().showInputDialog("renameUnit.text",
object.getName(),
"renameUnit.yes",
"renameUnit.no");
if (name == null || name.length() == 0) {
return; // user cancelled
}
} else {
logger.warning("Tried to rename an unsupported Nameable: "
+ object.toString());
return;
}
freeColClient.getClient().sendAndWait(new RenameMessage((FreeColGameObject) object, name).toXMLElement());
object.setName(name);
}
/**
* Removes the units we cannot see anymore from the map.
*/
private void removeUnitsOutsideLOS() {
Player player = freeColClient.getMyPlayer();
Map map = freeColClient.getGame().getMap();
player.resetCanSeeTiles();
Iterator<Position> tileIterator = map.getWholeMapIterator();
while (tileIterator.hasNext()) {
Tile t = map.getTile(tileIterator.next());
if (t != null && !player.canSee(t) && t.getFirstUnit() != null) {
if (t.getFirstUnit().getOwner() == player) {
logger.warning("Could not see one of my own units!");
}
t.disposeAllUnits();
}
}
player.resetCanSeeTiles();
}
/**
* Uses the active unit to build a colony.
*/
public void buildColony() {
if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) {
freeColClient.getCanvas().showInformationMessage("notYourTurn");
return;
}
Client client = freeColClient.getClient();
Game game = freeColClient.getGame();
GUI gui = freeColClient.getGUI();
Unit unit = freeColClient.getGUI().getActiveUnit();
if (unit == null || !unit.canBuildColony()) {
return;
}
Tile tile = unit.getTile();
if (tile == null) {
return;
}
if (freeColClient.getClientOptions().getBoolean(ClientOptions.SHOW_COLONY_WARNINGS) &&
!showColonyWarnings(tile, unit)) {
return;
}
String name = freeColClient.getCanvas().showInputDialog("nameColony.text",
freeColClient.getMyPlayer().getDefaultSettlementName(false), "nameColony.yes", "nameColony.no");
if (name == null) { // The user canceled the action.
return;
} else if (freeColClient.getMyPlayer().getSettlement(name) != null) {
// colony name must be unique (per Player)
freeColClient.getCanvas().showInformationMessage("nameColony.notUnique",
"%name%", name);
return;
}
Element reply = client.ask(new BuildColonyMessage(name, unit).toXMLElement());
if (reply.getTagName().equals("buildColonyConfirmed")) {
freeColClient.playSound(SoundEffect.BUILDING_COMPLETE);
Element updateElement = getChildElement(reply, "update");
if (updateElement == null) {
logger.warning("buildColonyConfirmed message missing update");
} else {
unit.setLocation(null); // new location arriving in update
freeColClient.getInGameInputHandler().update(updateElement);
// There should be a colony here now. Check units present
// for treasure cash-in.
ArrayList<Unit> units = new ArrayList<Unit>(tile.getUnitList());
for(Unit unitInTile : units) {
if (unitInTile.canCarryTreasure()) {
checkCashInTreasureTrain(unitInTile);
}
}
}
gui.setActiveUnit(null);
gui.setSelectedTile(tile.getPosition());
} else {
// Handle error message.
}
}
private boolean showColonyWarnings(Tile tile, Unit unit) {
boolean landLocked = true;
boolean ownedByEuropeans = false;
boolean ownedBySelf = false;
boolean ownedByIndians = false;
java.util.Map<GoodsType, Integer> goodsMap = new HashMap<GoodsType, Integer>();
for (GoodsType goodsType : FreeCol.getSpecification().getGoodsTypeList()) {
if (goodsType.isFoodType()) {
int potential = 0;
if (tile.primaryGoods() == goodsType) {
potential = tile.potential(goodsType, null);
}
goodsMap.put(goodsType, new Integer(potential));
} else if (goodsType.isBuildingMaterial()) {
while (goodsType.isRefined()) {
goodsType = goodsType.getRawMaterial();
}
int potential = 0;
if (tile.secondaryGoods() == goodsType) {
potential = tile.potential(goodsType, null);
}
goodsMap.put(goodsType, new Integer(potential));
}
}
Map map = tile.getGame().getMap();
Iterator<Position> tileIterator = map.getAdjacentIterator(tile.getPosition());
while (tileIterator.hasNext()) {
Tile newTile = map.getTile(tileIterator.next());
if (newTile.isLand()) {
for (Entry<GoodsType, Integer> entry : goodsMap.entrySet()) {
entry.setValue(entry.getValue().intValue() +
newTile.potential(entry.getKey(), null));
}
Player tileOwner = newTile.getOwner();
if (tileOwner == unit.getOwner()) {
if (newTile.getOwningSettlement() != null) {
// we are using newTile
ownedBySelf = true;
} else {
Iterator<Position> ownTileIt = map.getAdjacentIterator(newTile.getPosition());
while (ownTileIt.hasNext()) {
Colony colony = map.getTile(ownTileIt.next()).getColony();
if (colony != null && colony.getOwner() == unit.getOwner()) {
// newTile can be used from an own colony
ownedBySelf = true;
break;
}
}
}
} else if (tileOwner != null && tileOwner.isEuropean()) {
ownedByEuropeans = true;
} else if (tileOwner != null) {
ownedByIndians = true;
}
} else {
landLocked = false;
}
}
int food = 0;
for (Entry<GoodsType, Integer> entry : goodsMap.entrySet()) {
if (entry.getKey().isFoodType()) {
food += entry.getValue().intValue();
}
}
ArrayList<ModelMessage> messages = new ArrayList<ModelMessage>();
if (landLocked) {
messages.add(new ModelMessage(unit, ModelMessage.MessageType.MISSING_GOODS,
FreeCol.getSpecification().getGoodsType("model.goods.fish"),
"buildColony.landLocked"));
}
if (food < 8) {
messages.add(new ModelMessage(unit, ModelMessage.MessageType.MISSING_GOODS,
FreeCol.getSpecification().getGoodsType("model.goods.food"),
"buildColony.noFood"));
}
for (Entry<GoodsType, Integer> entry : goodsMap.entrySet()) {
if (!entry.getKey().isFoodType() && entry.getValue().intValue() < 4) {
messages.add(new ModelMessage(unit, ModelMessage.MessageType.MISSING_GOODS, entry.getKey(),
"buildColony.noBuildingMaterials",
"%goods%", entry.getKey().getName()));
}
}
if (ownedBySelf) {
messages.add(new ModelMessage(unit, ModelMessage.MessageType.WARNING, null, "buildColony.ownLand"));
}
if (ownedByEuropeans) {
messages.add(new ModelMessage(unit, ModelMessage.MessageType.WARNING, null, "buildColony.EuropeanLand"));
}
if (ownedByIndians) {
messages.add(new ModelMessage(unit, ModelMessage.MessageType.WARNING, null, "buildColony.IndianLand"));
}
if (messages.isEmpty()) {
return true;
} else {
ModelMessage[] modelMessages = messages.toArray(new ModelMessage[messages.size()]);
return freeColClient.getCanvas().showConfirmDialog(modelMessages, "buildColony.yes",
"buildColony.no");
}
}
/**
* Moves the active unit in a specified direction. This may result in an
* attack, move... action.
*
* @param direction The direction in which to move the Unit.
*/
public void moveActiveUnit(Direction direction) {
Unit unit = freeColClient.getGUI().getActiveUnit();
if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) {
freeColClient.getCanvas().showInformationMessage("notYourTurn");
return;
}
if (unit != null) {
clearGotoOrders(unit);
move(unit, direction);
// centers unit if option "always center" is active
// A few checks need to be remade, as the unit may no longer exist
//or no longer be on the map
boolean alwaysCenter = freeColClient.getClientOptions().getBoolean(ClientOptions.ALWAYS_CENTER);
if(alwaysCenter && unit.getTile() != null){
centerOnUnit(unit);
}
} // else: nothing: There is no active unit that can be moved.
}
/**
* Selects a destination for this unit. Europe and the player's colonies are
* valid destinations.
*
* @param unit The unit for which to select a destination.
*/
public void selectDestination(Unit unit) {
final Player player = freeColClient.getMyPlayer();
Map map = freeColClient.getGame().getMap();
final ArrayList<ChoiceItem<Location>> destinations = new ArrayList<ChoiceItem<Location>>();
if (unit.isNaval() && unit.getOwner().canMoveToEurope()) {
PathNode path = map.findPathToEurope(unit, unit.getTile());
if (path != null) {
int turns = path.getTotalTurns();
destinations.add(new ChoiceItem<Location>(player.getEurope().getName() + " (" + turns + ")", player.getEurope()));
} else if (unit.getTile() != null
&& (unit.getTile().canMoveToEurope() || map.isAdjacentToMapEdge(unit.getTile()))) {
destinations.add(new ChoiceItem<Location>(player.getEurope().getName() + " (0)", player.getEurope()));
}
}
final Settlement inSettlement = (unit.getTile() != null) ? unit.getTile().getSettlement() : null;
// Search for destinations we can reach:
map.search(unit, new GoalDecider() {
public PathNode getGoal() {
return null;
}
public boolean check(Unit u, PathNode p) {
if (p.getTile().getSettlement() != null && p.getTile().getSettlement().getOwner() == player
&& p.getTile().getSettlement() != inSettlement) {
Settlement s = p.getTile().getSettlement();
int turns = p.getTurns();
destinations.add(new ChoiceItem<Location>(s.toString() + " (" + turns + ")", s));
}
return false;
}
public boolean hasSubGoals() {
return false;
}
}, Integer.MAX_VALUE);
Canvas canvas = freeColClient.getCanvas();
Location destination = canvas.showChoiceDialog(Messages.message("selectDestination.text"),
Messages.message("selectDestination.cancel"),
destinations);
if (destination == null) {
// user aborted
return;
}
if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) {
setDestination(unit, destination);
return;
}
if (destination instanceof Europe && unit.getTile() != null
&& (unit.getTile().canMoveToEurope() || map.isAdjacentToMapEdge(unit.getTile()))) {
moveToEurope(unit);
nextActiveUnit();
} else {
setDestination(unit, destination);
moveToDestination(unit);
}
}
/**
* Sets the destination of the given unit and send the server
* a message for this action.
*
* @param unit The <code>Unit</code>.
* @param destination The <code>Location</code>.
* @see Unit#setDestination(Location)
*/
public void setDestination(Unit unit, Location destination) {
freeColClient.getClient().sendAndWait(new SetDestinationMessage(unit, destination).toXMLElement());
unit.setDestination(destination);
}
/**
* Moves the given unit towards the destination given by
* {@link Unit#getDestination()}.
*
* @param unit The unit to move.
*/
public void moveToDestination(Unit unit) {
final Canvas canvas = freeColClient.getCanvas();
final Map map = freeColClient.getGame().getMap();
final Location destination = unit.getDestination();
if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) {
canvas.showInformationMessage("notYourTurn");
return;
}
if (unit.getTradeRoute() != null) {
if (unit.getLocation().getTile() == unit.getCurrentStop().getLocation().getTile()) {
// Trade unit is at current stop
logger.info("Trade unit " + unit.getId() + " in route " +
unit.getTradeRoute().getName() + " is at " +
unit.getCurrentStop().getLocation().getLocationName());
followTradeRoute(unit);
return;
} else {
logger.info("Unit " + unit.getId() + " is a trade unit in route " +
unit.getTradeRoute().getName() + ", going to " +
unit.getCurrentStop().getLocation().getLocationName());
}
} else {
logger.info("Moving unit " + unit.getId() + " to position "
+ unit.getDestination().getLocationName());
}
// Destination is either invalid (like an abandoned colony, for example
//or is current tile
if(!(destination instanceof Europe) &&
(destination.getTile() == null ||
unit.getTile() == destination.getTile())) {
clearGotoOrders(unit);
return;
}
PathNode path;
if (destination instanceof Europe) {
path = map.findPathToEurope(unit, unit.getTile());
} else {
path = map.findPath(unit, unit.getTile(), destination.getTile());
}
if (path == null) {
canvas.showInformationMessage("selectDestination.failed", unit,
"%destination%", destination.getLocationName());
setDestination(unit, null);
return;
}
while (path != null) {
MoveType mt = unit.getMoveType(path.getDirection());
switch (mt) {
case MOVE:
reallyMove(unit, path.getDirection());
break;
case EXPLORE_LOST_CITY_RUMOUR:
exploreLostCityRumour(unit, path.getDirection());
if (unit.isDisposed())
return;
break;
case MOVE_HIGH_SEAS:
if (destination instanceof Europe) {
moveToEurope(unit);
path = null;
} else if (path == path.getLastNode()) {
move(unit, path.getDirection());
path = null;
} else {
reallyMove(unit, path.getDirection());
}
break;
case DISEMBARK:
disembark(unit, path.getDirection());
path = null;
break;
default:
if (path == path.getLastNode() && mt != MoveType.ILLEGAL_MOVE
&& (mt != MoveType.ATTACK || knownEnemyOnLastTile(path))) {
move(unit, path.getDirection());
// unit may have been destroyed while moving
if(unit.isDisposed()){
return;
}
} else {
Tile target = map.getNeighbourOrNull(path.getDirection(), unit.getTile());
if (unit.getMovesLeft() == 0 ||
(unit.getMoveCost(target) > unit.getMovesLeft() &&
(target.getFirstUnit() == null ||
target.getFirstUnit().getOwner() == unit.getOwner()) &&
(target.getSettlement() == null ||
target.getSettlement().getOwner() == unit.getOwner()))) {
// we can't go there now, but we don't want to wake up
unit.setMovesLeft(0);
nextActiveUnit();
return;
} else {
// Active unit to show path and permit to move it
// manually
freeColClient.getGUI().setActiveUnit(unit);
return;
}
}
}
if (path != null) {
path = path.next;
}
}
if (unit.getTile() != null && destination instanceof Europe &&
map.isAdjacentToMapEdge(unit.getTile())) {
moveToEurope(unit);
}
// we have reached our destination
// if in a trade route, unload and update next stop
if (unit.getTradeRoute() == null) {
setDestination(unit, null);
} else {
followTradeRoute(unit);
}
// Display a "cash in"-dialog if a treasure train have been
// moved into a coastal colony:
if (unit.canCarryTreasure() && checkCashInTreasureTrain(unit)) {
unit = null;
}
if (unit != null && unit.getMovesLeft() > 0 && unit.getTile() != null) {
freeColClient.getGUI().setActiveUnit(unit);
} else if (freeColClient.getGUI().getActiveUnit() == unit) {
nextActiveUnit();
}
return;
}
private boolean knownEnemyOnLastTile(PathNode path) {
if ((path != null) && path.getLastNode() != null) {
Tile tile = path.getLastNode().getTile();
return ((tile.getFirstUnit() != null &&
tile.getFirstUnit().getOwner() != freeColClient.getMyPlayer()) ||
(tile.getSettlement() != null &&
tile.getSettlement().getOwner() != freeColClient.getMyPlayer()));
} else {
return false;
}
}
private void checkTradeRoutesInEurope() {
Europe europe = freeColClient.getMyPlayer().getEurope();
if (europe == null) {
return;
}
List<Unit> units = europe.getUnitList();
for(Unit unit : units) {
// Process units that have a trade route and
//are actually in Europe, not bound to/from
if (unit.getTradeRoute() != null && unit.isInEurope()) {
followTradeRoute(unit);
}
}
}
private void followTradeRoute(Unit unit) {
Stop stop = unit.getCurrentStop();
if (stop == null || stop.getLocation() == null) {
freeColClient.getCanvas().showInformationMessage("traderoute.broken",
"%name%",
unit.getTradeRoute().getName());
return;
}
boolean inEurope = unit.isInEurope();
// ship has not arrived in europe yet
if (freeColClient.getMyPlayer().getEurope() == stop.getLocation() &&
!inEurope) {
return;
}
// Unit was already in this location at the beginning of the turn
// Allow loading
if (unit.getInitialMovesLeft() == unit.getMovesLeft()){
Stop oldStop = unit.getCurrentStop();
if (inEurope) {
buyTradeGoodsFromEurope(unit);
} else {
loadTradeGoodsFromColony(unit);
}
updateCurrentStop(unit);
// It may happen that the unit may need to wait
// (Not enough goods in warehouse to load yet)
if (oldStop.getLocation().getTile() == unit.getCurrentStop().getLocation().getTile()){
unit.setMovesLeft(0);
}
} else {
// Has only just arrived, unload and stop here, no more
// moves allowed
logger.info("Trade unit " + unit.getId() + " in route " + unit.getTradeRoute().getName() +
" arrives at " + unit.getCurrentStop().getLocation().getLocationName());
if (inEurope) {
sellTradeGoodsInEurope(unit);
} else {
unloadTradeGoodsToColony(unit);
}
unit.setMovesLeft(0);
}
}
private void loadTradeGoodsFromColony(Unit unit){
Stop stop = unit.getCurrentStop();
Location location = unit.getColony();
logger.info("Trade unit " + unit.getId() + " loading in " + location.getLocationName());
GoodsContainer warehouse = location.getGoodsContainer();
if (warehouse == null) {
throw new IllegalStateException("No warehouse in a stop's location");
}
ArrayList<GoodsType> goodsTypesToLoad = stop.getCargo();
Iterator<Goods> goodsIterator = unit.getGoodsIterator();
// First, finish loading partially empty slots
while (goodsIterator.hasNext()) {
Goods goods = goodsIterator.next();
if (goods.getAmount() < 100) {
for (int index = 0; index < goodsTypesToLoad.size(); index++) {
GoodsType goodsType = goodsTypesToLoad.get(index);
ExportData exportData = unit.getColony().getExportData(goodsType);
if (goods.getType() == goodsType) {
// complete goods until 100 units
// respect the lower limit for TradeRoute
int amountPresent = warehouse.getGoodsCount(goodsType) - exportData.getExportLevel();
if (amountPresent > 0) {
logger.finest("Automatically loading goods " + goods.getName());
int amountToLoad = Math.min(100 - goods.getAmount(), amountPresent);
loadCargo(new Goods(freeColClient.getGame(), location, goods.getType(),
amountToLoad), unit);
}
}
// remove item: other items of the same type
// may or may not be present
goodsTypesToLoad.remove(index);
break;
}
}
}
// load rest of the cargo that should be on board
//while space is available
for (GoodsType goodsType : goodsTypesToLoad) {
// no more space left
if (unit.getSpaceLeft() == 0) {
break;
}
// respect the lower limit for TradeRoute
ExportData exportData = unit.getColony().getExportData(goodsType);
int amountPresent = warehouse.getGoodsCount(goodsType) - exportData.getExportLevel();
if (amountPresent > 0){
logger.finest("Automatically loading goods " + goodsType.getName());
loadCargo(new Goods(freeColClient.getGame(), location, goodsType,
Math.min(amountPresent, 100)), unit);
} else {
logger.finest("Can not load " + goodsType.getName() + " due to export settings.");
}
}
}
private void unloadTradeGoodsToColony(Unit unit){
Stop stop = unit.getCurrentStop();
Location location = unit.getColony();
logger.info("Trade unit " + unit.getId() + " unloading in " + location.getLocationName());
GoodsContainer warehouse = location.getGoodsContainer();
if (warehouse == null) {
throw new IllegalStateException("No warehouse in a stop's location");
}
ArrayList<GoodsType> goodsTypesToKeep = stop.getCargo();
Iterator<Goods> goodsIterator = unit.getGoodsIterator();
while (goodsIterator.hasNext()) {
Goods goods = goodsIterator.next();
boolean toKeep = false;
for (int index = 0; index < goodsTypesToKeep.size(); index++) {
GoodsType goodsType = goodsTypesToKeep.get(index);
if (goods.getType() == goodsType) {
// remove item: other items of the same type
// may or may not be present
goodsTypesToKeep.remove(index);
toKeep = true;
break;
}
}
// Cargo should be kept
if(toKeep)
continue;
// do not unload more than the warehouse can store
int capacity = ((Colony) location).getWarehouseCapacity() - warehouse.getGoodsCount(goods.getType());
if (capacity < goods.getAmount() &&
!freeColClient.getCanvas().showConfirmDialog(Messages.message("traderoute.warehouseCapacity",
"%unit%", unit.getName(),
"%colony%", ((Colony) location).getName(),
"%amount%", String.valueOf(goods.getAmount() - capacity),
"%goods%", goods.getName()),
"yes", "no")) {
logger.finest("Automatically unloading " + capacity + " " + goods.getName());
unloadCargo(new Goods(freeColClient.getGame(), unit, goods.getType(), capacity));
} else {
logger.finest("Automatically unloading " + goods.getAmount() + " " + goods.getName());
unloadCargo(goods);
}
}
}
private void sellTradeGoodsInEurope(Unit unit) {
Stop stop = unit.getCurrentStop();
// unload cargo that should not be on board
ArrayList<GoodsType> goodsTypesToLoad = stop.getCargo();
Iterator<Goods> goodsIterator = unit.getGoodsIterator();
while (goodsIterator.hasNext()) {
Goods goods = goodsIterator.next();
boolean toKeep = false;
for (int index = 0; index < goodsTypesToLoad.size(); index++) {
GoodsType goodsType = goodsTypesToLoad.get(index);
if (goods.getType() == goodsType) {
// remove item: other items of the same type
// may or may not be present
goodsTypesToLoad.remove(index);
toKeep = true;
break;
}
}
if(toKeep)
continue;
// this type of goods was not in the cargo list
logger.finest("Automatically unloading " + goods.getName());
sellGoods(goods);
}
}
private void buyTradeGoodsFromEurope(Unit unit) {
Stop stop = unit.getCurrentStop();
// First, finish loading partially empty slots
ArrayList<GoodsType> goodsTypesToLoad = stop.getCargo();
Iterator<Goods> goodsIterator = unit.getGoodsIterator();
while (goodsIterator.hasNext()) {
Goods goods = goodsIterator.next();
for (int index = 0; index < goodsTypesToLoad.size(); index++) {
GoodsType goodsType = goodsTypesToLoad.get(index);
if (goods.getType() == goodsType) {
if (goods.getAmount() < 100) {
logger.finest("Automatically loading goods " + goods.getName());
buyGoods(goods.getType(), (100 - goods.getAmount()), unit);
}
// remove item: other items of the same type
// may or may not be present
goodsTypesToLoad.remove(index);
break;
}
}
}
// load rest of cargo that should be on board
for (GoodsType goodsType : goodsTypesToLoad) {
if (unit.getSpaceLeft() > 0) {
logger.finest("Automatically loading goods " + goodsType.getName());
buyGoods(goodsType, 100, unit);
}
}
}
private void updateCurrentStop(Unit unit) {
// Set destination to next stop's location
freeColClient.getClient().sendAndWait(new UpdateCurrentStopMessage(unit).toXMLElement());
Stop stop = unit.nextStop();
// go to next stop, unit can already be there waiting to load
if (stop != null && stop.getLocation() != unit.getColony()) {
if (unit.isInEurope()) {
moveToAmerica(unit);
} else {
moveToDestination(unit);
}
}
}
/**
* Moves the specified unit in a specified direction. This may result in an
* attack, move... action.
*
* @param unit The unit to be moved.
* @param direction The direction in which to move the Unit.
*/
public void move(Unit unit, Direction direction) {
if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) {
freeColClient.getCanvas().showInformationMessage("notYourTurn");
return;
}
// Be certain the tile we are about to move into has been updated by the
// server:
// Can be removed if we use 'client.ask' when moving:
/*
* try { while (game.getMap().getNeighbourOrNull(direction,
* unit.getTile()) != null &&
* game.getMap().getNeighbourOrNull(direction, unit.getTile()).getType() ==
* Tile.UNEXPLORED) { Thread.sleep(5); } } catch (InterruptedException
* ie) {}
*/
MoveType move = unit.getMoveType(direction);
switch (move) {
case MOVE:
reallyMove(unit, direction);
break;
case ATTACK:
attack(unit, direction);
break;
case DISEMBARK:
disembark(unit, direction);
break;
case EMBARK:
embark(unit, direction);
break;
case MOVE_HIGH_SEAS:
moveHighSeas(unit, direction);
break;
case ENTER_INDIAN_VILLAGE_WITH_SCOUT:
scoutIndianSettlement(unit, direction);
break;
case ENTER_INDIAN_VILLAGE_WITH_MISSIONARY:
useMissionary(unit, direction);
break;
case ENTER_INDIAN_VILLAGE_WITH_FREE_COLONIST:
learnSkillAtIndianSettlement(unit, direction);
break;
case ENTER_FOREIGN_COLONY_WITH_SCOUT:
scoutForeignColony(unit, direction);
break;
case ENTER_SETTLEMENT_WITH_CARRIER_AND_GOODS:
//TODO: unify trade and negotiations
Map map = freeColClient.getGame().getMap();
Settlement settlement = map.getNeighbourOrNull(direction, unit.getTile()).getSettlement();
if (settlement instanceof Colony) {
negotiate(unit, direction);
} else {
if (freeColClient.getGame().getCurrentPlayer().hasContacted(settlement.getOwner())) {
tradeWithSettlement(unit, direction);
}
else {
freeColClient.getCanvas().showInformationMessage("noContactWithIndians");
}
}
break;
case EXPLORE_LOST_CITY_RUMOUR:
exploreLostCityRumour(unit, direction);
break;
case ILLEGAL_MOVE:
freeColClient.playSound(SoundEffect.ILLEGAL_MOVE);
break;
default:
throw new RuntimeException("unrecognised move: " + move);
}
// Display a "cash in"-dialog if a treasure train have been moved into a
// colony:
if (unit.canCarryTreasure()) {
checkCashInTreasureTrain(unit);
if (unit.isDisposed()) {
nextActiveUnit();
}
}
nextModelMessage();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
freeColClient.getActionManager().update();
freeColClient.getCanvas().updateJMenuBar();
}
});
}
/**
* Initiates a negotiation with a foreign power. The player
* creates a DiplomaticTrade with the NegotiationDialog. The
* DiplomaticTrade is sent to the other player. If the other
* player accepts the offer, the trade is concluded. If not, this
* method returns, since the next offer must come from the other
* player.
*
* @param unit an <code>Unit</code> value
* @param direction an <code>int</code> value
*/
private void negotiate(Unit unit, Direction direction) {
Map map = freeColClient.getGame().getMap();
Settlement settlement = map.getNeighbourOrNull(direction, unit.getTile()).getSettlement();
// TODO: should the client be getting full details on the settlement?
// AFAICT it does not need it, so comment out and look to remove
// Element reply = freeColClient.getClient().ask(new SpySettlementMessage(unit, direction).toXMLElement());
// if (reply != null) {
// settlement.readFromXMLElement((Element) reply.getFirstChild());
//}
if (settlement == null) return;
DiplomaticTrade agreement = freeColClient.getCanvas().showNegotiationDialog(unit, settlement, null);
if (agreement != null) {
unit.setMovesLeft(0);
// Do not wait for response, if the trade is valid and accepted or countered
// it will be handled by InGameInputHandler.diplomaticTrade()
freeColClient.getClient().send(new DiplomaticTradeMessage(unit, direction, agreement).toXMLElement());
}
}
/**
* Enter in a foreign colony to spy it.
*
* @param unit an <code>Unit</code> value
* @param direction an <code>int</code> value
*/
private void spy(Unit unit, Direction direction) {
Game game = freeColClient.getGame();
Colony colony = game.getMap().getNeighbourOrNull(direction,
unit.getTile()).getColony();
Element reply = freeColClient.getClient().ask(new SpySettlementMessage(unit, direction).toXMLElement());
if (reply != null) {
unit.setMovesLeft(0);
NodeList childNodes = reply.getChildNodes();
colony.readFromXMLElement((Element) childNodes.item(0));
Tile tile = colony.getTile();
for(int i=1; i < childNodes.getLength(); i++) {
Element unitElement = (Element) childNodes.item(i);
Unit foreignUnit = (Unit) game.getFreeColGameObject(unitElement.getAttribute("ID"));
if (foreignUnit == null) {
foreignUnit = new Unit(game, unitElement);
} else {
foreignUnit.readFromXMLElement(unitElement);
}
tile.add(foreignUnit);
}
freeColClient.getCanvas().showColonyPanel(colony);
}
}
/**
* Ask for explore a lost city rumour, and move unit if player accepts
*
* @param unit The unit to be moved.
* @param direction The direction in which to move the Unit.
*/
private void exploreLostCityRumour(Unit unit, Direction direction) {
// center on the explorer
freeColClient.getGUI().setFocusImmediately(unit.getTile().getPosition());
if (freeColClient.getCanvas().showConfirmDialog("exploreLostCityRumour.text", "exploreLostCityRumour.yes",
"exploreLostCityRumour.no")) {
reallyMove(unit, direction);
}
}
/**
* Buys the given land from the indians.
*
* @param tile The land which should be bought from the indians.
*/
public void buyLand(Tile tile) {
if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) {
freeColClient.getCanvas().showInformationMessage("notYourTurn");
return;
}
Element buyLandElement = new BuyLandMessage(tile).toXMLElement();
freeColClient.getMyPlayer().buyLand(tile);
freeColClient.getClient().sendAndWait(buyLandElement);
freeColClient.getCanvas().updateGoldLabel();
}
/**
* Steals the given land from the indians.
*
* @param tile The land which should be stolen from the indians.
* @param colony a <code>Colony</code> value
*/
public void stealLand(Tile tile, Colony colony) {
if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) {
freeColClient.getCanvas().showInformationMessage("notYourTurn");
return;
}
Element stealLandElement = new StealLandMessage(tile, colony).toXMLElement();
freeColClient.getClient().sendAndWait(stealLandElement);
tile.takeOwnership(freeColClient.getMyPlayer(), colony);
}
/**
* Uses the given unit to trade with a <code>Settlement</code> in the
* given direction.
*
* @param unit The <code>Unit</code> that is a carrier containing goods.
* @param direction The direction the unit could move in order to enter the
* <code>Settlement</code>.
* @exception IllegalArgumentException if the unit is not a carrier, or if
* there is no <code>Settlement</code> in the given
* direction.
* @see Settlement
*/
private void tradeWithSettlement(Unit unit, Direction direction) {
if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) {
freeColClient.getCanvas().showInformationMessage("notYourTurn");
return;
} else if (!unit.canCarryGoods()) {
throw new IllegalArgumentException("The unit has to be able to carry goods in order to trade!");
}
Canvas canvas = freeColClient.getCanvas();
Map map = freeColClient.getGame().getMap();
Settlement settlement = map.getNeighbourOrNull(direction, unit.getTile()).getSettlement();
if (settlement == null) {
throw new IllegalArgumentException("No settlement in given direction!");
}
if (unit.getGoodsCount() == 0) {
canvas.errorMessage("noGoodsOnboard");
return;
}
// Save moves to restore if no action taken
int initialUnitMoves = unit.getMovesLeft();
boolean actionTaken = false;
java.util.Map<String, Boolean> transactionSession = getTransactionSession(unit,settlement);
unit.setMovesLeft(0);
boolean canBuy = transactionSession.get("canBuy") && unit.getSpaceLeft() != 0;
boolean canSell = transactionSession.get("canSell");
boolean canGift = transactionSession.get("canGift");
// Show main dialog
TradeAction tradeType = canvas.showIndianSettlementTradeDialog(canBuy,canSell,canGift);
while(tradeType != null){
boolean tradeFinished = false;
switch(tradeType){
case BUY:
tradeFinished = attemptBuyFromIndianSettlement(unit, settlement);
if(tradeFinished){
actionTaken = true;
canBuy = false;
}
break;
case SELL:
tradeFinished = attemptSellToIndianSettlement(unit,settlement);
if(tradeFinished){
actionTaken = true;
canSell = false;
// we may not have been able to buy only because of space constraints
// after selling, space is available, so a recheck is required
canBuy = transactionSession.get("canBuy") && unit.getSpaceLeft() != 0;
}
break;
case GIFT:
tradeFinished = deliverGiftToSettlement(unit, settlement, null);
if(tradeFinished){
actionTaken = true;
canGift = false;
}
break;
default:
logger.warning("Unkown trade type");
break;
}
// no more options available
if(!canBuy && !canSell && !canGift){
break;
}
// Still has options for trade, show the main menu again
tradeType = canvas.showIndianSettlementTradeDialog(canBuy,canSell,canGift);
}
freeColClient.getClient().ask(new CloseTransactionMessage(unit, settlement).toXMLElement());
// if no action taken, restore movement points
GUI gui = freeColClient.getGUI();
if (actionTaken) {
- gui.setActiveUnit(null);
+ nextActiveUnit();
} else {
unit.setMovesLeft(initialUnitMoves);
gui.setActiveUnit(unit);
}
}
private java.util.Map<String,Boolean> getTransactionSession(Unit unit, Settlement settlement){
Element reply = freeColClient.getClient().ask(new GetTransactionMessage(unit, settlement).toXMLElement());
if (reply == null || !reply.getTagName().equals("getTransactionAnswer")) {
logger.warning("Illegal reply to getTransaction.");
throw new IllegalStateException();
}
java.util.Map<String,Boolean> transactionSession = new HashMap<String,Boolean>();
transactionSession.put("canBuy", new Boolean(reply.getAttribute("canBuy")));
transactionSession.put("canSell", new Boolean(reply.getAttribute("canSell")));
transactionSession.put("canGift", new Boolean(reply.getAttribute("canGift")));
return transactionSession;
}
private ArrayList<Goods> getGoodsForSaleInIndianSettlement(Unit unit, Settlement settlement){
// Get goods for sale from server
Element reply = freeColClient.getClient().ask(new GoodsForSaleMessage(unit, settlement).toXMLElement());
if (reply == null || !reply.getTagName().equals(GoodsForSaleMessage.getXMLElementTagName())) {
throw new IllegalStateException("Illegal reply to goodsForSale message.");
}
// Get goods for sell from server response
ArrayList<Goods> goodsOffered = new ArrayList<Goods>();
NodeList childNodes = reply.getChildNodes();
for (int i = 0; i < childNodes.getLength(); i++) {
goodsOffered.add(new Goods(freeColClient.getGame(), (Element) childNodes.item(i)));
}
return goodsOffered;
}
private boolean attemptBuyFromIndianSettlement(Unit unit, Settlement settlement){
Canvas canvas = freeColClient.getCanvas();
// Get list of goods for sale
List<ChoiceItem<Goods>> goodsOffered = new ArrayList<ChoiceItem<Goods>>();
for (Goods goods : getGoodsForSaleInIndianSettlement(unit, settlement)) {
goodsOffered.add(new ChoiceItem<Goods>(goods));
}
Client client = freeColClient.getClient();
Goods goods = null;
do {
// Show dialog with goods for sale
goods = canvas.showChoiceDialog(Messages.message("buyProposition.text"),
Messages.message("buyProposition.cancel"),
goodsOffered);
if (goods == null) { // == Trade aborted by the player, cancel buy attempt
return false;
}
// Get price for chosen good from server
Element buyPropositionElement = Message.createNewRootElement("buyProposition");
buyPropositionElement.setAttribute("unit", unit.getId());
buyPropositionElement.appendChild(goods.toXMLElement(null, buyPropositionElement.getOwnerDocument()));
Element proposalReply = client.ask(buyPropositionElement);
while (proposalReply != null) {
if (!proposalReply.getTagName().equals("buyPropositionAnswer")) {
logger.warning("Illegal reply.");
throw new IllegalStateException();
}
int gold = Integer.parseInt(proposalReply.getAttribute("gold"));
// proposal was refused
if (gold <= NO_TRADE) {
canvas.showInformationMessage("noTrade");
return true;
}
//show dialog for chosen goods buy proposal
String text = Messages.message("buy.text",
"%nation%", settlement.getOwner().getNationAsString(),
"%goods%", goods.getName(),
"%gold%", Integer.toString(gold));
List<ChoiceItem<Integer>> choices = new ArrayList<ChoiceItem<Integer>>();
choices.add(new ChoiceItem<Integer>(Messages.message("buy.takeOffer"), 1));
choices.add(new ChoiceItem<Integer>(Messages.message("buy.moreGold"), 2));
Integer ci = canvas.showChoiceDialog(text, Messages.message("buy.cancel"), choices);
// player cancelled goods choice, return to goods to sale dialog
if (ci == null) {
break;
}
// process player choice
switch(ci.intValue()){
case 1:
// Accepts price, makes purchase
buyFromSettlement(unit, (IndianSettlement) settlement, goods, gold);
return true;
case 2:
// Try to negociate new price
int newPrice = gold * 9 / 10;
// send new proposal to server
buyPropositionElement = Message.createNewRootElement("buyProposition");
buyPropositionElement.setAttribute("unit", unit.getId());
buyPropositionElement.appendChild(goods.toXMLElement(null, buyPropositionElement.getOwnerDocument()));
buyPropositionElement.setAttribute("gold", Integer.toString(newPrice));
proposalReply = client.ask(buyPropositionElement);
break;
default:
logger.warning("Unknown choice for buying goods from Indian Settlement.");
throw new IllegalStateException();
}
}
} while(goods != null);
// This should not happen
logger.warning("Unexpected situation");
return false;
}
private boolean attemptSellToIndianSettlement(Unit unit, Settlement settlement){
Canvas canvas = freeColClient.getCanvas();
// show buy dialog
Goods choice = canvas.showSimpleChoiceDialog(Messages.message("tradeProposition.text"),
Messages.message("tradeProposition.cancel"),
unit.getGoodsList());
if (choice == null) { // == Trade aborted by the player.
return false;
}
Client client = freeColClient.getClient();
// Send initial proposal to server
Element tradePropositionElement = Message.createNewRootElement("tradeProposition");
tradePropositionElement.setAttribute("unit", unit.getId());
tradePropositionElement.setAttribute("settlement", settlement.getId());
tradePropositionElement.appendChild(choice.toXMLElement(null, tradePropositionElement.getOwnerDocument()));
Element reply = client.ask(tradePropositionElement);
while (reply != null) {
if (!reply.getTagName().equals("tradePropositionAnswer")) {
logger.warning("Illegal reply.");
throw new IllegalStateException();
}
int gold = Integer.parseInt(reply.getAttribute("gold"));
// Indian do not need the goods, refuse and end trade
if (gold == NO_NEED_FOR_THE_GOODS) {
canvas.showInformationMessage("noNeedForTheGoods", "%goods%", choice.getName());
return true;
}
// Deal is totally not acceptable, refuse and end trade
if (gold <= NO_TRADE) {
canvas.showInformationMessage("noTrade");
return true;
}
// Show proposal for goods
String text = Messages.message("trade.text",
"%nation%", settlement.getOwner().getNationAsString(),
"%goods%", choice.getName(),
"%gold%", Integer.toString(gold));
List<ChoiceItem<Integer>> choices = new ArrayList<ChoiceItem<Integer>>();
choices.add(new ChoiceItem<Integer>(Messages.message("trade.takeOffer"), 1));
choices.add(new ChoiceItem<Integer>(Messages.message("trade.moreGold"), 2));
choices.add(new ChoiceItem<Integer>(Messages.message("trade.gift", "%goods%",
choice.getName()), 0));
Integer offerReply = canvas.showChoiceDialog(text, Messages.message("trade.cancel"), choices);
if (offerReply == null) { // == Trade aborted by the player.
return false;
}
switch(offerReply.intValue()){
case 0:
// decide to make a gift of the goods
deliverGiftToSettlement(unit, settlement, choice);
return true;
case 1:
// deal accepted
sellToSettlement(unit, settlement, choice, gold);
return true;
case 2:
// ask for more money
gold = (gold * 11) / 10;
break;
default:
logger.warning("Unknon player reply to indian proposal for goods sale");
return false;
}
// send counter proposal
tradePropositionElement = Message.createNewRootElement("tradeProposition");
tradePropositionElement.setAttribute("unit", unit.getId());
tradePropositionElement.setAttribute("settlement", settlement.getId());
tradePropositionElement.appendChild(choice.toXMLElement(null, tradePropositionElement.getOwnerDocument()));
tradePropositionElement.setAttribute("gold", Integer.toString(gold));
reply = client.ask(tradePropositionElement);
}
logger.warning("Request for indian proposal for goods sale was null");
return false;
}
/**
* Sells the given goods. The goods gets transferred from the given
* <code>Unit</code> to the given <code>Settlement</code>, and the
* {@link Unit#getOwner unit's owner} collects the payment.
*/
private void sellToSettlement(Unit unit, Settlement settlement, Goods goods, int gold) {
if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) {
freeColClient.getCanvas().showInformationMessage("notYourTurn");
return;
}
// send the transaction to the server
Element tradeElement = Message.createNewRootElement("trade");
tradeElement.setAttribute("unit", unit.getId());
tradeElement.setAttribute("settlement", settlement.getId());
tradeElement.setAttribute("gold", Integer.toString(gold));
tradeElement.appendChild(goods.toXMLElement(null, tradeElement.getOwnerDocument()));
Client client = freeColClient.getClient();
Element reply = client.ask(tradeElement);
// Update local data
unit.trade(settlement, goods, gold);
freeColClient.getCanvas().updateGoldLabel();
/*
if (reply != null) {
if (!reply.getTagName().equals("sellProposition")) {
logger.warning("Illegal reply.");
throw new IllegalStateException();
}
ArrayList<Goods> goodsOffered = new ArrayList<Goods>();
NodeList childNodes = reply.getChildNodes();
for (int i = 0; i < childNodes.getLength(); i++) {
goodsOffered.add(new Goods(freeColClient.getGame(), (Element) childNodes.item(i)));
}
ChoiceItem choice = (ChoiceItem) freeColClient.getCanvas()
.showChoiceDialog(Messages.message("buyProposition.text"),
Messages.message("buyProposition.cancel"),
goodsOffered.iterator());
if (choice != null) {
Goods goodsToBuy = (Goods) choice.getObject();
buyFromSettlement(unit, goodsToBuy);
}
}
*/
//nextActiveUnit(unit.getTile());
}
/**
* Uses the given unit to try buying the given goods from an
* <code>IndianSettlement</code>.
*/
/*
private void buyFromSettlement(Unit unit, Goods goods) {
Canvas canvas = freeColClient.getCanvas();
Client client = freeColClient.getClient();
Element buyPropositionElement = Message.createNewRootElement("buyProposition");
buyPropositionElement.setAttribute("unit", unit.getId());
buyPropositionElement.appendChild(goods.toXMLElement(null, buyPropositionElement.getOwnerDocument()));
Element reply = client.ask(buyPropositionElement);
while (reply != null) {
if (!reply.getTagName().equals("buyPropositionAnswer")) {
logger.warning("Illegal reply.");
throw new IllegalStateException();
}
int gold = Integer.parseInt(reply.getAttribute("gold"));
if (gold <= NO_TRADE) {
canvas.showInformationMessage("noTrade");
return;
} else {
IndianSettlement settlement = (IndianSettlement) goods.getLocation();
String text = Messages.message("buy.text",
"%nation%", settlement.getOwner().getNationAsString(),
"%goods%", goods.getName(),
"%gold%", Integer.toString(gold));
ChoiceItem ci = (ChoiceItem) canvas
.showChoiceDialog(text, Messages.message("buy.cancel"),
new ChoiceItem<Integer>(Messages.message("buy.takeOffer"), 1),
new ChoiceItem<Integer>(Messages.message("buy.moreGold"), 2));
if (ci == null) { // == Trade aborted by the player.
return;
}
int ret = ci.getChoice();
if (ret == 1) {
buyFromSettlement(unit, goods, gold);
return;
}
} // Ask for more gold (ret == 2):
buyPropositionElement = Message.createNewRootElement("buyProposition");
buyPropositionElement.setAttribute("unit", unit.getId());
buyPropositionElement.appendChild(goods.toXMLElement(null, buyPropositionElement.getOwnerDocument()));
buyPropositionElement.setAttribute("gold", Integer.toString((gold * 9) / 10));
reply = client.ask(buyPropositionElement);
}
}
*/
/**
* Buys the given goods. The goods gets transferred from their location
* to the given <code>Unit</code>, and the {@link Unit#getOwner unit's owner}
* pays the given gold.
*/
private void buyFromSettlement(Unit unit, IndianSettlement settlement, Goods goods, int gold) {
if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) {
freeColClient.getCanvas().showInformationMessage("notYourTurn");
return;
}
// send transaction to the server
Element buyElement = Message.createNewRootElement("buy");
buyElement.setAttribute("unit", unit.getId());
buyElement.setAttribute("gold", Integer.toString(gold));
buyElement.appendChild(goods.toXMLElement(null, buyElement.getOwnerDocument()));
Client client = freeColClient.getClient();
client.ask(buyElement);
// add goods to settlement in order to client will be able to transfer the goods
settlement.add(goods);
// update local data
unit.buy(settlement, goods, gold);
freeColClient.getCanvas().updateGoldLabel();
}
/**
* Trades the given goods. The goods gets transferred from the given
* <code>Unit</code> to the given <code>Settlement</code>.
*/
private boolean deliverGiftToSettlement(Unit unit, Settlement settlement, Goods goods) {
Canvas canvas = freeColClient.getCanvas();
if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) {
canvas.showInformationMessage("notYourTurn");
return false;
}
// no goods were chosen as gift, show dialog to decide
if (goods == null){
goods = canvas.showSimpleChoiceDialog(Messages.message("gift.text"),
Messages.message("tradeProposition.cancel"),
unit.getGoodsList());
if (goods == null) { // == Trade aborted by the player.
return false;
}
}
// Send gift proposal to server
Element deliverGiftElement = Message.createNewRootElement("deliverGift");
deliverGiftElement.setAttribute("unit", unit.getId());
deliverGiftElement.setAttribute("settlement", settlement.getId());
deliverGiftElement.appendChild(goods.toXMLElement(null, deliverGiftElement.getOwnerDocument()));
Client client = freeColClient.getClient();
client.sendAndWait(deliverGiftElement);
unit.deliverGift(settlement, goods);
//nextActiveUnit(unit.getTile());
return true;
}
/**
* Transfers the gold carried by this unit to the {@link Player owner}.
*
* @param unit an <code>Unit</code> value
* @return a <code>boolean</code> value
* @exception IllegalStateException if this unit is not a treasure train. or
* if it cannot be cashed in at it's current location.
*/
public boolean checkCashInTreasureTrain(Unit unit) {
Canvas canvas = freeColClient.getCanvas();
if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) {
canvas.showInformationMessage("notYourTurn");
return false;
}
Client client = freeColClient.getClient();
if (unit.canCashInTreasureTrain()) {
boolean cash;
if (unit.getOwner().getEurope() == null) {
canvas.showInformationMessage("cashInTreasureTrain.text.independence",
"%nation%", unit.getOwner().getNationAsString());
cash = true;
} else {
int transportFee = unit.getTransportFee();
String message = (transportFee == 0) ?
"cashInTreasureTrain.text.free" :
"cashInTreasureTrain.text.pay";
cash = canvas.showConfirmDialog(message, "cashInTreasureTrain.yes", "cashInTreasureTrain.no");
}
if (cash) {
// Inform the server:
Element cashInTreasureTrainElement = Message.createNewRootElement("cashInTreasureTrain");
cashInTreasureTrainElement.setAttribute("unit", unit.getId());
client.sendAndWait(cashInTreasureTrainElement);
unit.cashInTreasureTrain();
freeColClient.getCanvas().updateGoldLabel();
return true;
}
}
return false;
}
/**
* Actually moves a unit in a specified direction.
*
* @param unit The unit to be moved.
* @param direction The direction in which to move the Unit.
*/
private void reallyMove(Unit unit, Direction direction) {
if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) {
freeColClient.getCanvas().showInformationMessage("notYourTurn");
return;
}
Canvas canvas = freeColClient.getCanvas();
Client client = freeColClient.getClient();
// Inform the server:
Element moveElement = Message.createNewRootElement("move");
moveElement.setAttribute("unit", unit.getId());
moveElement.setAttribute("direction", direction.toString());
// TODO: server can actually fail (illegal move)!
// Play an animation showing the unit movement
if (!freeColClient.isHeadless()) {
final String key = (freeColClient.getMyPlayer() == unit.getOwner()) ?
ClientOptions.MOVE_ANIMATION_SPEED :
ClientOptions.ENEMY_MOVE_ANIMATION_SPEED;
if (freeColClient.getClientOptions().getInteger(key) > 0) {
Animations.unitMove(canvas, unit, direction);
}
}
// move before ask to server, to be in new tile in case there is a
// rumours
unit.move(direction);
if (unit.getTile().isLand() && !unit.getOwner().isNewLandNamed()) {
String newLandName = canvas.showInputDialog("newLand.text", unit.getOwner().getNewLandName(),
"newLand.yes", null);
unit.getOwner().setNewLandName(newLandName);
Element setNewLandNameElement = Message.createNewRootElement("setNewLandName");
setNewLandNameElement.setAttribute("newLandName", newLandName);
client.sendAndWait(setNewLandNameElement);
canvas.showFreeColDialog(new EventPanel(canvas, EventPanel.EventType.FIRST_LANDING));
unit.getOwner().getHistory()
.add(new HistoryEvent(unit.getGame().getTurn().getNumber(),
HistoryEvent.Type.DISCOVER_NEW_WORLD,
"%name%", newLandName));
final Player player = freeColClient.getMyPlayer();
final BuildColonyAction bca = (BuildColonyAction) freeColClient.getActionManager()
.getFreeColAction(BuildColonyAction.id);
final KeyStroke keyStroke = bca.getAccelerator();
player.addModelMessage(new ModelMessage(player, ModelMessage.MessageType.TUTORIAL, player,
"tutorial.buildColony",
"%build_colony_key%",
FreeColActionUI.getHumanKeyStrokeText(keyStroke),
"%build_colony_menu_item%",
Messages.message("unit.state.7"),
"%orders_menu_item%",
Messages.message("menuBar.orders")));
nextModelMessage();
}
Region region = unit.getTile().getDiscoverableRegion();
if (region != null) {
String name = null;
if (region.isPacific()) {
name = Messages.message("model.region.pacific");
canvas.showFreeColDialog(new EventPanel(canvas, EventPanel.EventType.DISCOVER_PACIFIC));
} else if (unit.getGame().getGameOptions().getBoolean(GameOptions.EXPLORATION_POINTS)) {
String defaultName = unit.getOwner().getDefaultRegionName(region.getType());
name = freeColClient.getCanvas().showInputDialog("nameRegion.text", defaultName,
"ok", "cancel",
"%name%", region.getDisplayName());
moveElement.setAttribute("regionName", name);
}
if (name != null) {
freeColClient.getMyPlayer().getHistory()
.add(new HistoryEvent(freeColClient.getGame().getTurn().getNumber(),
HistoryEvent.Type.DISCOVER_REGION,
"%region%", name));
}
}
// reply is an "update" Element
Element reply = client.ask(moveElement);
freeColClient.getInGameInputHandler().handle(client.getConnection(), reply);
if (reply.hasAttribute("movesSlowed")) {
// ship slowed
unit.setMovesLeft(unit.getMovesLeft() - Integer.parseInt(reply.getAttribute("movesSlowed")));
Unit slowedBy = (Unit) freeColClient.getGame().getFreeColGameObject(reply.getAttribute("slowedBy"));
canvas.showInformationMessage("model.unit.slowed", slowedBy,
"%unit%", unit.getName(),
"%enemyUnit%", slowedBy.getName(),
"%enemyNation%", slowedBy.getOwner().getNationAsString());
}
// set location again in order to meet with people player don't see
// before move
if (!unit.isDisposed()) {
unit.setLocation(unit.getTile());
}
if (unit.getTile().getSettlement() != null && unit.isCarrier() && unit.getTradeRoute() == null
&& (unit.getDestination() == null || unit.getDestination().getTile() == unit.getTile())) {
canvas.showColonyPanel((Colony) unit.getTile().getSettlement());
} else if (unit.getMovesLeft() <= 0 || unit.isDisposed()) {
nextActiveUnit(unit.getTile());
}
nextModelMessage();
}
/**
* Ask for attack or demand a tribute when attacking an indian settlement,
* attack in other cases
*
* @param unit The unit to perform the attack.
* @param direction The direction in which to attack.
*/
private void attack(Unit unit, Direction direction) {
if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) {
freeColClient.getCanvas().showInformationMessage("notYourTurn");
return;
}
Tile target = freeColClient.getGame().getMap().getNeighbourOrNull(direction, unit.getTile());
if (target.getSettlement() != null && target.getSettlement() instanceof IndianSettlement && unit.isArmed()) {
IndianSettlement settlement = (IndianSettlement) target.getSettlement();
switch (freeColClient.getCanvas().showArmedUnitIndianSettlementDialog(settlement)) {
case INDIAN_SETTLEMENT_ATTACK:
if (confirmHostileAction(unit, target) && confirmPreCombat(unit, target)) {
reallyAttack(unit, direction);
}
return;
case CANCEL:
return;
case INDIAN_SETTLEMENT_TRIBUTE:
Element demandMessage = Message.createNewRootElement("armedUnitDemandTribute");
demandMessage.setAttribute("unit", unit.getId());
demandMessage.setAttribute("direction", direction.toString());
Element reply = freeColClient.getClient().ask(demandMessage);
if (reply != null && reply.getTagName().equals("armedUnitDemandTributeResult")) {
String result = reply.getAttribute("result");
if (result.equals("agree")) {
String amount = reply.getAttribute("amount");
unit.getOwner().modifyGold(Integer.parseInt(amount));
freeColClient.getCanvas().updateGoldLabel();
freeColClient.getCanvas().showInformationMessage("scoutSettlement.tributeAgree",
settlement,
"%replace%", amount);
} else if (result.equals("disagree")) {
freeColClient.getCanvas().showInformationMessage("scoutSettlement.tributeDisagree", settlement);
}
unit.setMovesLeft(0);
} else {
logger.warning("Server gave an invalid reply to an armedUnitDemandTribute message");
return;
}
nextActiveUnit(unit.getTile());
break;
default:
logger.warning("Incorrect response returned from Canvas.showArmedUnitIndianSettlementDialog()");
return;
}
} else {
if (confirmHostileAction(unit, target) && confirmPreCombat(unit, target)) {
reallyAttack(unit, direction);
}
return;
}
}
/**
* Check if an attack results in a transition from peace or cease fire to
* war and, if so, warn the player.
*
* @param attacker The potential attacker.
* @param target The target tile.
* @return true to attack, false to abort.
*/
private boolean confirmHostileAction(Unit attacker, Tile target) {
if (attacker.hasAbility("model.ability.piracy")) {
// Privateers can attack and remain at peace
return true;
}
Player enemy;
if (target.getSettlement() != null) {
enemy = target.getSettlement().getOwner();
} else {
Unit defender = target.getDefendingUnit(attacker);
if (defender == null) {
logger.warning("Attacking, but no defender - will try!");
return true;
}
if (defender.hasAbility("model.ability.piracy")) {
// Privateers can be attacked and remain at peace
return true;
}
enemy = defender.getOwner();
}
switch (attacker.getOwner().getStance(enemy)) {
case UNCONTACTED: case PEACE:
return freeColClient.getCanvas().showConfirmDialog("model.diplomacy.attack.peace",
"model.diplomacy.attack.confirm",
"cancel",
"%replace%", enemy.getNationAsString());
case WAR:
logger.finest("Player at war, no confirmation needed");
break;
case CEASE_FIRE:
return freeColClient.getCanvas().showConfirmDialog("model.diplomacy.attack.ceaseFire",
"model.diplomacy.attack.confirm",
"cancel",
"%replace%", enemy.getNationAsString());
case ALLIANCE:
return freeColClient.getCanvas().showConfirmDialog("model.diplomacy.attack.alliance",
"model.diplomacy.attack.confirm",
"cancel",
"%replace%", enemy.getNationAsString());
}
return true;
}
/**
* If the client options include a pre-combat dialog, allow the user to view
* the odds and possibly cancel the attack.
*
* @param attacker The attacker.
* @param target The target tile.
* @return true to attack, false to abort.
*/
private boolean confirmPreCombat(Unit attacker, Tile target) {
if (freeColClient.getClientOptions().getBoolean(ClientOptions.SHOW_PRECOMBAT)) {
Settlement settlementOrNull = target.getSettlement();
// Don't tell the player how a settlement is defended!
Unit defenderOrNull = settlementOrNull != null ? null : target.getDefendingUnit(attacker);
Canvas canvas = freeColClient.getCanvas();
return canvas.showFreeColDialog(new PreCombatDialog(attacker, defenderOrNull,
settlementOrNull, canvas));
}
return true;
}
/**
* Performs an attack in a specified direction. Note that the server handles
* the attack calculations here.
*
* @param unit The unit to perform the attack.
* @param direction The direction in which to attack.
*/
private void reallyAttack(Unit unit, Direction direction) {
Client client = freeColClient.getClient();
Game game = freeColClient.getGame();
Tile target = game.getMap().getNeighbourOrNull(direction, unit.getTile());
Element attackElement = Message.createNewRootElement("attack");
attackElement.setAttribute("unit", unit.getId());
attackElement.setAttribute("direction", direction.toString());
// Get the result of the attack from the server:
Element attackResultElement = client.ask(attackElement);
if (attackResultElement != null &&
attackResultElement.getTagName().equals("attackResult")) {
// process the combat result
CombatResultType result = Enum.valueOf(CombatResultType.class, attackResultElement.getAttribute("result"));
int damage = Integer.parseInt(attackResultElement.getAttribute("damage"));
int plunderGold = Integer.parseInt(attackResultElement.getAttribute("plunderGold"));
Location repairLocation = (Location) game.getFreeColGameObjectSafely(attackResultElement.getAttribute("repairIn"));
// If a successful attack against a colony, we need to update the
// tile:
Element utElement = getChildElement(attackResultElement, Tile.getXMLElementTagName());
if (utElement != null) {
Tile updateTile = (Tile) game.getFreeColGameObject(utElement.getAttribute("ID"));
updateTile.readFromXMLElement(utElement);
}
// If there are captured goods, add to unit
NodeList capturedGoods = attackResultElement.getElementsByTagName("capturedGoods");
for (int i = 0; i < capturedGoods.getLength(); ++i) {
Element goods = (Element) capturedGoods.item(i);
GoodsType type = FreeCol.getSpecification().getGoodsType(goods.getAttribute("type"));
int amount = Integer.parseInt(goods.getAttribute("amount"));
unit.getGoodsContainer().addGoods(type, amount);
}
// Get the defender:
Element unitElement = getChildElement(attackResultElement, Unit.getXMLElementTagName());
Unit defender;
if (unitElement != null) {
defender = (Unit) game.getFreeColGameObject(unitElement.getAttribute("ID"));
if (defender == null) {
defender = new Unit(game, unitElement);
} else {
defender.readFromXMLElement(unitElement);
}
defender.setLocation(target);
} else {
// TODO: Erik - ensure this cannot happen!
logger.log(Level.SEVERE, "Server reallyAttack did not return a defender!");
defender = target.getDefendingUnit(unit);
if (defender == null) {
throw new IllegalStateException("No defender available!");
}
}
if (result == CombatResultType.DONE_SETTLEMENT) {
freeColClient.playSound(SoundEffect.CAPTURED_BY_ARTILLERY);
} else if (defender.isNaval() && result == CombatResultType.GREAT_WIN
|| unit.isNaval() && result == CombatResultType.GREAT_LOSS) {
freeColClient.playSound(SoundEffect.SUNK);
} else if (unit.isNaval()) {
freeColClient.playSound(SoundEffect.ATTACK_NAVAL);
} else if (unit.hasAbility("model.ability.bombard")) {
freeColClient.playSound(SoundEffect.ATTACK_ARTILLERY);
} else if (unit.isMounted()) {
freeColClient.playSound(SoundEffect.ATTACK_DRAGOON);
}
Animations.unitAttack(freeColClient.getCanvas(), unit, defender, result);
try {
game.getCombatModel().attack(unit, defender, new CombatResult(result, damage), plunderGold, repairLocation);
} catch (Exception e) {
// Ignore the exception (the update further down will fix any
// problems).
LogRecord lr = new LogRecord(Level.WARNING, "Exception in reallyAttack");
lr.setThrown(e);
logger.log(lr);
}
// Get the convert
Element convertElement = getChildElement(attackResultElement, "convert");
Unit convert;
if (convertElement != null) {
unitElement = (Element) convertElement.getFirstChild();
convert = (Unit) game.getFreeColGameObject(unitElement.getAttribute("ID"));
if (convert == null) {
convert = new Unit(game, unitElement);
} else {
convert.readFromXMLElement(unitElement);
}
convert.setLocation(convert.getLocation());
String nation = defender.getOwner().getNationAsString();
ModelMessage message = new ModelMessage(convert,
"model.unit.newConvertFromAttack",
new String[][] {
{"%nation%", nation},
{"%unit%", convert.getName()}},
ModelMessage.MessageType.UNIT_ADDED);
freeColClient.getMyPlayer().addModelMessage(message);
nextModelMessage();
}
if (defender.canCarryTreasure() &&
(result == CombatResultType.WIN ||
result == CombatResultType.GREAT_WIN)) {
checkCashInTreasureTrain(defender);
}
if (!defender.isDisposed()
&& ((result == CombatResultType.DONE_SETTLEMENT && unitElement != null)
|| defender.getLocation() == null || !defender.isVisibleTo(freeColClient.getMyPlayer()))) {
defender.dispose();
}
Element updateElement = getChildElement(attackResultElement, "update");
if (updateElement != null) {
freeColClient.getInGameInputHandler().handle(client.getConnection(), updateElement);
}
// settlement was indian capital, indians surrender
if(attackResultElement.getAttribute("indianCapitalBurned") != ""){
Player indianPlayer = defender.getOwner();
indianPlayer.surrenderTo(freeColClient.getMyPlayer());
//show message
ModelMessage message = new ModelMessage(indianPlayer,
"indianSettlement.capitalBurned",
new String[][] {
{"%name%", indianPlayer.getDefaultSettlementName(true)},
{"%nation%", indianPlayer.getNationAsString()}},
ModelMessage.MessageType.COMBAT_RESULT);
freeColClient.getMyPlayer().addModelMessage(message);
nextModelMessage();
}
if (unit.getMovesLeft() <= 0) {
nextActiveUnit(unit.getTile());
}
freeColClient.getCanvas().refresh();
} else {
logger.log(Level.SEVERE, "Server returned null from reallyAttack!");
}
}
/**
* Disembarks the specified unit in a specified direction.
*
* @param unit The unit to be disembarked.
* @param direction The direction in which to disembark the Unit.
*/
private void disembark(Unit unit, Direction direction) {
if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) {
freeColClient.getCanvas().showInformationMessage("notYourTurn");
return;
}
// Make sure it is a carrier.
if (!unit.isCarrier()) {
throw new RuntimeException("Programming error: disembark called on non carrier.");
}
// Check if user wants to disembark.
Canvas canvas = freeColClient.getCanvas();
if (!canvas.showConfirmDialog("disembark.text", "disembark.yes", "disembark.no")) {
return;
}
Game game = freeColClient.getGame();
Tile destinationTile = game.getMap().getNeighbourOrNull(direction, unit.getTile());
unit.setStateToAllChildren(UnitState.ACTIVE);
// Disembark only the first unit.
Unit toDisembark = unit.getFirstUnit();
if (toDisembark.getMovesLeft() > 0) {
if (destinationTile.hasLostCityRumour()) {
exploreLostCityRumour(toDisembark, direction);
} else {
reallyMove(toDisembark, direction);
}
}
}
/**
* Embarks the specified unit in a specified direction.
*
* @param unit The unit to be embarked.
* @param direction The direction in which to embark the Unit.
*/
private void embark(Unit unit, Direction direction) {
if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) {
freeColClient.getCanvas().showInformationMessage("notYourTurn");
return;
}
Game game = freeColClient.getGame();
Client client = freeColClient.getClient();
GUI gui = freeColClient.getGUI();
Canvas canvas = freeColClient.getCanvas();
// Animate the units movement
Animations.unitMove(canvas, unit, direction);
Tile destinationTile = game.getMap().getNeighbourOrNull(direction, unit.getTile());
Unit destinationUnit = null;
if (destinationTile.getUnitCount() == 1) {
destinationUnit = destinationTile.getFirstUnit();
} else {
ArrayList<Unit> choices = new ArrayList<Unit>();
for (Unit nextUnit : destinationTile.getUnitList()) {
if (nextUnit.getSpaceLeft() >= unit.getType().getSpaceTaken()) {
choices.add(nextUnit);
}
}
if (choices.size() == 1) {
destinationUnit = choices.get(0);
} else if (choices.size() == 0) {
throw new IllegalStateException();
} else {
destinationUnit = canvas.showSimpleChoiceDialog(Messages.message("embark.text"),
Messages.message("embark.cancel"),
choices);
if (destinationUnit == null) { // == user cancelled
return;
}
}
}
unit.embark(destinationUnit);
if (destinationUnit.getMovesLeft() > 0) {
gui.setActiveUnit(destinationUnit);
} else {
nextActiveUnit(destinationUnit.getTile());
}
Element embarkElement = Message.createNewRootElement("embark");
embarkElement.setAttribute("unit", unit.getId());
embarkElement.setAttribute("direction", direction.toString());
embarkElement.setAttribute("embarkOnto", destinationUnit.getId());
client.sendAndWait(embarkElement);
}
/**
* Boards a specified unit onto a carrier. The carrier should be at the same
* tile as the boarding unit.
*
* @param unit The unit who is going to board the carrier.
* @param carrier The carrier.
* @return <i>true</i> if the <code>unit</code> actually gets on the
* <code>carrier</code>.
*/
public boolean boardShip(Unit unit, Unit carrier) {
if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) {
freeColClient.getCanvas().showInformationMessage("notYourTurn");
throw new IllegalStateException("Not your turn.");
}
if (unit == null) {
logger.warning("unit == null");
return false;
}
if (carrier == null) {
logger.warning("Trying to load onto a non-existent carrier.");
return false;
}
Client client = freeColClient.getClient();
if (unit.isCarrier()) {
logger.warning("Trying to load a carrier onto another carrier.");
return false;
}
freeColClient.playSound(SoundEffect.LOAD_CARGO);
Element boardShipElement = Message.createNewRootElement("boardShip");
boardShipElement.setAttribute("unit", unit.getId());
boardShipElement.setAttribute("carrier", carrier.getId());
unit.boardShip(carrier);
client.sendAndWait(boardShipElement);
return true;
}
/**
* Clear the speciality of a <code>Unit</code>. That is, makes it a
* <code>Unit.FREE_COLONIST</code>.
*
* @param unit The <code>Unit</code> to clear the speciality of.
*/
public void clearSpeciality(Unit unit) {
if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) {
freeColClient.getCanvas().showInformationMessage("notYourTurn");
return;
} else {
UnitType newUnit = unit.getType().getDowngrade(UnitType.DowngradeType.CLEAR_SKILL);
if (newUnit == null) {
freeColClient.getCanvas().showInformationMessage("clearSpeciality.impossible",
"%unit%", unit.getName());
return;
} else if (!freeColClient.getCanvas().showConfirmDialog("clearSpeciality.areYouSure", "yes", "no",
"%oldUnit%", unit.getName(),
"%unit%", newUnit.getName())) {
return;
}
}
Client client = freeColClient.getClient();
Element clearSpecialityElement = Message.createNewRootElement("clearSpeciality");
clearSpecialityElement.setAttribute("unit", unit.getId());
unit.clearSpeciality();
client.sendAndWait(clearSpecialityElement);
}
/**
* Leave a ship. This method should only be invoked if the ship is in a
* harbour.
*
* @param unit The unit who is going to leave the ship where it is located.
*/
public void leaveShip(Unit unit) {
if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) {
freeColClient.getCanvas().showInformationMessage("notYourTurn");
return;
}
Client client = freeColClient.getClient();
unit.leaveShip();
Element leaveShipElement = Message.createNewRootElement("leaveShip");
leaveShipElement.setAttribute("unit", unit.getId());
client.sendAndWait(leaveShipElement);
}
/**
* Loads a cargo onto a carrier.
*
* @param goods The goods which are going aboard the carrier.
* @param carrier The carrier.
*/
public void loadCargo(Goods goods, Unit carrier) {
if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) {
freeColClient.getCanvas().showInformationMessage("notYourTurn");
return;
}
if (carrier == null) {
throw new NullPointerException();
}
freeColClient.playSound(SoundEffect.LOAD_CARGO);
Client client = freeColClient.getClient();
goods.adjustAmount();
Element loadCargoElement = Message.createNewRootElement("loadCargo");
loadCargoElement.setAttribute("carrier", carrier.getId());
loadCargoElement.appendChild(goods.toXMLElement(freeColClient.getMyPlayer(), loadCargoElement
.getOwnerDocument()));
goods.loadOnto(carrier);
client.sendAndWait(loadCargoElement);
}
/**
* Unload cargo. If the unit carrying the cargo is not in a
* harbour, the goods will be dumped.
*
* @param goods The goods which are going to leave the ship where it is
* located.
*/
public void unloadCargo(Goods goods) {
unloadCargo(goods, false);
}
/**
* Unload cargo. If the unit carrying the cargo is not in a
* harbour, or if the given boolean is true, the goods will be
* dumped.
*
* @param goods The goods which are going to leave the ship where it is
* located.
* @param dump a <code>boolean</code> value
*/
public void unloadCargo(Goods goods, boolean dump) {
if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) {
freeColClient.getCanvas().showInformationMessage("notYourTurn");
return;
}
if (!dump && goods.getLocation() instanceof Unit &&
((Unit) goods.getLocation()).getLocation() instanceof Europe){
sellGoods(goods);
return;
}
Client client = freeColClient.getClient();
goods.adjustAmount();
Element unloadCargoElement = Message.createNewRootElement("unloadCargo");
unloadCargoElement.appendChild(goods.toXMLElement(freeColClient.getMyPlayer(), unloadCargoElement
.getOwnerDocument()));
if (!dump && goods.getLocation() instanceof Unit &&
((Unit) goods.getLocation()).getColony() != null) {
goods.unload();
} else {
goods.setLocation(null);
}
client.sendAndWait(unloadCargoElement);
}
/**
* Buys goods in Europe. The amount of goods is adjusted if there is lack of
* space in the <code>carrier</code>.
*
* @param type The type of goods to buy.
* @param amount The amount of goods to buy.
* @param carrier The carrier.
*/
public void buyGoods(GoodsType type, int amount, Unit carrier) {
if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) {
freeColClient.getCanvas().showInformationMessage("notYourTurn");
return;
}
Client client = freeColClient.getClient();
Player myPlayer = freeColClient.getMyPlayer();
Canvas canvas = freeColClient.getCanvas();
if (carrier == null) {
throw new NullPointerException();
}
if (carrier.getOwner() != myPlayer
|| (carrier.getSpaceLeft() <= 0 && (carrier.getGoodsContainer().getGoodsCount(type) % 100 == 0))) {
return;
}
if (carrier.getSpaceLeft() <= 0) {
amount = Math.min(amount, 100 - carrier.getGoodsContainer().getGoodsCount(type) % 100);
}
if (myPlayer.getMarket().getBidPrice(type, amount) > myPlayer.getGold()) {
canvas.errorMessage("notEnoughGold");
return;
}
freeColClient.playSound(SoundEffect.LOAD_CARGO);
Element buyGoodsElement = Message.createNewRootElement("buyGoods");
buyGoodsElement.setAttribute("carrier", carrier.getId());
buyGoodsElement.setAttribute("type", type.getId());
buyGoodsElement.setAttribute("amount", Integer.toString(amount));
carrier.buyGoods(type, amount);
freeColClient.getCanvas().updateGoldLabel();
client.sendAndWait(buyGoodsElement);
}
/**
* Sells goods in Europe.
*
* @param goods The goods to be sold.
*/
public void sellGoods(Goods goods) {
if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) {
freeColClient.getCanvas().showInformationMessage("notYourTurn");
return;
}
Client client = freeColClient.getClient();
Player player = freeColClient.getMyPlayer();
freeColClient.playSound(SoundEffect.SELL_CARGO);
goods.adjustAmount();
Element sellGoodsElement = Message.createNewRootElement("sellGoods");
sellGoodsElement.appendChild(goods.toXMLElement(freeColClient.getMyPlayer(), sellGoodsElement
.getOwnerDocument()));
player.getMarket().sell(goods, player);
freeColClient.getCanvas().updateGoldLabel();
client.sendAndWait(sellGoodsElement);
}
/**
* Sets the export settings of the custom house.
*
* @param colony The colony with the custom house.
* @param goodsType The goods for which to set the settings.
*/
public void setGoodsLevels(Colony colony, GoodsType goodsType) {
Client client = freeColClient.getClient();
ExportData data = colony.getExportData(goodsType);
Element setGoodsLevelsElement = Message.createNewRootElement("setGoodsLevels");
setGoodsLevelsElement.setAttribute("colony", colony.getId());
setGoodsLevelsElement.appendChild(data.toXMLElement(colony.getOwner(), setGoodsLevelsElement
.getOwnerDocument()));
client.sendAndWait(setGoodsLevelsElement);
}
/**
* Equips or unequips a <code>Unit</code> with a certain type of
* <code>Goods</code>.
*
* @param unit The <code>Unit</code>.
* @param type an <code>EquipmentType</code> value
* @param amount How many of these goods the unit should have.
*/
public void equipUnit(Unit unit, EquipmentType type, int amount) {
if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) {
freeColClient.getCanvas().showInformationMessage("notYourTurn");
return;
}
if (amount == 0) {
// no changes
return;
}
Client client = freeColClient.getClient();
Player myPlayer = freeColClient.getMyPlayer();
Unit carrier = null;
if (unit.isOnCarrier()) {
carrier = (Unit) unit.getLocation();
leaveShip(unit);
}
Element equipUnitElement = Message.createNewRootElement("equipUnit");
equipUnitElement.setAttribute("unit", unit.getId());
equipUnitElement.setAttribute("type", type.getId());
equipUnitElement.setAttribute("amount", Integer.toString(amount));
if (amount > 0) {
for (AbstractGoods requiredGoods : type.getGoodsRequired()) {
GoodsType goodsType = requiredGoods.getType();
if (unit.isInEurope()) {
if (!myPlayer.canTrade(goodsType)) {
payArrears(goodsType);
if (!myPlayer.canTrade(goodsType)) {
return; // The user cancelled the action.
}
}
}
}
for (int count = 0; count < amount; count++) {
unit.equipWith(type);
}
} else {
for (int count = 0; count > amount; count--) {
unit.removeEquipment(type);
}
}
freeColClient.getCanvas().updateGoldLabel();
client.sendAndWait(equipUnitElement);
if (unit.getLocation() instanceof Colony || unit.getLocation() instanceof Building
|| unit.getLocation() instanceof ColonyTile) {
putOutsideColony(unit);
} else if (carrier != null) {
boardShip(unit, carrier);
}
}
/**
* Moves a <code>Unit</code> to a <code>WorkLocation</code>.
*
* @param unit The <code>Unit</code>.
* @param workLocation The <code>WorkLocation</code>.
*/
public void work(Unit unit, WorkLocation workLocation) {
if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) {
freeColClient.getCanvas().showInformationMessage("notYourTurn");
return;
}
Client client = freeColClient.getClient();
Element workElement = Message.createNewRootElement("work");
workElement.setAttribute("unit", unit.getId());
workElement.setAttribute("workLocation", workLocation.getId());
unit.work(workLocation);
client.sendAndWait(workElement);
}
/**
* Puts the specified unit outside the colony.
*
* @param unit The <code>Unit</code>
* @return <i>true</i> if the unit was successfully put outside the colony.
*/
public boolean putOutsideColony(Unit unit) {
if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) {
freeColClient.getCanvas().showInformationMessage("notYourTurn");
throw new IllegalStateException("Not your turn.");
} else if (!unit.getColony().canReducePopulation()) {
throw new IllegalStateException("Can not reduce population.");
}
Element putOutsideColonyElement = Message.createNewRootElement("putOutsideColony");
putOutsideColonyElement.setAttribute("unit", unit.getId());
unit.putOutsideColony();
Client client = freeColClient.getClient();
client.sendAndWait(putOutsideColonyElement);
return true;
}
/**
* Changes the work type of this <code>Unit</code>.
*
* @param unit The <code>Unit</code>
* @param workType The new <code>GoodsType</code> to produce.
*/
public void changeWorkType(Unit unit, GoodsType workType) {
if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) {
freeColClient.getCanvas().showInformationMessage("notYourTurn");
return;
}
Client client = freeColClient.getClient();
Element changeWorkTypeElement = Message.createNewRootElement("changeWorkType");
changeWorkTypeElement.setAttribute("unit", unit.getId());
changeWorkTypeElement.setAttribute("workType", workType.getId());
unit.setWorkType(workType);
client.sendAndWait(changeWorkTypeElement);
}
/**
* Changes the work type of this <code>Unit</code>.
*
* @param unit The <code>Unit</code>
* @param improvementType a <code>TileImprovementType</code> value
*/
public void changeWorkImprovementType(Unit unit, TileImprovementType improvementType) {
if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) {
freeColClient.getCanvas().showInformationMessage("notYourTurn");
return;
}
if (!(unit.checkSetState(UnitState.IMPROVING))) {
return; // Don't bother (and don't log, this is not exceptional)
}
if (improvementType.getId().equals("model.improvement.Road") ||
improvementType.getId().equals("model.improvement.Plow") ||
improvementType.getId().equals("model.improvement.ClearForest")) {
// Buy the land from the Indians first?
int price = unit.getOwner().getLandPrice(unit.getTile());
if (price > 0) {
Player nation = unit.getTile().getOwner();
List<ChoiceItem<Integer>> choices = new ArrayList<ChoiceItem<Integer>>();
choices.add(new ChoiceItem<Integer>(Messages.message("indianLand.pay" ,"%amount%",
Integer.toString(price)), 1));
choices.add(new ChoiceItem<Integer>(Messages.message("indianLand.take"), 2));
Integer ci = freeColClient.getCanvas()
.showChoiceDialog(Messages.message("indianLand.text",
"%player%", nation.getName()),
Messages.message("indianLand.cancel"), choices);
if (ci == null) {
return;
} else if (ci.intValue() == 1) {
if (price > freeColClient.getMyPlayer().getGold()) {
freeColClient.getCanvas().errorMessage("notEnoughGold");
return;
}
buyLand(unit.getTile());
}
}
}
Element changeWorkTypeElement = Message.createNewRootElement("workImprovement");
changeWorkTypeElement.setAttribute("unit", unit.getId());
changeWorkTypeElement.setAttribute("improvementType", improvementType.getId());
Element reply = freeColClient.getClient().ask(changeWorkTypeElement);
Element containerElement = getChildElement(reply, TileItemContainer.getXMLElementTagName());
if (containerElement != null) {
TileItemContainer container = (TileItemContainer) freeColClient.getGame()
.getFreeColGameObject(containerElement.getAttribute("ID"));
if (container == null) {
container = new TileItemContainer(freeColClient.getGame(), unit.getTile(), containerElement);
unit.getTile().setTileItemContainer(container);
} else {
container.readFromXMLElement(containerElement);
}
}
Element improvementElement = getChildElement(reply, TileImprovement.getXMLElementTagName());
if (improvementElement != null) {
TileImprovement improvement = (TileImprovement) freeColClient.getGame()
.getFreeColGameObject(improvementElement.getAttribute("ID"));
if (improvement == null) {
improvement = new TileImprovement(freeColClient.getGame(), improvementElement);
unit.getTile().add(improvement);
} else {
improvement.readFromXMLElement(improvementElement);
}
unit.work(improvement);
}
}
/**
* Assigns a unit to a teacher <code>Unit</code>.
*
* @param student an <code>Unit</code> value
* @param teacher an <code>Unit</code> value
*/
public void assignTeacher(Unit student, Unit teacher) {
Player player = freeColClient.getMyPlayer();
if (freeColClient.getGame().getCurrentPlayer() != player) {
freeColClient.getCanvas().showInformationMessage("notYourTurn");
return;
}
if (!student.canBeStudent(teacher)) {
throw new IllegalStateException("Unit can not be student!");
}
if (!teacher.getColony().canTrain(teacher)) {
throw new IllegalStateException("Unit can not be teacher!");
}
if (student.getOwner() != player) {
throw new IllegalStateException("Student is not your unit!");
}
if (teacher.getOwner() != player) {
throw new IllegalStateException("Teacher is not your unit!");
}
if (student.getColony() != teacher.getColony()) {
throw new IllegalStateException("Student and teacher are not in the same colony!");
}
if (!(student.getLocation() instanceof WorkLocation)) {
throw new IllegalStateException("Student is not in a WorkLocation!");
}
Element assignTeacherElement = Message.createNewRootElement("assignTeacher");
assignTeacherElement.setAttribute("student", student.getId());
assignTeacherElement.setAttribute("teacher", teacher.getId());
if (student.getTeacher() != null) {
student.getTeacher().setStudent(null);
}
student.setTeacher(teacher);
if (teacher.getStudent() != null) {
teacher.getStudent().setTeacher(null);
}
teacher.setStudent(student);
freeColClient.getClient().sendAndWait(assignTeacherElement);
}
/**
* Changes the current construction project of a <code>Colony</code>.
*
* @param colony The <code>Colony</code>
*/
public void setBuildQueue(Colony colony, List<BuildableType> buildQueue) {
if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) {
freeColClient.getCanvas().showInformationMessage("notYourTurn");
return;
}
colony.setBuildQueue(buildQueue);
Element setBuildQueueElement = Message.createNewRootElement("setBuildQueue");
setBuildQueueElement.setAttribute("colony", colony.getId());
setBuildQueueElement.setAttribute("size", Integer.toString(buildQueue.size()));
for (int x = 0; x < buildQueue.size(); x++) {
setBuildQueueElement.setAttribute("x" + Integer.toString(x), buildQueue.get(x).getId());
}
freeColClient.getClient().sendAndWait(setBuildQueueElement);
}
/**
* Changes the state of this <code>Unit</code>.
*
* @param unit The <code>Unit</code>
* @param state The state of the unit.
*/
public void changeState(Unit unit, UnitState state) {
if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) {
freeColClient.getCanvas().showInformationMessage("notYourTurn");
return;
}
Client client = freeColClient.getClient();
Game game = freeColClient.getGame();
Canvas canvas = freeColClient.getCanvas();
if (!(unit.checkSetState(state))) {
return; // Don't bother (and don't log, this is not exceptional)
}
if (state == UnitState.FORTIFYING && unit.isOffensiveUnit() &&
!unit.hasAbility("model.ability.piracy")) { // check if it's going to occupy a work tile
Tile tile = unit.getTile();
if (tile != null && tile.getOwningSettlement() != null) { // check stance with settlement's owner
Player myPlayer = unit.getOwner();
Player enemy = tile.getOwningSettlement().getOwner();
if (myPlayer != enemy && myPlayer.getStance(enemy) != Stance.ALLIANCE
&& !confirmHostileAction(unit, tile.getOwningSettlement().getTile())) { // player has aborted
return;
}
}
}
unit.setState(state);
// NOTE! The call to nextActiveUnit below can lead to the dreaded
// "not your turn" error, so let's finish networking first.
Element changeStateElement = Message.createNewRootElement("changeState");
changeStateElement.setAttribute("unit", unit.getId());
changeStateElement.setAttribute("state", state.toString());
client.sendAndWait(changeStateElement);
if (!freeColClient.getCanvas().isShowingSubPanel() &&
(unit.getMovesLeft() == 0 || unit.getState() == UnitState.SENTRY ||
unit.getState() == UnitState.SKIPPED)) {
nextActiveUnit();
} else {
freeColClient.getCanvas().refresh();
}
}
/**
* Clears the orders of the given <code>Unit</code> The orders are cleared
* by making the unit {@link UnitState#ACTIVE} and setting a null destination
*
* @param unit The <code>Unit</code>.
*/
public void clearOrders(Unit unit) {
if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) {
freeColClient.getCanvas().showInformationMessage("notYourTurn");
return;
}
if (unit == null) {
return;
}
if (unit.getState()==UnitState.IMPROVING) {
// Ask the user for confirmation, as this is a classic mistake.
// Canceling a pioneer terrain improvement is a waste of many turns
ModelMessage message = new ModelMessage(unit, ModelMessage.MessageType.WARNING, unit,
"model.unit.confirmCancelWork", "%turns%", new Integer(unit.getWorkLeft()).toString());
boolean cancelWork = freeColClient.getCanvas().showConfirmDialog(new ModelMessage[] {message}, "yes", "no");
if (!cancelWork) {
return;
}
}
/*
* report to server, in order not to restore destination if it's
* received in a update message
*/
clearGotoOrders(unit);
assignTradeRoute(unit, TradeRoute.NO_TRADE_ROUTE);
changeState(unit, UnitState.ACTIVE);
}
/**
* Clears the orders of the given <code>Unit</code>. The orders are
* cleared by making the unit {@link UnitState#ACTIVE}.
*
* @param unit The <code>Unit</code>.
*/
public void clearGotoOrders(Unit unit) {
if (unit == null) {
return;
}
/*
* report to server, in order not to restore destination if it's
* received in a update message
*/
if (unit.getDestination() != null)
setDestination(unit, null);
}
/**
* Moves the specified unit in the "high seas" in a specified direction.
* This may result in an ordinary move, no move or a move to europe.
*
* @param unit The unit to be moved.
* @param direction The direction in which to move the Unit.
*/
private void moveHighSeas(Unit unit, Direction direction) {
if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) {
freeColClient.getCanvas().showInformationMessage("notYourTurn");
return;
}
Canvas canvas = freeColClient.getCanvas();
Map map = freeColClient.getGame().getMap();
// getTile() == null : Unit in europe
if (!unit.isAlreadyOnHighSea()
&& (unit.getTile() == null || canvas.showConfirmDialog("highseas.text", "highseas.yes", "highseas.no"))) {
moveToEurope(unit);
nextActiveUnit();
} else if (map.getNeighbourOrNull(direction, unit.getTile()) != null) {
reallyMove(unit, direction);
}
}
/**
* Moves the specified free colonist into an Indian settlement to learn a
* skill. Of course, the colonist won't physically get into the village, it
* will just stay where it is and gain the skill.
*
* @param unit The unit to learn the skill.
* @param direction The direction in which the Indian settlement lies.
*/
private void learnSkillAtIndianSettlement(Unit unit, Direction direction) {
if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) {
freeColClient.getCanvas().showInformationMessage("notYourTurn");
return;
}
Client client = freeColClient.getClient();
Canvas canvas = freeColClient.getCanvas();
Map map = freeColClient.getGame().getMap();
IndianSettlement settlement = (IndianSettlement) map.getNeighbourOrNull(direction, unit.getTile())
.getSettlement();
if (settlement != null && (settlement.getLearnableSkill() != null || !settlement.hasBeenVisited())) {
unit.setMovesLeft(0);
String skillName;
Element askSkill = Message.createNewRootElement("askSkill");
askSkill.setAttribute("unit", unit.getId());
askSkill.setAttribute("direction", direction.toString());
Element reply = client.ask(askSkill);
UnitType skill = null;
if (reply.getTagName().equals("provideSkill")) {
if (reply.hasAttribute("skill")) {
skill = FreeCol.getSpecification().getUnitType(reply.getAttribute("skill"));
skillName = skill.getName();
} else {
skillName = null;
}
} else {
logger.warning("Server gave an invalid reply to an askSkill message");
return;
}
settlement.setLearnableSkill(skill);
settlement.setVisited(unit.getOwner());
if (skillName == null) {
canvas.errorMessage("indianSettlement.noMoreSkill");
} else if (!unit.getType().canBeUpgraded(skill, UnitType.UpgradeType.NATIVES)) {
canvas.showInformationMessage("indianSettlement.cantLearnSkill",
settlement,
"%unit%", unit.getName(),
"%skill%", skillName);
} else {
Element learnSkill = Message.createNewRootElement("learnSkillAtSettlement");
learnSkill.setAttribute("unit", unit.getId());
learnSkill.setAttribute("direction", direction.toString());
if (!canvas.showConfirmDialog("learnSkill.text", "learnSkill.yes", "learnSkill.no",
"%replace%", skillName)) {
// the player declined to learn the skill
learnSkill.setAttribute("action", "cancel");
}
Element reply2 = freeColClient.getClient().ask(learnSkill);
String result = reply2.getAttribute("result");
if (result.equals("die")) {
unit.dispose();
canvas.showInformationMessage("learnSkill.die");
} else if (result.equals("leave")) {
canvas.showInformationMessage("learnSkill.leave");
} else if (result.equals("success")) {
unit.setType(skill);
if (!settlement.isCapital())
settlement.setLearnableSkill(null);
} else if (result.equals("cancelled")) {
// do nothing
} else {
logger.warning("Server gave an invalid reply to an learnSkillAtSettlement message");
}
}
} else if (unit.getDestination() != null) {
setDestination(unit, null);
}
nextActiveUnit(unit.getTile());
}
/**
* Ask for spy the foreign colony, negotiate with the foreign power
* or attack the colony
*
* @param unit The unit that will spy, negotiate or attack.
* @param direction The direction in which the foreign colony lies.
*/
private void scoutForeignColony(Unit unit, Direction direction) {
Player player = freeColClient.getGame().getCurrentPlayer();
if (player != freeColClient.getMyPlayer()) {
freeColClient.getCanvas().showInformationMessage("notYourTurn");
return;
}
Canvas canvas = freeColClient.getCanvas();
Map map = freeColClient.getGame().getMap();
Tile tile = map.getNeighbourOrNull(direction, unit.getTile());
Colony colony = tile.getColony();
if (colony != null && !player.hasContacted(colony.getOwner())) {
player.setContacted(colony.getOwner(), true);
}
ScoutAction userAction = canvas.showScoutForeignColonyDialog(colony, unit);
switch (userAction) {
case CANCEL:
break;
case FOREIGN_COLONY_ATTACK:
attack(unit, direction);
break;
case FOREIGN_COLONY_NEGOTIATE:
negotiate(unit, direction);
break;
case FOREIGN_COLONY_SPY:
spy(unit, direction);
break;
default:
logger.warning("Incorrect response returned from Canvas.showScoutForeignColonyDialog()");
return;
}
}
/**
* Moves the specified scout into an Indian settlement to speak with the
* chief or demand a tribute etc. Of course, the scout won't physically get
* into the village, it will just stay where it is.
*
* @param unit The unit that will speak, attack or ask tribute.
* @param direction The direction in which the Indian settlement lies.
*/
private void scoutIndianSettlement(Unit unit, Direction direction) {
if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) {
freeColClient.getCanvas().showInformationMessage("notYourTurn");
return;
}
Client client = freeColClient.getClient();
Canvas canvas = freeColClient.getCanvas();
Map map = freeColClient.getGame().getMap();
Tile tile = map.getNeighbourOrNull(direction, unit.getTile());
IndianSettlement settlement = (IndianSettlement) tile.getSettlement();
// The scout loses his moves because the skill data and
// tradeable goods data is fetched from the server and the
// moves are the price we have to pay to obtain that data.
// In case we want to attack the settlement, we backup movesLeft.
int movesLeft = unit.getMovesLeft();
unit.setMovesLeft(0);
Element scoutMessage = Message.createNewRootElement("scoutIndianSettlement");
scoutMessage.setAttribute("unit", unit.getId());
scoutMessage.setAttribute("direction", direction.toString());
scoutMessage.setAttribute("action", "basic");
Element reply = client.ask(scoutMessage);
if (reply.getTagName().equals("scoutIndianSettlementResult")) {
UnitType skill = null;
String skillStr = reply.getAttribute("skill");
// TODO: find out how skillStr can be empty
if (skillStr != null && !skillStr.equals("")) {
skill = FreeCol.getSpecification().getUnitType(skillStr);
}
settlement.setLearnableSkill(skill);
settlement.setWantedGoods(0, FreeCol.getSpecification().getGoodsType(reply.getAttribute("highlyWantedGoods")));
settlement.setWantedGoods(1, FreeCol.getSpecification().getGoodsType(reply.getAttribute("wantedGoods1")));
settlement.setWantedGoods(2, FreeCol.getSpecification().getGoodsType(reply.getAttribute("wantedGoods2")));
settlement.setVisited(unit.getOwner());
settlement.getOwner().setNumberOfSettlements(Integer.parseInt(reply.getAttribute("numberOfCamps")));
freeColClient.getInGameInputHandler().update(reply);
} else {
logger.warning("Server gave an invalid reply to an askSkill message");
return;
}
ScoutAction userAction = canvas.showScoutIndianSettlementDialog(settlement);
switch (userAction) {
case INDIAN_SETTLEMENT_ATTACK:
scoutMessage.setAttribute("action", "attack");
// The movesLeft has been set to 0 when the scout initiated its
// action.If it wants to attack then it can and it will need some
// moves to do it.
unit.setMovesLeft(movesLeft);
client.sendAndWait(scoutMessage);
// TODO: Check if this dialog is needed, one has just been displayed
if (confirmPreCombat(unit, tile)) {
reallyAttack(unit, direction);
} else {
//The player chose to not attack, so the scout shouldn't get back his moves
unit.setMovesLeft(0);
}
return;
case CANCEL:
scoutMessage.setAttribute("action", "cancel");
client.sendAndWait(scoutMessage);
return;
case INDIAN_SETTLEMENT_SPEAK:
scoutMessage.setAttribute("action", "speak");
reply = client.ask(scoutMessage);
break;
case INDIAN_SETTLEMENT_TRIBUTE:
scoutMessage.setAttribute("action", "tribute");
reply = client.ask(scoutMessage);
break;
default:
logger.warning("Incorrect response returned from Canvas.showScoutIndianSettlementDialog()");
return;
}
if (reply.getTagName().equals("scoutIndianSettlementResult")) {
String result = reply.getAttribute("result"), action = scoutMessage.getAttribute("action");
if (result.equals("die")) {
// unit killed
unit.dispose();
canvas.showInformationMessage("scoutSettlement.speakDie", settlement);
} else if (action.equals("speak") && result.equals("tales")) {
// receive an update of the surrounding tiles.
Element updateElement = getChildElement(reply, "update");
if (updateElement != null) {
freeColClient.getInGameInputHandler().handle(client.getConnection(), updateElement);
}
canvas.showInformationMessage("scoutSettlement.speakTales", settlement);
} else if (action.equals("speak") && result.equals("beads")) {
// receive a small gift of gold
String amount = reply.getAttribute("amount");
unit.getOwner().modifyGold(Integer.parseInt(amount));
freeColClient.getCanvas().updateGoldLabel();
canvas.showInformationMessage("scoutSettlement.speakBeads",
settlement,
"%replace%", amount);
} else if (action.equals("speak") && result.equals("nothing")) {
// nothing special
canvas.showInformationMessage("scoutSettlement.speakNothing", settlement);
} else if (action.equals("tribute") && result.equals("agree")) {
// receive a tribute
String amount = reply.getAttribute("amount");
unit.getOwner().modifyGold(Integer.parseInt(amount));
freeColClient.getCanvas().updateGoldLabel();
canvas.showInformationMessage("scoutSettlement.tributeAgree",
settlement,
"%replace%", amount);
} else if (action.equals("tribute") && result.equals("disagree")) {
// no tribute
canvas.showInformationMessage("scoutSettlement.tributeDisagree", settlement);
}
} else {
logger.warning("Server gave an invalid reply to an scoutIndianSettlement message");
return;
}
nextActiveUnit(unit.getTile());
}
/**
* Moves a missionary into an indian settlement.
*
* @param unit The unit that will enter the settlement.
* @param direction The direction in which the Indian settlement lies.
*/
private void useMissionary(Unit unit, Direction direction) {
if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) {
freeColClient.getCanvas().showInformationMessage("notYourTurn");
return;
}
Client client = freeColClient.getClient();
Canvas canvas = freeColClient.getCanvas();
Map map = freeColClient.getGame().getMap();
IndianSettlement settlement = (IndianSettlement) map.getNeighbourOrNull(direction, unit.getTile())
.getSettlement();
List<Object> response = canvas.showUseMissionaryDialog(settlement);
MissionaryAction action = (MissionaryAction) response.get(0);
Element missionaryMessage = Message.createNewRootElement("missionaryAtSettlement");
missionaryMessage.setAttribute("unit", unit.getId());
missionaryMessage.setAttribute("direction", direction.toString());
Element reply = null;
unit.setMovesLeft(0);
String success = "";
switch (action) {
case CANCEL:
missionaryMessage.setAttribute("action", "cancel");
client.sendAndWait(missionaryMessage);
break;
case ESTABLISH_MISSION:
missionaryMessage.setAttribute("action", "establish");
reply = client.ask(missionaryMessage);
if (!reply.getTagName().equals("missionaryReply")) {
logger.warning("Server gave an invalid reply to a missionaryAtSettlement message");
return;
}
success = reply.getAttribute("success");
Tension.Level tension = Tension.Level.valueOf(reply.getAttribute("tension"));
String missionResponse = null;
String[] data = new String [] {"%nation%",settlement.getOwner().getNationAsString() };
if (success.equals("true")) {
settlement.setMissionary(unit);
freeColClient.playSound(SoundEffect.MISSION_ESTABLISHED);
missionResponse = settlement.getResponseToMissionaryAttempt(tension, success);
canvas.showInformationMessage(missionResponse,settlement,data);
}
else{
missionResponse = settlement.getResponseToMissionaryAttempt(tension, success);
canvas.showInformationMessage(missionResponse,settlement,data);
unit.dispose();
}
nextActiveUnit(); // At this point: unit.getTile() == null
return;
case DENOUNCE_HERESY:
missionaryMessage.setAttribute("action", "heresy");
reply = client.ask(missionaryMessage);
if (!reply.getTagName().equals("missionaryReply")) {
logger.warning("Server gave an invalid reply to a missionaryAtSettlement message");
return;
}
success = reply.getAttribute("success");
if (success.equals("true")) {
freeColClient.playSound(SoundEffect.MISSION_ESTABLISHED);
settlement.setMissionary(unit);
nextActiveUnit(); // At this point: unit.getTile() == null
} else {
unit.dispose();
nextActiveUnit(); // At this point: unit == null
}
return;
case INCITE_INDIANS:
missionaryMessage.setAttribute("action", "incite");
missionaryMessage.setAttribute("incite", ((Player) response.get(1)).getId());
reply = client.ask(missionaryMessage);
if (reply.getTagName().equals("missionaryReply")) {
int amount = Integer.parseInt(reply.getAttribute("amount"));
boolean confirmed = canvas.showInciteDialog((Player) response.get(1), amount);
if (confirmed && unit.getOwner().getGold() < amount) {
canvas.showInformationMessage("notEnoughGold");
confirmed = false;
}
Element inciteMessage = Message.createNewRootElement("inciteAtSettlement");
inciteMessage.setAttribute("unit", unit.getId());
inciteMessage.setAttribute("direction", direction.toString());
inciteMessage.setAttribute("confirmed", confirmed ? "true" : "false");
inciteMessage.setAttribute("enemy", ((Player) response.get(1)).getId());
if (confirmed) {
Player briber = unit.getOwner();
Player indianNation = settlement.getOwner();
Player proposedEnemy = (Player) response.get(1);
briber.modifyGold(-amount);
// Maybe at this point we can keep track of the fact that
// the indian is now at
// war with the chosen european player, but is this really
// necessary at the client
// side?
indianNation.changeRelationWithPlayer(proposedEnemy, Stance.WAR);
}
client.sendAndWait(inciteMessage);
} else {
logger.warning("Server gave an invalid reply to a missionaryAtSettlement message");
return;
}
}
nextActiveUnit(unit.getTile());
}
/**
* Moves the specified unit to Europe.
*
* @param unit The unit to be moved to Europe.
*/
public void moveToEurope(Unit unit) {
if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) {
freeColClient.getCanvas().showInformationMessage("notYourTurn");
return;
}
Client client = freeColClient.getClient();
unit.moveToEurope();
Element moveToEuropeElement = Message.createNewRootElement("moveToEurope");
moveToEuropeElement.setAttribute("unit", unit.getId());
client.sendAndWait(moveToEuropeElement);
}
/**
* Moves the specified unit to America.
*
* @param unit The unit to be moved to America.
*/
public void moveToAmerica(Unit unit) {
final Canvas canvas = freeColClient.getCanvas();
final Player player = freeColClient.getMyPlayer();
if (freeColClient.getGame().getCurrentPlayer() != player) {
canvas.showInformationMessage("notYourTurn");
return;
}
final Client client = freeColClient.getClient();
final ClientOptions co = canvas.getClient().getClientOptions();
// Ask for autoload emigrants
if (unit.getLocation() instanceof Europe) {
final boolean autoload = co.getBoolean(ClientOptions.AUTOLOAD_EMIGRANTS);
if (autoload) {
int spaceLeft = unit.getSpaceLeft();
List<Unit> unitsInEurope = new ArrayList<Unit>(unit.getLocation().getUnitList());
for (Unit possiblePassenger : unitsInEurope) {
if (possiblePassenger.isNaval()) {
continue;
}
if (possiblePassenger.getType().getSpaceTaken() <= spaceLeft) {
boardShip(possiblePassenger, unit);
spaceLeft -= possiblePassenger.getType().getSpaceTaken();
} else {
break;
}
}
}
}
unit.moveToAmerica();
Element moveToAmericaElement = Message.createNewRootElement("moveToAmerica");
moveToAmericaElement.setAttribute("unit", unit.getId());
client.sendAndWait(moveToAmericaElement);
}
/**
* Trains a unit of a specified type in Europe.
*
* @param unitType The type of unit to be trained.
*/
public void trainUnitInEurope(UnitType unitType) {
if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) {
freeColClient.getCanvas().showInformationMessage("notYourTurn");
return;
}
Client client = freeColClient.getClient();
Canvas canvas = freeColClient.getCanvas();
Game game = freeColClient.getGame();
Player myPlayer = freeColClient.getMyPlayer();
Europe europe = myPlayer.getEurope();
if (myPlayer.getGold() < europe.getUnitPrice(unitType)) {
canvas.errorMessage("notEnoughGold");
return;
}
Element trainUnitInEuropeElement = Message.createNewRootElement("trainUnitInEurope");
trainUnitInEuropeElement.setAttribute("unitType", unitType.getId());
Element reply = client.ask(trainUnitInEuropeElement);
if (reply.getTagName().equals("trainUnitInEuropeConfirmed")) {
Element unitElement = (Element) reply.getFirstChild();
Unit unit = (Unit) game.getFreeColGameObject(unitElement.getAttribute("ID"));
if (unit == null) {
unit = new Unit(game, unitElement);
} else {
unit.readFromXMLElement(unitElement);
}
europe.train(unit);
} else {
logger.warning("Could not train unit in europe.");
return;
}
freeColClient.getCanvas().updateGoldLabel();
}
/**
* Buys the remaining hammers and tools for the {@link Building} currently
* being built in the given <code>Colony</code>.
*
* @param colony The {@link Colony} where the building should be bought.
*/
public void payForBuilding(Colony colony) {
if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) {
freeColClient.getCanvas().showInformationMessage("notYourTurn");
return;
}
if (!freeColClient.getCanvas()
.showConfirmDialog("payForBuilding.text", "payForBuilding.yes", "payForBuilding.no",
"%replace%", Integer.toString(colony.getPriceForBuilding()))) {
return;
}
if (colony.getPriceForBuilding() > freeColClient.getMyPlayer().getGold()) {
freeColClient.getCanvas().errorMessage("notEnoughGold");
return;
}
Element payForBuildingElement = Message.createNewRootElement("payForBuilding");
payForBuildingElement.setAttribute("colony", colony.getId());
colony.payForBuilding();
freeColClient.getClient().sendAndWait(payForBuildingElement);
}
/**
* Recruit a unit from a specified "slot" in Europe.
*
* @param slot The slot to recruit the unit from. Either 1, 2 or 3.
*/
public void recruitUnitInEurope(int slot) {
if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) {
freeColClient.getCanvas().showInformationMessage("notYourTurn");
return;
}
Client client = freeColClient.getClient();
Canvas canvas = freeColClient.getCanvas();
Game game = freeColClient.getGame();
Player myPlayer = freeColClient.getMyPlayer();
Europe europe = myPlayer.getEurope();
if (myPlayer.getGold() < myPlayer.getRecruitPrice()) {
canvas.errorMessage("notEnoughGold");
return;
}
Element recruitUnitInEuropeElement = Message.createNewRootElement("recruitUnitInEurope");
recruitUnitInEuropeElement.setAttribute("slot", Integer.toString(slot));
Element reply = client.ask(recruitUnitInEuropeElement);
if (reply.getTagName().equals("recruitUnitInEuropeConfirmed")) {
Element unitElement = (Element) reply.getFirstChild();
Unit unit = (Unit) game.getFreeColGameObject(unitElement.getAttribute("ID"));
if (unit == null) {
unit = new Unit(game, unitElement);
} else {
unit.readFromXMLElement(unitElement);
}
String unitId = reply.getAttribute("newRecruitable");
UnitType unitType = FreeCol.getSpecification().getUnitType(unitId);
europe.recruit(slot, unit, unitType);
} else {
logger.warning("Could not recruit the specified unit in europe.");
return;
}
freeColClient.getCanvas().updateGoldLabel();
}
/**
* Cause a unit to emigrate from a specified "slot" in Europe. If the player
* doesn't have William Brewster in the congress then the value of the slot
* parameter is not important (it won't be used).
*
* @param slot The slot from which the unit emigrates. Either 1, 2 or 3 if
* William Brewster is in the congress.
*/
private void emigrateUnitInEurope(int slot) {
if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) {
freeColClient.getCanvas().showInformationMessage("notYourTurn");
return;
}
Client client = freeColClient.getClient();
Game game = freeColClient.getGame();
Player myPlayer = freeColClient.getMyPlayer();
Europe europe = myPlayer.getEurope();
Element emigrateUnitInEuropeElement = Message.createNewRootElement("emigrateUnitInEurope");
if (myPlayer.hasAbility("model.ability.selectRecruit")) {
emigrateUnitInEuropeElement.setAttribute("slot", Integer.toString(slot));
}
Element reply = client.ask(emigrateUnitInEuropeElement);
if (reply == null || !reply.getTagName().equals("emigrateUnitInEuropeConfirmed")) {
logger.warning("Could not recruit unit: " + myPlayer.getImmigration() + "/" + myPlayer.getImmigrationRequired());
throw new IllegalStateException();
}
if (!myPlayer.hasAbility("model.ability.selectRecruit")) {
slot = Integer.parseInt(reply.getAttribute("slot"));
}
Element unitElement = (Element) reply.getFirstChild();
Unit unit = (Unit) game.getFreeColGameObject(unitElement.getAttribute("ID"));
if (unit == null) {
unit = new Unit(game, unitElement);
} else {
unit.readFromXMLElement(unitElement);
}
String unitId = reply.getAttribute("newRecruitable");
UnitType newRecruitable = FreeCol.getSpecification().getUnitType(unitId);
europe.emigrate(slot, unit, newRecruitable);
freeColClient.getCanvas().updateGoldLabel();
}
/**
* Updates a trade route.
*
* @param route The trade route to update.
*/
public void updateTradeRoute(TradeRoute route) {
logger.finest("Entering method updateTradeRoute");
/*
* if (freeColClient.getGame().getCurrentPlayer() !=
* freeColClient.getMyPlayer()) {
* freeColClient.getCanvas().showInformationMessage("notYourTurn");
* return; }
*/
Element tradeRouteElement = Message.createNewRootElement("updateTradeRoute");
tradeRouteElement.appendChild(route.toXMLElement(null, tradeRouteElement.getOwnerDocument()));
freeColClient.getClient().sendAndWait(tradeRouteElement);
}
/**
* Sets the trade routes for this player
*
* @param routes The trade routes to set.
*/
public void setTradeRoutes(List<TradeRoute> routes) {
Player myPlayer = freeColClient.getMyPlayer();
myPlayer.setTradeRoutes(routes);
/*
* if (freeColClient.getGame().getCurrentPlayer() !=
* freeColClient.getMyPlayer()) {
* freeColClient.getCanvas().showInformationMessage("notYourTurn");
* return; }
*/
Element tradeRoutesElement = Message.createNewRootElement("setTradeRoutes");
for(TradeRoute route : routes) {
Element routeElement = tradeRoutesElement.getOwnerDocument().createElement(TradeRoute.getXMLElementTagName());
routeElement.setAttribute("id", route.getId());
tradeRoutesElement.appendChild(routeElement);
}
freeColClient.getClient().sendAndWait(tradeRoutesElement);
}
/**
* Assigns a trade route to a unit.
*
* @param unit The unit to assign a trade route to.
*/
public void assignTradeRoute(Unit unit) {
Canvas canvas = freeColClient.getCanvas();
TradeRoute tradeRoute = canvas.showFreeColDialog(new TradeRouteDialog(canvas, unit.getTradeRoute()));
assignTradeRoute(unit, tradeRoute);
}
public void assignTradeRoute(Unit unit, TradeRoute tradeRoute) {
if (tradeRoute != null) {
Element assignTradeRouteElement = Message.createNewRootElement("assignTradeRoute");
assignTradeRouteElement.setAttribute("unit", unit.getId());
if (tradeRoute == TradeRoute.NO_TRADE_ROUTE) {
unit.setTradeRoute(null);
freeColClient.getClient().sendAndWait(assignTradeRouteElement);
setDestination(unit, null);
} else {
unit.setTradeRoute(tradeRoute);
assignTradeRouteElement.setAttribute("tradeRoute", tradeRoute.getId());
freeColClient.getClient().sendAndWait(assignTradeRouteElement);
Location location = unit.getLocation();
if (location instanceof Tile)
location = ((Tile) location).getColony();
if (tradeRoute.getStops().get(0).getLocation() == location) {
followTradeRoute(unit);
} else if (freeColClient.getGame().getCurrentPlayer() == freeColClient.getMyPlayer()) {
moveToDestination(unit);
}
}
}
}
/**
* Pays the tax arrears on this type of goods.
*
* @param goods The goods for which to pay arrears.
*/
public void payArrears(Goods goods) {
payArrears(goods.getType());
}
/**
* Pays the tax arrears on this type of goods.
*
* @param type The type of goods for which to pay arrears.
*/
public void payArrears(GoodsType type) {
if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) {
freeColClient.getCanvas().showInformationMessage("notYourTurn");
return;
}
Client client = freeColClient.getClient();
Player player = freeColClient.getMyPlayer();
int arrears = player.getArrears(type);
if (player.getGold() >= arrears) {
if (freeColClient.getCanvas().showConfirmDialog("model.europe.payArrears", "ok", "cancel",
"%replace%", String.valueOf(arrears))) {
player.modifyGold(-arrears);
freeColClient.getCanvas().updateGoldLabel();
player.resetArrears(type);
// send to server
Element payArrearsElement = Message.createNewRootElement("payArrears");
payArrearsElement.setAttribute("goodsType", type.getId());
client.sendAndWait(payArrearsElement);
}
} else {
freeColClient.getCanvas().showInformationMessage("model.europe.cantPayArrears",
"%amount%", String.valueOf(arrears));
}
}
/**
* Purchases a unit of a specified type in Europe.
*
* @param unitType The type of unit to be purchased.
*/
public void purchaseUnitFromEurope(UnitType unitType) {
trainUnitInEurope(unitType);
}
/**
* Gathers information about opponents.
*/
public Element getForeignAffairsReport() {
return freeColClient.getClient().ask(Message.createNewRootElement("foreignAffairs"));
}
/**
* Retrieves high scores from server.
*/
public Element getHighScores() {
return freeColClient.getClient().ask(Message.createNewRootElement("highScores"));
}
/**
* Gathers information about the REF.
* @return a <code>List</code> value
*/
public List<AbstractUnit> getREFUnits() {
if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) {
freeColClient.getCanvas().showInformationMessage("notYourTurn");
return Collections.emptyList();
}
Element reply = freeColClient.getClient().ask(Message.createNewRootElement("getREFUnits"));
if (reply == null) {
return Collections.emptyList();
} else {
List<AbstractUnit> result = new ArrayList<AbstractUnit>();
NodeList childElements = reply.getChildNodes();
for (int index = 0; index < childElements.getLength(); index++) {
AbstractUnit unit = new AbstractUnit();
unit.readFromXMLElement((Element) childElements.item(index));
result.add(unit);
}
return result;
}
}
/**
* Disbands the active unit.
*/
public void disbandActiveUnit() {
if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) {
freeColClient.getCanvas().showInformationMessage("notYourTurn");
return;
}
GUI gui = freeColClient.getGUI();
Unit unit = gui.getActiveUnit();
Client client = freeColClient.getClient();
if (unit == null) {
return;
}
if (!freeColClient.getCanvas().showConfirmDialog("disbandUnit.text", "disbandUnit.yes", "disbandUnit.no")) {
return;
}
Element disbandUnit = Message.createNewRootElement("disbandUnit");
disbandUnit.setAttribute("unit", unit.getId());
unit.dispose();
client.sendAndWait(disbandUnit);
nextActiveUnit();
}
/**
* Centers the map on the selected tile.
*/
public void centerActiveUnit() {
Unit activeUnit = freeColClient.getGUI().getActiveUnit();
if (activeUnit == null){
return;
}
centerOnUnit(activeUnit);
}
/**
* Centers the map on the given unit location.
*/
public void centerOnUnit(Unit unit) {
// Sanitation
if(unit == null){
return;
}
Tile unitTile = unit.getTile();
if(unitTile == null){
return;
}
freeColClient.getGUI().setFocus(unitTile.getPosition());
}
/**
* Executes the units' goto orders.
*/
public void executeGotoOrders() {
executeGoto = true;
nextActiveUnit(null);
}
/**
* Makes a new unit active.
*/
public void nextActiveUnit() {
nextActiveUnit(null);
}
/**
* Makes a new unit active. Displays any new <code>ModelMessage</code>s
* (uses {@link #nextModelMessage}).
*
* @param tile The tile to select if no new unit can be made active.
*/
public void nextActiveUnit(Tile tile) {
if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) {
freeColClient.getCanvas().showInformationMessage("notYourTurn");
return;
}
nextModelMessage();
Canvas canvas = freeColClient.getCanvas();
Player myPlayer = freeColClient.getMyPlayer();
if (endingTurn || executeGoto) {
while (!freeColClient.getCanvas().isShowingSubPanel() && myPlayer.hasNextGoingToUnit()) {
Unit unit = myPlayer.getNextGoingToUnit();
moveToDestination(unit);
nextModelMessage();
if (unit.getMovesLeft() > 0) {
if (endingTurn) {
unit.setMovesLeft(0);
} else {
return;
}
}
}
if (!myPlayer.hasNextGoingToUnit() && !freeColClient.getCanvas().isShowingSubPanel()) {
if (endingTurn) {
canvas.getGUI().setActiveUnit(null);
endingTurn = false;
Element endTurnElement = Message.createNewRootElement("endTurn");
freeColClient.getClient().send(endTurnElement);
return;
} else {
executeGoto = false;
}
}
}
GUI gui = freeColClient.getGUI();
Unit nextActiveUnit = myPlayer.getNextActiveUnit();
if (nextActiveUnit != null) {
canAutoEndTurn = true;
gui.setActiveUnit(nextActiveUnit);
} else {
// no more active units, so we can move the others
nextActiveUnit = myPlayer.getNextGoingToUnit();
if (nextActiveUnit != null) {
moveToDestination(nextActiveUnit);
} else if (tile != null) {
Position p = tile.getPosition();
if (p != null) {
// this really shouldn't happen
gui.setSelectedTile(p);
}
gui.setActiveUnit(null);
} else {
gui.setActiveUnit(null);
}
if (canAutoEndTurn && !endingTurn
&& freeColClient.getClientOptions().getBoolean(ClientOptions.AUTO_END_TURN)) {
endTurn();
}
}
}
/**
* Ignore this ModelMessage from now on until it is not generated in a turn.
*
* @param message a <code>ModelMessage</code> value
* @param flag whether to ignore the ModelMessage or not
*/
public synchronized void ignoreMessage(ModelMessage message, boolean flag) {
String key = message.getSource().getId();
String[] data = message.getData();
for (int index = 0; index < data.length; index += 2) {
if (data[index].equals("%goods%")) {
key += data[index + 1];
break;
}
}
if (flag) {
startIgnoringMessage(key, freeColClient.getGame().getTurn().getNumber());
} else {
stopIgnoringMessage(key);
}
}
/**
* Displays the next <code>ModelMessage</code>.
*
* @see net.sf.freecol.common.model.ModelMessage ModelMessage
*/
public void nextModelMessage() {
displayModelMessages(false);
}
public void displayModelMessages(final boolean allMessages) {
int thisTurn = freeColClient.getGame().getTurn().getNumber();
final ArrayList<ModelMessage> messageList = new ArrayList<ModelMessage>();
List<ModelMessage> inputList;
if (allMessages) {
inputList = freeColClient.getMyPlayer().getModelMessages();
} else {
inputList = freeColClient.getMyPlayer().getNewModelMessages();
}
for (ModelMessage message : inputList) {
if (shouldAllowMessage(message)) {
if (message.getType() == ModelMessage.MessageType.WAREHOUSE_CAPACITY) {
String key = message.getSource().getId();
String[] data = message.getData();
for (int index = 0; index < data.length; index += 2) {
if (data[index].equals("%goods%")) {
key += data[index + 1];
break;
}
}
Integer turn = getTurnForMessageIgnored(key);
if (turn != null && turn.intValue() == thisTurn - 1) {
startIgnoringMessage(key, thisTurn);
message.setBeenDisplayed(true);
continue;
}
} else if (message.getType() == ModelMessage.MessageType.BUILDING_COMPLETED) {
freeColClient.playSound(SoundEffect.BUILDING_COMPLETE);
} else if (message.getType() == ModelMessage.MessageType.FOREIGN_DIPLOMACY) {
if (message.getId().equals("EventPanel.MEETING_AZTEC")) {
freeColClient.playMusicOnce("aztec");
}
}
messageList.add(message);
}
// flag all messages delivered as "beenDisplayed".
message.setBeenDisplayed(true);
}
purgeOldMessagesFromMessagesToIgnore(thisTurn);
final ModelMessage[] messages = messageList.toArray(new ModelMessage[0]);
Runnable uiTask = new Runnable() {
public void run() {
Canvas canvas = freeColClient.getCanvas();
if (messageList.size() > 0) {
if (allMessages || messageList.size() > 5) {
canvas.addAsFrame(new ReportTurnPanel(canvas, messages));
} else {
canvas.showModelMessages(messages);
}
}
freeColClient.getActionManager().update();
}
};
if (SwingUtilities.isEventDispatchThread()) {
uiTask.run();
} else {
try {
SwingUtilities.invokeAndWait(uiTask);
} catch (InterruptedException e) {
// Ignore
} catch (InvocationTargetException e) {
// Ignore
}
}
}
private synchronized Integer getTurnForMessageIgnored(String key) {
return messagesToIgnore.get(key);
}
private synchronized void startIgnoringMessage(String key, int turn) {
logger.finer("Ignoring model message with key " + key);
messagesToIgnore.put(key, new Integer(turn));
}
private synchronized void stopIgnoringMessage(String key) {
logger.finer("Removing model message with key " + key + " from ignored messages.");
messagesToIgnore.remove(key);
}
private synchronized void purgeOldMessagesFromMessagesToIgnore(int thisTurn) {
List<String> keysToRemove = new ArrayList<String>();
for (Entry<String, Integer> entry : messagesToIgnore.entrySet()) {
if (entry.getValue().intValue() < thisTurn - 1) {
if (logger.isLoggable(Level.FINER)) {
logger.finer("Removing old model message with key " + entry.getKey() + " from ignored messages.");
}
keysToRemove.add(entry.getKey());
}
}
for (String key : keysToRemove) {
stopIgnoringMessage(key);
}
}
/**
* Provides an opportunity to filter the messages delivered to the canvas.
*
* @param message the message that is candidate for delivery to the canvas
* @return true if the message should be delivered
*/
private boolean shouldAllowMessage(ModelMessage message) {
switch (message.getType()) {
case DEFAULT:
return true;
case WARNING:
return freeColClient.getClientOptions().getBoolean(ClientOptions.SHOW_WARNING);
case SONS_OF_LIBERTY:
return freeColClient.getClientOptions().getBoolean(ClientOptions.SHOW_SONS_OF_LIBERTY);
case GOVERNMENT_EFFICIENCY:
return freeColClient.getClientOptions().getBoolean(ClientOptions.SHOW_GOVERNMENT_EFFICIENCY);
case WAREHOUSE_CAPACITY:
return freeColClient.getClientOptions().getBoolean(ClientOptions.SHOW_WAREHOUSE_CAPACITY);
case UNIT_IMPROVED:
return freeColClient.getClientOptions().getBoolean(ClientOptions.SHOW_UNIT_IMPROVED);
case UNIT_DEMOTED:
return freeColClient.getClientOptions().getBoolean(ClientOptions.SHOW_UNIT_DEMOTED);
case UNIT_LOST:
return freeColClient.getClientOptions().getBoolean(ClientOptions.SHOW_UNIT_LOST);
case UNIT_ADDED:
return freeColClient.getClientOptions().getBoolean(ClientOptions.SHOW_UNIT_ADDED);
case BUILDING_COMPLETED:
return freeColClient.getClientOptions().getBoolean(ClientOptions.SHOW_BUILDING_COMPLETED);
case FOREIGN_DIPLOMACY:
return freeColClient.getClientOptions().getBoolean(ClientOptions.SHOW_FOREIGN_DIPLOMACY);
case MARKET_PRICES:
return freeColClient.getClientOptions().getBoolean(ClientOptions.SHOW_MARKET_PRICES);
case MISSING_GOODS:
return freeColClient.getClientOptions().getBoolean(ClientOptions.SHOW_MISSING_GOODS);
case TUTORIAL:
return freeColClient.getClientOptions().getBoolean(ClientOptions.SHOW_TUTORIAL);
default:
return true;
}
}
/**
* End the turn.
*/
public void endTurn() {
if (freeColClient.getGame().getCurrentPlayer() != freeColClient.getMyPlayer()) {
freeColClient.getCanvas().showInformationMessage("notYourTurn");
return;
}
endingTurn = true;
canAutoEndTurn = false;
nextActiveUnit(null);
}
/**
* Convenience method: returns the first child element with the specified
* tagname.
*
* @param element The <code>Element</code> to search for the child
* element.
* @param tagName The tag name of the child element to be found.
* @return The child of the given <code>Element</code> with the given
* <code>tagName</code> or <code>null</code> if no such child
* exists.
*/
protected Element getChildElement(Element element, String tagName) {
NodeList n = element.getChildNodes();
for (int i = 0; i < n.getLength(); i++) {
if (((Element) n.item(i)).getTagName().equals(tagName)) {
return (Element) n.item(i);
}
}
return null;
}
/**
* Abandon a colony with no units
*
* @param colony The colony to be abandoned
*/
public void abandonColony(Colony colony) {
if (colony == null) {
return;
}
Client client = freeColClient.getClient();
Element abandonColony = Message.createNewRootElement("abandonColony");
abandonColony.setAttribute("colony", colony.getId());
colony.getOwner().getHistory()
.add(new HistoryEvent(colony.getGame().getTurn().getNumber(),
HistoryEvent.Type.ABANDON_COLONY,
"%colony%", colony.getName()));
colony.dispose();
client.sendAndWait(abandonColony);
}
/**
* Retrieves server statistics
*/
public StatisticsMessage getServerStatistics() {
Element request = Message.createNewRootElement(StatisticsMessage.getXMLElementTagName());
Element reply = freeColClient.getClient().ask(request);
StatisticsMessage m = new StatisticsMessage(reply);
return m;
}
}
| true | false | null | null |
diff --git a/src/org/schemeway/plugins/schemescript/editor/SchemeParenthesisPainter.java b/src/org/schemeway/plugins/schemescript/editor/SchemeParenthesisPainter.java
index 5df312a..68dab67 100644
--- a/src/org/schemeway/plugins/schemescript/editor/SchemeParenthesisPainter.java
+++ b/src/org/schemeway/plugins/schemescript/editor/SchemeParenthesisPainter.java
@@ -1,233 +1,237 @@
/*
* Copyright (c) 2004 Nu Echo Inc.
*
* This is free software. For terms and warranty disclaimer, see ./COPYING
*/
package org.schemeway.plugins.schemescript.editor;
import org.eclipse.jface.text.*;
import org.eclipse.jface.text.source.*;
import org.eclipse.swt.custom.*;
import org.eclipse.swt.events.*;
import org.eclipse.swt.graphics.*;
import org.schemeway.plugins.schemescript.parser.*;
public class SchemeParenthesisPainter implements IPainter, PaintListener {
private Position mBracketPosition = new Position(0, 0);
private SchemeEditor mEditor;
private boolean mIsActive = false;
private ISourceViewer mSourceViewer;
private StyledText mTextWidget;
private Color mDefaultColor = new Color(null, 0, 0, 0);
private Color mMismatchColor = new Color(null, 196, 0, 0);
private Color mColor;
private boolean mBox;
private boolean mMismatch = false;
private IPaintPositionManager mPositionManager;
/**
* Constructor
*
* @param sourceViewer Source in which to paint brackets.
*/
public SchemeParenthesisPainter(final ISourceViewer sourceViewer, SchemeEditor editor) {
mEditor = editor;
mSourceViewer = sourceViewer;
mTextWidget = sourceViewer.getTextWidget();
}
/**
* @see IPainter#setHighlightColor
*/
public final void setHighlightColor(final Color color) {
mColor = color;
}
public final void setParenthesisColor(Color color) {
mDefaultColor = color;
}
/**
* @see IPainter#setHighlightStyle
*/
public final void setHighlightStyle(final boolean box) {
mBox = box;
}
/**
* @see IPainter#dispose
*/
public void dispose() {
mColor = null;
mTextWidget = null;
}
/**
* @see IPainter#deactivate
*/
public final void deactivate(final boolean redraw) {
if (mIsActive) {
mIsActive = false;
mTextWidget.removePaintListener(this);
if (mPositionManager != null) {
mPositionManager.unmanagePosition(mBracketPosition);
}
if (redraw) {
handleDrawRequest(null);
}
}
}
/**
* @see IPainter#paintControl
*/
public final void paintControl(final PaintEvent event) {
if (mTextWidget != null) {
handleDrawRequest(event.gc);
}
}
/**
* Internal draw request handler.
*
* @param gc Graphics context to update.
*/
private final void handleDrawRequest(final GC gc) {
if (mBracketPosition.isDeleted) {
return;
}
int length = mBracketPosition.getLength();
if (length < 1) {
return;
}
int offset = mBracketPosition.getOffset();
IRegion region = mSourceViewer.getVisibleRegion();
if (region.getOffset() <= offset && region.getOffset() + region.getLength() >= offset + length) {
offset -= region.getOffset();
draw(gc, offset, 1);
}
}
/**
* @see IPainter#draw
*/
private final void draw(final GC gc, final int offset, final int length) {
if (gc != null) {
Point left = mTextWidget.getLocationAtOffset(offset);
Point right = mTextWidget.getLocationAtOffset(offset + length);
Color color = mMismatch ? mMismatchColor : mColor;
if (mBox) {
gc.setForeground(color);
- gc.drawRectangle(left.x, left.y, right.x - left.x - 1, gc.getFontMetrics().getHeight() - 1);
+ int x = left.x;
+ int y = left.y;
+ int w = right.x - left.x - 1;
+ int h = gc.getFontMetrics().getHeight();
+ gc.drawRectangle(x, y, w, h);
}
else {
gc.setForeground(mDefaultColor);
gc.setBackground(color);
gc.drawString(mTextWidget.getTextRange(offset, 1), left.x, left.y, false);
}
}
else {
mTextWidget.redrawRange(offset, length, true);
}
}
/**
* @see IPainter#paint(int)
*/
public final void paint(final int reason) {
Point selection = mSourceViewer.getSelectedRange();
if (selection.y > 0) {
deactivate(true);
return;
}
SexpNavigator explorer = mEditor.getExplorer();
boolean backward = true;
boolean closeToParen = false;
int offset = selection.x;
IDocument document = mEditor.getDocument();
try {
char previousChar = '\0';
char nextChar = '\0';
if (selection.x > 0)
previousChar = document.getChar(selection.x - 1);
if (selection.x > 0
&& SchemeScannerUtilities.isClosingParenthesis(previousChar)
&& document.getPartition(selection.x - 1).getType() == IDocument.DEFAULT_CONTENT_TYPE) {
closeToParen = true;
}
else {
nextChar = document.getChar(selection.x);
if (selection.x < document.getLength() - 1
&& SchemeScannerUtilities.isOpeningParenthesis(nextChar)
&& document.getPartition(selection.x).getType() == IDocument.DEFAULT_CONTENT_TYPE) {
closeToParen = true;
backward = false;
}
}
if (closeToParen && backward && explorer.backwardSexpression(selection.x)) {
offset = explorer.getListStart();
char matchingChar = document.getChar(offset);
mMismatch = SchemeScannerUtilities.getParenthesisType(previousChar) != SchemeScannerUtilities.getParenthesisType(matchingChar);
}
else {
if (closeToParen && !backward && explorer.forwardSexpression(selection.x)) {
offset = explorer.getSexpEnd() - 1;
char matchingChar = document.getChar(offset);
mMismatch = SchemeScannerUtilities.getParenthesisType(nextChar) != SchemeScannerUtilities.getParenthesisType(matchingChar);
}
else {
deactivate(true);
return;
}
}
}
catch (BadLocationException exception) {
deactivate(true);
return;
}
if (mIsActive) {
// only if different
if (offset != mBracketPosition.getOffset()) {
// remove old highlighting
handleDrawRequest(null);
// update position
mBracketPosition.isDeleted = false;
mBracketPosition.offset = offset;
mBracketPosition.length = 1;
// apply new highlighting
handleDrawRequest(null);
}
}
else {
mIsActive = true;
mBracketPosition.isDeleted = false;
mBracketPosition.offset = offset;
mBracketPosition.length = 1;
mTextWidget.addPaintListener(this);
mPositionManager.managePosition(mBracketPosition);
handleDrawRequest(null);
}
}
/**
* @see IPainter#setPositionManager(IPaintPositionManager)
*/
public void setPositionManager(final IPaintPositionManager manager) {
mPositionManager = manager;
}
}
\ No newline at end of file
| true | false | null | null |
diff --git a/cadpage/src/net/anei/cadpage/parsers/NY/NYMadisonCountyGLASParser.java b/cadpage/src/net/anei/cadpage/parsers/NY/NYMadisonCountyGLASParser.java
index c38a19df9..5216f96f3 100644
--- a/cadpage/src/net/anei/cadpage/parsers/NY/NYMadisonCountyGLASParser.java
+++ b/cadpage/src/net/anei/cadpage/parsers/NY/NYMadisonCountyGLASParser.java
@@ -1,67 +1,68 @@
package net.anei.cadpage.parsers.NY;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import net.anei.cadpage.parsers.MsgInfo.Data;
import net.anei.cadpage.parsers.MsgParser;
/*
Madison County - Greator Lenox Amulance Service (GLAS), NY
Contact: "Kyle M. Cashel" <[email protected]>
Contact: "[email protected]" <[email protected]>
Contact: Erick Haas <[email protected]>
Sender: [email protected]
FRM:[email protected]\nSUBJ:Greater Lenox\nMSG:Sick Person\n7738 WISE RD , LENOX ( / N COURT)
FRM:[email protected]\nSUBJ:Greater Lenox\nMSG:Assist\n400 LAMB AV , CANASTOTA VILLAGE ( / DEPPOLITI AV)
FRM:[email protected]\nSUBJ:Greater Lenox\nMSG:Heart Problem\n@MADISON COUNTY DSS (133 NORTH COURT ST (WAMPSVILLE VIL
FRM:[email protected]\nSUBJ:Greater Lenox\nMSG:Convulsions/Seizures\n7216 NELSON RD , LENOX (SENECA TRNPK / PAVONE PL)
FRM:[email protected]\nSUBJ:Greater Lenox\nMSG:Sick Person\n400 LAMB AV , CANASTOTA VILLAGE ( / DEPPOLITI AV)
FRM:[email protected]\nSUBJ:Greater Lenox\nMSG:Chest Pain\n123 CAYUGA AV , SULLIVAN ( ONEIDA LAKE AV / ROUTE 31)
FRM:[email protected]\nSUBJ:Greater Lenox\nMSG:Sick Person\n7885 TACKABURY RD , LENOX ( DITCH BANK RD / INDIAN OPENING RD)
FRM:[email protected]\nSUBJ:Greater Lenox\nMSG: Chest Pain\n3881 COTTONS RD , LINCOLN ( CLOCKVILLE RD / NELSON RD)
FRM:[email protected]\nSUBJ:Greater Lenox\nMSG:MVA - Personal Injury\n@MM 261.7 (261 70 I90 )
FRM:[email protected]\nSUBJ:Greater Lenox\nMSG:MVA - Unknown\nRAILROAD \ DEPOT (, CANASTOTA VILLAGE)
FRM:[email protected]\nSUBJ:Greater Lenox\nMSG:Sick Person\n400 LAMB AV , CANASTOTA VILLAGE ( / DEPPOLITI AV)
FRM:[email protected]\nSUBJ:Greater Lenox\nMSG:MVA - Personal Injury\n5050 BURLESON RD , LINCOLN ( VEDDER RD / FOREST AV)
FRM:[email protected]\nSUBJ:Greater Lenox\nMSG:Falls\n400 LAMB AV #144, CANASTOTA VILLAGE ( / DEPPOLITI AV)
(Greater Lenox) Convulsions/Seizures\n7216 NELSON RD , LENOX ( SENECA TRNPK / PAVONE PL)
+FRM:[email protected]\nSUBJ:Greater Lenox\nMSG:MVA - Unknown\nCANAL RD , LENOX
*/
public class NYMadisonCountyGLASParser extends MsgParser {
- private static final Pattern MASTER = Pattern.compile("(.*?)\n(.*?)(?: *, (.*?))? \\((.*?)\\)?");
+ private static final Pattern MASTER = Pattern.compile("(.*?)\n(.*?)(?: *, (.*?))?(?: \\((.*?)\\)?)?");
public NYMadisonCountyGLASParser() {
super("MADISON COUNTY", "NY");
}
@Override
public String getFilter() {
return "[email protected]";
}
@Override
protected boolean parseMsg(String subject, String body, Data data) {
if (!subject.equals("Greater Lenox")) return false;
Matcher match = MASTER.matcher(body);
if (!match.matches()) return false;
data.strCall = match.group(1).trim();
parseAddress(match.group(2).trim(), data);
data.strCity = getOptGroup(match.group(3));
- String sCross = match.group(4).trim();
+ String sCross = getOptGroup(match.group(4));
if (sCross.startsWith("/")) sCross = sCross.substring(1).trim();
if (sCross.startsWith(",")) {
data.strCity = sCross.substring(1).trim();
} else {
data.strCross = sCross;
}
return true;
}
}
\ No newline at end of file
| false | false | null | null |
diff --git a/src/main/java/lcmc/configs/DistResource_redhat_6.java b/src/main/java/lcmc/configs/DistResource_redhat_6.java
index 2bfe2875..47183092 100644
--- a/src/main/java/lcmc/configs/DistResource_redhat_6.java
+++ b/src/main/java/lcmc/configs/DistResource_redhat_6.java
@@ -1,122 +1,125 @@
/*
* This file is part of DRBD Management Console by LINBIT HA-Solutions GmbH
* written by Rasto Levrinc.
*
* Copyright (C) 2009, LINBIT HA-Solutions GmbH.
*
* DRBD Management Console 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, or (at your option)
* any later version.
*
* DRBD Management Console 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 drbd; see the file COPYING. If not, write to
* the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
*/
package lcmc.configs;
import java.util.Arrays;
/**
* Here are commands for centos verson 6.
*/
public final class DistResource_redhat_6 extends java.util.ListResourceBundle {
/** Get contents. */
@Override
protected Object[][] getContents() {
return Arrays.copyOf(contents, contents.length);
}
/** Contents. */
private static Object[][] contents = {
/* Kernel versions and their counterpart in @KERNELVERSION@ variable in
* the donwload url. Must begin with "kernel:" keyword. deprecated */
/* distribution name that is used in the download url */
{"distributiondir", "rhel6"},
/* support */
{"Support", "redhat-6"},
///* Corosync/Openais/Pacemaker clusterlabs */
//{"PmInst.install.text.1",
// "clusterlabs repo: 1.0.x/1.2.x" },
//{"PmInst.install.1",
// "wget -N -nd -P /etc/yum.repos.d/"
// + " http://www.clusterlabs.org/rpm/epel-6/clusterlabs.repo && "
// + " rpm -Uvh http://download.fedora.redhat.com/pub/epel/5/i386"
// + "/epel-release-6-5.noarch.rpm ; "
// + "(yum -y -x resource-agents-3.* -x openais-1* -x openais-0.9*"
// + " -x heartbeat-2.1* install pacemaker.@ARCH@ corosync.@ARCH@"
// + " && if [ -e /etc/corosync/corosync.conf ]; then"
// + " mv /etc/corosync/corosync.conf /etc/corosync/corosync.conf.orig;"
// + " fi)"
// + " && (/sbin/chkconfig --del heartbeat;"
// + " /sbin/chkconfig --level 2345 corosync on"
// + " && /sbin/chkconfig --level 016 corosync off)"},
/* Next Corosync/Openais/Pacemaker clusterlabs */
//{"PmInst.install.text.2",
// "clusterlabs test repo: 1.1.x/1.2.x" },
//{"PmInst.install.staging.2", "true"},
//{"PmInst.install.2",
// "wget -N -nd -P /etc/yum.repos.d/"
// + " http://www.clusterlabs.org/rpm-next/epel-6/clusterlabs.repo && "
// + " rpm -Uvh http://download.fedora.redhat.com/pub/epel/5/i386"
// + "/epel-release-6-5.noarch.rpm ; "
// + "(yum -y -x resource-agents-3.* -x openais-1* -x openais-0.9*"
// + " -x heartbeat-2.1* install pacemaker.@ARCH@ corosync.@ARCH@"
// + " && if [ -e /etc/corosync/corosync.conf ]; then"
// + " mv /etc/corosync/corosync.conf /etc/corosync/corosync.conf.orig;"
// + " fi)"
// + " && (/sbin/chkconfig --del heartbeat;"
// + " /sbin/chkconfig --level 2345 corosync on"
// + " && /sbin/chkconfig --level 016 corosync off)"},
///* Heartbeat/Pacemaker clusterlabs */
//{"HbPmInst.install.text.1",
// "clusterlabs repo: 1.0.x/3.0.x" },
//{"HbPmInst.install.1",
// "wget -N -nd -P /etc/yum.repos.d/"
// + " http://www.clusterlabs.org/rpm/epel-6/clusterlabs.repo && "
// + " rpm -Uvh http://download.fedora.redhat.com/pub/epel/5/i386"
// + "/epel-release-6-5.noarch.rpm ; "
// + "yum -y -x resource-agents-3.* -x openais-1* -x openais-0.9*"
// + " -x heartbeat-2.1* install pacemaker.@ARCH@ heartbeat.@ARCH@"
// + " && /sbin/chkconfig --add heartbeat"},
/* pacamker / corosync / yum */
{"PmInst.install.text.2", "yum install" },
{"PmInst.install.2",
- "/usr/bin/yum -y install corosync pacemaker"
- + "&& /sbin/chkconfig --add corosync"},
+ "/usr/bin/yum -y install corosync pacemaker"},
+
+ {"Corosync.addToRc",
+ DistResource.SUDO + "/sbin/chkconfig --level 2345 corosync on "
+ + "&& " + DistResource.SUDO + "/sbin/chkconfig --level 016 corosync off"},
///* Next Heartbeat/Pacemaker clusterlabs */
//{"HbPmInst.install.text.3",
// "clusterlabs next repo: 1.1.x/3.0.x" },
//{"HbPmInst.install.staging.3", "true"},
//{"HbPmInst.install.3",
// "wget -N -nd -P /etc/yum.repos.d/"
// + " http://www.clusterlabs.org/rpm-next/epel-6/clusterlabs.repo && "
// + " rpm -Uvh http://download.fedora.redhat.com/pub/epel/5/i386"
// + "/epel-release-6-5.noarch.rpm ; "
// + "yum -y -x resource-agents-3.* -x openais-1* -x openais-0.9*"
// + " -x heartbeat-2.1* install pacemaker.@ARCH@ heartbeat.@ARCH@"
// + " && /sbin/chkconfig --add heartbeat"},
};
}
| true | false | null | null |
diff --git a/src/main/java/com/craftfire/commons/managers/DataManager.java b/src/main/java/com/craftfire/commons/managers/DataManager.java
index 02d6287..462102f 100644
--- a/src/main/java/com/craftfire/commons/managers/DataManager.java
+++ b/src/main/java/com/craftfire/commons/managers/DataManager.java
@@ -1,849 +1,854 @@
/*
* This file is part of CraftCommons.
*
* Copyright (c) 2011-2012, CraftFire <http://www.craftfire.com/>
* CraftCommons is licensed under the GNU Lesser General Public License.
*
* CraftCommons 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.
*
* CraftCommons 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, see <http://www.gnu.org/licenses/>.
*/
package com.craftfire.commons.managers;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.sql.*;
import java.util.*;
import java.util.Date;
import java.util.Map.Entry;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import com.craftfire.commons.database.DataField;
import com.craftfire.commons.database.Results;
import com.craftfire.commons.enums.DataType;
import com.craftfire.commons.enums.FieldType;
public class DataManager {
private boolean keepAlive, reconnect;
private String host, username, password, database, prefix, query,
directory;
private String url = null;
private Map<Long, String> queries = new HashMap<Long, String>();
private long startup;
private int timeout = 0, port = 3306, queriesCount = 0;
private Connection con = null;
private final DataType datatype;
private PreparedStatement pStmt = null;
private Statement stmt = null;
private ResultSet rs = null;
private ClassLoader classLoader = null;
private LoggingManager loggingManager = new LoggingManager("CraftFire.DataManager", "[DataManager]");
public DataManager(String username, String password) {
this(DataType.MYSQL, username, password);
}
public DataManager(DataType type, String username, String password) {
this.datatype = type;
this.username = username;
this.password = password;
this.startup = System.currentTimeMillis() / 1000;
if (!getLogging().isLogging()) {
getLogging().setDirectory(this.directory);
getLogging().setLogging(true);
}
}
public String getURL() {
return this.url;
}
public LoggingManager getLogging() {
return this.loggingManager;
}
public void setLoggingManager(LoggingManager loggingManager) {
this.loggingManager = loggingManager;
}
public ClassLoader getClassLoader() {
return this.classLoader;
}
public void setClassLoader(ClassLoader classLoader) {
this.classLoader = classLoader;
}
public boolean isKeepAlive() {
return this.keepAlive;
}
public void setKeepAlive(boolean keepAlive) {
this.keepAlive = keepAlive;
if (keepAlive) {
this.connect();
}
}
public int getTimeout() {
return this.timeout;
}
public void setTimeout(int timeout) {
this.timeout = timeout;
}
public Long getStartup() {
return this.startup;
}
public String getHost() {
return this.host;
}
public void setHost(String host) {
this.host = host;
}
public int getPort() {
return this.port;
}
public void setPort(int port) {
this.port = port;
}
public String getDatabase() {
return this.database;
}
public void setDatabase(String database) {
this.database = database;
}
public String getUsername() {
return this.username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
public String getDirectory() {
return this.directory;
}
public void setDirectory(String directory) {
File file = new File(directory);
if (!file.exists()) {
getLogging().debug(directory + " does not exist, attempting to create it.");
if (file.mkdirs()) {
getLogging().debug("Successfully created directory: " + directory);
} else {
getLogging().error("Could not create directory: " + directory);
}
}
this.directory = directory;
}
public String getPrefix() {
return this.prefix;
}
public void setPrefix(String prefix) {
this.prefix = prefix;
}
public ResultSet getCurrentResultSet() {
return this.rs;
}
public PreparedStatement getCurrentPreparedStatement() {
return this.pStmt;
}
public Statement getCurrentStatement() {
return this.stmt;
}
public int getQueriesCount() {
return this.queriesCount;
}
public Map<Long, String> getQueries() {
return this.queries;
}
public String getLastQuery() {
return this.query;
}
public DataType getDataType() {
return this.datatype;
}
public Connection getConnection() {
return this.con;
}
protected void setURL() {
switch (this.datatype) {
case MYSQL:
this.url = "jdbc:mysql://" + this.host + "/" + this.database
+ "?zeroDateTimeBehavior=convertToNull"
+ "&jdbcCompliantTruncation=false"
+ "&autoReconnect=true"
+ "&characterEncoding=UTF-8"
+ "&characterSetResults=UTF-8";
break;
case H2:
this.url = "jdbc:h2:" + this.directory + this.database + ";AUTO_RECONNECT=TRUE";
break;
}
}
public boolean exist(String table, String field, Object value) {
try {
return this.getField(FieldType.STRING, "SELECT `" + field + "` "
+ "FROM `" + this.getPrefix() + table + "` " + "WHERE `"
+ field + "` = '" + value + "' " + "LIMIT 1") != null;
} catch (SQLException e) {
return false;
}
}
public int getLastID(String field, String table) {
DataField f;
try {
f = this.getField(FieldType.INTEGER, "SELECT `" + field
+ "` FROM `" + this.getPrefix() + table + "` ORDER BY `"
+ field + "` DESC LIMIT 1");
if (f != null) {
return f.getInt();
}
} catch (SQLException e) {
getLogging().stackTrace(e);
}
return 0;
}
public int getLastID(String field, String table, String where) {
DataField f;
try {
f = this.getField(FieldType.INTEGER, "SELECT `" + field + "` "
+ "FROM `" + this.getPrefix() + table + "` " + "WHERE "
+ where + " " + "ORDER BY `" + field + "` DESC LIMIT 1");
if (f != null) {
return f.getInt();
}
} catch (SQLException e) {
getLogging().stackTrace(e);
}
return 0;
}
public int getCount(String table, String where) {
DataField f;
try {
f = this.getField(FieldType.INTEGER, "SELECT COUNT(*) FROM `"
+ this.getPrefix() + table + "` WHERE " + where
+ " LIMIT 1");
if (f != null) {
return f.getInt();
}
} catch (SQLException e) {
getLogging().stackTrace(e);
}
return 0;
}
public int getCount(String table) {
DataField f;
try {
f = this.getField(FieldType.INTEGER, "SELECT COUNT(*) FROM `"
+ this.getPrefix() + table + "` LIMIT 1");
if (f != null) {
return f.getInt();
}
} catch (SQLException e) {
getLogging().stackTrace(e);
}
return 0;
}
public void increaseField(String table, String field, String where) throws SQLException {
this.executeQuery("UPDATE `" + this.getPrefix() + table + "` SET `" + field
+ "` = " + field + " + 1 WHERE " + where);
}
public String getStringField(String query) {
DataField f;
try {
f = this.getField(FieldType.STRING, query);
if (f != null) {
return f.getString();
}
} catch (SQLException e) {
getLogging().stackTrace(e);
}
return null;
}
public String getStringField(String table, String field, String where) {
DataField f;
try {
f = this.getField(FieldType.STRING, table, field, where);
if (f != null) {
return f.getString();
}
} catch (SQLException e) {
getLogging().stackTrace(e);
}
return null;
}
public int getIntegerField(String query) {
DataField f;
try {
f = this.getField(FieldType.INTEGER, query);
if (f != null) {
return f.getInt();
}
} catch (SQLException e) {
getLogging().stackTrace(e);
}
return 0;
}
public int getIntegerField(String table, String field, String where) {
DataField f;
try {
f = this.getField(FieldType.INTEGER, table, field, where);
if (f != null) {
return f.getInt();
}
} catch (SQLException e) {
getLogging().stackTrace(e);
}
return 0;
}
public Date getDateField(String query) {
DataField f;
try {
f = this.getField(FieldType.DATE, query);
if (f != null) {
return f.getDate();
}
} catch (SQLException e) {
getLogging().stackTrace(e);
}
return null;
}
public Date getDateField(String table, String field, String where) {
DataField f;
try {
f = this.getField(FieldType.DATE, table, field, where);
if (f != null) {
return f.getDate();
}
} catch (SQLException e) {
getLogging().stackTrace(e);
}
return null;
}
public Blob getBlobField(String query) {
DataField f;
try {
f = this.getField(FieldType.BLOB, query);
if (f != null) {
return f.getBlob();
}
} catch (SQLException e) {
getLogging().stackTrace(e);
}
return null;
}
public Blob getBlobField(String table, String field, String where) {
DataField f;
try {
f = this.getField(FieldType.BLOB, table, field, where);
if (f != null) {
return f.getBlob();
}
} catch (SQLException e) {
getLogging().stackTrace(e);
}
return null;
}
public boolean getBooleanField(String query) {
DataField f;
try {
f = this.getField(FieldType.BOOLEAN, query);
if (f != null) {
return f.getBool();
}
} catch (SQLException e) {
getLogging().stackTrace(e);
}
return false;
}
public boolean getBooleanField(String table, String field, String where) {
DataField f;
try {
f = this.getField(FieldType.BOOLEAN, table, field, where);
if (f != null) {
return f.getBool();
}
} catch (SQLException e) {
getLogging().stackTrace(e);
}
return false;
}
public double getDoubleField(String query) {
DataField f;
try {
f = this.getField(FieldType.REAL, query);
if (f != null) {
return f.getDouble();
}
} catch (SQLException e) {
getLogging().stackTrace(e);
}
return 0;
}
public double getDoubleField(String table, String field, String where) {
DataField f;
try {
f = this.getField(FieldType.REAL, table, field, where);
if (f != null) {
return f.getDouble();
}
} catch (SQLException e) {
getLogging().stackTrace(e);
}
return 0;
}
public String getBinaryField(String query) {
DataField f;
try {
f = this.getField(FieldType.BINARY, query);
if (f != null) {
return f.getString();
}
} catch (SQLException e) {
getLogging().stackTrace(e);
}
return null;
}
public String getBinaryField(String table, String field, String where) {
DataField f;
try {
f = this.getField(FieldType.BINARY, table, field, where);
if (f != null) {
return f.getString();
}
} catch (SQLException e) {
getLogging().stackTrace(e);
}
return null;
}
public DataField getField(FieldType fieldType, String table, String field,
String where) throws SQLException {
return this.getField(fieldType, "SELECT `" + field + "` FROM `"
+ this.getPrefix() + table + "` WHERE " + where + " LIMIT 1");
}
public DataField getField(FieldType field, String query)
throws SQLException {
try {
this.connect();
this.stmt = this.con.createStatement();
this.rs = this.stmt.executeQuery(query);
this.log(query);
if (this.rs.next()) {
Object value = null;
if (field.equals(FieldType.STRING)) {
value = this.rs.getString(1);
} else if (field.equals(FieldType.INTEGER)) {
value = this.rs.getInt(1);
} else if (field.equals(FieldType.DATE)) {
value = this.rs.getDate(1);
} else if (field.equals(FieldType.BLOB)) {
value = this.rs.getBlob(1);
} else if (field.equals(FieldType.BINARY)) {
value = this.rs.getBytes(1);
} else if (field.equals(FieldType.BOOLEAN)) {
value = this.rs.getBoolean(1);
} else if (field.equals(FieldType.REAL)) {
value = this.rs.getDouble(1);
} else if (field.equals(FieldType.UNKNOWN)) {
return new DataField(1, this.rs);
}
this.close();
if (value == null) {
return null;
}
return new DataField(field, this.rs.getMetaData()
.getColumnDisplaySize(1), value);
}
} finally {
this.close();
}
return null;
}
public void executeQuery(String query) throws SQLException {
this.connect();
this.pStmt = this.con.prepareStatement(query);
this.pStmt.executeUpdate();
this.log(query);
this.close();
}
public void executeQueryVoid(String query) {
try {
this.connect();
this.pStmt = this.con.prepareStatement(query);
this.pStmt.executeUpdate();
this.log(query);
this.close();
} catch (SQLException e) {
getLogging().stackTrace(e);
}
}
public void updateBlob(String table, String field, String where, String data) {
try {
String query = "UPDATE `" + this.getPrefix() + table + "` " + "SET `"
+ field + "` = ? " + "WHERE " + where;
byte[] array = data.getBytes();
ByteArrayInputStream inputStream = new ByteArrayInputStream(array);
this.connect();
this.log(query);
this.stmt = this.con.createStatement();
this.pStmt = this.con.prepareStatement(query);
this.pStmt.setBlob(1, inputStream, array.length);
this.pStmt.executeUpdate();
this.close();
} catch (SQLException e) {
getLogging().stackTrace(e);
}
}
public void updateField(String table, String field, Object value, String where) throws SQLException {
executeQuery("UPDATE `" + this.getPrefix() + table + "` SET `" + field + "` = '" + value + "' WHERE " + where);
}
public void updateFields(HashMap<String, Object> data, String table, String where) throws SQLException {
String update = this.updateFieldsString(data);
executeQuery("UPDATE `" + this.getPrefix() + table + "`" + update + " WHERE " + where);
}
public void insertFields(HashMap<String, Object> data, String table) throws SQLException {
String insert = this.insertFieldString(data);
executeQuery("INSERT INTO `" + this.getPrefix() + table + "` " + insert);
}
public TableModel resultSetToTableModel(String query) {
try {
this.connect();
Statement stmt = this.con.createStatement();
this.rs = stmt.executeQuery(query);
this.log(query);
ResultSetMetaData metaData = this.rs.getMetaData();
int numberOfColumns = metaData.getColumnCount();
Vector<String> columnNames = new Vector<String>();
for (int column = 0; column < numberOfColumns; column++) {
columnNames.addElement(metaData.getColumnLabel(column + 1));
}
Vector<Vector<Object>> rows = new Vector<Vector<Object>>();
while (this.rs.next()) {
Vector<Object> newRow = new Vector<Object>();
for (int i = 1; i <= numberOfColumns; i++) {
newRow.addElement(this.rs.getObject(i));
}
rows.addElement(newRow);
}
this.close();
return new DefaultTableModel(rows, columnNames);
} catch (Exception e) {
getLogging().stackTrace(e);
this.close();
return null;
}
}
public Results getResults(String query) throws SQLException {
try {
this.connect();
this.stmt = this.con.createStatement();
this.rs = this.stmt.executeQuery(query);
this.log(query);
Results results = new Results(query, this.rs);
this.close();
return results;
} finally {
this.close();
}
}
@Deprecated
public HashMap<String, Object> getArray(String query) {
try {
this.connect();
this.stmt = this.con.createStatement();
this.rs = this.stmt.executeQuery(query);
this.log(query);
ResultSetMetaData metaData = this.rs.getMetaData();
int numberOfColumns = metaData.getColumnCount();
HashMap<String, Object> data = new HashMap<String, Object>();
while (this.rs.next()) {
for (int i = 1; i <= numberOfColumns; i++) {
data.put(metaData.getColumnLabel(i), this.rs.getObject(i));
}
}
this.close();
return data;
} catch (SQLException e) {
this.close();
getLogging().stackTrace(e);
}
return null;
}
@Deprecated
public List<HashMap<String, Object>> getArrayList(String query) {
try {
this.connect();
List<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();
this.stmt = this.con.createStatement();
this.rs = this.stmt.executeQuery(query);
this.log(query);
ResultSetMetaData metaData = this.rs.getMetaData();
int numberOfColumns = metaData.getColumnCount();
while (this.rs.next()) {
HashMap<String, Object> data = new HashMap<String, Object>();
for (int i = 1; i <= numberOfColumns; i++) {
data.put(metaData.getColumnLabel(i), this.rs.getString(i));
}
list.add(data);
}
this.close();
return list;
} catch (SQLException e) {
this.close();
getLogging().stackTrace(e);
}
return null;
}
public ResultSet getResultSet(String query) throws SQLException {
this.connect();
this.stmt = this.con.createStatement();
this.log(query);
this.rs = this.stmt.executeQuery(query);
return this.rs;
}
private void log(String query) {
this.query = query;
this.queries.put(System.currentTimeMillis(), query);
this.queriesCount++;
}
+ private void outputDrivers() {
+ if (getLogging().isDebug()) {
+ getLogging().debug("Checking DriverManager drivers.");
+ Enumeration driverList = DriverManager.getDrivers();
+ int count = 0;
+ while (driverList.hasMoreElements()) {
+ Driver driverClass = (Driver) driverList.nextElement();
+ getLogging().debug("Found driver #" + count + ": " + driverClass.getClass().getName());
+ count++;
+ }
+ getLogging().debug("Found " + count + " drivers in DriverManager.");
+ }
+ }
+
public boolean isConnected() {
try {
if (this.con != null) {
return !this.con.isClosed();
}
} catch (SQLException e) {
getLogging().stackTrace(e);
}
return false;
}
public boolean hasConnection() {
try {
boolean result = false;
this.connect();
if (this.con != null) {
result = !this.con.isClosed();
}
this.close();
return result;
} catch (SQLException e) {
getLogging().stackTrace(e);
}
return false;
}
public void connect() {
if (this.url == null) {
this.setURL();
}
if (this.con != null && this.isConnected()) {
return;
}
try {
switch (this.datatype) {
case MYSQL:
if (getClassLoader() != null) {
getLogging().debug("Loading custom class loader for MySQL driver: " + getClassLoader().toString());
Class.forName("com.mysql.jdbc.Driver", true, getClassLoader());
} else {
getLogging().debug("Loading MySQL driver.");
Class.forName("com.mysql.jdbc.Driver");
}
+ outputDrivers();
this.con = DriverManager.getConnection(this.url, this.username, this.password);
break;
case H2:
if (getClassLoader() != null) {
getLogging().debug("Loading custom class loader for H2 driver: " + getClassLoader().toString());
Class.forName("org.h2.Driver", true, getClassLoader()).newInstance();
} else {
getLogging().debug("Loading H2 driver.");
Class.forName("org.h2.Driver");
}
+ outputDrivers();
this.con = DriverManager.getConnection(this.url, this.username, this.password);
break;
}
- if (getLogging().isDebug()) {
- getLogging().debug("Checking DriverManager drivers.");
- Enumeration driverList = DriverManager.getDrivers();
- int count = 0;
- while (driverList.hasMoreElements()) {
- Driver driverClass = (Driver) driverList.nextElement();
- getLogging().debug("Found driver #" + count + ": " + driverClass.getClass().getName());
- count++;
- }
- getLogging().debug("Found " + count + " drivers in DriverManager.");
- }
} catch (ClassNotFoundException e) {
getLogging().stackTrace(e);
} catch (SQLException e) {
getLogging().stackTrace(e);
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
public void close() {
if (this.keepAlive && !this.reconnect) {
if (this.timeout == 0) {
return;
} else if ((System.currentTimeMillis() / 1000) < (this.startup + this.timeout)) {
return;
}
}
try {
this.con.close();
if (this.rs != null) {
this.rs.close();
this.rs = null;
}
if (this.pStmt != null) {
this.pStmt.close();
this.pStmt = null;
}
if (this.stmt != null) {
this.stmt.close();
this.stmt = null;
}
if (this.keepAlive) {
this.connect();
}
} catch (SQLException e) {
getLogging().stackTrace(e);
}
}
public void reconnect() {
this.reconnect = true;
this.close();
this.connect();
}
private String updateFieldsString(HashMap<String, Object> data) {
String query = " SET", suffix = ",";
int i = 1;
Iterator<Entry<String, Object>> it = data.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, Object> pairs = it.next();
if (i == data.size()) {
suffix = "";
}
Object val = pairs.getValue();
String valstr = null;
if (val instanceof Date) {
val = new Timestamp(((Date) val).getTime());
}
if (val == null) {
valstr = "NULL";
} else {
valstr = "'" + val.toString().replaceAll("'", "''") + "'";
}
query += " `" + pairs.getKey() + "` = " + valstr + suffix;
i++;
}
return query;
}
private String insertFieldString(HashMap<String, Object> data) {
String fields = "", values = "", query = "", suffix = ",";
int i = 1;
Iterator<Entry<String, Object>> it = data.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, Object> pairs = it.next();
if (i == data.size()) {
suffix = "";
}
Object val = pairs.getValue();
String valstr = null;
if (val instanceof Date) {
val = new Timestamp(((Date) val).getTime());
}
if (val == null) {
valstr = "''";
} else {
valstr = "'" + val.toString().replaceAll("'", "''") + "'";
}
fields += " `" + pairs.getKey() + "`" + suffix;
values += valstr + suffix;
i++;
}
query = "(" + fields + ") VALUES (" + values + ")";
return query;
}
}
diff --git a/src/main/java/com/craftfire/commons/managers/LoggingManager.java b/src/main/java/com/craftfire/commons/managers/LoggingManager.java
index 8c60343..cbbd68d 100644
--- a/src/main/java/com/craftfire/commons/managers/LoggingManager.java
+++ b/src/main/java/com/craftfire/commons/managers/LoggingManager.java
@@ -1,212 +1,212 @@
/*
* This file is part of CraftCommons.
*
* Copyright (c) 2011-2012, CraftFire <http://www.craftfire.com/>
* CraftCommons is licensed under the GNU Lesser General Public License.
*
* CraftCommons 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.
*
* CraftCommons 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, see <http://www.gnu.org/licenses/>.
*/
package com.craftfire.commons.managers;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.logging.Logger;
public class LoggingManager {
private final Logger logger;
private String prefix, directory, format = "HH:mm:ss";
private boolean debug = false, logging = false;
public LoggingManager(String logger, String prefix) {
this.logger = Logger.getLogger(logger);
this.prefix = prefix;
}
public static enum Type {
error, debug
}
public Logger getLogger() {
return this.logger;
}
public String getPrefix() {
return this.prefix;
}
public void setPrefix(String prefix) {
this.prefix = prefix;
}
public String getDirectory() {
return this.directory;
}
public void setDirectory(String directory) {
this.directory = directory;
if (directory == null || directory.isEmpty()) {
this.logging = false;
}
}
public boolean isDebug() {
return this.debug;
}
public void setDebug(boolean debug) {
this.debug = debug;
}
public boolean isLogging() {
return this.logging;
}
public void setLogging(boolean logging) {
this.logging = (this.directory != null) && (!this.directory.isEmpty()) && logging;
}
public String getFormat() {
return this.format;
}
public void setFormat(String format) {
this.format = format;
}
public void info(String line) {
this.logger.info(this.prefix + " " + line);
}
public void warning(String line) {
this.logger.warning(this.prefix + " " + line);
}
public void severe(String line) {
this.logger.severe(this.prefix + " " + line);
}
public void debug(String line) {
- if (this.debug) {
+ if (isDebug()) {
this.logger.info(this.prefix + " [Debug] " + line);
toFile(Type.debug, line);
}
}
public void error(String error) {
warning(error);
toFile(Type.error, error);
}
public void advancedWarning() {
warning(System.getProperty("line.separator")
+ "|-----------------------------------------------------------------------------|"
+ System.getProperty("line.separator")
+ "|---------------------------------- WARNING ----------------------------------|"
+ System.getProperty("line.separator")
+ "|-----------------------------------------------------------------------------|");
}
public void stackTrace(final Exception e) {
stackTrace(e, null);
}
public void stackTrace(final Exception e, HashMap<Integer, String> extra) {
advancedWarning();
warning("Class name: " + e.getStackTrace()[1].getClassName());
warning("Error message: " + e.getMessage());
warning("Error cause: " + e.getCause());
warning("File name: " + e.getStackTrace()[1].getFileName());
warning("Function name: " + e.getStackTrace()[1].getMethodName());
warning("Error line: " + e.getStackTrace()[1].getLineNumber());
if (this.logging) {
DateFormat LogFormat = new SimpleDateFormat(this.format);
Date date = new Date();
warning("Check log file: " + this.directory + "error\\"
+ LogFormat.format(date) + "-error.log");
} else {
warning("Enable logging in the config to get more information about the error.");
}
logError("--------------------------- STACKTRACE ERROR ---------------------------");
logError("Class name: " + e.getStackTrace()[1].getClassName());
logError("Error message: " + e.getMessage());
logError("Error cause: " + e.getCause());
logError("File name: " + e.getStackTrace()[1].getFileName());
logError("Function name: " + e.getStackTrace()[1].getMethodName());
logError("Error line: " + e.getStackTrace()[1].getLineNumber());
if (extra != null) {
for (int id : extra.keySet()) {
logError(extra.get(id));
}
}
logError("--------------------------- STACKTRACE START ---------------------------");
for (int i = 0; i < e.getStackTrace().length; i++) {
logError(e.getStackTrace()[i].toString());
}
logError("---------------------------- STACKTRACE END ----------------------------");
}
public void logError(String error) {
toFile(Type.error, error);
}
private void toFile(Type type, String line) {
if (this.logging) {
File data = new File(this.directory, "");
if (!data.exists()) {
if (data.mkdir()) {
debug("Created missing directory: " + this.directory);
}
}
data = new File(this.directory + type.toString() + "/", "");
if (!data.exists()) {
if (data.mkdir()) {
debug("Created missing directory: " + this.directory
+ type.toString());
}
}
DateFormat logFormat = new SimpleDateFormat(this.format);
Date date = new Date();
data = new File(this.directory + type.toString() + "/"
+ logFormat.format(date) + "-" + type.toString() + ".log");
if (!data.exists()) {
try {
data.createNewFile();
} catch (IOException e) {
stackTrace(e);
}
}
try {
DateFormat stringFormat = new SimpleDateFormat(
"yyyy/MM/dd HH:mm:ss");
FileWriter writer = new FileWriter(this.directory
+ type.toString() + "/" + logFormat.format(date) + "-"
+ type.toString() + ".log", true);
BufferedWriter buffer = new BufferedWriter(writer);
buffer.write(stringFormat.format(date) + " - " + line
+ System.getProperty("line.separator"));
buffer.close();
writer.close();
} catch (IOException e) {
stackTrace(e);
}
}
}
}
| false | false | null | null |
diff --git a/Code/src/com/ecn/urbapp/fragments/ZoneFragment.java b/Code/src/com/ecn/urbapp/fragments/ZoneFragment.java
index 3518c1c..f5c5794 100644
--- a/Code/src/com/ecn/urbapp/fragments/ZoneFragment.java
+++ b/Code/src/com/ecn/urbapp/fragments/ZoneFragment.java
@@ -1,720 +1,726 @@
package com.ecn.urbapp.fragments;
import java.util.ArrayList;
import java.util.Vector;
import android.app.Fragment;
import android.content.res.Resources;
import android.graphics.Matrix;
import android.graphics.Point;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.os.Bundle;
import android.os.Environment;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import com.ecn.urbapp.R;
import com.ecn.urbapp.activities.MainActivity;
import com.ecn.urbapp.db.Element;
import com.ecn.urbapp.db.PixelGeom;
import com.ecn.urbapp.dialogs.TopologyExceptionDialogFragment;
import com.ecn.urbapp.dialogs.UnionDialogFragment;
import com.ecn.urbapp.utils.ConvertGeom;
import com.ecn.urbapp.utils.GetId;
import com.ecn.urbapp.zones.BitmapLoader;
import com.ecn.urbapp.zones.DrawZoneView;
import com.ecn.urbapp.zones.UtilCharacteristicsZone;
import com.ecn.urbapp.zones.Zone;
import com.vividsolutions.jts.geom.TopologyException;
import com.vividsolutions.jts.io.ParseException;
/**
* @author COHENDET Sébastien
* DAVID Nicolas
* GUILBART Gabriel
* PALOMINOS Sylvain
* PARTY Jules
* RAMBEAU Merwan
*
* ZoneFragment class
*
* This is the fragment used to define the different zones.
*
*/
public class ZoneFragment extends Fragment implements OnClickListener, OnTouchListener{
/**
* Field defining the radius tolerance on touch
*/
- private int TOUCH_RADIUS_TOLERANCE = 30;//only for catching points in edit mode
+ private final int REFERENCE_TOUCH_RADIUS_TOLERANCE = 30;//only for catching points in edit mode
/**
* Constant field defining the reference height to correct the size of point for the zone creation
*/
private final int REFERENCE_HEIGHT = 600;
/**
* Constant field defining the reference width to correct the size of point for the zone creation
*/
private final int REFERENCE_WIDTH = 1200;
/**
* Constant field defining the reference time length to force selection
*/
private final int REFERENCE_TIME = 150;
/**
* Field defining the actual sate of definition of zones
*/
public static int state;
/**
* Button cancel
*/
private Button cancel;
/**
* Button fusion
*/
//private Button fusion;
/**
* Button back
*/
private Button back;
/**
* Button validate
*/
private Button validate;
/**
* Button delete
*/
private Button delete;
/**
* Image displayed
*/
private static ImageView myImage;
/**
* Matrix for displaying
*/
private Matrix matrix;
/**
* Temporary zone for edition
*/
private Zone zoneCache ;
/**
* Temporary pixelGeom for edition
*/
public static PixelGeom geomCache;
/**
* Zone selected
*/
private Zone zone;
/**
* Point selected
*/
private Point selected;
+
+ /**
+ * Tolerance range on selection
+ */
+ private float touchRadiusTolerance;
+
public static Element elementTemp;
private DrawZoneView drawzoneview;
private int imageHeight; private int imageWidth;
/**
* Constant value
*/
public static final int IMAGE_CREATION = 2;
/**
* Constant value
*/
public static final int IMAGE_EDITION = 3;
/**
* Constant value
*/
public static final int IMAGE_SELECTION= 1;
/**
* Point selection indicator, works in both creation and edition modes
*/
private boolean POINT_SELECTED = false;
private int moving;
//private SetCharactFragment scf;
//private RecapCharactFragment rcf;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public void onClick(View v) {
Log.d("Move","Etat:"+state);
switch(state){
case IMAGE_SELECTION:
break;
case IMAGE_CREATION:
switch(v.getId()){
case R.id.zone_button_back:
if(!zone.back()){
Toast.makeText(getActivity(), R.string.no_back, Toast.LENGTH_SHORT).show();
}
refreshDisplay();
break;
case R.id.zone_button_cancel:
//scf.resetAffichage();
state = IMAGE_SELECTION;
exitAction();
break;
case R.id.zone_button_delete:
if(POINT_SELECTED){
if (!zone.deletePoint(selected)){
Toast.makeText(getActivity(), R.string.point_deleting_impossible, Toast.LENGTH_SHORT).show();
}
selected.set(0,0);//no selected point anymore
refreshDisplay();
delete.setEnabled(false);
POINT_SELECTED = false;
}
break;
/*case R.id.zone_button_fusion:
UnionDialogFragment summarydialog = new UnionDialogFragment();
summarydialog.show(getFragmentManager(), "UnionDialogFragment");
break;*/
case R.id.zone_button_validate:
validateCreation();//it's also possible to create a zone by looping polygon, use this method !
break;
}
break;
case IMAGE_EDITION:
switch(v.getId()){
case R.id.zone_button_delete:
if(POINT_SELECTED){
if (!zone.deletePoint(selected)){
Toast.makeText(getActivity(), "Impossible de supprimer ce point", Toast.LENGTH_SHORT).show();
}
selected.set(0,0);//no selected point anymore
refreshDisplay();
delete.setEnabled(false);
POINT_SELECTED = false;
}
else{
int pos;
for(pos=0; pos<MainActivity.pixelGeom.size(); pos++){
if(MainActivity.pixelGeom.get(pos).getPixelGeomId()==geomCache.getPixelGeomId()){
for(int i=0; i<MainActivity.element.size(); i++){
if(MainActivity.element.get(i).getPixelGeom_id()==MainActivity.pixelGeom.get(pos).getPixelGeomId()){
MainActivity.element.remove(i);
//scf.resetAffichage();
break;
}
}
MainActivity.pixelGeom.remove(pos);
break;
}
}
state = IMAGE_SELECTION;
exitAction();
}
break;
case R.id.zone_button_back:
if(!zone.back()){
Toast.makeText(getActivity(), R.string.no_back, Toast.LENGTH_SHORT).show();
}
refreshDisplay();
break;
case R.id.zone_button_cancel:
//scf.resetAffichage();
exitAction();
state = IMAGE_SELECTION;
break;
/*case R.id.zone_button_fusion:
UnionDialogFragment summarydialog = new UnionDialogFragment();
summarydialog.show(getFragmentManager(), "UnionDialogFragment");
break;*/
case R.id.zone_button_validate:
if(!zone.getPoints().isEmpty()){
//scf.validation();
ArrayList<PixelGeom> lpg = new ArrayList<PixelGeom>();
for (PixelGeom pg : MainActivity.pixelGeom) {
lpg.add(pg);
}
ArrayList<Element> le = new ArrayList<Element>();
for (Element elt : MainActivity.element) {
le.add(elt);
}
try {
//MainActivity.zones.remove(zoneCache); //delete original
MainActivity.pixelGeom.remove(geomCache);
PixelGeom pg = new PixelGeom();
pg.setPixelGeom_the_geom((new Zone(zone)).getPolygon().toText());
UtilCharacteristicsZone.addInMainActivityZones(pg, null);
exitAction();
zone.clearBacks();//remove list of actions backs
} catch(TopologyException e) {
MainActivity.pixelGeom = lpg;
MainActivity.element = le;
TopologyExceptionDialogFragment diag = new TopologyExceptionDialogFragment();
diag.show(getFragmentManager(), "TopologyExceptionDialogFragment");
} catch (ParseException e) {
e.printStackTrace();
}
}
for(PixelGeom pg : MainActivity.pixelGeom){
pg.selected=false;
}
state = IMAGE_SELECTION;
exitAction();
break;
}
break;
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View v = inflater.inflate(R.layout.layout_zone, null);
back = (Button) v.findViewById(R.id.zone_button_back);
//fusion = (Button) v.findViewById(R.id.zone_button_fusion);
cancel = (Button) v.findViewById(R.id.zone_button_cancel);
validate = (Button) v.findViewById(R.id.zone_button_validate);
delete = (Button) v.findViewById(R.id.zone_button_delete);
back.setOnClickListener(this);
cancel.setOnClickListener(this);
validate.setOnClickListener(this);
delete.setOnClickListener(this);
//fusion.setOnClickListener(this);
validate.setEnabled(false);
back.setEnabled(false);
cancel.setEnabled(false);
//fusion.setEnabled(false);
delete.setEnabled(false);
zone = new Zone(); zoneCache = new Zone(); selected = new Point(0,0);
zone = new Zone(); selected = new Point(0,0);
myImage = (ImageView) v.findViewById(R.id.image_zone);
drawzoneview = new DrawZoneView(zone, selected) ;
DisplayMetrics metrics = Resources.getSystem().getDisplayMetrics();
Drawable[] drawables = {
new BitmapDrawable(
getResources(),
BitmapLoader.decodeSampledBitmapFromFile(
Environment.getExternalStorageDirectory()+"/featureapp/"+MainActivity.photo.getPhoto_url(), metrics.widthPixels, metrics.heightPixels - 174)), drawzoneview
};//TODO 174 corresponds to menu bar + buttons bar. Calculate this value ! Maybe by charging a small picture before to know ImageView size
myImage.setImageDrawable(new LayerDrawable(drawables));
myImage.setOnTouchListener(this);
//scf = (SetCharactFragment)getFragmentManager().findFragmentById(R.id.fragmentCaract);
//rcf = (RecapCharactFragment)getFragmentManager().findFragmentById(R.id.fragmentRecap);
//rcf.setZoneFragment(this);
return v;
}
@Override
public void onStart(){
super.onStart();
state=1;
imageHeight = myImage.getDrawable().getIntrinsicHeight();
imageWidth = myImage.getDrawable().getIntrinsicWidth();
float ratioW =((float)REFERENCE_WIDTH/imageWidth);
float ratioH =((float)REFERENCE_HEIGHT/imageHeight);
float ratio = ratioW < ratioH ? ratioW : ratioH ;
drawzoneview.setRatio(ratio);
- TOUCH_RADIUS_TOLERANCE/=ratio;
+ touchRadiusTolerance = REFERENCE_TOUCH_RADIUS_TOLERANCE/ratio;
}
/**
* Common action to do on exit (cancel or validation)
*/
private void exitAction(){
drawzoneview.onZonePage();
validate.setEnabled(false);
back.setEnabled(false);
cancel.setEnabled(false);
//fusion.setEnabled(false);
delete.setEnabled(false);
zone.setZone(new Zone());
selected.set(0,0);
drawzoneview.setIntersections(new Vector<Point>());
myImage.invalidate();
//rcf.refresh();
}
private void validateCreation(){
//scf.validation();
ArrayList<PixelGeom> lpg = new ArrayList<PixelGeom>();
for (PixelGeom pg : MainActivity.pixelGeom) {
lpg.add(pg);
}
ArrayList<Element> le = new ArrayList<Element>();
for (Element elt : MainActivity.element) {
le.add(elt);
}
try {
PixelGeom pg = new PixelGeom();
pg.setPixelGeom_the_geom((new Zone(zone)).getPolygon().toText());
if(elementTemp.getElementType_id()==0 && elementTemp.getMaterial_id()==0){
UtilCharacteristicsZone.addInMainActivityZones(pg, null);
}
else{
UtilCharacteristicsZone.addInMainActivityZones(pg, elementTemp);
//MainActivity.element.add(elementTemp);
}
exitAction();
zone.clearBacks();
} catch(TopologyException e) {
MainActivity.pixelGeom = lpg;
MainActivity.element = le;
TopologyExceptionDialogFragment diag = new TopologyExceptionDialogFragment();
diag.show(getFragmentManager(), "TopologyExceptionDialogFragment");
} catch (ParseException e) {
e.printStackTrace();
}
state = IMAGE_SELECTION;
exitAction();
}
public Point getTouchedPoint(MotionEvent event){
float[] coord = {event.getX(),event.getY()};//get touched point coord
getMatrix();
matrix.mapPoints(coord);//apply matrix transformation on points coord
int pointX = (int)coord[0]; int pointY = (int)coord[1];
Log.d("Touch","x:"+pointX+" y:"+pointY);
if(pointX<0){
pointX=0;
}else{
if(pointX>imageWidth){
pointX=imageWidth;
}
}
if(pointY<0){
pointY=0;
}else{
if(pointY>imageHeight){
pointY=imageHeight;
}
}
return(new Point(pointX,pointY));
}
public void getMatrix(){
matrix = new Matrix();
myImage.getImageMatrix().invert(matrix);
}
public void refreshDisplay(){
Vector<Point> points = zone.getPoints();
if(! points.isEmpty()){
back.setEnabled(false);
validate.setEnabled(false);
if(points.size()>1+1){
back.setEnabled(true);
if(points.size()>2+1){
validate.setEnabled(true);
//cannot be intersections with less than 3 points but needed for refreshing displaying
Vector<Point> intersections = new Vector<Point>(zone.isSelfIntersecting());
if(!intersections.isEmpty()){
validate.setEnabled(false);
}
drawzoneview.setIntersections(intersections);
}
}
}
myImage.invalidate();
}
/*public void refreshDisplay(){
Vector<Point> points = zone.getPoints();
if(points.size()<3+1){//+1 corresponds to the ending point closing polygon
validate.setEnabled(false);
}
else{
if(points.size()>2+1){
validate.setEnabled(true);
if(points.size()>3+1){
Vector<Point> intersections = new Vector<Point>(zone.isSelfIntersecting());
if(!intersections.isEmpty()){
validate.setEnabled(false);
}
drawzoneview.setIntersections(intersections);
}
}
}
myImage.invalidate();
}*/
/**
* All touches handling method. Override Android API method.
*/
@Override
public boolean onTouch(View v, MotionEvent event) {
switch(state){
case IMAGE_EDITION: case IMAGE_CREATION: //app behavior in these two cases are quite the same, except some ifs
Log.d("Move","Moving:"+moving);
if(event.getAction() == MotionEvent.ACTION_DOWN && !POINT_SELECTED){
moving = 0;//ACTION_MOVE occurrences
Log.d("Move","Action Down");
selected.set(0, 0);
Point touch = getTouchedPoint(event);
for(Point p : zone.getPoints()){//is the touched point a normal point ?
float dx=Math.abs(p.x-touch.x);
float dy=Math.abs(p.y-touch.y);
- if((dx*dx+dy*dy)<TOUCH_RADIUS_TOLERANCE*TOUCH_RADIUS_TOLERANCE){//10 radius tolerance
+ if((dx*dx+dy*dy)<touchRadiusTolerance*touchRadiusTolerance){//10 radius tolerance
selected.set(p.x,p.y);
}
}
if(selected.x == 0 && selected.y == 0){//is the touched point a middle point ?
for(Point p : zone.getMiddles()){
float dx=Math.abs(p.x-touch.x);
float dy=Math.abs(p.y-touch.y);
- if((dx*dx+dy*dy)<TOUCH_RADIUS_TOLERANCE*TOUCH_RADIUS_TOLERANCE){
+ if((dx*dx+dy*dy)<touchRadiusTolerance*touchRadiusTolerance){
selected.set(p.x,p.y);
}
}
}
}
if (event.getAction() == MotionEvent.ACTION_UP) {
Log.d("Move","Action Up, down time:"+(event.getEventTime()-event.getDownTime()));
if(POINT_SELECTED){
selected.set(0, 0);
POINT_SELECTED = false; delete.setEnabled(false);
}
else{
if(selected.x==0 && selected.y==0){
if(state == IMAGE_CREATION){
zone.addPoint2(getTouchedPoint(event));
}else{
//if the user is touching a long time, and not by moving, a zone, switch zone selected
if(moving < 2){
hasZoneSelected(event);
}
}
}
else{
if(state == IMAGE_CREATION && event.getEventTime()-event.getDownTime()<REFERENCE_TIME){
if(zone.getPoints().size()>2+1){
float dx=Math.abs(zone.getPoints().get(0).x-selected.x);
float dy=Math.abs(zone.getPoints().get(0).y-selected.y);
- if((dx*dx+dy*dy)<TOUCH_RADIUS_TOLERANCE*TOUCH_RADIUS_TOLERANCE){//10 radius tolerance
+ if((dx*dx+dy*dy)<touchRadiusTolerance*touchRadiusTolerance){//10 radius tolerance
validateCreation();
break;
}
}
}
Point touch = getTouchedPoint(event);
if(moving > 2){//if there is a real movement
zone.updatePoint(selected, touch);
zone.endMove(touch);
selected.set(0, 0);//No selected point anymore
}
else{
POINT_SELECTED = true; delete.setEnabled(true);
moving=0;
}
}
}
}
if (event.getAction() == MotionEvent.ACTION_MOVE && !POINT_SELECTED) {
moving ++;
Log.d("Move","Action Move");
if(selected.x!=0 || selected.y!=0){
Point touch = getTouchedPoint(event);
if (moving==3){
if (! zone.updatePoint(selected, touch)){//Is it a normal point ?
zone.updateMiddle(selected, touch);//If not it's a "middle" point, and it's upgraded to normal
zone.startMove(null);
}else{
zone.startMove(selected);
}
selected.set(touch.x,touch.y);
}
else{
if(moving>3){
zone.updatePoint(selected, touch);
selected.set(touch.x,touch.y);
}
}
}
}
refreshDisplay();//display new point, refresh buttons' availabilities
break;
case IMAGE_SELECTION:
if (event.getAction() == MotionEvent.ACTION_UP) {
if(!hasZoneSelected(event)){
getMatrix();
zone.addPoint2(getTouchedPoint(event));
refreshDisplay();
state = IMAGE_CREATION; drawzoneview.onCreateMode();
validate.setEnabled(false);
back.setEnabled(false);
cancel.setEnabled(true);
//fusion.setEnabled(true);
elementTemp = new Element();
elementTemp.setElement_id(GetId.Element());
elementTemp.setPhoto_id(MainActivity.photo.getPhoto_id());
elementTemp.setPixelGeom_id(GetId.PixelGeom());
elementTemp.setGpsGeom_id(MainActivity.photo.getGpsGeom_id());
}
}
break;
}
return true;
}
@Override
public void onStop(){
super.onStop();
}
public void selectGeom(long i){
if(state==IMAGE_CREATION){
//scf.resetAffichage();
state = IMAGE_SELECTION;
exitAction();
}
else if(state==IMAGE_EDITION){
//scf.resetAffichage();
exitAction();
}
Zone z=null;
for(PixelGeom pg : MainActivity.pixelGeom){
z=ConvertGeom.pixelGeomToZone(pg);
}
zoneCache = z;
zone.setZone(z);
for(int j=0; j<MainActivity.pixelGeom.size(); j++){
if(MainActivity.pixelGeom.get(j).getPixelGeom_the_geom().equals(ConvertGeom.ZoneToPixelGeom(zoneCache))){
geomCache = MainActivity.pixelGeom.get(j);
MainActivity.pixelGeom.get(j).selected=true;
}
}
state = IMAGE_EDITION; drawzoneview.onEditMode();
validate.setEnabled(true);
back.setEnabled(false);
cancel.setEnabled(true);
//fusion.setEnabled(true);
delete.setEnabled(true);
refreshDisplay();
//scf.setAffichage(geomCache);
}
public static ImageView getMyImage(){
return myImage;
}
/**
* Add the equivalent of the attribute zone in MainActivity.pixelGeom.
* Intersect this new PixelGeom wih older if the boolean in parameter is true.
* @param tryIntersect intersect the zone to add with existing zones if true
*/
public void addZone(boolean tryIntersect) {
PixelGeom pgeom = new PixelGeom();
zone.closePolygon();
zone.actualizePolygon();
pgeom.setPixelGeom_the_geom(zone.getPolygon().toText());
try {
if (tryIntersect) {
ArrayList<PixelGeom> lpg = new ArrayList<PixelGeom>();
for (PixelGeom pg : MainActivity.pixelGeom) {
lpg.add(pg);
}
ArrayList<Element> le = new ArrayList<Element>();
for (Element elt : MainActivity.element) {
le.add(elt);
}
try {
UtilCharacteristicsZone.addInMainActivityZones(pgeom, null);
exitAction();
} catch(TopologyException e) {
MainActivity.pixelGeom = lpg;
MainActivity.element = le;
TopologyExceptionDialogFragment diag = new TopologyExceptionDialogFragment();
diag.show(getFragmentManager(), "TopologyExceptionDialogFragment");
}
} else {
UtilCharacteristicsZone.addPixelGeom(pgeom, null);
exitAction();
}
} catch (ParseException e) {
e.printStackTrace();
}
}
/**
* Is user selecting a zone ?
* @param event : the user action object
* @return yes if zone selected, no otherwise. The selected zone is saved in a fragment's attribute.
*/
private boolean hasZoneSelected(MotionEvent event){
getMatrix();
Point touch = getTouchedPoint(event);
boolean flag=false;
Zone z=null;
if(event.getEventTime()-event.getDownTime()>REFERENCE_TIME){
for(PixelGeom pg: MainActivity.pixelGeom){
if(ConvertGeom.pixelGeomToZone(pg).containPoint(touch)){
flag=true;
z=ConvertGeom.pixelGeomToZone(pg);
//scf.setAffichage(pg);
break;
}
}
}
if(flag){
zoneCache = z;
zone.setZone(z);
for(int i=0; i<MainActivity.pixelGeom.size(); i++){
if(MainActivity.pixelGeom.get(i).getPixelGeom_the_geom().equals(ConvertGeom.ZoneToPixelGeom(zoneCache))){
geomCache = MainActivity.pixelGeom.get(i);
MainActivity.pixelGeom.get(i).selected=true;
}
}
state = IMAGE_EDITION; drawzoneview.onEditMode();
validate.setEnabled(true);
back.setEnabled(false);
cancel.setEnabled(true);
//fusion.setEnabled(true);
delete.setEnabled(true);
refreshDisplay();
return true;
}
else{
return false;
}
}
}
\ No newline at end of file
| false | false | null | null |
diff --git a/src/net/nightwhistler/pageturner/activity/ReadingFragment.java b/src/net/nightwhistler/pageturner/activity/ReadingFragment.java
index a9a11e6..069ce74 100644
--- a/src/net/nightwhistler/pageturner/activity/ReadingFragment.java
+++ b/src/net/nightwhistler/pageturner/activity/ReadingFragment.java
@@ -1,1858 +1,1863 @@
/*
* Copyright (C) 2011 Alex Kuiper
*
* This file is part of PageTurner
*
* PageTurner 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.
*
* PageTurner 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 PageTurner. If not, see <http://www.gnu.org/licenses/>.*
*/
package net.nightwhistler.pageturner.activity;
import java.net.URLEncoder;
import java.util.List;
import net.nightwhistler.htmlspanner.HtmlSpanner;
import net.nightwhistler.htmlspanner.spans.CenterSpan;
import net.nightwhistler.pageturner.Configuration;
import net.nightwhistler.pageturner.Configuration.AnimationStyle;
import net.nightwhistler.pageturner.Configuration.ColourProfile;
import net.nightwhistler.pageturner.Configuration.ScrollStyle;
import net.nightwhistler.pageturner.R;
import net.nightwhistler.pageturner.animation.Animations;
import net.nightwhistler.pageturner.animation.Animator;
import net.nightwhistler.pageturner.animation.PageCurlAnimator;
import net.nightwhistler.pageturner.animation.PageTimer;
import net.nightwhistler.pageturner.animation.RollingBlindAnimator;
import net.nightwhistler.pageturner.library.LibraryService;
import net.nightwhistler.pageturner.sync.AccessException;
import net.nightwhistler.pageturner.sync.BookProgress;
import net.nightwhistler.pageturner.sync.ProgressService;
import net.nightwhistler.pageturner.tasks.SearchTextTask;
import net.nightwhistler.pageturner.view.AnimatedImageView;
import net.nightwhistler.pageturner.view.NavGestureDetector;
import net.nightwhistler.pageturner.view.ProgressListAdapter;
import net.nightwhistler.pageturner.view.SearchResultAdapter;
import net.nightwhistler.pageturner.view.bookview.BookView;
import net.nightwhistler.pageturner.view.bookview.BookViewListener;
import net.nightwhistler.pageturner.view.bookview.FixedPagesStrategy;
import net.nightwhistler.pageturner.view.bookview.TextSelectionCallback;
import nl.siegmann.epublib.domain.Author;
import nl.siegmann.epublib.domain.Book;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import roboguice.RoboGuice;
import roboguice.inject.InjectView;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.SpannedString;
import android.text.TextPaint;
import android.util.DisplayMetrics;
import android.view.ContextMenu;
import android.view.Display;
import android.view.GestureDetector;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.MotionEvent;
import android.view.Surface;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewSwitcher;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.github.rtyley.android.sherlock.roboguice.fragment.RoboSherlockFragment;
import com.google.inject.Inject;
public class ReadingFragment extends RoboSherlockFragment implements
BookViewListener, TextSelectionCallback {
private static final String POS_KEY = "offset:";
private static final String IDX_KEY = "index:";
protected static final int REQUEST_CODE_GET_CONTENT = 2;
public static final String PICK_RESULT_ACTION = "colordict.intent.action.PICK_RESULT";
public static final String SEARCH_ACTION = "colordict.intent.action.SEARCH";
public static final String EXTRA_QUERY = "EXTRA_QUERY";
public static final String EXTRA_FULLSCREEN = "EXTRA_FULLSCREEN";
public static final String EXTRA_HEIGHT = "EXTRA_HEIGHT";
public static final String EXTRA_WIDTH = "EXTRA_WIDTH";
public static final String EXTRA_GRAVITY = "EXTRA_GRAVITY";
public static final String EXTRA_MARGIN_LEFT = "EXTRA_MARGIN_LEFT";
public static final String EXTRA_MARGIN_TOP = "EXTRA_MARGIN_TOP";
public static final String EXTRA_MARGIN_BOTTOM = "EXTRA_MARGIN_BOTTOM";
public static final String EXTRA_MARGIN_RIGHT = "EXTRA_MARGIN_RIGHT";
private static final Logger LOG = LoggerFactory
.getLogger(ReadingFragment.class);
@Inject
private ProgressService progressService;
@Inject
private LibraryService libraryService;
@Inject
private Configuration config;
@InjectView(R.id.mainContainer)
private ViewSwitcher viewSwitcher;
@InjectView(R.id.bookView)
private BookView bookView;
@InjectView(R.id.myTitleBarTextView)
private TextView titleBar;
@InjectView(R.id.myTitleBarLayout)
private RelativeLayout titleBarLayout;
@InjectView(R.id.titleProgress)
private SeekBar progressBar;
@InjectView(R.id.percentageField)
private TextView percentageField;
@InjectView(R.id.authorField)
private TextView authorField;
@InjectView(R.id.dummyView)
private AnimatedImageView dummyView;
@InjectView(R.id.pageNumberView)
private TextView pageNumberView;
private ProgressDialog waitDialog;
private AlertDialog tocDialog;
private String bookTitle;
private String titleBase;
private String fileName;
private int progressPercentage;
private int currentPageNumber = -1;
private static enum Orientation {
HORIZONTAL, VERTICAL
}
private static class SavedConfigState {
private boolean brightness;
private boolean stripWhiteSpace;
private String fontName;
private boolean usePageNum;
private boolean fullscreen;
private int vMargin;
private int hMargin;
private int textSize;
private boolean scrolling;
}
private SavedConfigState savedConfigState = new SavedConfigState();
private CharSequence selectedWord = null;
private Handler uiHandler;
private Handler backgroundHandler;
private Toast brightnessToast;
private BroadcastReceiver mReceiver = new ScreenReceiver();
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Restore preferences
this.uiHandler = new Handler();
HandlerThread bgThread = new HandlerThread("background");
bgThread.start();
this.backgroundHandler = new Handler(bgThread.getLooper());
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_reading, container, false);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
setHasOptionsMenu(true);
this.bookView.init();
this.waitDialog = new ProgressDialog(getActivity());
this.waitDialog.setOwnerActivity(getActivity());
this.waitDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
@Override
public boolean onKey(DialogInterface dialog, int keyCode,
KeyEvent event) {
// This just consumes all key events and does nothing.
return true;
}
});
this.progressBar.setFocusable(true);
this.progressBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
private int seekValue;
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
bookView.navigateToPercentage(this.seekValue);
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onProgressChanged(SeekBar seekBar,
int progress, boolean fromUser) {
if (fromUser) {
seekValue = progress;
percentageField.setText(progress + "% ");
}
}
});
this.bookView.setConfiguration(config);
this.bookView.addListener(this);
this.bookView.setSpanner(RoboGuice.getInjector(getActivity()).getInstance(
HtmlSpanner.class));
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
DisplayMetrics metrics = new DisplayMetrics();
getActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics);
if (config.isShowPageNumbers()) {
displayPageNumber(-1); // Initializes the pagenumber view properly
}
final GestureDetector gestureDetector = new GestureDetector(getActivity(),
new NavGestureDetector(bookView, this, metrics));
View.OnTouchListener gestureListener = new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
return gestureDetector.onTouchEvent(event);
}
};
this.viewSwitcher.setOnTouchListener(gestureListener);
this.bookView.setOnTouchListener(gestureListener);
registerForContextMenu(bookView);
saveConfigState();
String file = getActivity().getIntent().getStringExtra("file_name");
if (file == null && getActivity().getIntent().getData() != null) {
file = getActivity().getIntent().getData().getPath();
}
if (file == null) {
file = config.getLastOpenedFile();
}
updateFromPrefs();
updateFileName(savedInstanceState, file);
if ("".equals(fileName)) {
Intent intent = new Intent(getActivity(), LibraryActivity.class);
startActivity(intent);
getActivity().finish();
return;
} else {
if (savedInstanceState == null && config.isSyncEnabled()) {
new DownloadProgressTask().execute();
} else {
bookView.restore();
}
}
}
private void saveConfigState() {
// Cache old settings to check if we'll need a restart later
savedConfigState.brightness = config.isBrightnessControlEnabled();
savedConfigState.stripWhiteSpace = config.isStripWhiteSpaceEnabled();
savedConfigState.usePageNum = config.isShowPageNumbers();
savedConfigState.fullscreen = config.isFullScreenEnabled();
savedConfigState.hMargin = config.getHorizontalMargin();
savedConfigState.vMargin = config.getVerticalMargin();
savedConfigState.textSize = config.getTextSize();
savedConfigState.fontName = config.getFontFamily().getName();
savedConfigState.scrolling = config.isScrollingEnabled();
}
/*
* @see roboguice.activity.RoboActivity#onPause()
*/
@Override
public void onPause() {
// when the screen is about to turn off
if (ScreenReceiver.wasScreenOn) {
// this is the case when onPause() is called by the system due to a
// screen state change
sendProgressUpdateToServer();
} else {
// this is when onPause() is called when the screen state has not
// changed
}
getActivity().unregisterReceiver(mReceiver);
super.onPause();
}
@Override
public void onResume() {
registerReceiver();
super.onResume();
}
private void registerReceiver() {
// initialize receiver
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
getActivity().registerReceiver(mReceiver, filter);
}
private void updateFileName(Bundle savedInstanceState, String fileName) {
this.fileName = fileName;
int lastPos = config.getLastPosition(fileName);
int lastIndex = config.getLastIndex(fileName);
if (savedInstanceState != null) {
lastPos = savedInstanceState.getInt(POS_KEY, lastPos);
lastIndex = savedInstanceState.getInt(IDX_KEY, lastIndex);
}
this.bookView.setFileName(fileName);
this.bookView.setPosition(lastPos);
this.bookView.setIndex(lastIndex);
config.setLastOpenedFile(fileName);
}
@Override
public void progressUpdate(int progressPercentage, int pageNumber,
int totalPages) {
if ( ! isAdded() || getActivity() == null ) {
return;
}
this.currentPageNumber = pageNumber;
// Work-around for calculation errors and weird values.
if (progressPercentage < 0 || progressPercentage > 100) {
return;
}
this.progressPercentage = progressPercentage;
if (config.isShowPageNumbers() && pageNumber > 0) {
percentageField.setText("" + progressPercentage + "% "
+ pageNumber + " / " + totalPages);
displayPageNumber(pageNumber);
} else {
percentageField.setText("" + progressPercentage + "%");
}
this.progressBar.setProgress(progressPercentage);
this.progressBar.setMax(100);
}
private void displayPageNumber(int pageNumber) {
String pageString;
if (pageNumber > 0) {
pageString = Integer.toString(pageNumber) + "\n";
} else {
pageString = "\n";
}
SpannableStringBuilder builder = new SpannableStringBuilder(pageString);
builder.setSpan(new CenterSpan(), 0, builder.length(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
pageNumberView.setTextColor(config.getTextColor());
pageNumberView.setTextSize(config.getTextSize());
pageNumberView.setBackgroundColor(config.getBackgroundColor());
pageNumberView.setTypeface(config.getFontFamily().getDefaultTypeface());
pageNumberView.setText(builder);
}
private void updateFromPrefs() {
this.progressService.setConfig(this.config);
bookView.setTextSize(config.getTextSize());
int marginH = config.getHorizontalMargin();
int marginV = config.getVerticalMargin();
this.bookView.setFontFamily(config.getFontFamily());
bookView.setHorizontalMargin(marginH);
bookView.setVerticalMargin(marginV);
if (!isAnimating()) {
bookView.setEnableScrolling(config.isScrollingEnabled());
}
bookView.setStripWhiteSpace(config.isStripWhiteSpaceEnabled());
bookView.setLineSpacing(config.getLineSpacing());
if (config.isFullScreenEnabled()) {
getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
getActivity().getWindow().clearFlags(
WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
getSherlockActivity().getSupportActionBar().hide();
} else {
getActivity().getWindow().addFlags(
WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
getActivity().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
getSherlockActivity().getSupportActionBar().show();
}
if (config.isKeepScreenOn()) {
getActivity().getWindow()
.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
} else {
getActivity().getWindow().clearFlags(
WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
restoreColorProfile();
// Check if we need a restart
if (config.isFullScreenEnabled() != savedConfigState.fullscreen
|| config.isShowPageNumbers() != savedConfigState.usePageNum
|| config.isBrightnessControlEnabled() != savedConfigState.brightness
|| config.isStripWhiteSpaceEnabled() != savedConfigState.stripWhiteSpace
|| !config.getFontFamily().getName().equalsIgnoreCase(savedConfigState.fontName)
|| config.getHorizontalMargin() != savedConfigState.hMargin
|| config.getVerticalMargin() != savedConfigState.vMargin
|| config.getTextSize() != savedConfigState.textSize
|| config.isScrollingEnabled() != savedConfigState.scrolling ) {
restartActivity();
}
Configuration.OrientationLock orientation = config
.getScreenOrientation();
switch (orientation) {
case PORTRAIT:
getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
break;
case LANDSCAPE:
getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
break;
case REVERSE_LANDSCAPE:
getActivity().setRequestedOrientation(8); // Android 2.3+ value
break;
case REVERSE_PORTRAIT:
getActivity().setRequestedOrientation(9); // Android 2.3+ value
break;
default:
getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
}
}
private void restartActivity() {
onStop();
Intent intent = new Intent(getActivity(), ReadingActivity.class);
intent.setData(Uri.parse(this.fileName));
startActivity(intent);
this.libraryService.close();
getActivity().finish();
}
public void onWindowFocusChanged(boolean hasFocus) {
if (hasFocus) {
updateFromPrefs();
} else {
getActivity().getWindow().clearFlags(
WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
}
public boolean onTouchEvent(MotionEvent event) {
return bookView.onTouchEvent(event);
}
@Override
public void bookOpened(final Book book) {
if ( ! isAdded() || getActivity() == null ) {
return;
}
this.bookTitle = book.getTitle();
this.titleBase = this.bookTitle;
getActivity().setTitle(titleBase);
this.titleBar.setText(titleBase);
getActivity().supportInvalidateOptionsMenu();
if (book.getMetadata() != null
&& !book.getMetadata().getAuthors().isEmpty()) {
Author author = book.getMetadata().getAuthors().get(0);
this.authorField.setText(author.getFirstname() + " "
+ author.getLastname());
}
backgroundHandler.post(new Runnable() {
@Override
public void run() {
try {
libraryService.storeBook(fileName, book, true,
config.isCopyToLibrayEnabled());
} catch (Exception io) {
LOG.error("Copy to library failed.", io);
}
}
});
updateFromPrefs();
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenu.ContextMenuInfo menuInfo) {
// This is a hack to give the longclick handler time
// to find the word the user long clicked on.
if (this.selectedWord != null) {
final CharSequence word = this.selectedWord;
String header = String.format(getString(R.string.word_select),
selectedWord);
menu.setHeaderTitle(header);
if (isDictionaryAvailable()) {
android.view.MenuItem item = menu
.add(getString(R.string.dictionary_lookup));
item.setOnMenuItemClickListener(new OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(android.view.MenuItem item) {
lookupDictionary(word.toString());
return true;
}
});
}
android.view.MenuItem newItem = menu
.add(getString(R.string.wikipedia_lookup));
newItem.setOnMenuItemClickListener(new OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(android.view.MenuItem item) {
lookupWikipedia(word.toString());
return true;
}
});
android.view.MenuItem newItem2 = menu
.add(getString(R.string.google_lookup));
newItem2.setOnMenuItemClickListener(new OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(android.view.MenuItem item) {
lookupGoogle(word.toString());
return true;
}
});
this.selectedWord = null;
}
}
@Override
public void highLight(int from, int to, Color color) {
// TODO Auto-generated method stub
}
@Override
public boolean isDictionaryAvailable() {
return isIntentAvailable(getActivity(), getDictionaryIntent());
}
@Override
public void lookupDictionary(String text) {
Intent intent = getDictionaryIntent();
intent.putExtra(EXTRA_QUERY, text); // Search Query
startActivityForResult(intent, 5);
}
@Override
public void lookupWikipedia(String text) {
openBrowser("http://en.wikipedia.org/wiki/Special:Search?search="
+ URLEncoder.encode(text));
}
@Override
public void lookupGoogle(String text) {
openBrowser("http://www.google.com/search?q=" + URLEncoder.encode(text));
}
private Intent getDictionaryIntent() {
final Intent intent = new Intent(PICK_RESULT_ACTION);
intent.putExtra(EXTRA_FULLSCREEN, false); //
intent.putExtra(EXTRA_HEIGHT, 400); // 400pixel, if you don't specify,
// fill_parent"
intent.putExtra(EXTRA_GRAVITY, Gravity.BOTTOM);
intent.putExtra(EXTRA_MARGIN_LEFT, 100);
return intent;
}
private void openBrowser(String url) {
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
public static boolean isIntentAvailable(Context context, Intent intent) {
final PackageManager packageManager = context.getPackageManager();
List<ResolveInfo> list = packageManager.queryIntentActivities(intent,
PackageManager.MATCH_DEFAULT_ONLY);
return list.size() > 0;
}
private void restoreColorProfile() {
this.bookView.setBackgroundColor(config.getBackgroundColor());
this.viewSwitcher.setBackgroundColor(config.getBackgroundColor());
this.pageNumberView.setBackgroundColor(config.getBackgroundColor());
this.bookView.setTextColor(config.getTextColor());
this.bookView.setLinkColor(config.getLinkColor());
int brightness = config.getBrightNess();
if (config.isBrightnessControlEnabled()) {
setScreenBrightnessLevel(brightness);
}
}
private void setScreenBrightnessLevel(int level) {
WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
lp.screenBrightness = (float) level / 100f;
getActivity().getWindow().setAttributes(lp);
}
@Override
public void errorOnBookOpening(String errorMessage) {
this.waitDialog.hide();
String message = String.format(getString(R.string.error_open_bk),
errorMessage);
bookView.setText(new SpannedString(message));
}
@Override
public void parseEntryComplete(int entry, String name) {
if ( ! isAdded() || getActivity() == null ) {
return;
}
if (name != null && !name.equals(this.bookTitle)) {
this.titleBase = this.bookTitle + " - " + name;
} else {
this.titleBase = this.bookTitle;
}
getActivity().setTitle(this.titleBase);
this.waitDialog.hide();
}
@Override
public void parseEntryStart(int entry) {
if ( ! isAdded() || getActivity() == null ) {
return;
}
this.viewSwitcher.clearAnimation();
this.viewSwitcher.setBackgroundDrawable(null);
restoreColorProfile();
displayPageNumber(-1); //Clear page number
this.waitDialog.setTitle(getString(R.string.loading_wait));
this.waitDialog.setMessage(null);
this.waitDialog.show();
}
@Override
public void readingFile() {
this.waitDialog.setTitle(R.string.opening_file);
this.waitDialog.setMessage(null);
}
@Override
public void renderingText() {
this.waitDialog.setTitle(R.string.loading_text);
this.waitDialog.setMessage(null);
}
@TargetApi(Build.VERSION_CODES.FROYO)
private boolean handleVolumeButtonEvent(KeyEvent event) {
if (!config.isVolumeKeyNavEnabled()) {
return false;
}
boolean invert = false;
int rotation = Surface.ROTATION_0;
if (Build.VERSION.SDK_INT >= 8) {
Display display = getActivity().getWindowManager().getDefaultDisplay();
rotation = display.getRotation();
}
switch (rotation) {
case Surface.ROTATION_0:
case Surface.ROTATION_90:
invert = false;
break;
case Surface.ROTATION_180:
case Surface.ROTATION_270:
invert = true;
break;
}
- if (event.getAction() != KeyEvent.ACTION_DOWN)
- return false;
- else {
- if (event.getKeyCode() == KeyEvent.KEYCODE_VOLUME_UP)
- if (invert)
- pageDown(Orientation.HORIZONTAL);
- else
- pageUp(Orientation.HORIZONTAL);
- if (event.getKeyCode() == KeyEvent.KEYCODE_VOLUME_DOWN)
- if (invert)
- pageUp(Orientation.HORIZONTAL);
- else
- pageDown(Orientation.HORIZONTAL);
+ if (event.getAction() != KeyEvent.ACTION_DOWN) {
return true;
- }
+ }
+
+ if (event.getKeyCode() == KeyEvent.KEYCODE_VOLUME_UP) {
+ if (invert) {
+ pageDown(Orientation.HORIZONTAL);
+ }
+ else {
+ pageUp(Orientation.HORIZONTAL);
+ }
+ } else if (event.getKeyCode() == KeyEvent.KEYCODE_VOLUME_DOWN) {
+ if (invert) {
+ pageUp(Orientation.HORIZONTAL);
+ } else {
+ pageDown(Orientation.HORIZONTAL);
+ }
+ }
+
+ return true;
}
public boolean dispatchKeyEvent(KeyEvent event) {
int action = event.getAction();
int keyCode = event.getKeyCode();
if (isAnimating() && action == KeyEvent.ACTION_DOWN) {
stopAnimating();
return true;
}
switch (keyCode) {
case KeyEvent.KEYCODE_VOLUME_DOWN:
case KeyEvent.KEYCODE_VOLUME_UP:
return handleVolumeButtonEvent(event);
case KeyEvent.KEYCODE_DPAD_RIGHT:
if (action == KeyEvent.ACTION_DOWN) {
pageDown(Orientation.HORIZONTAL);
}
return true;
case KeyEvent.KEYCODE_DPAD_LEFT:
if (action == KeyEvent.ACTION_DOWN) {
pageUp(Orientation.HORIZONTAL);
}
return true;
case KeyEvent.KEYCODE_BACK:
if (action == KeyEvent.ACTION_DOWN) {
if (titleBarLayout.getVisibility() == View.VISIBLE) {
hideTitleBar();
} else if (bookView.hasPrevPosition()) {
bookView.goBackInHistory();
return true;
} else {
getActivity().finish();
}
}
}
return false;
}
private boolean isAnimating() {
Animator anim = dummyView.getAnimator();
return anim != null && !anim.isFinished();
}
private void startAutoScroll() {
if (viewSwitcher.getCurrentView() == this.dummyView) {
viewSwitcher.showNext();
}
this.viewSwitcher.setInAnimation(null);
this.viewSwitcher.setOutAnimation(null);
bookView.setKeepScreenOn(true);
ScrollStyle style = config.getAutoScrollStyle();
if (style == ScrollStyle.ROLLING_BLIND) {
prepareRollingBlind();
} else {
preparePageTimer();
}
viewSwitcher.showNext();
uiHandler.post(new AutoScrollRunnable());
}
private void prepareRollingBlind() {
Bitmap before = getBookViewSnapshot();
bookView.pageDown();
Bitmap after = getBookViewSnapshot();
RollingBlindAnimator anim = new RollingBlindAnimator();
anim.setAnimationSpeed(config.getScrollSpeed());
anim.setBackgroundBitmap(before);
anim.setForegroundBitmap(after);
dummyView.setAnimator(anim);
}
private void preparePageTimer() {
bookView.pageDown();
Bitmap after = getBookViewSnapshot();
PageTimer timer = new PageTimer(after, pageNumberView.getHeight());
timer.setSpeed(config.getScrollSpeed());
dummyView.setAnimator(timer);
}
private void doPageCurl(boolean flipRight) {
if (isAnimating() || bookView == null ) {
return;
}
this.viewSwitcher.setInAnimation(null);
this.viewSwitcher.setOutAnimation(null);
if (viewSwitcher.getCurrentView() == this.dummyView) {
viewSwitcher.showNext();
}
Bitmap before = getBookViewSnapshot();
this.pageNumberView.setVisibility(View.GONE);
PageCurlAnimator animator = new PageCurlAnimator(flipRight);
// Pagecurls should only take a few frames. When the screen gets
// bigger, so do the frames.
animator.SetCurlSpeed(bookView.getWidth() / 8);
animator.setBackgroundColor(config.getBackgroundColor());
if (flipRight) {
bookView.pageDown();
Bitmap after = getBookViewSnapshot();
animator.setBackgroundBitmap(after);
animator.setForegroundBitmap(before);
} else {
bookView.pageUp();
Bitmap after = getBookViewSnapshot();
animator.setBackgroundBitmap(before);
animator.setForegroundBitmap(after);
}
dummyView.setAnimator(animator);
this.viewSwitcher.showNext();
uiHandler.post(new PageCurlRunnable(animator));
dummyView.invalidate();
}
private class PageCurlRunnable implements Runnable {
private PageCurlAnimator animator;
public PageCurlRunnable(PageCurlAnimator animator) {
this.animator = animator;
}
@Override
public void run() {
if (this.animator.isFinished()) {
if (viewSwitcher.getCurrentView() == dummyView) {
viewSwitcher.showNext();
}
dummyView.setAnimator(null);
pageNumberView.setVisibility(View.VISIBLE);
} else {
this.animator.advanceOneFrame();
dummyView.invalidate();
int delay = 1000 / this.animator.getAnimationSpeed();
uiHandler.postDelayed(this, delay);
}
}
}
private class AutoScrollRunnable implements Runnable {
@Override
public void run() {
if (dummyView.getAnimator() == null) {
LOG.debug("BookView no longer has an animator. Aborting rolling blind.");
stopAnimating();
} else {
Animator anim = dummyView.getAnimator();
if (anim.isFinished()) {
startAutoScroll();
} else {
anim.advanceOneFrame();
dummyView.invalidate();
uiHandler.postDelayed(this, anim.getAnimationSpeed() * 2);
}
}
}
}
private void stopAnimating() {
if (dummyView.getAnimator() != null) {
dummyView.getAnimator().stop();
this.dummyView.setAnimator(null);
}
if (viewSwitcher.getCurrentView() == this.dummyView) {
viewSwitcher.showNext();
}
this.pageNumberView.setVisibility(View.VISIBLE);
bookView.setKeepScreenOn(false);
}
private Bitmap getBookViewSnapshot() {
try {
Bitmap bitmap = Bitmap.createBitmap(viewSwitcher.getWidth(),
viewSwitcher.getHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
bookView.layout(0, 0, viewSwitcher.getWidth(),
viewSwitcher.getHeight());
bookView.draw(canvas);
if (config.isShowPageNumbers()) {
/**
* FIXME: creating an intermediate bitmap here because I can't
* figure out how to draw the pageNumberView directly on the
* canvas and have it show up in the right place.
*/
Bitmap pageNumberBitmap = Bitmap.createBitmap(
pageNumberView.getWidth(), pageNumberView.getHeight(),
Config.ARGB_8888);
Canvas pageNumberCanvas = new Canvas(pageNumberBitmap);
pageNumberView.layout(0, 0, pageNumberView.getWidth(),
pageNumberView.getHeight());
pageNumberView.draw(pageNumberCanvas);
canvas.drawBitmap(pageNumberBitmap, 0, viewSwitcher.getHeight()
- pageNumberView.getHeight(), new Paint());
pageNumberBitmap.recycle();
}
return bitmap;
} catch (OutOfMemoryError out) {
viewSwitcher.setBackgroundColor(config.getBackgroundColor());
}
return null;
}
private void prepareSlide(Animation inAnim, Animation outAnim) {
Bitmap bitmap = getBookViewSnapshot();
dummyView.setImageBitmap(bitmap);
this.pageNumberView.setVisibility(View.GONE);
inAnim.setAnimationListener(new Animation.AnimationListener() {
public void onAnimationStart(Animation animation) {}
public void onAnimationRepeat(Animation animation) {}
@Override
public void onAnimationEnd(Animation animation) {
onSlideFinished();
}
});
viewSwitcher.layout(0, 0, viewSwitcher.getWidth(),
viewSwitcher.getHeight());
dummyView.layout(0, 0, viewSwitcher.getWidth(),
viewSwitcher.getHeight());
this.viewSwitcher.showNext();
this.viewSwitcher.setInAnimation(inAnim);
this.viewSwitcher.setOutAnimation(outAnim);
}
private void onSlideFinished() {
if ( currentPageNumber > 0 ) {
this.pageNumberView.setVisibility(View.VISIBLE);
}
}
private void pageDown(Orientation o) {
if (bookView.isAtEnd()) {
return;
}
stopAnimating();
if (o == Orientation.HORIZONTAL) {
AnimationStyle animH = config.getHorizontalAnim();
if (animH == AnimationStyle.CURL) {
doPageCurl(true);
} else if (animH == AnimationStyle.SLIDE) {
prepareSlide(Animations.inFromRightAnimation(),
Animations.outToLeftAnimation());
viewSwitcher.showNext();
bookView.pageDown();
} else {
bookView.pageDown();
}
} else {
if (config.getVerticalAnim() == AnimationStyle.SLIDE) {
prepareSlide(Animations.inFromBottomAnimation(),
Animations.outToTopAnimation());
viewSwitcher.showNext();
}
bookView.pageDown();
}
}
private void pageUp(Orientation o) {
if (bookView.isAtStart()) {
return;
}
stopAnimating();
if (o == Orientation.HORIZONTAL) {
AnimationStyle animH = config.getHorizontalAnim();
if (animH == AnimationStyle.CURL) {
doPageCurl(false);
} else if (animH == AnimationStyle.SLIDE) {
prepareSlide(Animations.inFromLeftAnimation(),
Animations.outToRightAnimation());
viewSwitcher.showNext();
bookView.pageUp();
} else {
bookView.pageUp();
}
} else {
if (config.getVerticalAnim() == AnimationStyle.SLIDE) {
prepareSlide(Animations.inFromTopAnimation(),
Animations.outToBottomAnimation());
viewSwitcher.showNext();
}
bookView.pageUp();
}
}
@Override
public void onPrepareOptionsMenu(Menu menu) {
if (this.tocDialog == null) {
initTocDialog();
}
MenuItem nightMode = menu.findItem(R.id.profile_night);
MenuItem dayMode = menu.findItem(R.id.profile_day);
MenuItem showToc = menu.findItem(R.id.show_toc);
showToc.setEnabled(this.tocDialog != null);
getSherlockActivity().getSupportActionBar().show();
if (config.getColourProfile() == ColourProfile.DAY) {
dayMode.setVisible(false);
nightMode.setVisible(true);
} else {
dayMode.setVisible(true);
nightMode.setVisible(false);
}
// Only show open file item if we have a file manager installed
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("file/*");
intent.addCategory(Intent.CATEGORY_OPENABLE);
if (!isIntentAvailable(getActivity(), intent)) {
menu.findItem(R.id.open_file).setVisible(false);
}
getActivity().getWindow().addFlags(
WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
getActivity().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
private void hideTitleBar() {
titleBarLayout.setVisibility(View.GONE);
}
/**
* This is called after the file manager finished.
*/
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK && data != null) {
// obtain the filename
Uri fileUri = data.getData();
if (fileUri != null) {
String filePath = fileUri.getPath();
if (filePath != null) {
loadNewBook(filePath);
}
}
}
}
private void loadNewBook(String fileName) {
getActivity().setTitle(R.string.app_name);
this.tocDialog = null;
this.bookTitle = null;
this.titleBase = null;
bookView.clear();
updateFileName(null, fileName);
new DownloadProgressTask().execute();
}
@Override
public void onStop() {
super.onStop();
saveReadingPosition();
this.waitDialog.dismiss();
}
private void saveReadingPosition() {
if (this.bookView != null) {
int index = this.bookView.getIndex();
int position = this.bookView.getPosition();
if ( index != -1 && position != -1 ) {
config.setLastPosition(this.fileName, position);
config.setLastIndex(this.fileName, index);
sendProgressUpdateToServer(index, position);
}
}
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.reading_menu, menu);
}
@Override
public void onOptionsMenuClosed(android.view.Menu menu) {
updateFromPrefs();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
hideTitleBar();
// Handle item selection
switch (item.getItemId()) {
case R.id.profile_night:
config.setColourProfile(ColourProfile.NIGHT);
this.restartActivity();
return true;
case R.id.profile_day:
config.setColourProfile(ColourProfile.DAY);
this.restartActivity();
return true;
case R.id.manual_sync:
if (config.isSyncEnabled()) {
new ManualProgressSync().execute();
} else {
Toast.makeText(getActivity(), R.string.enter_email, Toast.LENGTH_LONG)
.show();
}
return true;
case R.id.search_text:
onSearchClick();
return true;
case R.id.preferences:
saveConfigState();
Intent i = new Intent(getActivity(), PageTurnerPrefsActivity.class);
startActivity(i);
return true;
case R.id.show_toc:
this.tocDialog.show();
return true;
case R.id.open_file:
launchFileManager();
return true;
case R.id.open_library:
launchLibrary();
return true;
case R.id.rolling_blind:
startAutoScroll();
return true;
case R.id.about:
Dialogs.showAboutDialog(getActivity());
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public boolean onSwipeDown() {
if (config.isVerticalSwipeEnabled()) {
pageDown(Orientation.VERTICAL);
return true;
}
return false;
}
@Override
public boolean onSwipeUp() {
if (config.isVerticalSwipeEnabled()) {
pageUp(Orientation.VERTICAL);
return true;
}
return false;
}
@Override
public void onScreenTap() {
stopAnimating();
if (this.titleBarLayout.getVisibility() == View.VISIBLE) {
titleBarLayout.setVisibility(View.GONE);
updateFromPrefs();
} else {
titleBarLayout.setVisibility(View.VISIBLE);
getSherlockActivity().getSupportActionBar().show();
getActivity().getWindow().addFlags(
WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
getActivity().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
}
@Override
public boolean onSwipeLeft() {
if (config.isHorizontalSwipeEnabled()) {
pageDown(Orientation.HORIZONTAL);
return true;
}
return false;
}
@Override
public boolean onSwipeRight() {
if (config.isHorizontalSwipeEnabled()) {
pageUp(Orientation.HORIZONTAL);
return true;
}
return false;
}
@Override
public boolean onTapLeftEdge() {
if (config.isHorizontalTappingEnabled()) {
pageUp(Orientation.HORIZONTAL);
return true;
}
return false;
}
@Override
public boolean onTapRightEdge() {
if (config.isHorizontalTappingEnabled()) {
pageDown(Orientation.HORIZONTAL);
return true;
}
return false;
}
@Override
public boolean onTapTopEdge() {
if (config.isVerticalTappingEnabled()) {
pageUp(Orientation.VERTICAL);
return true;
}
return false;
}
@Override
public boolean onTapBottomEdge() {
if (config.isVerticalTappingEnabled()) {
pageDown(Orientation.VERTICAL);
return true;
}
return false;
}
@Override
public boolean onLeftEdgeSlide(int value) {
if (config.isBrightnessControlEnabled() && value != 0) {
int baseBrightness = config.getBrightNess();
int brightnessLevel = Math.min(99, value + baseBrightness);
brightnessLevel = Math.max(1, brightnessLevel);
final int level = brightnessLevel;
String brightness = getString(R.string.brightness);
setScreenBrightnessLevel(brightnessLevel);
if (brightnessToast == null) {
brightnessToast = Toast
.makeText(getActivity(), brightness + ": "
+ brightnessLevel, Toast.LENGTH_SHORT);
} else {
brightnessToast.setText(brightness + ": " + brightnessLevel);
}
brightnessToast.show();
backgroundHandler.post(new Runnable() {
@Override
public void run() {
config.setBrightness(level);
}
});
return true;
}
return false;
}
@Override
public boolean onRightEdgeSlide(int value) {
return false;
}
@Override
public void onWordLongPressed(CharSequence word) {
this.selectedWord = word;
getActivity().openContextMenu(bookView);
}
private void launchFileManager() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("file/*");
intent.addCategory(Intent.CATEGORY_OPENABLE);
try {
startActivityForResult(intent, REQUEST_CODE_GET_CONTENT);
} catch (ActivityNotFoundException e) {
// No compatible file manager was found.
Toast.makeText(getActivity(), getString(R.string.install_oi),
Toast.LENGTH_SHORT).show();
}
}
private void launchLibrary() {
Intent intent = new Intent(getActivity(), LibraryActivity.class);
startActivity(intent);
saveReadingPosition();
this.bookView.releaseResources();
getActivity().finish();
}
private void showPickProgressDialog(final List<BookProgress> results) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(getString(R.string.cloud_bm));
ProgressListAdapter adapter = new ProgressListAdapter(getActivity(), bookView, results);
builder.setAdapter(adapter, adapter);
AlertDialog dialog = builder.create();
dialog.setOwnerActivity(getActivity());
dialog.show();
}
private void initTocDialog() {
if (this.tocDialog != null) {
return;
}
final List<BookView.TocEntry> tocList = this.bookView
.getTableOfContents();
if (tocList == null || tocList.isEmpty()) {
return;
}
final CharSequence[] items = new CharSequence[tocList.size()];
for (int i = 0; i < items.length; i++) {
items[i] = tocList.get(i).getTitle();
}
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.toc_label);
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
bookView.navigateTo(tocList.get(item).getHref());
}
});
this.tocDialog = builder.create();
this.tocDialog.setOwnerActivity(getActivity());
}
@Override
public void onSaveInstanceState(final Bundle outState) {
if (this.bookView != null) {
outState.putInt(POS_KEY, this.bookView.getPosition());
outState.putInt(IDX_KEY, this.bookView.getIndex());
sendProgressUpdateToServer();
libraryService.close();
}
}
private void sendProgressUpdateToServer(final int index, final int position) {
/*
* If either percentage or position is 0 or -1,
* chances are good this update would be invalid
*/
if ( progressPercentage < 1 || position < 1 ) {
return;
}
backgroundHandler.post(new Runnable() {
@Override
public void run() {
try {
libraryService.updateReadingProgress(fileName, progressPercentage);
progressService.storeProgress(fileName,
index, position,
progressPercentage);
} catch (Exception e) {
LOG.error("Error saving progress", e);
}
}
});
}
private void sendProgressUpdateToServer() {
final int index = bookView.getIndex();
final int position = bookView.getPosition();
sendProgressUpdateToServer(index, position);
}
private void onSearchClick() {
final ProgressDialog searchProgress = new ProgressDialog(getActivity());
searchProgress.setOwnerActivity(getActivity());
searchProgress.setCancelable(true);
searchProgress.setMax(100);
searchProgress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
AlertDialog.Builder alert = new AlertDialog.Builder(getActivity());
alert.setTitle(R.string.search_text);
alert.setMessage(R.string.enter_query);
// Set an EditText view to get user input
final EditText input = new EditText(getActivity());
alert.setView(input);
final SearchTextTask task = new SearchTextTask(bookView.getBook()) {
int i = 0;
@Override
protected void onPreExecute() {
super.onPreExecute();
// Hide on-screen keyboard if it is showing
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Activity.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);
}
@Override
protected void onProgressUpdate(SearchResult... values) {
super.onProgressUpdate(values);
LOG.debug("Found match at index=" + values[0].getIndex()
+ ", offset=" + values[0].getStart() + " with context "
+ values[0].getDisplay());
SearchResult res = values[0];
if (res.getDisplay() != null) {
i++;
String update = String.format(
getString(R.string.search_hits), i);
searchProgress.setTitle(update);
}
searchProgress.setProgress(res.getPercentage());
}
@Override
protected void onCancelled() {
Toast.makeText(getActivity(), R.string.search_cancelled,
Toast.LENGTH_LONG).show();
}
protected void onPostExecute(java.util.List<SearchResult> result) {
searchProgress.dismiss();
if (!isCancelled()) {
if (result.size() > 0) {
showSearchResultDialog(result);
} else {
Toast.makeText(getActivity(),
R.string.search_no_matches, Toast.LENGTH_LONG)
.show();
}
}
};
};
searchProgress
.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
task.cancel(true);
}
});
alert.setPositiveButton(android.R.string.search_go,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
CharSequence value = input.getText();
searchProgress.setTitle(R.string.search_wait);
searchProgress.show();
task.execute(value.toString());
}
});
alert.setNegativeButton(android.R.string.cancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
}
});
alert.show();
}
private void showSearchResultDialog(
final List<SearchTextTask.SearchResult> results) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.search_results);
SearchResultAdapter adapter = new SearchResultAdapter(getActivity(), bookView, results);
builder.setAdapter(adapter, adapter);
AlertDialog dialog = builder.create();
dialog.setOwnerActivity(getActivity());
dialog.show();
}
private class ManualProgressSync extends
AsyncTask<Void, Integer, List<BookProgress>> {
private boolean accessDenied = false;
@Override
protected void onPreExecute() {
waitDialog.setTitle(R.string.syncing);
waitDialog.show();
}
@Override
protected List<BookProgress> doInBackground(Void... params) {
try {
return progressService.getProgress(fileName);
} catch (AccessException e) {
accessDenied = true;
return null;
}
}
@Override
protected void onPostExecute(List<BookProgress> progress) {
waitDialog.hide();
if (progress == null) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(
getActivity());
alertDialog.setTitle(R.string.sync_failed);
if (accessDenied) {
alertDialog.setMessage(R.string.access_denied);
} else {
alertDialog.setMessage(R.string.connection_fail);
}
alertDialog.setNeutralButton(android.R.string.ok,
new OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
dialog.dismiss();
}
});
alertDialog.show();
} else {
showPickProgressDialog(progress);
}
}
}
private class DownloadProgressTask extends
AsyncTask<Void, Integer, BookProgress> {
@Override
protected void onPreExecute() {
waitDialog.setTitle(R.string.syncing);
waitDialog.show();
}
@Override
protected BookProgress doInBackground(Void... params) {
try {
List<BookProgress> updates = progressService
.getProgress(fileName);
if (updates != null && updates.size() > 0) {
return updates.get(0);
}
} catch (AccessException e) {
}
return null;
}
@Override
protected void onPostExecute(BookProgress progress) {
waitDialog.hide();
int index = bookView.getIndex();
int pos = bookView.getPosition();
if (progress != null) {
if (progress.getIndex() > index) {
bookView.setIndex(progress.getIndex());
bookView.setPosition(progress.getProgress());
} else if (progress.getIndex() == index) {
pos = Math.max(pos, progress.getProgress());
bookView.setPosition(pos);
}
}
bookView.restore();
}
}
}
class ScreenReceiver extends BroadcastReceiver {
public static boolean wasScreenOn = true;
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
// do whatever you need to do here
wasScreenOn = false;
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
// and do whatever you need to do here
wasScreenOn = true;
}
}
}
| false | false | null | null |
diff --git a/src/net/sf/freecol/client/gui/Canvas.java b/src/net/sf/freecol/client/gui/Canvas.java
index 84daea480..1031d415b 100644
--- a/src/net/sf/freecol/client/gui/Canvas.java
+++ b/src/net/sf/freecol/client/gui/Canvas.java
@@ -1,1852 +1,1855 @@
package net.sf.freecol.client.gui;
import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.Rectangle;
import java.awt.event.KeyListener;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.MissingResourceException;
import java.util.logging.Logger;
import javax.swing.JComponent;
import javax.swing.JLayeredPane;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.UIManager;
import javax.swing.filechooser.FileFilter;
import net.sf.freecol.client.FreeColClient;
import net.sf.freecol.client.gui.i18n.Messages;
import net.sf.freecol.client.gui.panel.*;
import net.sf.freecol.common.model.Colony;
import net.sf.freecol.common.model.Europe;
import net.sf.freecol.common.model.FreeColGameObject;
import net.sf.freecol.common.model.Game;
import net.sf.freecol.common.model.IndianSettlement;
import net.sf.freecol.common.model.Map;
import net.sf.freecol.common.model.ModelMessage;
import net.sf.freecol.common.model.Player;
import net.sf.freecol.common.model.Tile;
import net.sf.freecol.common.model.WorkLocation;
import net.sf.freecol.common.model.Map.Position;
/**
* The main container for the other GUI components in FreeCol.
* This container is where the panels, dialogs and menus are added.
* In addition, this is the component in which the map graphics are displayed.
*
* <br><br>
*
* <br><b>Displaying panels and a dialogs</b>
* <br><br>
*
* <code>Canvas</code> contains methods to display various panels
* and dialogs. Most of these methods use
* {@link net.sf.freecol.client.gui.i18n i18n} to get localized
* text. Here is an example:
*
* <br>
*
* <PRE>
* if (canvas.showConfirmDialog("choice.text", "choice.yes", "choice.no")) {
* // DO SOMETHING.
* }
* </PRE>
*
* <br>
*
* where "choice.text", "choice.yes" and "choice.no" are keys for a localized
* message. See {@link net.sf.freecol.client.gui.i18n i18n} for more
* information.
*
* <br><br>
*
* <br><b>The difference between a panel and a dialog</b>
* <br><br>
*
* When displaying a dialog, using a <code>showXXXDialog</code>, the calling thread
* will wait until that dialog is dismissed before returning. In contrast, a
* <code>showXXXPanel</code>-method returns immediatly.
*/
public final class Canvas extends JLayeredPane {
private static final Logger logger = Logger.getLogger(Canvas.class.getName());
public static final String COPYRIGHT = "Copyright (C) 2003-2005 The FreeCol Team";
public static final String LICENSE = "http://www.gnu.org/licenses/gpl.html";
public static final String REVISION = "$Revision$";
public static final Integer START_GAME_LAYER = DEFAULT_LAYER,
SERVER_LIST_LAYER = DEFAULT_LAYER,
VICTORY_LAYER = DEFAULT_LAYER,
CHAT_LAYER = DEFAULT_LAYER,
NEW_GAME_LAYER = DEFAULT_LAYER,
MODEL_MESSAGE_LAYER = new Integer(DEFAULT_LAYER.intValue() + 11),
CONFIRM_LAYER = new Integer(DEFAULT_LAYER.intValue() + 12),
GAME_OPTIONS_LAYER = new Integer(DEFAULT_LAYER.intValue() + 9),
CLIENT_OPTIONS_LAYER = new Integer(DEFAULT_LAYER.intValue() + 9),
LOAD_LAYER = new Integer(DEFAULT_LAYER.intValue() + 10),
SAVE_LAYER = new Integer(DEFAULT_LAYER.intValue() + 10),
SCOUT_INDIAN_SETTLEMENT_LAYER = new Integer(DEFAULT_LAYER.intValue() + 9),
USE_MISSIONARY_LAYER = new Integer(DEFAULT_LAYER.intValue() + 9),
INCITE_LAYER = new Integer(DEFAULT_LAYER.intValue() + 9),
INPUT_LAYER = new Integer(DEFAULT_LAYER.intValue() + 11),
CHOICE_LAYER = new Integer(DEFAULT_LAYER.intValue() + 11),
STATUS_LAYER = new Integer(DEFAULT_LAYER.intValue() + 7),
COLOPEDIA_LAYER = new Integer(DEFAULT_LAYER.intValue() + 1),
REPORT_LAYER = new Integer(DEFAULT_LAYER.intValue() + 1),
MAIN_LAYER = DEFAULT_LAYER,
QUIT_LAYER = new Integer(DEFAULT_LAYER.intValue() + 15),
INFORMATION_LAYER = new Integer(DEFAULT_LAYER.intValue() + 13),
ERROR_LAYER = new Integer(DEFAULT_LAYER.intValue() + 13),
EMIGRATION_LAYER = new Integer(DEFAULT_LAYER.intValue() + 1),
MONARCH_LAYER = new Integer(DEFAULT_LAYER.intValue() + 1),
TILE_LAYER = new Integer(DEFAULT_LAYER.intValue() + 1),
INDIAN_SETTLEMENT_LAYER = DEFAULT_LAYER,
COLONY_LAYER = DEFAULT_LAYER,
EUROPE_LAYER = DEFAULT_LAYER,
EVENT_LAYER = new Integer(DEFAULT_LAYER.intValue() + 1),
CHOOSE_FOUNDING_FATHER = new Integer(DEFAULT_LAYER.intValue() + 1);
private final FreeColClient freeColClient;
private final MainPanel mainPanel;
private final NewPanel newPanel;
private final ErrorPanel errorPanel;
private final StartGamePanel startGamePanel;
private final QuitDialog quitDialog;
private final ColonyPanel colonyPanel;
private final IndianSettlementPanel indianSettlementPanel;
private final TilePanel tilePanel;
private final MonarchPanel monarchPanel;
private final EuropePanel europePanel;
private final StatusPanel statusPanel;
private final ChatPanel chatPanel;
private final GUI gui;
private final ChatDisplayThread chatDisplayThread;
private final VictoryPanel victoryPanel;
private final ChooseFoundingFatherDialog chooseFoundingFatherDialog;
private final EventPanel eventPanel;
private final EmigrationPanel emigrationPanel;
private final ColopediaPanel colopediaPanel;
private final ReportReligiousPanel reportReligiousPanel;
private final ReportTradePanel reportTradePanel;
private final ReportLabourPanel reportLabourPanel;
private final ReportForeignAffairPanel reportForeignAffairPanel;
private final ReportIndianPanel reportIndianPanel;
private final ReportContinentalCongressPanel reportContinentalCongressPanel;
private final ServerListPanel serverListPanel;
private final GameOptionsDialog gameOptionsDialog;
private final ClientOptionsDialog clientOptionsDialog;
private final DeclarationDialog declarationDialog;
private TakeFocusThread takeFocusThread;
private JMenuBar jMenuBar;
/**
* The constructor to use.
*
* @param client main control class.
* @param bounds The bounds of this <code>Canvas</code>.
* @param gui The object responsible of drawing the map onto this component.
*/
public Canvas(FreeColClient client, Rectangle bounds, GUI gui) {
this.freeColClient = client;
this.gui = gui;
setBounds(bounds);
setOpaque(false);
setLayout(null);
takeFocusThread = null;
mainPanel = new MainPanel(this, freeColClient);
newPanel = new NewPanel(this, freeColClient.getConnectController());
errorPanel = new ErrorPanel(this);
startGamePanel = new StartGamePanel(this, freeColClient);
serverListPanel = new ServerListPanel(this, freeColClient, freeColClient.getConnectController());
quitDialog = new QuitDialog(this);
colonyPanel = new ColonyPanel(this, freeColClient);
indianSettlementPanel = new IndianSettlementPanel();
tilePanel = new TilePanel(this);
monarchPanel = new MonarchPanel(this);
declarationDialog = new DeclarationDialog(this, freeColClient);
europePanel = new EuropePanel(this, freeColClient, freeColClient.getInGameController());
statusPanel = new StatusPanel(this);
chatPanel = new ChatPanel(this, freeColClient);
victoryPanel = new VictoryPanel(this, freeColClient);
chooseFoundingFatherDialog = new ChooseFoundingFatherDialog(this);
eventPanel = new EventPanel(this, freeColClient);
emigrationPanel = new EmigrationPanel();
colopediaPanel = new ColopediaPanel(this);
reportReligiousPanel = new ReportReligiousPanel(this);
reportTradePanel = new ReportTradePanel(this);
reportLabourPanel = new ReportLabourPanel(this);
reportForeignAffairPanel = new ReportForeignAffairPanel(this);
reportIndianPanel = new ReportIndianPanel(this);
reportContinentalCongressPanel = new ReportContinentalCongressPanel(this);
gameOptionsDialog = new GameOptionsDialog(this, freeColClient);
clientOptionsDialog = new ClientOptionsDialog(this, freeColClient);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
//takeFocus();
chatDisplayThread = new ChatDisplayThread();
chatDisplayThread.start();
Runtime runtime = Runtime.getRuntime();
runtime.addShutdownHook(new Thread() {
public void run() {
freeColClient.getConnectController().quitGame(true);
}
});
logger.info("Canvas created.");
}
/**
* Returns the <code>ClientOptionsDialog</code>.
*
* @return The <code>ClientOptionsDialog</code>
* @see net.sf.freecol.client.ClientOptions
*/
public ClientOptionsDialog getClientOptionsDialog() {
return clientOptionsDialog;
}
/**
* Sets the menu bar. The menu bar will be resized to fit the width
* of the gui and made visible.
*
* @param mb The menu bar.
* @see FreeColMenuBar
*/
public void setJMenuBar(JMenuBar mb) {
if (jMenuBar != null) {
remove(jMenuBar);
}
Image menuborderImage = (Image) UIManager.get("menuborder.image");
if (menuborderImage == null) {
mb.setLocation(0, 0);
} else {
mb.setLocation(0, menuborderImage.getHeight(null));
}
mb.setSize(getWidth(), (int) mb.getPreferredSize().getHeight());
add(mb);
jMenuBar = mb;
}
/**
* Gets the menu bar.
* @return The menu bar.
* @see FreeColMenuBar
*/
public JMenuBar getJMenuBar() {
return jMenuBar;
}
/**
* Updates the label displaying the current amount of gold.
*/
public void updateGoldLabel() {
getJMenuBar().repaint();
}
/**
* Paints this component. This method will use
* {@link GUI#display} to draw the map/background on this component.
*
* @param g The Graphics context in which to draw this component.
* @see GUI#display
*/
public void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
gui.display(g2d);
// Draw menubar border:
if (jMenuBar != null) {
Image menuborderImage = (Image) UIManager.get("menuborder.image");
if (menuborderImage != null) {
int width = getWidth();
for (int x=0; x<width; x+=menuborderImage.getWidth(null)) {
g.drawImage(menuborderImage, x, 0, null);
g.drawImage(menuborderImage, x, menuborderImage.getHeight(null) + jMenuBar.getHeight(), null);
}
}
}
}
/**
* Gets the height of the menu bar.
* @return The menubar + any borders.
*/
public int getMenuBarHeight() {
if (jMenuBar == null) {
return 0;
} else {
int height = jMenuBar.getHeight();
Image menuborderImage = (Image) UIManager.get("menuborder.image");
if (menuborderImage != null) {
height += menuborderImage.getHeight(null) * 2;
}
return height;
}
}
/**
* Displays the <code>StartGamePanel</code>.
*
* @param game The <code>Game</code> that is about to start.
* @param player The <code>Player</code> using this client.
* @param singlePlayerMode 'true' if the user wants to start a single player game,
* 'false' otherwise.
* @see StartGamePanel
*/
public void showStartGamePanel(Game game, Player player, boolean singlePlayerMode) {
closeMenus();
if (game != null && player != null) {
startGamePanel.initialize(singlePlayerMode);
addCentered(startGamePanel, START_GAME_LAYER);
startGamePanel.requestFocus();
} else {
logger.warning("Tried to open 'StartGamePanel' without having 'game' and/or 'player' set.");
}
}
/**
* Displays the <code>ServerListPanel</code>.
*
* @param username The username that should be used when connecting
* to one of the servers on the list.
* @param serverList The list containing the servers retrived from the
* metaserver.
* @see ServerListPanel
*/
public void showServerListPanel(String username, ArrayList serverList) {
closeMenus();
serverListPanel.initialize(username, serverList);
addCentered(serverListPanel, SERVER_LIST_LAYER);
serverListPanel.requestFocus();
}
/**
* Displays the <code>VictoryPanel</code>.
* @see VictoryPanel
*/
public void showVictoryPanel() {
closeMenus();
setEnabled(false);
addCentered(victoryPanel);
victoryPanel.requestFocus();
}
/**
* Displays the <code>ChatPanel</code>.
* @see ChatPanel
*/
public void showChatPanel() {
closeMenus();
setEnabled(false);
addCentered(chatPanel);
chatPanel.requestFocus();
}
/**
* Displays the <code>NewGamePanel</code>.
* @see NewPanel
*/
public void showNewGamePanel() {
closeMenus();
addCentered(newPanel);
newPanel.requestFocus();
}
/**
* Displays a <code>ModelMessage</code> in a modal dialog.
* The message is displayed in this way:
*
* <ol>
* <li>The <code>messageID</code> is used to get the message from
* {@link net.sf.freecol.client.gui.i18n.Messages#message(String)}.
* <li>Every occuranse of <code>data[x][0]</code> is replaced with
* <code>data[x][1]</code> for every <code>x</code>.
* <li>The message is displayed using a modal dialog.
* </ol>
*
* A specialized panel may be used. In this case the <code>messageID</code>
* of the <code>ModelMessage</code> if used as a key for this panel.
*
* @param m The <code>ModelMessage</code> to be displayed.
*/
public void showModelMessage(ModelMessage m) {
String okText = "ok";
String cancelText = "display";
String message = m.getMessageID();
if (message.equals("EventPanel.MEETING_EUROPEANS")) {
// Skip for now:
//showEventDialog(EventPanel.MEETING_EUROPEANS);
freeColClient.getInGameController().nextModelMessage();
} else if (message.equals("EventPanel.MEETING_NATIVES")) {
// Skip for now:
//showEventDialog(EventPanel.MEETING_NATIVES);
freeColClient.getInGameController().nextModelMessage();
} else if (message.equals("EventPanel.MEETING_AZTEC")) {
// Skip for now:
//showEventDialog(EventPanel.MEETING_AZTEC);
freeColClient.getInGameController().nextModelMessage();
} else if (message.equals("EventPanel.MEETING_INCA")) {
// Skip for now:
//showEventDialog(EventPanel.MEETING_INCA);
freeColClient.getInGameController().nextModelMessage();
} else {
try {
okText = Messages.message(okText);
cancelText = Messages.message(cancelText);
message = Messages.message(message, m.getData());
} catch (MissingResourceException e) {
logger.warning("could not find message with id: " + okText + ".");
}
FreeColGameObject source = m.getSource();
if (source instanceof Europe && !europePanel.isShowing() ||
(source instanceof Colony || source instanceof WorkLocation) && !colonyPanel.isShowing()) {
FreeColDialog confirmDialog = FreeColDialog.createConfirmDialog(message, okText, cancelText);
addCentered(confirmDialog, MODEL_MESSAGE_LAYER);
confirmDialog.requestFocus();
if (!confirmDialog.getResponseBoolean()) {
remove(confirmDialog);
if (source instanceof Europe) {
showEuropePanel();
} else if (source instanceof Colony) {
showColonyPanel((Colony) source);
} else if (source instanceof WorkLocation) {
showColonyPanel(((WorkLocation) source).getColony());
}
} else {
remove(confirmDialog);
freeColClient.getInGameController().nextModelMessage();
}
} else {
FreeColDialog informationDialog = FreeColDialog.createInformationDialog(message, okText);
addCentered(informationDialog, MODEL_MESSAGE_LAYER);
informationDialog.requestFocus();
informationDialog.getResponse();
remove(informationDialog);
freeColClient.getInGameController().nextModelMessage();
}
}
}
public void showModelMessages(ModelMessage[] modelMessages) {
String okText = "ok";
String cancelText = "display";
//String message = m.getMessageID();
String[] messageText = new String[modelMessages.length];
try {
okText = Messages.message(okText);
} catch (MissingResourceException e) {
logger.warning("could not find message with id: " + okText + ".");
}
try {
cancelText = Messages.message(cancelText);
} catch (MissingResourceException e) {
logger.warning("could not find message with id: " + cancelText + ".");
}
for (int i = 0; i < modelMessages.length; i++) {
try {
messageText[i] = Messages.message(modelMessages[i].getMessageID(),
modelMessages[i].getData());
} catch (MissingResourceException e) {
logger.warning("could not find message with id: " + modelMessages[i].getMessageID() + ".");
}
}
// source should be the same for all messages
FreeColGameObject source = modelMessages[0].getSource();
if ((source instanceof Europe && !europePanel.isShowing()) ||
(source instanceof Colony || source instanceof WorkLocation) &&
!colonyPanel.isShowing()) {
FreeColDialog confirmDialog = FreeColDialog.createConfirmDialog(messageText, okText, cancelText);
addCentered(confirmDialog, MODEL_MESSAGE_LAYER);
confirmDialog.requestFocus();
if (!confirmDialog.getResponseBoolean()) {
remove(confirmDialog);
if (source instanceof Europe) {
showEuropePanel();
} else if (source instanceof Colony) {
showColonyPanel((Colony) source);
} else if (source instanceof WorkLocation) {
showColonyPanel(((WorkLocation) source).getColony());
}
} else {
remove(confirmDialog);
freeColClient.getInGameController().nextModelMessage();
}
} else {
FreeColDialog informationDialog = FreeColDialog.createInformationDialog(messageText);
addCentered(informationDialog, MODEL_MESSAGE_LAYER);
informationDialog.requestFocus();
informationDialog.getResponse();
remove(informationDialog);
freeColClient.getInGameController().nextModelMessage();
}
}
/**
* Shows the <code>DeclarationDialog</code>.
* @see DeclarationDialog
*/
public void showDeclarationDialog() {
addCentered(declarationDialog, CONFIRM_LAYER);
declarationDialog.requestFocus();
declarationDialog.initialize();
boolean response = declarationDialog.getResponseBoolean();
remove(declarationDialog);
}
/**
* Displays a dialog with a text and a ok/cancel option.
*
* @param text The text that explains the choice for the user.
* @param okText The text displayed on the "ok"-button.
* @param cancelText The text displayed on the "cancel"-button.
* @return <i>true</i> if the user clicked the "ok"-button
* and <i>false</i> otherwise.
* @see FreeColDialog
*/
public boolean showConfirmDialog(String text, String okText, String cancelText) {
return showConfirmDialog(text, okText, cancelText, null);
}
/**
* Displays a dialog with a text and a ok/cancel option.
*
* @param text The text that explains the choice for the user.
* @param okText The text displayed on the "ok"-button.
* @param cancelText The text displayed on the "cancel"-button.
* @param replace An array of strings that will be inserted somewhere in the text.
* @return <i>true</i> if the user clicked the "ok"-button
* and <i>false</i> otherwise.
* @see FreeColDialog
*/
public boolean showConfirmDialog(String text, String okText, String cancelText, String[][] replace) {
try {
text = Messages.message(text, replace);
okText = Messages.message(okText);
cancelText = Messages.message(cancelText);
} catch (MissingResourceException e) {
logger.warning("could not find message with id: " + text + ", " + okText + " or " + cancelText + ".");
}
FreeColDialog confirmDialog = FreeColDialog.createConfirmDialog(text, okText, cancelText);
addCentered(confirmDialog, CONFIRM_LAYER);
confirmDialog.requestFocus();
boolean response = confirmDialog.getResponseBoolean();
remove(confirmDialog);
return response;
}
/**
* Checks if this <code>Canvas</code> displaying another panel.
*
* @return <code>true</code> if the <code>Canvas</code> is
* displaying a sub panel other than
* {@link net.sf.freecol.client.gui.panel.InfoPanel} and
* {@link net.sf.freecol.client.gui.panel.MiniMap}.
*/
public boolean isShowingSubPanel() {
if (getColonyPanel().isShowing() || getEuropePanel().isShowing()) {
return true;
}
Component[] comps = getComponents();
for (int i=0; i < comps.length; i++) {
if (comps[i] instanceof FreeColPanel && !(comps[i] instanceof InfoPanel)) {
return true;
}
}
return false;
}
/**
* Displays a dialog for setting game options.
* @return <code>true</code> if the game options have been modified,
* and <code>false</code> otherwise.
*/
public boolean showGameOptionsDialog() {
gameOptionsDialog.initialize();
addCentered(gameOptionsDialog, GAME_OPTIONS_LAYER);
gameOptionsDialog.requestFocus();
boolean r = gameOptionsDialog.getResponseBoolean();
remove(gameOptionsDialog);
return r;
}
/**
* Displays a dialog for setting client options.
* @return <code>true</code> if the client options have been modified,
* and <code>false</code> otherwise.
*/
public boolean showClientOptionsDialog() {
clientOptionsDialog.initialize();
addCentered(clientOptionsDialog, CLIENT_OPTIONS_LAYER);
clientOptionsDialog.requestFocus();
boolean r = clientOptionsDialog.getResponseBoolean();
remove(clientOptionsDialog);
return r;
}
/**
* Displays a dialog where the user may choose a file.
* This is the same as calling:
*
* <br><br><code>
* showLoadDialog(directory, new FileFilter[] {FreeColDialog.getFSGFileFilter()});
* </code>
*
* @param directory The directory containing the files.
* @return The <code>File</code>.
* @see FreeColDialog
*/
public File showLoadDialog(File directory) {
return showLoadDialog(directory, new FileFilter[] {FreeColDialog.getFSGFileFilter()});
}
/**
* Displays a dialog where the user may choose a file.
*
* @param directory The directory containing the files.
* @param fileFilters The file filters which the user can
* select in the dialog.
* @return The <code>File</code>.
* @see FreeColDialog
*/
public File showLoadDialog(File directory, FileFilter[] fileFilters) {
FreeColDialog loadDialog = FreeColDialog.createLoadDialog(directory, fileFilters);
addCentered(loadDialog, LOAD_LAYER);
loadDialog.requestFocus();
File response = (File) loadDialog.getResponse();
while (response != null && !response.isFile()) {
errorMessage("noSuchFile");
response = (File) loadDialog.getResponse();
}
remove(loadDialog);
return response;
}
/**
* Displays a dialog where the user may choose a filename.
* This is the same as calling:
*
* <br><br><code>
* showSaveDialog(directory, new FileFilter[] {FreeColDialog.getFSGFileFilter()});
* </code>
*
* @param directory The directory containing the files in which the
* user may overwrite.
* @return The <code>File</code>.
* @see FreeColDialog
*/
public File showSaveDialog(File directory) {
return showSaveDialog(directory, ".fsg", new FileFilter[] {FreeColDialog.getFSGFileFilter()});
}
/**
* Displays a dialog where the user may choose a filename.
*
* @param directory The directory containing the files
* in which the user may overwrite.
* @param standardName This extension will be added to the
* specified filename (if not added by the user).
* @param fileFilters The available file filters in the
* dialog.
* @return The <code>File</code>.
* @see FreeColDialog
*/
public File showSaveDialog(File directory, String standardName, FileFilter[] fileFilters) {
FreeColDialog saveDialog = FreeColDialog.createSaveDialog(directory, standardName, fileFilters);
addCentered(saveDialog, SAVE_LAYER);
saveDialog.requestFocus();
File response = (File) saveDialog.getResponse();
remove(saveDialog);
return response;
}
/**
* Displays a dialog that asks the user what he wants to do with his scout in the indian
* settlement.
*
* @param settlement The indian settlement that is being scouted.
*
* @return FreeColDialog.SCOUT_INDIAN_SETTLEMENT_CANCEL if the action was cancelled,
* FreeColDialog.SCOUT_INDIAN_SETTLEMENT_SPEAK if he wants to speak with the chief,
* FreeColDialog.SCOUT_INDIAN_SETTLEMENT_TRIBUTE if he wants to demand tribute,
* FreeColDialog.SCOUT_INDIAN_SETTLEMENT_ATTACK if he wants to attack the settlement.
*/
public int showScoutIndianSettlementDialog(IndianSettlement settlement) {
FreeColDialog scoutDialog = FreeColDialog.createScoutIndianSettlementDialog(settlement, freeColClient.getMyPlayer());
addCentered(scoutDialog, SCOUT_INDIAN_SETTLEMENT_LAYER);
scoutDialog.requestFocus();
int response = scoutDialog.getResponseInt();
remove(scoutDialog);
return response;
}
/**
* Displays a dialog that asks the user what he wants to do with his missionary in the indian
* settlement.
*
* @param settlement The indian settlement that is being visited.
*
* @return ArrayList with an Integer and optionally a Player refencing the player to attack in case
* of "incite indians". Integer can be any of:
* FreeColDialog.MISSIONARY_ESTABLISH if he wants to establish a mission,
* FreeColDialog.MISSIONARY_DENOUNCE_AS_HERESY if he wants to denounce the existing
* (foreign) mission as heresy,
* FreeColDialog.MISSIONARY_INCITE_INDIANS if he wants to incite the indians
* (requests their support for war against another European power),
* FreeColDialog.MISSIONARY_CANCEL if the action was cancelled.
*/
public List showUseMissionaryDialog(IndianSettlement settlement) {
FreeColDialog missionaryDialog = FreeColDialog.createUseMissionaryDialog(settlement, freeColClient.getMyPlayer());
addCentered(missionaryDialog, USE_MISSIONARY_LAYER);
missionaryDialog.requestFocus();
Integer response = (Integer)missionaryDialog.getResponse();
ArrayList returnValue = new ArrayList();
returnValue.add(response);
remove(missionaryDialog);
if (response.intValue() == FreeColDialog.MISSIONARY_INCITE_INDIANS) {
FreeColDialog inciteDialog = FreeColDialog.createInciteDialog(freeColClient.getGame().getEuropeanPlayers(), freeColClient.getMyPlayer());
addCentered(inciteDialog, USE_MISSIONARY_LAYER);
inciteDialog.requestFocus();
Player response2 = (Player)inciteDialog.getResponse();
if (response2 != null) {
returnValue.add(response2);
}
else {
returnValue.clear();
returnValue.add(new Integer(FreeColDialog.MISSIONARY_CANCEL));
}
remove(inciteDialog);
}
return returnValue;
}
/**
* Displays a yes/no question to the user asking if he wants to pay the given amount to an
* indian tribe in order to have them declare war on the given player.
*
* @param enemy The european player to attack.
* @param amount The amount of gold to pay.
*
* @return true if the players wants to pay, false otherwise.
*/
public boolean showInciteDialog(Player enemy, int amount) {
String message = Messages.message("missionarySettlement.inciteConfirm");
message = message.replaceAll("%player%", enemy.getName());
message = message.replaceAll("%amount%", String.valueOf(amount));
FreeColDialog confirmDialog = FreeColDialog.createConfirmDialog(message, Messages.message("yes"), Messages.message("no"));
addCentered(confirmDialog, INCITE_LAYER);
confirmDialog.requestFocus();
boolean result = confirmDialog.getResponseBoolean();
remove(confirmDialog);
return result;
}
/**
* Displays a dialog with a text field and a ok/cancel option.
*
* @param text The text that explains the action to the user.
* @param defaultValue The default value appearing in the text field.
* @param okText The text displayed on the "ok"-button.
* @param cancelText The text displayed on the "cancel"-button.
* Use <i>null</i> to disable the cancel-option.
* @return The text the user have entered or <i>null</i> if the
* user chose to cancel the action.
* @see FreeColDialog
*/
public String showInputDialog(String text, String defaultValue, String okText, String cancelText) {
try {
text = Messages.message(text);
okText = Messages.message(okText);
if (cancelText != null) {
cancelText = Messages.message(cancelText);
}
} catch (MissingResourceException e) {
logger.warning("could not find message with id: " + text + ", " + okText + " or " + cancelText + ".");
}
FreeColDialog inputDialog = FreeColDialog.createInputDialog(text, defaultValue, okText, cancelText);
addCentered(inputDialog, INPUT_LAYER);
inputDialog.requestFocus();
String response = (String) inputDialog.getResponse();
// checks if the user entered some text.
if((response != null) && (response.length() == 0)) {
String okTxt = "ok";
String txt = "enterSomeText";
try {
okTxt = Messages.message(okTxt);
txt = Messages.message(txt);
}
catch(MissingResourceException e) {
logger.warning("could not find message with id: " + txt + " or " + okTxt + ".");
}
FreeColDialog informationDialog = FreeColDialog.createInformationDialog(txt, okTxt);
do {
remove(inputDialog);
addCentered(informationDialog, INPUT_LAYER);
informationDialog.requestFocus();
informationDialog.getResponse();
remove(informationDialog);
addCentered(inputDialog, INPUT_LAYER);
inputDialog.requestFocus();
response = (String) inputDialog.getResponse();
} while((response != null) && (response.length() == 0));
}
remove(inputDialog);
return response;
}
/**
* Displays a dialog with a text and a cancel-button,
* in addition to buttons for each of the objects returned for the given
* <code>Iterator</code>.
*
* @param text The text that explains the choice for the user.
* @param cancelText The text displayed on the "cancel"-button.
* @param iterator The <code>Iterator</code> containing the objects to create
* buttons for.
* @return The choosen object, or <i>null</i> for the cancel-button.
*/
public Object showChoiceDialog(String text, String cancelText, Iterator iterator) {
ArrayList a = new ArrayList();
while (iterator.hasNext()) {
a.add(iterator.next());
}
return showChoiceDialog(text, cancelText, a.toArray());
}
/**
* Displays a dialog with a text and a cancel-button,
* in addition to buttons for each of the objects in the array.
*
* @param text The text that explains the choice for the user.
* @param cancelText The text displayed on the "cancel"-button.
* @param objects The array containing the objects to create
* buttons for.
* @return The choosen object, or <i>null</i> for the cancel-button.
*/
public Object showChoiceDialog(String text, String cancelText, Object[] objects) {
/*
try {
text = Messages.message(text);
cancelText = Messages.message(cancelText);
} catch (MissingResourceException e) {
logger.warning("could not find message with id: " + text + " or " + cancelText + ".");
}
*/
FreeColDialog choiceDialog = FreeColDialog.createChoiceDialog(text, cancelText, objects);
addCentered(choiceDialog, CHOICE_LAYER);
choiceDialog.requestFocus();
Object response = choiceDialog.getResponse();
remove(choiceDialog);
return response;
}
/**
* Shows a status message that cannot be dismissed.
* The panel will be removed when another component
* is added to this <code>Canvas</code>. This includes
* all the <code>showXXX</code>-methods. In addition,
* {@link #closeStatusPanel()} and {@link #closeMenus()}
* also removes this panel.
*
* @param message The text message to display on the
* status panel.
* @see StatusPanel
*/
public void showStatusPanel(String message) {
statusPanel.setStatusMessage(message);
addCentered(statusPanel, STATUS_LAYER);
}
/**
* Closes the <code>StatusPanel</code>.
* @see #showStatusPanel
*/
public void closeStatusPanel() {
remove(statusPanel);
}
/**
* Shows a panel displaying Colopedia Information.
* @param type The type of colopedia panel to display.
*/
public void showColopediaPanel(int type) {
colopediaPanel.initialize(type);
setEnabled(false);
addCentered(colopediaPanel, COLOPEDIA_LAYER);
colopediaPanel.requestFocus();
}
/**
* Shows a report panel.
* @param classname The class name of the report panel
* to be displayed.
*/
public void showReportPanel(String classname) {
ReportPanel reportPanel = null;
if ("net.sf.freecol.client.gui.panel.ReportReligiousPanel".equals(classname)) {
reportPanel = reportReligiousPanel;
} else if ("net.sf.freecol.client.gui.panel.ReportLabourPanel".equals(classname)) {
reportPanel = reportLabourPanel;
} else if ("net.sf.freecol.client.gui.panel.ReportForeignAffairPanel".equals(classname)) {
reportPanel = reportForeignAffairPanel;
} else if ("net.sf.freecol.client.gui.panel.ReportIndianPanel".equals(classname)) {
reportPanel = reportIndianPanel;
} else if ("net.sf.freecol.client.gui.panel.ReportContinentalCongressPanel".equals(classname)) {
reportPanel = reportContinentalCongressPanel;
} else if ("net.sf.freecol.client.gui.panel.ReportTradePanel".equals(classname)) {
reportPanel = reportTradePanel;
} else {
logger.warning("Request for Report panel could not be processed. Name="+ classname );
}
if (reportPanel != null) {
reportPanel.initialize();
setEnabled(false);
addCentered(reportPanel, REPORT_LAYER);
reportPanel.requestFocus();
}
}
/**
* Shows a panel where the player may choose the next founding father to recruit.
* @param possibleFoundingFathers The different founding fathers the player may choose.
* @return The founding father the player has chosen.
* @see net.sf.freecol.common.model.FoundingFather
*/
public int showChooseFoundingFatherDialog(int[] possibleFoundingFathers) {
+ remove(statusPanel);
+
chooseFoundingFatherDialog.initialize(possibleFoundingFathers);
addCentered(chooseFoundingFatherDialog, CHOOSE_FOUNDING_FATHER);
setEnabled(false);
chooseFoundingFatherDialog.requestFocus();
int response = chooseFoundingFatherDialog.getResponseInt();
remove(chooseFoundingFatherDialog);
setEnabled(true);
return response;
}
/**
* Gets the dialog which is used for choosing a founding father.
* @return The dialog.
*/
public ChooseFoundingFatherDialog getChooseFoundingFatherDialog() {
return chooseFoundingFatherDialog;
}
/**
* Shows the {@link EventPanel}.
* @param eventID The type of <code>EventPanel</code> to be displayed.
* @return <code>true</code>.
*/
public boolean showEventDialog(int eventID) {
eventPanel.initialize(eventID);
addCentered(eventPanel, EVENT_LAYER);
setEnabled(false);
eventPanel.requestFocus();
boolean response = eventPanel.getResponseBoolean();
remove(eventPanel);
setEnabled(true);
return response;
}
/**
* Gets the <code>EventPanel</code>.
* @return The panel.
*/
public EventPanel getEventPanel() {
return eventPanel;
}
/**
* Displays the <code>EuropePanel</code>.
* @see EuropePanel
*/
public void showEuropePanel() {
closeMenus();
if (freeColClient.getGame() == null) {
errorMessage("europe.noGame");
} else {
europePanel.initialize(freeColClient.getMyPlayer().getEurope(), freeColClient.getGame());
europePanel.setLocation(0, getMenuBarHeight());
setEnabled(false);
add(europePanel, EUROPE_LAYER);
europePanel.requestFocus();
}
}
/**
* Displays the colony panel of the given <code>Colony</code>.
* @param colony The colony whose panel needs to be displayed.
* @see ColonyPanel
*/
public void showColonyPanel(Colony colony) {
closeMenus();
colonyPanel.initialize(colony, freeColClient.getGame());
setEnabled(false);
addCentered(colonyPanel, COLONY_LAYER);
colonyPanel.requestFocus();
}
/**
* Displays the indian settlement panel of the given <code>IndianSettlement</code>.
* @param settlement The indian settlement whose panel needs to be displayed.
* @see IndianSettlement
*/
public void showIndianSettlementPanel(IndianSettlement settlement) {
closeMenus();
indianSettlementPanel.initialize(settlement);
addCentered(indianSettlementPanel, INDIAN_SETTLEMENT_LAYER);
indianSettlementPanel.requestFocus();
indianSettlementPanel.getResponseBoolean();
remove(indianSettlementPanel);
}
/**
* Displays the tile panel of the given <code>Tile</code>.
* @param tile The tile whose panel needs to be displayed.
* @see Tile
*/
public void showTilePanel(Tile tile) {
closeMenus();
tilePanel.initialize(tile);
addCentered(tilePanel, TILE_LAYER);
tilePanel.requestFocus();
tilePanel.getResponseBoolean();
remove(tilePanel);
}
/**
* Displays the monarch action panel.
* @param action The monarch action.
* @param replace The replacement strings.
* @return true or false
* @see net.sf.freecol.common.model.Monarch
*/
public boolean showMonarchPanel(int action, String [][] replace) {
+ remove(statusPanel);
monarchPanel.initialize(action, replace);
addCentered(monarchPanel, MONARCH_LAYER);
monarchPanel.requestFocus();
boolean response = monarchPanel.getResponseBoolean();
remove(monarchPanel);
return response;
}
/**
* Shows the panel that allows the user to choose which unit will emigrate
* from Europe. This method may only be called if the user has William Brewster
* in congress.
* @return The emigrant that was chosen by the user (1, 2 or 3).
*/
public int showEmigrationPanel() {
emigrationPanel.initialize(freeColClient.getMyPlayer().getEurope());
addCentered(emigrationPanel, EMIGRATION_LAYER);
emigrationPanel.requestFocus();
int response = emigrationPanel.getResponseInt();
remove(emigrationPanel);
return response;
}
/**
* Updates the menu bar.
*/
public void updateJMenuBar() {
if (jMenuBar instanceof FreeColMenuBar) {
((FreeColMenuBar) jMenuBar).update();
}
}
/**
* Creates and sets a <code>FreeColMenuBar</code> on this <code>Canvas</code>.
* @see FreeColMenuBar
*/
public void resetFreeColMenuBar() {
FreeColMenuBar freeColMenuBar = new FreeColMenuBar(freeColClient, this, freeColClient.getGUI());
setJMenuBar(freeColMenuBar);
}
/**
* Removes the given component from this Container.
* @param comp The component to remove from this Container.
*/
public void remove(Component comp) {
remove(comp, true);
}
/**
* Removes the given component from this Container.
* @param comp The component to remove from this Container.
* @param update The <code>Canvas</code> will be enabled,
* the graphics repainted and both the menubar and
* the actions will be updated if this parameter is
* <code>true</code>.
*/
public void remove(Component comp, boolean update) {
if (comp != null) {
if (comp == jMenuBar) {
jMenuBar = null;
}
boolean takeFocus = true;
if (comp == statusPanel) {
takeFocus = false;
}
Rectangle bounds = comp.getBounds();
super.remove(comp);
if (update) {
setEnabled(true);
updateJMenuBar();
freeColClient.getActionManager().update();
if (takeFocus && !isShowingSubPanel()) {
takeFocus();
}
repaint(bounds.x, bounds.y, bounds.width, bounds.height);
}
}
}
/**
* Adds a component to this Canvas.
* @param comp The component to add to this ToEuropePanel.
* @return The component argument.
*/
public Component add(Component comp) {
add(comp, null);
return comp;
}
/**
* Adds a component centered on this Canvas. Removes the statuspanel if visible
* (and <code>comp != statusPanel</code>).
* @param comp The component to add to this ToEuropePanel.
* @return The component argument.
*/
public Component addCentered(Component comp) {
addCentered(comp, null);
return comp;
}
/**
* Adds a component centered on this Canvas. Removes the statuspanel if visible
* (and <code>comp != statusPanel</code>).
* @param comp The component to add to this ToEuropePanel.
* @param i The layer to add the component to (see JLayeredPane).
*/
public void addCentered(Component comp, Integer i) {
comp.setLocation(getWidth() / 2 - comp.getWidth() / 2,
(getHeight() + getMenuBarHeight()) / 2 - comp.getHeight() / 2);
add(comp, i);
}
/**
* Adds a component to this Canvas. Removes the statuspanel if visible
* (and <code>comp != statusPanel</code>).
* @param comp The component to add to this ToEuropePanel.
* @param i The layer to add the component to (see JLayeredPane).
*/
public void add(Component comp, Integer i) {
if ((takeFocusThread != null) && (takeFocusThread.isAlive())) {
takeFocusThread.stopWorking();
}
if (comp != statusPanel && !(comp instanceof JMenuItem) && !(comp instanceof FreeColDialog)) {
remove(statusPanel, false);
}
if (i == null) {
super.add(comp);
} else {
super.add(comp, i);
}
updateJMenuBar();
freeColClient.getActionManager().update();
}
/**
* Makes sure that this Canvas takes the focus. It will keep on trying for
* a while even its request doesn't get granted immediately.
*/
private void takeFocus() {
JComponent c = this;
if (startGamePanel.isShowing()) {
c = startGamePanel;
} else if (newPanel.isShowing()) {
c = newPanel;
} else if (mainPanel.isShowing()) {
c = mainPanel;
} else if (europePanel.isShowing()) {
c = europePanel;
} else if (colonyPanel.isShowing()) {
c = colonyPanel;
}
if (takeFocusThread != null) {
takeFocusThread.stopWorking();
}
if (c != this) {
c.requestFocus();
} else {
takeFocusThread = new TakeFocusThread(c);
takeFocusThread.start();
}
}
/**
* Gets the <code>ColonyPanel</code>.
* @return The <code>ColonyPanel</code>
*/
public ColonyPanel getColonyPanel() {
return colonyPanel;
}
/**
* Gets the <code>EuropePanel</code>.
* @return The <code>EuropePanel</code>.
*/
public EuropePanel getEuropePanel() {
return europePanel;
}
/**
* Enables or disables this component depending on the given argument.
* @param b Must be set to 'true' if this component needs to be enabled
* or to 'false' otherwise.
*/
public void setEnabled(boolean b) {
if (isEnabled() != b) {
for (int i = 0; i < getComponentCount(); i++) {
getComponent(i).setEnabled(b);
}
/*
if (jMenuBar != null) {
jMenuBar.setEnabled(b);
}
*/
freeColClient.getActionManager().update();
super.setEnabled(b);
}
}
/**
* Shows the given popup at the given position on the screen.
*
* @param popup The JPopupMenu to show.
* @param x The x-coordinate at which to show the popup.
* @param y The y-coordinate at which to show the popup.
*/
public void showPopup(JPopupMenu popup, int x, int y) {
closeMenus();
popup.show(this, x, y);
}
/**
* Shows a tile popup.
*
* @param pos The coordinates of the Tile where the popup occured.
* @param x The x-coordinate on the screen where the popup needs to be placed.
* @param y The y-coordinate on the screen where the popup needs to be placed.
* @see TilePopup
*/
public void showTilePopup(Map.Position pos, int x, int y) {
if (pos != null) {
Tile t = freeColClient.getGame().getMap().getTileOrNull(pos.getX(), pos.getY());
if (t != null) {
TilePopup tp = new TilePopup(t, freeColClient, this, getGUI());
if (tp.hasItem()) {
showPopup(tp, x, y);
} else if (t.getType() != Tile.UNEXPLORED) {
showTilePanel(t);
}
}
}
}
/**
* Displays an error message.
* @param messageID The i18n-keyname of the error message to display.
*/
public void errorMessage(String messageID) {
errorMessage(messageID, "Unspecified error: " + messageID);
}
/**
* Displays an error message.
*
* @param messageID The i18n-keyname of the error message to display.
* @param message An alternativ message to display if the resource
* specified by <code>messageID</code> is unavailable.
*/
public void errorMessage(String messageID, String message) {
if (messageID != null) {
try {
message = Messages.message(messageID);
} catch (MissingResourceException e) {
logger.warning("could not find message with id: " + messageID);
}
}
errorPanel.initialize(message);
//setEnabled(false);
addCentered(errorPanel, ERROR_LAYER);
errorPanel.requestFocus();
errorPanel.getResponse();
closeErrorPanel();
}
/**
* Shows a message with some information and an "OK"-button.
* @param messageId The messageId of the message to display.
*/
public void showInformationMessage(String messageId) {
showInformationMessage(messageId, null);
}
/**
* Shows a message with some information and an "OK"-button.
* @param messageId The messageId of the message to display.
* @param replaceString The string that we need to use to replace all occurences of %replace% in the
* message.
*/
/*public void showInformationMessage(String messageId, String replaceString) {
showInformationDialog(messageId, {{"%replace%", replaceString}});
}*/
/**
* Shows a message with some information and an "OK"-button.
*
* <br><br><b>Example:</b>
* <br><code>canvas.showInformationMessage("noNeedForTheGoods", new String[][] {{"%goods%", goods.getName()}});</code>
* @param messageId The messageId of the message to display.
* @param replace All occurances of <code>replace[i][0]</code> in
* the message gets replaced by <code>replace[i][1]</code>.
*/
public void showInformationMessage(String messageId, String[][] replace) {
String text;
try {
text = Messages.message(messageId, replace);
} catch (MissingResourceException e) {
text = messageId;
logger.warning("Missing i18n resource: " + messageId);
}
FreeColDialog infoDialog = FreeColDialog.createInformationDialog(text);
addCentered(infoDialog, INFORMATION_LAYER);
infoDialog.requestFocus();
infoDialog.getResponse();
remove(infoDialog);
}
/**
* Closes the <code>ErrorPanel</code>.
*/
public void closeErrorPanel() {
remove(errorPanel);
}
/**
* Refreshes this Canvas visually.
*/
public void refresh() {
gui.forceReposition();
repaint(0, 0, getWidth(), getHeight());
}
/**
* Refreshes the screen at the specified Tile.
*
* @param x The x-coordinate of the Tile to refresh.
* @param y The y-coordinate of the Tile to refresh.
*/
public void refreshTile(int x, int y) {
if (x >= 0 && y >= 0) {
repaint(gui.getTileBounds(x, y));
}
}
/**
* Refreshes the screen at the specified Tile.
* @param t The tile to refresh.
*/
public void refreshTile(Tile t) {
refreshTile(t.getX(), t.getY());
}
/**
* Refreshes the screen at the specified Tile.
* @param p The position of the tile to refresh.
*/
public void refreshTile(Position p) {
refreshTile(p.getX(), p.getY());
}
/**
* Returns the image provider that is being used by this canvas.
* @return The image provider that is being used by this canvas.
*/
public ImageProvider getImageProvider() {
return gui.getImageLibrary();
}
/**
* Closes all the menus that are currently open.
*/
public void closeMenus() {
remove(newPanel, false);
remove(startGamePanel, false);
remove(serverListPanel, false);
remove(colonyPanel, false);
remove(europePanel, false);
remove(statusPanel);
}
/**
* Shows the <code>MainPanel</code>.
* @see MainPanel
*/
public void showMainPanel() {
closeMenus();
addCentered(mainPanel, MAIN_LAYER);
mainPanel.requestFocus();
}
/**
* Closes the {@link MainPanel}.
*/
public void closeMainPanel() {
remove(mainPanel);
}
/**
* Shows the <code>OpenGamePanel</code>.
*/
public void showOpenGamePanel() {
errorMessage("openGame.unimplemented");
}
/**
* Gets the <code>StartGamePanel</code> that lies in this container.
* @return The <code>StartGamePanel</code>.
* @see StartGamePanel
*/
public StartGamePanel getStartGamePanel() {
return startGamePanel;
}
/**
* Tells the map controls that a chat message was recieved.
* @param sender The player who sent the chat message to the server.
* @param message The chat message.
* @param privateChat 'true' if the message is a private one, 'false' otherwise.
* @see GUIMessage
*/
public void displayChatMessage(Player sender, String message, boolean privateChat) {
gui.addMessage(new GUIMessage(sender.getName() + ": " + message, sender.getColor()));
}
/**
* Displays a chat message originating from this client.
* @param message The chat message.
*/
public void displayChatMessage(String message) {
displayChatMessage(freeColClient.getMyPlayer(), message, false);
}
/**
* Quits the application. This method uses {@link #confirmQuitDialog()}
* in order to get a "Are you sure"-confirmation from the user.
*/
public void quit() {
if (confirmQuitDialog()) {
freeColClient.quit();
}
}
/**
* Closes all panels, changes the background and shows the main menu.
*/
public void returnToTitle() {
// TODO: check if the GUI object knows that we're not inGame. (Retrieve value
// of GUI::inGame.)
// If GUI thinks we're still in the game then log an error because at this
// point the GUI should have been informed.
setEnabled(false);
closeMenus();
removeInGameComponents();
showMainPanel();
}
/**
* Removes components that is only used when in game.
*/
public void removeInGameComponents() {
// remove listeners, they will be added when launching the new game...
KeyListener[] keyListeners = getKeyListeners();
for(int i = 0; i < keyListeners.length; ++i) {
removeKeyListener(keyListeners[i]);
}
MouseListener[] mouseListeners = getMouseListeners();
for(int i = 0; i < mouseListeners.length; ++i) {
removeMouseListener(mouseListeners[i]);
}
MouseMotionListener[] mouseMotionListeners = getMouseMotionListeners();
for(int i = 0; i < mouseMotionListeners.length; ++i) {
removeMouseMotionListener(mouseMotionListeners[i]);
}
if (jMenuBar != null) {
remove(jMenuBar);
}
}
/**
* Checks if this <code>Canvas</code> contains any
* ingame components.
*
* @return <code>true</code> if there is a single ingame
* component.
*/
public boolean containsInGameComponents() {
// remove listeners, they will be added when launching the new game...
KeyListener[] keyListeners = getKeyListeners();
if (keyListeners.length > 0) {
return true;
}
MouseListener[] mouseListeners = getMouseListeners();
if (mouseListeners.length > 0) {
return true;
}
MouseMotionListener[] mouseMotionListeners = getMouseMotionListeners();
if (mouseMotionListeners.length > 0) {
return true;
}
return false;
}
/**
* Displays a "Are you sure you want to quit"-dialog
* in which the user may choose to quit or cancel.
*
* @return <i>true</i> if the user desides to quit and
* <i>false</i> otherwise.
*/
public boolean confirmQuitDialog() {
addCentered(quitDialog, QUIT_LAYER);
quitDialog.requestFocus();
return quitDialog.getResponseBoolean();
}
/**
* Returns this <code>Canvas</code>'s <code>GUI</code>.
* @return The <code>GUI</code>.
*/
public GUI getGUI() {
return gui;
}
/** Returns the freeColClient.
* @return The <code>freeColClient</code> associated with this <code>Canvas</code>.
*/
public FreeColClient getClient() {
return freeColClient;
}
/**
* Displays a quit dialog and, if desired, logouts the current game and shows the new game panel.
*/
public void newGame() {
if(!showConfirmDialog("stopCurrentGame.text", "stopCurrentGame.yes", "stopCurrentGame.no")) {
return;
}
freeColClient.getConnectController().quitGame(true);
removeInGameComponents();
showNewGamePanel();
}
/**
* Makes sure that old chat messages are removed in time.
*/
private final class ChatDisplayThread extends Thread {
/**
* The constructor to use.
*/
public ChatDisplayThread() {
super("ChatDisplayThread");
}
/**
* Removes old chat messages regularly.
*/
public void run() {
for (;;) {
if (gui.removeOldMessages()) {
refresh();
}
try {
sleep(500);
} catch (InterruptedException e) {
}
}
}
}
/**
* Makes sure that a given component takes the focus.
*/
private final class TakeFocusThread extends Thread {
private final JComponent component;
private boolean doYourWork;
/**
* The constructor to use.
* @param component The component that needs focus.
*/
public TakeFocusThread(JComponent component) {
super("TakeFocusThread");
this.component = component;
doYourWork = true;
}
/**
* Makes sure that this thread stops working.
*/
public void stopWorking() {
doYourWork = false;
}
/**
* Returns 'true' if this thread is going to keep on working, 'false' otherwise.
* @return 'true' if this thread is going to keep on working, 'false' otherwise.
*/
public boolean isStillWorking() {
return doYourWork;
}
/**
* Gets the component this thread is trying to take focus for.
* @return The component.
*/
public JComponent getComponent() {
return component;
}
/**
* Makes sure that the given component takes the focus.
*/
public void run() {
int count = 0;
while ((!component.hasFocus()) && doYourWork) {
component.requestFocus();
try {
sleep(100);
}
catch (InterruptedException e) {
}
count++;
if (count > 50) {
// We're already been trying for 5 seconds, there must be something wrong.
logger.warning("Component can't get focus: " + component.toString());
}
}
}
}
}
diff --git a/src/net/sf/freecol/server/control/InGameController.java b/src/net/sf/freecol/server/control/InGameController.java
index df349443d..43e011663 100644
--- a/src/net/sf/freecol/server/control/InGameController.java
+++ b/src/net/sf/freecol/server/control/InGameController.java
@@ -1,515 +1,515 @@
package net.sf.freecol.server.control;
import java.io.IOException;
import java.util.Iterator;
import java.util.Random;
import java.util.logging.Logger;
import net.sf.freecol.common.model.Colony;
import net.sf.freecol.common.model.FoundingFather;
import net.sf.freecol.common.model.Game;
import net.sf.freecol.common.model.GameOptions;
import net.sf.freecol.common.model.Goods;
import net.sf.freecol.common.model.Map;
import net.sf.freecol.common.model.Market;
import net.sf.freecol.common.model.Monarch;
import net.sf.freecol.common.model.Player;
import net.sf.freecol.common.model.Tile;
import net.sf.freecol.common.model.Unit;
import net.sf.freecol.common.networking.Message;
import net.sf.freecol.server.FreeColServer;
import net.sf.freecol.server.model.ServerPlayer;
import org.w3c.dom.Element;
/**
*
*/
public final class InGameController extends Controller {
private static Logger logger = Logger.getLogger(InGameController.class.getName());
public static final String COPYRIGHT = "Copyright (C) 2003-2005 The FreeCol Team";
public static final String LICENSE = "http://www.gnu.org/licenses/gpl.html";
public static final String REVISION = "$Revision$";
private Random random = new Random();
public int debugOnlyAITurns = 0;
/**
* The constructor to use.
* @param freeColServer The main server object.
*/
public InGameController(FreeColServer freeColServer) {
super(freeColServer);
}
/**
* Ends the turn of the given player.
*
* @param player The player to end the turn of.
*/
public void endTurn(ServerPlayer player) {
FreeColServer freeColServer = getFreeColServer();
Game game = freeColServer.getGame();
ServerPlayer oldPlayer = (ServerPlayer) game.getCurrentPlayer();
if (oldPlayer != player) {
throw new IllegalArgumentException("It is not " + player.getName() + "'s turn!");
}
// Clean up server side model messages:
game.clearModelMessages();
ServerPlayer nextPlayer = (ServerPlayer) game.getNextPlayer();
while (nextPlayer != null && checkForDeath(nextPlayer)) {
nextPlayer.setDead(true);
Element setDeadElement = Message.createNewRootElement("setDead");
setDeadElement.setAttribute("player", nextPlayer.getID());
freeColServer.getServer().sendToAll(setDeadElement, null);
nextPlayer = (ServerPlayer) game.getNextPlayer();
}
while (nextPlayer != null && !nextPlayer.isConnected()) {
game.setCurrentPlayer(nextPlayer);
nextPlayer = (ServerPlayer) game.getPlayerAfter(nextPlayer);
}
while (nextPlayer != null && !nextPlayer.isAI() && debugOnlyAITurns > 0) {
nextPlayer = (ServerPlayer) game.getPlayerAfter(nextPlayer);
}
if (nextPlayer == null) {
game.setCurrentPlayer(null);
return;
}
Player winner = checkForWinner();
if (winner != null) {
Element gameEndedElement = Message.createNewRootElement("gameEnded");
gameEndedElement.setAttribute("winner", winner.getID());
freeColServer.getServer().sendToAll(gameEndedElement, null);
return;
}
freeColServer.getModelController().clearTaskRegister();
if (game.isNextPlayerInNewTurn()) {
game.newTurn();
if (debugOnlyAITurns > 0) {
debugOnlyAITurns--;
}
Element newTurnElement = Message.createNewRootElement("newTurn");
freeColServer.getServer().sendToAll(newTurnElement, null);
}
if (nextPlayer.isEuropean()) {
try {
Market market = game.getMarket();
// make random change to the market
market.add(random.nextInt(Goods.NUMBER_OF_TYPES), (50 - random.nextInt(71)));
Element updateElement = Message.createNewRootElement("update");
updateElement.appendChild(game.getMarket().toXMLElement(nextPlayer, updateElement.getOwnerDocument()));
nextPlayer.getConnection().send(updateElement);
} catch (IOException e) {
logger.warning("Could not send message to: " + nextPlayer.getName() + " with connection " + nextPlayer.getConnection());
}
}
game.setCurrentPlayer(nextPlayer);
- Element setCurrentPlayerElement = Message.createNewRootElement("setCurrentPlayer");
- setCurrentPlayerElement.setAttribute("player", nextPlayer.getID());
- freeColServer.getServer().sendToAll(setCurrentPlayerElement, null);
-
// Ask the player to choose a founding father if none has been chosen:
if (nextPlayer.isEuropean()) {
if (nextPlayer.getCurrentFather() == -1) {
chooseFoundingFather(nextPlayer);
}
if (nextPlayer.getMonarch() != null) {
monarchAction(nextPlayer);
}
}
- }
+
+ Element setCurrentPlayerElement = Message.createNewRootElement("setCurrentPlayer");
+ setCurrentPlayerElement.setAttribute("player", nextPlayer.getID());
+ freeColServer.getServer().sendToAll(setCurrentPlayerElement, null);
+ }
private void chooseFoundingFather(ServerPlayer player) {
final ServerPlayer nextPlayer = player;
Thread t = new Thread() {
public void run() {
int[] randomFoundingFathers = getRandomFoundingFathers(nextPlayer);
boolean atLeastOneChoice = false;
Element chooseFoundingFatherElement = Message.createNewRootElement("chooseFoundingFather");
for (int i=0; i<randomFoundingFathers.length; i++) {
chooseFoundingFatherElement.setAttribute("foundingFather" + Integer.toString(i), Integer.toString(randomFoundingFathers[i]));
if (randomFoundingFathers[i] != -1) {
atLeastOneChoice = true;
}
}
if (!atLeastOneChoice) {
nextPlayer.setCurrentFather(-1);
} else {
try {
Element reply = nextPlayer.getConnection().ask(chooseFoundingFatherElement);
int foundingFather = Integer.parseInt(reply.getAttribute("foundingFather"));
boolean foundIt = false;
for (int i=0; i<randomFoundingFathers.length; i++) {
if (randomFoundingFathers[i] == foundingFather) {
foundIt = true;
break;
}
}
if (!foundIt) {
throw new IllegalArgumentException();
}
nextPlayer.setCurrentFather(foundingFather);
} catch (IOException e) {
logger.warning("Could not send message to: " + nextPlayer.getName());
}
}
}
};
t.start();
}
/**
* Returns an <code>int[]</code> with the size of {@link FoundingFather#TYPE_COUNT},
* containing random founding fathers (not including the founding fathers
* the player has already) of each type.
*
* @param player The <code>Player</code> that should pick a founding father from this list.
*/
private int[] getRandomFoundingFathers(Player player) {
Game game = getFreeColServer().getGame();
int[] randomFoundingFathers = new int[FoundingFather.TYPE_COUNT];
for (int i=0; i<FoundingFather.TYPE_COUNT; i++) {
int weightSum = 0;
for (int j=0; j<FoundingFather.FATHER_COUNT; j++) {
if (!player.hasFather(j) && FoundingFather.getType(j) == i) {
weightSum += FoundingFather.getWeight(j, game.getTurn().getAge());
}
}
if (weightSum == 0) {
randomFoundingFathers[i] = -1;
} else {
int r = random.nextInt(weightSum)+1;
weightSum = 0;
for (int j=0; j<FoundingFather.FATHER_COUNT; j++) {
if (!player.hasFather(j) && FoundingFather.getType(j) == i) {
weightSum += FoundingFather.getWeight(j, game.getTurn().getAge());
if (weightSum >= r) {
randomFoundingFathers[i] = j;
break;
}
}
}
}
}
return randomFoundingFathers;
}
/**
* Checks if anybody has won the game and returns that player.
* @return The <code>Player</code> who have won the game or <i>null</i>
* if the game is not finished.
*/
private Player checkForWinner() {
Game game = getFreeColServer().getGame();
GameOptions go = game.getGameOptions();
if (go.getBoolean(GameOptions.VICTORY_DEFEAT_REF)) {
Iterator playerIterator = game.getPlayerIterator();
while (playerIterator.hasNext()) {
Player p = (Player) playerIterator.next();
if (!p.isAI() && p.getRebellionState() == Player.REBELLION_POST_WAR) {
return p;
}
}
}
if (go.getBoolean(GameOptions.VICTORY_DEFEAT_EUROPEANS)) {
Player winner = null;
Iterator playerIterator = game.getPlayerIterator();
while (playerIterator.hasNext()) {
Player p = (Player) playerIterator.next();
if (!p.isDead() && p.isEuropean() && !p.isREF()) {
if (winner != null) {
// There is more than one european player alive:
winner = null;
break;
} else {
winner = p;
}
}
}
if (winner != null) {
return winner;
}
}
if (go.getBoolean(GameOptions.VICTORY_DEFEAT_HUMANS)) {
Player winner = null;
Iterator playerIterator = game.getPlayerIterator();
while (playerIterator.hasNext()) {
Player p = (Player) playerIterator.next();
if (!p.isDead() && !p.isAI()) {
if (winner != null) {
// There is more than one human player alive:
winner = null;
break;
} else {
winner = p;
}
}
}
if (winner != null) {
return winner;
}
}
return null;
}
/**
* Checks if this player has died.
* @return <i>true</i> if this player should die.
*/
private boolean checkForDeath(Player player) {
// Die if: (No colonies or units on map) && ((After 20 turns) || (Cannot get a unit from Europe))
Game game = getFreeColServer().getGame();
Map map = game.getMap();
if (player.isREF()) {
return false;
}
Iterator tileIterator = map.getWholeMapIterator();
while (tileIterator.hasNext()) {
Tile t = map.getTile((Map.Position) tileIterator.next());
if (t != null && ((t.getFirstUnit() != null && t.getFirstUnit().getOwner().equals(player))
|| t.getSettlement() != null && t.getSettlement().getOwner().equals(player))) {
return false;
}
}
// At this point we know the player does not have any units or settlements on the map.
if (player.getNation() >= 0 && player.getNation() <= 3) {
/*if (game.getTurn().getNumber() > 20 || player.getEurope().getFirstUnit() == null
&& player.getGold() < 600 && player.getGold() < player.getRecruitPrice()) {
*/
if (game.getTurn().getNumber() > 20) {
return true;
} else if (player.getEurope() == null) {
return true;
} else if (player.getGold() < 1000) {
Iterator unitIterator = player.getEurope().getUnitIterator();
while (unitIterator.hasNext()) {
if (((Unit) unitIterator.next()).isCarrier()) {
return false;
}
}
return true;
} else {
return false;
}
} else {
return true;
}
}
/**
* Checks for monarch actions.
*
* @param player The server player.
*/
private void monarchAction(ServerPlayer player) {
final ServerPlayer nextPlayer = player;
final Game game = getFreeColServer().getGame();
Thread t = new Thread() {
public void run() {
Monarch monarch = nextPlayer.getMonarch();
int action = monarch.getAction();
Unit newUnit;
Element monarchActionElement = Message.createNewRootElement("monarchAction");
monarchActionElement.setAttribute("action", String.valueOf(action));
switch (action) {
case Monarch.RAISE_TAX:
int newTax = monarch.getNewTax();
Goods goods = nextPlayer.getMostValuableGoods();
if (newTax > 100) {
logger.warning("Tax rate exceeds 100 percent.");
return;
}
monarchActionElement.setAttribute("amount", String.valueOf(newTax));
if (goods != null)
monarchActionElement.setAttribute("goods", goods.getName());
try {
Element reply = nextPlayer.getConnection().ask(monarchActionElement);
boolean accepted = Boolean.valueOf(reply.getAttribute("accepted")).booleanValue();
if (accepted) {
nextPlayer.setTax(newTax);
} else {
Element removeGoodsElement = Message.createNewRootElement("removeGoods");
if (goods != null) {
((Colony) goods.getLocation()).removeGoods(goods);
nextPlayer.setArrears(goods);
removeGoodsElement.appendChild(goods.toXMLElement(nextPlayer,
removeGoodsElement.getOwnerDocument()));
}
nextPlayer.getConnection().send(removeGoodsElement);
}
} catch (IOException e) {
logger.warning("Could not send message to: " + nextPlayer.getName());
}
break;
case Monarch.ADD_TO_REF:
int[] addition = monarch.addToREF();
Element additionElement = monarchActionElement.getOwnerDocument().createElement("addition");
additionElement.setAttribute("xLength", Integer.toString(addition.length));
for (int x = 0; x < addition.length; x++) {
additionElement.setAttribute("x" + Integer.toString(x), Integer.toString(addition[x]));
}
monarchActionElement.appendChild(additionElement);
try {
nextPlayer.getConnection().send(monarchActionElement);
} catch (IOException e) {
logger.warning("Could not send message to: " + nextPlayer.getName());
}
break;
case Monarch.DECLARE_WAR:
int nation = monarch.declareWar();
if (nation == Player.NO_NATION) {
// this should not happen
logger.warning( "Declared war on nobody." );
return;
}
nextPlayer.setStance(game.getPlayer(nation), Player.WAR);
monarchActionElement.setAttribute("nation", String.valueOf(nation));
try {
nextPlayer.getConnection().send(monarchActionElement);
} catch (IOException e) {
logger.warning("Could not send message to: " + nextPlayer.getName());
}
break;
case Monarch.SUPPORT_LAND:
int[] additions = monarch.supportLand();
createUnits(additions, monarchActionElement, nextPlayer);
try {
nextPlayer.getConnection().send(monarchActionElement);
} catch (IOException e) {
logger.warning("Could not send message to: " + nextPlayer.getName());
}
break;
case Monarch.SUPPORT_SEA:
newUnit = new Unit(game,
nextPlayer.getEurope(),
nextPlayer,
Unit.FRIGATE,
Unit.ACTIVE);
nextPlayer.getEurope().add(newUnit);
monarchActionElement.appendChild(newUnit.toXMLElement(nextPlayer,
monarchActionElement.getOwnerDocument()));
try {
nextPlayer.getConnection().send(monarchActionElement);
} catch (IOException e) {
logger.warning("Could not send message to: " + nextPlayer.getName());
}
break;
case Monarch.OFFER_MERCENARIES:
int[] units = monarch.getMercenaries();
int price = monarch.getPrice(units, true);
Element mercenaryElement = monarchActionElement.getOwnerDocument().createElement("mercenaries");
monarchActionElement.setAttribute("price", String.valueOf(price));
mercenaryElement.setAttribute("xLength", Integer.toString(units.length));
monarchActionElement.appendChild(mercenaryElement);
for (int x = 0; x < units.length; x++) {
mercenaryElement.setAttribute("x" + Integer.toString(x), Integer.toString(units[x]));
}
try {
Element reply = nextPlayer.getConnection().ask(monarchActionElement);
boolean accepted = Boolean.valueOf(reply.getAttribute("accepted")).booleanValue();
if (accepted) {
Element updateElement = Message.createNewRootElement("monarchAction");
updateElement.setAttribute("action", String.valueOf(Monarch.ADD_UNITS));
nextPlayer.modifyGold(-price);
createUnits(units, updateElement, nextPlayer);
nextPlayer.getConnection().send(updateElement);
}
} catch (IOException e) {
logger.warning("Could not send message to: " + nextPlayer.getName());
}
break;
}
}
};
t.start();
}
private void createUnits(int[] units, Element element, ServerPlayer nextPlayer) {
final Game game = getFreeColServer().getGame();
Unit newUnit;
for (int type = 0; type < units.length; type++) {
for (int i = 0; i < units[type]; i++) {
if (type == Monarch.ARTILLERY) {
newUnit = new Unit(game,
nextPlayer.getEurope(),
nextPlayer,
Unit.ARTILLERY,
Unit.ACTIVE);
} else {
boolean mounted = false;
if (type == Monarch.DRAGOON) {
mounted = true;
}
newUnit = new Unit(game,
nextPlayer.getEurope(),
nextPlayer,
Unit.VETERAN_SOLDIER,
Unit.ACTIVE,
true,
mounted,
0,
false);
}
nextPlayer.getEurope().add(newUnit);
if (element != null) {
element.appendChild(newUnit.toXMLElement(nextPlayer, element.getOwnerDocument()));
}
}
}
}
}
| false | false | null | null |
diff --git a/src/java/org/lwjgl/opengl/WindowsDisplay.java b/src/java/org/lwjgl/opengl/WindowsDisplay.java
index ce9b36dd..606dabef 100644
--- a/src/java/org/lwjgl/opengl/WindowsDisplay.java
+++ b/src/java/org/lwjgl/opengl/WindowsDisplay.java
@@ -1,1104 +1,1105 @@
/*
* Copyright (c) 2002-2008 LWJGL Project
* 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 'LWJGL' 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.lwjgl.opengl;
/**
* This is the Display implementation interface. Display delegates
* to implementors of this interface. There is one DisplayImplementation
* for each supported platform.
* @author elias_naur
*/
import java.nio.*;
import java.awt.Canvas;
import org.lwjgl.LWJGLException;
import org.lwjgl.LWJGLUtil;
import org.lwjgl.BufferUtils;
import org.lwjgl.MemoryUtil;
import org.lwjgl.input.Cursor;
import org.lwjgl.input.Mouse;
import org.lwjgl.opengles.EGL;
final class WindowsDisplay implements DisplayImplementation {
private static final int GAMMA_LENGTH = 256;
private static final int WM_CANCELMODE = 0x001F;
private static final int WM_MOUSEMOVE = 0x0200;
private static final int WM_LBUTTONDOWN = 0x0201;
private static final int WM_LBUTTONUP = 0x0202;
private static final int WM_LBUTTONDBLCLK = 0x0203;
private static final int WM_RBUTTONDOWN = 0x0204;
private static final int WM_RBUTTONUP = 0x0205;
private static final int WM_RBUTTONDBLCLK = 0x0206;
private static final int WM_MBUTTONDOWN = 0x0207;
private static final int WM_MBUTTONUP = 0x0208;
private static final int WM_MBUTTONDBLCLK = 0x0209;
private static final int WM_XBUTTONDOWN = 0x020B;
private static final int WM_XBUTTONUP = 0x020C;
private static final int WM_XBUTTONDBLCLK = 0x020D;
private static final int WM_MOUSEWHEEL = 0x020A;
private static final int WM_CAPTURECHANGED = 0x0215;
private static final int WM_MOUSELEAVE = 0x02A3;
private static final int WM_ENTERSIZEMOVE = 0x0231;
private static final int WM_EXITSIZEMOVE = 0x0232;
private static final int WM_SIZING = 0x0214;
private static final int WM_KEYDOWN = 256;
private static final int WM_KEYUP = 257;
private static final int WM_SYSKEYUP = 261;
private static final int WM_SYSKEYDOWN = 260;
private static final int WM_SYSCHAR = 262;
private static final int WM_CHAR = 258;
private static final int WM_SETICON = 0x0080;
private static final int WM_SETCURSOR = 0x0020;
private static final int WM_QUIT = 0x0012;
private static final int WM_SYSCOMMAND = 0x0112;
private static final int WM_PAINT = 0x000F;
private static final int WM_KILLFOCUS = 8;
private static final int WM_SETFOCUS = 7;
private static final int SC_SIZE = 0xF000;
private static final int SC_MOVE = 0xF010;
private static final int SC_MINIMIZE = 0xF020;
private static final int SC_MAXIMIZE = 0xF030;
private static final int SC_NEXTWINDOW = 0xF040;
private static final int SC_PREVWINDOW = 0xF050;
private static final int SC_CLOSE = 0xF060;
private static final int SC_VSCROLL = 0xF070;
private static final int SC_HSCROLL = 0xF080;
private static final int SC_MOUSEMENU = 0xF090;
private static final int SC_KEYMENU = 0xF100;
private static final int SC_ARRANGE = 0xF110;
private static final int SC_RESTORE = 0xF120;
private static final int SC_TASKLIST = 0xF130;
private static final int SC_SCREENSAVE = 0xF140;
private static final int SC_HOTKEY = 0xF150;
private static final int SC_DEFAULT = 0xF160;
private static final int SC_MONITORPOWER = 0xF170;
private static final int SC_CONTEXTHELP = 0xF180;
private static final int SC_SEPARATOR = 0xF00F;
static final int SM_CXCURSOR = 13;
static final int SM_CYCURSOR = 14;
static final int SM_CMOUSEBUTTONS = 43;
static final int SM_MOUSEWHEELPRESENT = 75;
private static final int SIZE_RESTORED = 0;
private static final int SIZE_MINIMIZED = 1;
private static final int SIZE_MAXIMIZED = 2;
private static final int WM_SIZE = 0x0005;
private static final int WM_ACTIVATE = 0x0006;
private static final int WA_INACTIVE = 0;
private static final int WA_ACTIVE = 1;
private static final int WA_CLICKACTIVE = 2;
private static final int SW_NORMAL = 1;
private static final int SW_SHOWMINNOACTIVE = 7;
private static final int SW_SHOWDEFAULT = 10;
private static final int SW_RESTORE = 9;
private static final int ICON_SMALL = 0;
private static final int ICON_BIG = 1;
private static final IntBuffer rect_buffer = BufferUtils.createIntBuffer(4);
private static final Rect rect = new Rect();
private static final long HWND_TOP = 0;
private static final long HWND_BOTTOM = 1;
private static final long HWND_TOPMOST = -1;
private static final long HWND_NOTOPMOST = -2;
private static final int SWP_NOSIZE = 0x0001;
private static final int SWP_NOMOVE = 0x0002;
private static final int SWP_NOZORDER = 0x0004;
private static final int SWP_FRAMECHANGED = 0x0020;
private static final int GWL_STYLE = -16;
private static final int GWL_EXSTYLE = -20;
private static final int WS_THICKFRAME = 0x00040000;
private static final int WS_MAXIMIZEBOX = 0x00010000;
private static final int HTCLIENT = 0x01;
private static final int MK_XBUTTON1 = 0x0020;
private static final int MK_XBUTTON2 = 0x0040;
private static final int XBUTTON1 = 0x0001;
private static final int XBUTTON2 = 0x0002;
private static WindowsDisplay current_display;
private static boolean cursor_clipped;
private WindowsDisplayPeerInfo peer_info;
private Object current_cursor;
private Canvas parent;
private static boolean hasParent;
private WindowsKeyboard keyboard;
private WindowsMouse mouse;
private boolean close_requested;
private boolean is_dirty;
private ByteBuffer current_gamma;
private ByteBuffer saved_gamma;
private DisplayMode current_mode;
private boolean mode_set;
private boolean isMinimized;
private boolean isFocused;
private boolean did_maximize;
private boolean inAppActivate;
private boolean resized;
private boolean resizable;
private int width;
private int height;
private long hwnd;
private long hdc;
private long small_icon;
private long large_icon;
private int captureMouse = -1;
private boolean trackingMouse;
private boolean mouseInside;
WindowsDisplay() {
current_display = this;
}
public void createWindow(DrawableLWJGL drawable, DisplayMode mode, Canvas parent, int x, int y) throws LWJGLException {
close_requested = false;
is_dirty = false;
isMinimized = false;
isFocused = false;
did_maximize = false;
this.parent = parent;
hasParent = parent != null;
long parent_hwnd = parent != null ? getHwnd(parent) : 0;
this.hwnd = nCreateWindow(x, y, mode.getWidth(), mode.getHeight(), Display.isFullscreen() || isUndecorated(), parent != null, parent_hwnd);
if (hwnd == 0) {
throw new LWJGLException("Failed to create window");
}
this.hdc = getDC(hwnd);
if (hdc == 0) {
nDestroyWindow(hwnd);
throw new LWJGLException("Failed to get dc");
}
try {
if ( drawable instanceof DrawableGL ) {
int format = WindowsPeerInfo.choosePixelFormat(getHdc(), 0, 0, (PixelFormat)drawable.getPixelFormat(), null, true, true, false, true);
WindowsPeerInfo.setPixelFormat(getHdc(), format);
} else {
peer_info = new WindowsDisplayPeerInfo(true);
((DrawableGLES)drawable).initialize(hwnd, hdc, EGL.EGL_WINDOW_BIT, (org.lwjgl.opengles.PixelFormat)drawable.getPixelFormat());
}
peer_info.initDC(getHwnd(), getHdc());
showWindow(getHwnd(), SW_SHOWDEFAULT);
updateWidthAndHeight();
if ( parent == null ) {
if(Display.isResizable()) {
setResizable(true);
}
setForegroundWindow(getHwnd());
setFocus(getHwnd());
}
} catch (LWJGLException e) {
nReleaseDC(hwnd, hdc);
nDestroyWindow(hwnd);
throw e;
}
}
private void updateWidthAndHeight() {
getClientRect(hwnd, rect_buffer);
rect.copyFromBuffer(rect_buffer);
width = rect.right - rect.left;
height = rect.bottom - rect.top;
}
private static native long nCreateWindow(int x, int y, int width, int height, boolean undecorated, boolean child_window, long parent_hwnd) throws LWJGLException;
private static boolean isUndecorated() {
return Display.getPrivilegedBoolean("org.lwjgl.opengl.Window.undecorated");
}
private static long getHwnd(Canvas parent) throws LWJGLException {
AWTCanvasImplementation awt_impl = AWTGLCanvas.createImplementation();
WindowsPeerInfo parent_peer_info = (WindowsPeerInfo)awt_impl.createPeerInfo(parent, null, null);
ByteBuffer parent_peer_info_handle = parent_peer_info.lockAndGetHandle();
try {
return parent_peer_info.getHwnd();
} finally {
parent_peer_info.unlock();
}
}
public void destroyWindow() {
nReleaseDC(hwnd, hdc);
nDestroyWindow(hwnd);
freeLargeIcon();
freeSmallIcon();
resetCursorClipping();
}
private static native void nReleaseDC(long hwnd, long hdc);
private static native void nDestroyWindow(long hwnd);
static void resetCursorClipping() {
if (cursor_clipped) {
try {
clipCursor(null);
} catch (LWJGLException e) {
LWJGLUtil.log("Failed to reset cursor clipping: " + e);
}
cursor_clipped = false;
}
}
private static void getGlobalClientRect(long hwnd, Rect rect) {
rect_buffer.put(0, 0).put(1, 0);
clientToScreen(hwnd, rect_buffer);
int offset_x = rect_buffer.get(0);
int offset_y = rect_buffer.get(1);
getClientRect(hwnd, rect_buffer);
rect.copyFromBuffer(rect_buffer);
rect.offset(offset_x, offset_y);
}
static void setupCursorClipping(long hwnd) throws LWJGLException {
cursor_clipped = true;
getGlobalClientRect(hwnd, rect);
rect.copyToBuffer(rect_buffer);
clipCursor(rect_buffer);
}
private static native void clipCursor(IntBuffer rect) throws LWJGLException;
public void switchDisplayMode(DisplayMode mode) throws LWJGLException {
nSwitchDisplayMode(mode);
current_mode = mode;
mode_set = true;
}
private static native void nSwitchDisplayMode(DisplayMode mode) throws LWJGLException;
/*
* Called when the application is alt-tabbed to or from
*/
private void appActivate(boolean active) {
if (inAppActivate) {
return;
}
inAppActivate = true;
isFocused = active;
if (active) {
if (Display.isFullscreen()) {
restoreDisplayMode();
}
if (parent == null) {
showWindow(getHwnd(), SW_RESTORE);
setForegroundWindow(getHwnd());
setFocus(getHwnd());
}
did_maximize = true;
if (Display.isFullscreen())
updateClipping();
} else if (Display.isFullscreen()) {
showWindow(getHwnd(), SW_SHOWMINNOACTIVE);
resetDisplayMode();
} else
updateClipping();
updateCursor();
inAppActivate = false;
}
private static native void showWindow(long hwnd, int mode);
private static native void setForegroundWindow(long hwnd);
private static native void setFocus(long hwnd);
private void restoreDisplayMode() {
try {
doSetGammaRamp(current_gamma);
} catch (LWJGLException e) {
LWJGLUtil.log("Failed to restore gamma: " + e.getMessage());
}
if (!mode_set) {
mode_set = true;
try {
nSwitchDisplayMode(current_mode);
} catch (LWJGLException e) {
LWJGLUtil.log("Failed to restore display mode: " + e.getMessage());
}
}
}
public void resetDisplayMode() {
try {
doSetGammaRamp(saved_gamma);
} catch (LWJGLException e) {
LWJGLUtil.log("Failed to reset gamma ramp: " + e.getMessage());
}
current_gamma = saved_gamma;
if (mode_set) {
mode_set = false;
nResetDisplayMode();
+ setResizable(this.resizable);
}
resetCursorClipping();
}
private static native void nResetDisplayMode();
public int getGammaRampLength() {
return GAMMA_LENGTH;
}
public void setGammaRamp(FloatBuffer gammaRamp) throws LWJGLException {
doSetGammaRamp(convertToNativeRamp(gammaRamp));
}
private static native ByteBuffer convertToNativeRamp(FloatBuffer gamma_ramp) throws LWJGLException;
private static native ByteBuffer getCurrentGammaRamp() throws LWJGLException;
private void doSetGammaRamp(ByteBuffer native_gamma) throws LWJGLException {
nSetGammaRamp(native_gamma);
current_gamma = native_gamma;
}
private static native void nSetGammaRamp(ByteBuffer native_ramp) throws LWJGLException;
public String getAdapter() {
try {
String maxObjNo = WindowsRegistry.queryRegistrationKey(
WindowsRegistry.HKEY_LOCAL_MACHINE,
"HARDWARE\\DeviceMap\\Video",
"MaxObjectNumber");
int maxObjectNumber = maxObjNo.charAt(0);
String vga_driver_value = "";
for(int i=0;i<maxObjectNumber;i++) {
String adapter_string = WindowsRegistry.queryRegistrationKey(
WindowsRegistry.HKEY_LOCAL_MACHINE,
"HARDWARE\\DeviceMap\\Video",
"\\Device\\Video" + i);
String root_key = "\\registry\\machine\\";
if (adapter_string.toLowerCase().startsWith(root_key)) {
String driver_value = WindowsRegistry.queryRegistrationKey(
WindowsRegistry.HKEY_LOCAL_MACHINE,
adapter_string.substring(root_key.length()),
"InstalledDisplayDrivers");
if(driver_value.toUpperCase().startsWith("VGA")) {
vga_driver_value = driver_value;
} else if(!driver_value.toUpperCase().startsWith("RDP") && !driver_value.toUpperCase().startsWith("NMNDD")) {
return driver_value;
}
}
}
if(!vga_driver_value.equals("")) {
return vga_driver_value;
}
} catch (LWJGLException e) {
LWJGLUtil.log("Exception occurred while querying registry: " + e);
}
return null;
}
public String getVersion() {
String driver = getAdapter();
if (driver != null) {
String[] drivers = driver.split(",");
if(drivers.length>0) {
WindowsFileVersion version = nGetVersion(drivers[0] + ".dll");
if (version != null)
return version.toString();
}
}
return null;
}
private native WindowsFileVersion nGetVersion(String driver);
public DisplayMode init() throws LWJGLException {
current_gamma = saved_gamma = getCurrentGammaRamp();
return current_mode = getCurrentDisplayMode();
}
private static native DisplayMode getCurrentDisplayMode() throws LWJGLException;
public void setTitle(String title) {
ByteBuffer buffer = MemoryUtil.encodeUTF16(title);
nSetTitle(hwnd, MemoryUtil.getAddress0(buffer));
}
private static native void nSetTitle(long hwnd, long title);
public boolean isCloseRequested() {
boolean saved = close_requested;
close_requested = false;
return saved;
}
public boolean isVisible() {
return !isMinimized;
}
public boolean isActive() {
return isFocused;
}
public boolean isDirty() {
boolean saved = is_dirty;
is_dirty = false;
return saved;
}
public PeerInfo createPeerInfo(PixelFormat pixel_format, ContextAttribs attribs) throws LWJGLException {
peer_info = new WindowsDisplayPeerInfo(false);
return peer_info;
}
public void update() {
nUpdate();
if (parent != null && parent.isFocusOwner()) {
setFocus(getHwnd());
}
if (did_maximize) {
did_maximize = false;
/**
* WORKAROUND:
* Making the context current (redundantly) when the window
* is maximized helps some gfx cards recover from fullscreen
*/
try {
Context context = ((DrawableLWJGL)Display.getDrawable()).getContext();
if (context != null && context.isCurrent())
context.makeCurrent();
} catch (LWJGLException e) {
LWJGLUtil.log("Exception occurred while trying to make context current: " + e);
}
}
}
private static native void nUpdate();
public void reshape(int x, int y, int width, int height) {
nReshape(getHwnd(), x, y, width, height, Display.isFullscreen() || isUndecorated(), parent != null);
}
private static native void nReshape(long hwnd, int x, int y, int width, int height, boolean undecorated, boolean child);
public native DisplayMode[] getAvailableDisplayModes() throws LWJGLException;
/* Mouse */
public boolean hasWheel() {
return mouse.hasWheel();
}
public int getButtonCount() {
return mouse.getButtonCount();
}
public void createMouse() throws LWJGLException {
mouse = new WindowsMouse(getHwnd());
}
public void destroyMouse() {
if (mouse != null)
mouse.destroy();
mouse = null;
}
public void pollMouse(IntBuffer coord_buffer, ByteBuffer buttons) {
mouse.poll(coord_buffer, buttons);
}
public void readMouse(ByteBuffer buffer) {
mouse.read(buffer);
}
public void grabMouse(boolean grab) {
mouse.grab(grab, shouldGrab());
updateCursor();
}
public int getNativeCursorCapabilities() {
return Cursor.CURSOR_ONE_BIT_TRANSPARENCY;
}
public void setCursorPosition(int x, int y) {
getGlobalClientRect(getHwnd(), rect);
int transformed_x = rect.left + x;
int transformed_y = rect.bottom - 1 - y;
nSetCursorPosition(transformed_x, transformed_y);
setMousePosition(x, y);
}
private static native void nSetCursorPosition(int x, int y);
public void setNativeCursor(Object handle) throws LWJGLException {
current_cursor = handle;
updateCursor();
}
private void updateCursor() {
try {
if (mouse != null && shouldGrab())
nSetNativeCursor(getHwnd(), mouse.getBlankCursor());
else
nSetNativeCursor(getHwnd(), current_cursor);
} catch (LWJGLException e) {
LWJGLUtil.log("Failed to update cursor: " + e);
}
}
static native void nSetNativeCursor(long hwnd, Object handle) throws LWJGLException;
public int getMinCursorSize() {
return getSystemMetrics(SM_CXCURSOR);
}
public int getMaxCursorSize() {
return getSystemMetrics(SM_CXCURSOR);
}
static native int getSystemMetrics(int index);
private static native long getDllInstance();
private long getHwnd() {
return hwnd;
}
private long getHdc() {
return hdc;
}
private static native long getDC(long hwnd);
private static native long getDesktopWindow();
private static native long getForegroundWindow();
static void centerCursor(long hwnd) {
if (getForegroundWindow() != hwnd && !hasParent)
return;
getGlobalClientRect(hwnd, rect);
int local_offset_x = rect.left;
int local_offset_y = rect.top;
/* -- This is wrong on multi-monitor setups
getGlobalClientRect(getDesktopWindow(), rect2);
Rect.intersect(rect, rect2, rect);
*/
int center_x = (rect.left + rect.right)/2;
int center_y = (rect.top + rect.bottom)/2;
nSetCursorPosition(center_x, center_y);
int local_x = center_x - local_offset_x;
int local_y = center_y - local_offset_y;
if (current_display != null)
current_display.setMousePosition(local_x, transformY(hwnd, local_y));
}
private void setMousePosition(int x, int y) {
if (mouse != null)
mouse.setPosition(x, y);
}
/* Keyboard */
public void createKeyboard() throws LWJGLException {
keyboard = new WindowsKeyboard(getHwnd());
}
public void destroyKeyboard() {
keyboard.destroy();
keyboard = null;
}
public void pollKeyboard(ByteBuffer keyDownBuffer) {
keyboard.poll(keyDownBuffer);
}
public void readKeyboard(ByteBuffer buffer) {
keyboard.read(buffer);
}
// public native int isStateKeySet(int key);
public static native ByteBuffer nCreateCursor(int width, int height, int xHotspot, int yHotspot, int numImages, IntBuffer images, int images_offset, IntBuffer delays, int delays_offset) throws LWJGLException;
public Object createCursor(int width, int height, int xHotspot, int yHotspot, int numImages, IntBuffer images, IntBuffer delays) throws LWJGLException {
return doCreateCursor(width, height, xHotspot, yHotspot, numImages, images, delays);
}
static Object doCreateCursor(int width, int height, int xHotspot, int yHotspot, int numImages, IntBuffer images, IntBuffer delays) throws LWJGLException {
return nCreateCursor(width, height, xHotspot, yHotspot, numImages, images, images.position(), delays, delays != null ? delays.position() : -1);
}
public void destroyCursor(Object cursorHandle) {
doDestroyCursor(cursorHandle);
}
static native void doDestroyCursor(Object cursorHandle);
public int getPbufferCapabilities() {
try {
// Return the capabilities of a minimum pixel format
return nGetPbufferCapabilities(new PixelFormat(0, 0, 0, 0, 0, 0, 0, 0, false));
} catch (LWJGLException e) {
LWJGLUtil.log("Exception occurred while determining pbuffer capabilities: " + e);
return 0;
}
}
private native int nGetPbufferCapabilities(PixelFormat format) throws LWJGLException;
public boolean isBufferLost(PeerInfo handle) {
return ((WindowsPbufferPeerInfo)handle).isBufferLost();
}
public PeerInfo createPbuffer(int width, int height, PixelFormat pixel_format, ContextAttribs attribs,
IntBuffer pixelFormatCaps,
IntBuffer pBufferAttribs) throws LWJGLException {
return new WindowsPbufferPeerInfo(width, height, pixel_format, pixelFormatCaps, pBufferAttribs);
}
public void setPbufferAttrib(PeerInfo handle, int attrib, int value) {
((WindowsPbufferPeerInfo)handle).setPbufferAttrib(attrib, value);
}
public void bindTexImageToPbuffer(PeerInfo handle, int buffer) {
((WindowsPbufferPeerInfo)handle).bindTexImageToPbuffer(buffer);
}
public void releaseTexImageFromPbuffer(PeerInfo handle, int buffer) {
((WindowsPbufferPeerInfo)handle).releaseTexImageFromPbuffer(buffer);
}
private void freeSmallIcon() {
if (small_icon != 0) {
destroyIcon(small_icon);
small_icon = 0;
}
}
private void freeLargeIcon() {
if (large_icon != 0) {
destroyIcon(large_icon);
large_icon = 0;
}
}
/**
* Sets one or more icons for the Display.
* <ul>
* <li>On Windows you should supply at least one 16x16 icon and one 32x32.</li>
* <li>Linux (and similar platforms) expect one 32x32 icon.</li>
* <li>Mac OS X should be supplied one 128x128 icon</li>
* </ul>
* The implementation will use the supplied ByteBuffers with image data in RGBA and perform any conversions nescesarry for the specific platform.
*
* @param icons Array of icons in RGBA mode
* @return number of icons used.
*/
public int setIcon(ByteBuffer[] icons) {
boolean done_small = false;
boolean done_large = false;
int used = 0;
int small_icon_size = 16;
int large_icon_size = 32;
for ( ByteBuffer icon : icons ) {
int size = icon.limit() / 4;
if ( (((int)Math.sqrt(size)) == small_icon_size) && (!done_small) ) {
long small_new_icon = createIcon(small_icon_size, small_icon_size, icon.asIntBuffer());
sendMessage(hwnd, WM_SETICON, ICON_SMALL, small_new_icon);
freeSmallIcon();
small_icon = small_new_icon;
used++;
done_small = true;
}
if ( (((int)Math.sqrt(size)) == large_icon_size) && (!done_large) ) {
long large_new_icon = createIcon(large_icon_size, large_icon_size, icon.asIntBuffer());
sendMessage(hwnd, WM_SETICON, ICON_BIG, large_new_icon);
freeLargeIcon();
large_icon = large_new_icon;
used++;
done_large = true;
}
}
return used;
}
private static native long createIcon(int width, int height, IntBuffer icon);
private static native void destroyIcon(long handle);
private static native long sendMessage(long hwnd, long msg, long wparam, long lparam);
private static native long setWindowLongPtr(long hwnd, int nindex, long longPtr);
private static native long getWindowLongPtr(long hwnd, int nindex);
private static native boolean setWindowPos(long hwnd, long hwnd_after, int x, int y, int cx, int cy, long uflags);
private void handleMouseButton(int button, int state, long millis) {
if (mouse != null) {
mouse.handleMouseButton((byte)button, (byte)state, millis);
// need to capture?
if (captureMouse == -1 && button != -1 && state == 1) {
captureMouse = button;
nSetCapture(hwnd);
}
// done with capture?
if(captureMouse != -1 && button == captureMouse && state == 0) {
captureMouse = -1;
nReleaseCapture();
}
}
if (parent != null && !isFocused) {
setFocus(getHwnd());
}
}
private boolean shouldGrab() {
return !isMinimized && isFocused && Mouse.isGrabbed();
}
private void handleMouseMoved(int x, int y, long millis) {
if (mouse != null) {
mouse.handleMouseMoved(x, y, millis, shouldGrab());
}
}
private static native long nSetCapture(long hwnd);
private static native boolean nReleaseCapture();
private void handleMouseScrolled(int amount, long millis) {
if (mouse != null)
mouse.handleMouseScrolled(amount, millis);
}
private static native void getClientRect(long hwnd, IntBuffer rect);
private void handleChar(long wParam, long lParam, long millis) {
byte previous_state = (byte)((lParam >>> 30) & 0x1);
byte state = (byte)(1 - ((lParam >>> 31) & 0x1));
boolean repeat = state == previous_state;
if (keyboard != null)
keyboard.handleChar((int)(wParam & 0xFFFF), millis, repeat);
}
private void handleKeyButton(long wParam, long lParam, long millis) {
byte previous_state = (byte)((lParam >>> 30) & 0x1);
byte state = (byte)(1 - ((lParam >>> 31) & 0x1));
boolean repeat = state == previous_state; // Repeat message
byte extended = (byte)((lParam >>> 24) & 0x1);
int scan_code = (int)((lParam >>> 16) & 0xFF);
if (keyboard != null) {
keyboard.handleKey((int)wParam, scan_code, extended != 0, state, millis, repeat);
}
}
private static int transformY(long hwnd, int y) {
getClientRect(hwnd, rect_buffer);
rect.copyFromBuffer(rect_buffer);
return (rect.bottom - rect.top) - 1 - y;
}
private static native void clientToScreen(long hwnd, IntBuffer point);
private static int handleMessage(long hwnd, int msg, long wParam, long lParam, long millis) {
if (current_display != null)
return current_display.doHandleMessage(hwnd, msg, wParam, lParam, millis);
else
return defWindowProc(hwnd, msg, wParam, lParam);
}
private static native int defWindowProc(long hwnd, int msg, long wParam, long lParam);
private void checkCursorState() {
updateClipping();
}
private void updateClipping() {
if ((Display.isFullscreen() || (mouse != null && mouse.isGrabbed())) && !isMinimized && isFocused && (getForegroundWindow() == getHwnd() || hasParent)) {
try {
setupCursorClipping(getHwnd());
} catch (LWJGLException e) {
LWJGLUtil.log("setupCursorClipping failed: " + e.getMessage());
}
} else {
resetCursorClipping();
}
}
private void setMinimized(boolean m) {
isMinimized = m;
checkCursorState();
}
private int doHandleMessage(long hwnd, int msg, long wParam, long lParam, long millis) {
switch (msg) {
// disable screen saver and monitor power down messages which wreak havoc
case WM_ACTIVATE:
switch ((int)wParam) {
case WA_ACTIVE:
case WA_CLICKACTIVE:
appActivate(true);
break;
case WA_INACTIVE:
appActivate(false);
break;
}
return 0;
case WM_SIZE:
switch ((int)wParam) {
case SIZE_RESTORED:
case SIZE_MAXIMIZED:
resized = true;
updateWidthAndHeight();
setMinimized(false);
break;
case SIZE_MINIMIZED:
setMinimized(true);
break;
}
return defWindowProc(hwnd, msg, wParam, lParam);
case WM_ENTERSIZEMOVE:
return defWindowProc(hwnd, msg, wParam, lParam);
case WM_EXITSIZEMOVE:
return defWindowProc(hwnd, msg, wParam, lParam);
case WM_SIZING:
resized = true;
updateWidthAndHeight();
return defWindowProc(hwnd, msg, wParam, lParam);
case WM_SETCURSOR:
if((lParam & 0xFFFF) == HTCLIENT) {
// if the cursor is inside the client area, reset it
// to the current LWJGL-cursor
updateCursor();
return -1; //TRUE
} else {
// let Windows handle cursors outside the client area for resizing, etc.
return defWindowProc(hwnd, msg, wParam, lParam);
}
case WM_KILLFOCUS:
appActivate(false);
return 0;
case WM_SETFOCUS:
appActivate(true);
return 0;
case WM_MOUSEMOVE:
int xPos = (int)(short)(lParam & 0xFFFF);
int yPos = transformY(getHwnd(), (int)(short)((lParam >> 16) & 0xFFFF));
handleMouseMoved(xPos, yPos, millis);
checkCursorState();
mouseInside = true;
if(!trackingMouse) {
trackingMouse = nTrackMouseEvent(hwnd);
}
return 0;
case WM_MOUSEWHEEL:
int dwheel = (int)(short)((wParam >> 16) & 0xFFFF);
handleMouseScrolled(dwheel, millis);
return 0;
case WM_LBUTTONDOWN:
handleMouseButton(0, 1, millis);
return 0;
case WM_LBUTTONUP:
handleMouseButton(0, 0, millis);
return 0;
case WM_RBUTTONDOWN:
handleMouseButton(1, 1, millis);
return 0;
case WM_RBUTTONUP:
handleMouseButton(1, 0, millis);
return 0;
case WM_MBUTTONDOWN:
handleMouseButton(2, 1, millis);
return 0;
case WM_MBUTTONUP:
handleMouseButton(2, 0, millis);
return 0;
case WM_XBUTTONUP:
if((wParam >> 16) == XBUTTON1) {
handleMouseButton(3, 0, millis);
} else {
handleMouseButton(4, 0, millis);
}
return 1;
case WM_XBUTTONDOWN:
if((wParam & 0xFF) == MK_XBUTTON1) {
handleMouseButton(3, 1, millis);
} else {
handleMouseButton(4, 1, millis);
}
return 1;
case WM_SYSCHAR:
case WM_CHAR:
handleChar(wParam, lParam, millis);
return 0;
case WM_SYSKEYUP:
/* Fall through */
case WM_KEYUP:
// SysRq apparently only generates WM_KEYUP, so we'll fake a WM_KEYDOWN
if (wParam == WindowsKeycodes.VK_SNAPSHOT && keyboard != null &&
!keyboard.isKeyDown(org.lwjgl.input.Keyboard.KEY_SYSRQ)) {
// Set key state to pressed
long fake_lparam = lParam & ~(1 << 31);
// Set key previous state to released
fake_lparam &= ~(1 << 30);
handleKeyButton(wParam, fake_lparam, millis);
}
/* Fall through */
case WM_SYSKEYDOWN:
/* Fall through */
case WM_KEYDOWN:
handleKeyButton(wParam, lParam, millis);
return defWindowProc(hwnd, msg, wParam, lParam);
case WM_QUIT:
close_requested = true;
return 0;
case WM_SYSCOMMAND:
switch ((int)(wParam & 0xfff0)) {
case SC_KEYMENU:
case SC_MOUSEMENU:
case SC_SCREENSAVE:
case SC_MONITORPOWER:
return 0;
case SC_CLOSE:
close_requested = true;
return 0;
default:
break;
}
return defWindowProc(hwnd, msg, wParam, lParam);
case WM_PAINT:
is_dirty = true;
return defWindowProc(hwnd, msg, wParam, lParam);
case WM_MOUSELEAVE:
mouseInside = false;
trackingMouse = false;
return defWindowProc(hwnd, msg, wParam, lParam);
case WM_CANCELMODE:
nReleaseCapture();
/* fall through */
case WM_CAPTURECHANGED:
if(captureMouse != -1) {
handleMouseButton(captureMouse, 0, millis);
captureMouse = -1;
}
return 0;
default:
return defWindowProc(hwnd, msg, wParam, lParam);
}
}
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
private int firstMouseButtonDown() {
for(int i=0; i<Mouse.getButtonCount(); i++) {
if(Mouse.isButtonDown(i)) {
return i;
}
}
return -1;
}
private native boolean nTrackMouseEvent(long hwnd);
public boolean isInsideWindow() {
return mouseInside;
}
public void setResizable(boolean resizable) {
if(this.resizable != resizable) {
long style = getWindowLongPtr(hwnd, GWL_STYLE);
long styleex = getWindowLongPtr(hwnd, GWL_EXSTYLE);
// update frame style
if(resizable) {
setWindowLongPtr(hwnd, GWL_STYLE, style |= (WS_THICKFRAME | WS_MAXIMIZEBOX));
} else {
setWindowLongPtr(hwnd, GWL_STYLE, style &= ~(WS_THICKFRAME | WS_MAXIMIZEBOX));
}
// from the existing client rect, determine the new window rect
// based on the style changes - using AdjustWindowRectEx.
getClientRect(hwnd, rect_buffer);
rect.copyFromBuffer(rect_buffer);
adjustWindowRectEx(rect_buffer, style, false, styleex);
rect.copyFromBuffer(rect_buffer);
// force a frame update and resize accordingly
setWindowPos(hwnd, HWND_TOP, 0, 0, rect.right - rect.left, rect.bottom - rect.top, SWP_NOMOVE | SWP_NOZORDER | SWP_FRAMECHANGED);
updateWidthAndHeight();
resized = false;
}
this.resizable = resizable;
}
private native boolean adjustWindowRectEx(IntBuffer rectBuffer, long style, boolean menu, long styleex);
public boolean wasResized() {
if(resized) {
resized = false;
return true;
}
return false;
}
private static final class Rect {
public int top;
public int bottom;
public int left;
public int right;
public void copyToBuffer(IntBuffer buffer) {
buffer.put(0, top).put(1, bottom).put(2, left).put(3, right);
}
public void copyFromBuffer(IntBuffer buffer) {
top = buffer.get(0);
bottom = buffer.get(1);
left = buffer.get(2);
right = buffer.get(3);
}
public void offset(int offset_x, int offset_y) {
left += offset_x;
right += offset_x;
top += offset_y;
bottom += offset_y;
}
public static void intersect(Rect r1, Rect r2, Rect dst) {
dst.top = Math.max(r1.top, r2.top);
dst.bottom = Math.min(r1.bottom, r2.bottom);
dst.left = Math.max(r1.left, r2.left);
dst.right = Math.min(r1.right, r2.right);
}
public String toString() {
return "Rect: top = " + top + " bottom = " + bottom + " left = " + left + " right = " + right + ", width: " + (right - left) + ", height: " + (bottom - top);
}
}
}
| 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/src/com/winthier/photos/PhotoCommand.java b/src/com/winthier/photos/PhotoCommand.java
index 619b2d1..debfdb9 100644
--- a/src/com/winthier/photos/PhotoCommand.java
+++ b/src/com/winthier/photos/PhotoCommand.java
@@ -1,136 +1,136 @@
package com.winthier.photos;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.scheduler.BukkitRunnable;
public class PhotoCommand implements CommandExecutor {
public final PhotosPlugin plugin;
public PhotoCommand(PhotosPlugin plugin) {
this.plugin = plugin;
}
public void load(final Player player, final String url) {
ItemStack item = player.getItemInHand();
if (item == null || item.getType() != Material.MAP) {
player.sendMessage("" + ChatColor.RED + "You must hold a photo");
return;
}
short mapId = item.getDurability();
final Photo photo = plugin.getPhoto(mapId);
if (photo == null) {
player.sendMessage("" + ChatColor.RED + "This map is not a photo. To get a photo, visit");
player.sendMessage("" + ChatColor.BLUE + "http://www.winthier.com/contributions");
return;
}
if (!plugin.photosConfig.hasPlayerMap(player, mapId)) {
player.sendMessage("" + ChatColor.RED + "You don't own this map. To get a photo, visit");
player.sendMessage("" + ChatColor.BLUE + "http://www.winthier.com/contributions");
return;
}
new BukkitRunnable() {
public void run() {
if (!photo.loadURL(url)) {
sendAsyncMessage(player, "" + ChatColor.RED + "Can't load URL: " + url);
return;
}
- sendAsyncMessage(player, "" + ChatColor.GREEN + "Image loaded" + url);
+ sendAsyncMessage(player, "" + ChatColor.GREEN + "Image loaded: " + url);
photo.save();
}
}.runTaskAsynchronously(plugin);
}
public void rename(Player player, String name) {
ItemStack item = player.getItemInHand();
if (item == null || item.getType() != Material.MAP) {
player.sendMessage("" + ChatColor.RED + "You must hold the photo you want to rename");
return;
}
short mapId = item.getDurability();
final Photo photo = plugin.getPhoto(mapId);
if (photo == null) {
player.sendMessage("" + ChatColor.RED + "This map is not a photo. To get a photo, visit");
player.sendMessage("" + ChatColor.BLUE + "http://www.winthier.com/contributions");
return;
}
if (!plugin.photosConfig.hasPlayerMap(player, mapId)) {
player.sendMessage("" + ChatColor.RED + "You don't own this map. To get a photo, visit");
player.sendMessage("" + ChatColor.BLUE + "http://www.winthier.com/contributions");
return;
}
photo.setName(name);
player.sendMessage("" + ChatColor.GREEN + "Name changed. Purchase a new copy by typing \"/photo menu\"");
}
public void sendAsyncMessage(final Player sender, final String message) {
new BukkitRunnable() {
public void run() {
sender.sendMessage(message);
}
}.runTask(plugin);
}
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String args[]) {
Player player = null;
if (sender instanceof Player) player = (Player)sender;
if (args.length == 2 && args[0].equals("load")) {
if (player == null) return false;
load(player, args[1]);
return true;
}
if (args.length >= 1 && args[0].equals("create")) {
if (player == null) return false;
String name = "Photo";
if (args.length > 1) {
StringBuilder sb = new StringBuilder(args[1]);
for (int i = 2; i < args.length; ++i) {
sb.append(" ").append(args[i]);
}
if (sb.length() > 32) {
player.sendMessage("" + ChatColor.RED + "Name is too long");
return true;
}
name = sb.toString();
}
plugin.createPhoto(player, name);
return true;
}
if (args.length > 1 && args[0].equals("rename")) {
if (player == null) return false;
StringBuilder sb = new StringBuilder(args[1]);
for (int i = 2; i < args.length; ++i) {
sb.append(" ").append(args[i]);
}
if (sb.length() > 32) {
player.sendMessage("" + ChatColor.RED + "Name is too long");
return true;
}
String name = sb.toString();
rename(player, name);
return true;
}
if (args.length == 1 && args[0].equals("menu")) {
if (player == null) return false;
plugin.photosMenu.openMenu(player);
return true;
}
sender.sendMessage("" + ChatColor.YELLOW + "Usage: /photo [args...]");
sender.sendMessage("" + ChatColor.GRAY + "--- SYNOPSIS ---");
sender.sendMessage("" + ChatColor.YELLOW + "/photo menu");
sender.sendMessage("" + ChatColor.GRAY + "View a menu with all your photos.");
sender.sendMessage("" + ChatColor.YELLOW + "/photo create [name]");
sender.sendMessage("" + ChatColor.GRAY + "Create a photo with the give name.");
sender.sendMessage("" + ChatColor.YELLOW + "/photo rename <url>");
sender.sendMessage("" + ChatColor.GRAY + "Change the name of a photo.");
sender.sendMessage("" + ChatColor.YELLOW + "/photo load <url>");
sender.sendMessage("" + ChatColor.GRAY + "Load a photo from the internet onto the map in your hand.");
return true;
}
}
diff --git a/src/com/winthier/photos/PhotosCommand.java b/src/com/winthier/photos/PhotosCommand.java
index e76ca2d..76ae7e2 100644
--- a/src/com/winthier/photos/PhotosCommand.java
+++ b/src/com/winthier/photos/PhotosCommand.java
@@ -1,51 +1,52 @@
package com.winthier.photos;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class PhotosCommand implements CommandExecutor {
public final PhotosPlugin plugin;
public PhotosCommand(PhotosPlugin plugin) {
this.plugin = plugin;
}
public void grant(CommandSender sender, String player, int amount) {
}
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String args[]) {
Player player = null;
if (sender instanceof Player) player = (Player)sender;
if (args.length == 1 && args[0].equals("reload")) {
plugin.load();
sender.sendMessage("Configuraton reloaded");
return true;
}
if (args.length == 1 && args[0].equals("save")) {
plugin.save();
sender.sendMessage("Configuraton saved");
return true;
}
if (args.length == 3 && args[0].equals("grant")) {
String name = args[1];
Integer amount = null;
try { amount = Integer.parseInt(args[2]); } catch (NumberFormatException e) {}
if (amount == null || amount <= 0) {
sender.sendMessage("" + ChatColor.RED + "[Photos] Positive number exptected: " + args[2]);
return true;
}
plugin.photosConfig.addPlayerBlanks(name, amount);
- sender.sendMessage("" + ChatColor.GREEN + "[Photos] Granted " + player.getName() + " " + amount + " blank photos");
+ plugin.photosConfig.saveConfig();
+ sender.sendMessage("" + ChatColor.GREEN + "[Photos] Granted " + name + " " + amount + " blank photos");
return true;
}
sender.sendMessage("" + ChatColor.YELLOW + "Usage: /photos [args...]");
sender.sendMessage("" + ChatColor.GRAY + "--- SYNOPSIS ---");
sender.sendMessage("" + ChatColor.YELLOW + "/photos grant <player> <#photos>");
sender.sendMessage("" + ChatColor.GRAY + "Give a player more blank photos");
return true;
}
}
| false | false | null | null |
diff --git a/jtrim-core/src/main/java/org/jtrim/concurrent/executor/ThreadPoolTaskExecutor.java b/jtrim-core/src/main/java/org/jtrim/concurrent/executor/ThreadPoolTaskExecutor.java
index b083d74a..e7231d34 100644
--- a/jtrim-core/src/main/java/org/jtrim/concurrent/executor/ThreadPoolTaskExecutor.java
+++ b/jtrim-core/src/main/java/org/jtrim/concurrent/executor/ThreadPoolTaskExecutor.java
@@ -1,586 +1,588 @@
package org.jtrim.concurrent.executor;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jtrim.collections.RefCollection;
import org.jtrim.collections.RefLinkedList;
import org.jtrim.collections.RefList;
import org.jtrim.event.*;
import org.jtrim.utils.ExceptionHelper;
import org.jtrim.utils.ObjectFinalizer;
/**
*
* @author Kelemen Attila
*/
public final class ThreadPoolTaskExecutor extends AbstractTaskExecutorService {
private static final Logger LOGGER = Logger.getLogger(ThreadPoolTaskExecutor.class.getName());
private static final long DEFAULT_THREAD_TIMEOUT_MS = 5000;
private final ObjectFinalizer finalizer;
private final String poolName;
private final ListenerManager<Runnable, Void> listeners;
private volatile int maxQueueSize;
private volatile long threadTimeoutNanos;
private volatile int maxThreadCount;
private final Lock mainLock;
// activeWorkers contains workers which may execute tasks and not only
// cleanup tasks.
private final RefList<Worker> activeWorkers;
private final RefList<Worker> runningWorkers;
private final RefList<QueuedItem> queue; // the oldest task is the head of the queue
private final Condition notFullQueueSignal;
private final Condition checkQueueSignal;
private final Condition terminateSignal;
private volatile ExecutorState state;
public ThreadPoolTaskExecutor(String poolName) {
this(poolName, Runtime.getRuntime().availableProcessors());
}
public ThreadPoolTaskExecutor(String poolName, int maxThreadCount) {
this(poolName, maxThreadCount, Integer.MAX_VALUE);
}
public ThreadPoolTaskExecutor(String poolName, int maxThreadCount, int maxQueueSize) {
this(poolName, maxThreadCount, maxQueueSize,
DEFAULT_THREAD_TIMEOUT_MS, TimeUnit.MILLISECONDS);
}
public ThreadPoolTaskExecutor(
String poolName,
int maxThreadCount,
int maxQueueSize,
long threadTimeout,
TimeUnit timeUnit) {
ExceptionHelper.checkNotNullArgument(poolName, "poolName");
ExceptionHelper.checkArgumentInRange(maxThreadCount, 1, Integer.MAX_VALUE, "maxThreadCount");
ExceptionHelper.checkArgumentInRange(maxQueueSize, 1, Integer.MAX_VALUE, "maxQueueSize");
ExceptionHelper.checkArgumentInRange(threadTimeout, 0, Long.MAX_VALUE, "threadTimeout");
ExceptionHelper.checkNotNullArgument(timeUnit, "timeUnit");
this.poolName = poolName;
this.listeners = new CopyOnTriggerListenerManager<>();
this.maxThreadCount = maxThreadCount;
this.maxQueueSize = maxQueueSize;
this.threadTimeoutNanos = timeUnit.toNanos(threadTimeout);
this.state = ExecutorState.RUNNING;
this.activeWorkers = new RefLinkedList<>();
this.runningWorkers = new RefLinkedList<>();
this.queue = new RefLinkedList<>();
this.mainLock = new ReentrantLock();
this.notFullQueueSignal = mainLock.newCondition();
this.checkQueueSignal = mainLock.newCondition();
this.terminateSignal = mainLock.newCondition();
this.finalizer = new ObjectFinalizer(new Runnable() {
@Override
public void run() {
doShutdown();
}
}, poolName + " ThreadPoolTaskExecutor shutdown");
}
public void setMaxThreadCount(int maxThreadCount) {
ExceptionHelper.checkArgumentInRange(maxThreadCount, 1, Integer.MAX_VALUE, "maxThreadCount");
this.maxThreadCount = maxThreadCount;
}
public void setMaxQueueSize(int maxQueueSize) {
ExceptionHelper.checkArgumentInRange(maxQueueSize, 1, Integer.MAX_VALUE, "maxQueueSize");
this.maxQueueSize = maxQueueSize;
mainLock.lock();
try {
// Actually it might be full but awaking all the waiting threads
// cause only a performance loss. This performance loss is of
// little consequence becuase we don't expect this method to be
// called that much.
notFullQueueSignal.signalAll();
} finally {
mainLock.unlock();
}
}
public void setThreadTimeout(long threadTimeout, TimeUnit timeUnit) {
ExceptionHelper.checkArgumentInRange(threadTimeout, 0, Long.MAX_VALUE, "threadTimeout");
this.threadTimeoutNanos = timeUnit.toNanos(threadTimeout);
}
@Override
protected void submitTask(
CancellationToken cancelToken,
CancellationController cancelController,
CancelableTask task,
Runnable cleanupTask,
boolean hasUserDefinedCleanup) {
CancellationToken waitQueueCancelToken = hasUserDefinedCleanup
? CancellationSource.UNCANCELABLE_TOKEN
: cancelToken;
QueuedItem newItem = isShutdown()
? new QueuedItem(cleanupTask)
: new QueuedItem(cancelToken, cancelController, task, cleanupTask);
try {
boolean submitted = false;
do {
Worker newWorker = new Worker();
if (newWorker.tryStartWorker(newItem)) {
submitted = true;
}
else {
mainLock.lock();
try {
if (!runningWorkers.isEmpty()) {
if (queue.size() < maxQueueSize) {
queue.addLastGetReference(newItem);
checkQueueSignal.signal();
submitted = true;
}
else {
CancelableWaits.await(waitQueueCancelToken, notFullQueueSignal);
}
}
} finally {
mainLock.unlock();
}
}
} while (!submitted);
} catch (OperationCanceledException ex) {
// Notice that this can only be thrown if there
// is no user defined cleanup task and only when waiting for the
// queue to allow adding more elements.
cleanupTask.run();
}
}
private void doShutdown() {
mainLock.lock();
try {
if (state == ExecutorState.RUNNING) {
state = ExecutorState.SHUTTING_DOWN;
checkQueueSignal.signalAll();
}
} finally {
mainLock.unlock();
tryTerminateAndNotify();
}
}
@Override
public void shutdown() {
finalizer.doFinalize();
}
private void setTerminating() {
mainLock.lock();
try {
if (!isTerminating()) {
state = ExecutorState.TERMINATING;
}
// All the workers must wake up, so that they can detect that
// the executor is shutting down and so must they.
checkQueueSignal.signalAll();
} finally {
mainLock.unlock();
tryTerminateAndNotify();
}
}
private void cancelTasksOfWorkers() {
List<Worker> currentWorkers;
mainLock.lock();
try {
currentWorkers = new ArrayList<>(activeWorkers);
} finally {
mainLock.unlock();
}
Throwable toThrow = null;
for (Worker worker: currentWorkers) {
try {
worker.cancelCurrentTask();
} catch (Throwable ex) {
if (toThrow == null) {
toThrow = ex;
}
else {
toThrow.addSuppressed(ex);
}
}
}
if (toThrow != null) {
ExceptionHelper.rethrow(toThrow);
}
}
@Override
public void shutdownAndCancel() {
// First, stop allowing submitting anymore tasks.
// Also, the current implementation mandates shutdown() to be called
// before this ThreadPoolTaskExecutor becomes unreachable.
shutdown();
setTerminating();
cancelTasksOfWorkers();
}
@Override
public boolean isShutdown() {
return state.getStateIndex() >= ExecutorState.SHUTTING_DOWN.getStateIndex();
}
private boolean isTerminating() {
return state.getStateIndex() >= ExecutorState.TERMINATING.getStateIndex();
}
@Override
public boolean isTerminated() {
return state == ExecutorState.TERMINATED;
}
private void notifyTerminate() {
listeners.onEvent(RunnableDispatcher.INSTANCE, null);
}
@Override
public ListenerRef addTerminateListener(Runnable listener) {
ExceptionHelper.checkNotNullArgument(listener, "listener");
// A quick check for the already terminate case.
if (isTerminated()) {
listener.run();
return UnregisteredListenerRef.INSTANCE;
}
AutoUnregisterListener autoListener = new AutoUnregisterListener(listener);
ListenerRef result = autoListener.registerWith(listeners);
if (isTerminated()) {
autoListener.run();
}
return result;
}
@Override
public boolean awaitTermination(CancellationToken cancelToken, long timeout, TimeUnit unit) {
if (!isTerminated()) {
long startTime = System.nanoTime();
long timeoutNanos = unit.toNanos(startTime);
mainLock.lock();
try {
while (!isTerminated()) {
long elapsed = System.nanoTime() - startTime;
long toWaitNanos = timeoutNanos - elapsed;
if (toWaitNanos <= 0) {
throw new OperationCanceledException();
}
CancelableWaits.await(cancelToken,
toWaitNanos, TimeUnit.NANOSECONDS, terminateSignal);
}
} finally {
mainLock.unlock();
}
}
return true;
}
private void tryTerminateAndNotify() {
if (tryTerminate()) {
notifyTerminate();
}
}
private boolean tryTerminate() {
if (isShutdown() && state != ExecutorState.TERMINATED) {
mainLock.lock();
try {
// This check should be more clever because this way can only
// terminate if even cleanup methods were finished.
if (isShutdown() && activeWorkers.isEmpty()) {
if (state != ExecutorState.TERMINATED) {
state = ExecutorState.TERMINATED;
return true;
}
}
} finally {
mainLock.unlock();
}
}
return false;
}
private void writeLog(Level level, String prefix, Throwable ex) {
if (LOGGER.isLoggable(level)) {
LOGGER.log(level, prefix + " in the " + poolName
+ " ThreadPoolTaskExecutor", ex);
}
}
private class Worker extends Thread {
private RefCollection.ElementRef<?> activeSelfRef;
private RefCollection.ElementRef<?> selfRef;
private QueuedItem firstTask;
private final AtomicReference<CancellationController> currentControllerRef;
public Worker() {
this.firstTask = null;
this.activeSelfRef = null;
this.selfRef = null;
this.currentControllerRef = new AtomicReference<>(null);
}
public boolean tryStartWorker(QueuedItem firstTask) {
mainLock.lock();
try {
if (firstTask == null && queue.isEmpty()) {
return false;
}
if (runningWorkers.size() >= maxThreadCount) {
return false;
}
if (!isTerminated()) {
activeSelfRef = activeWorkers.addLastGetReference(this);
}
selfRef = runningWorkers.addLastGetReference(this);
} finally {
mainLock.unlock();
}
this.firstTask = firstTask;
start();
return true;
}
public void cancelCurrentTask() {
CancellationController currentController = currentControllerRef.get();
if (currentController != null) {
currentController.cancel();
}
}
private void executeTask(QueuedItem item) {
assert Thread.currentThread() == this;
currentControllerRef.set(item.cancelController);
try {
if (!isTerminating()) {
item.task.execute(item.cancelToken);
}
else {
if (activeSelfRef != null) {
mainLock.lock();
try {
activeSelfRef.remove();
} finally {
mainLock.unlock();
}
activeSelfRef = null;
}
tryTerminateAndNotify();
}
} finally {
currentControllerRef.set(null);
item.cleanupTask.run();
}
}
private void restartIfNeeded() {
Worker newWorker = null;
mainLock.lock();
try {
if (!queue.isEmpty()) {
newWorker = new Worker();
}
} finally {
mainLock.unlock();
}
if (newWorker != null) {
newWorker.tryStartWorker(null);
}
}
private void finishWorking() {
mainLock.lock();
try {
if (activeSelfRef != null) {
activeSelfRef.remove();
}
selfRef.remove();
} finally {
mainLock.unlock();
}
}
private QueuedItem pollFromQueue() {
long startTime = System.nanoTime();
long toWaitNanos = threadTimeoutNanos;
mainLock.lock();
try {
do {
if (!queue.isEmpty()) {
- return queue.remove(0);
+ QueuedItem result = queue.remove(0);
+ notFullQueueSignal.signal();
+ return result;
}
if (isShutdown()) {
return null;
}
try {
toWaitNanos = checkQueueSignal.awaitNanos(toWaitNanos);
} catch (InterruptedException ex) {
// In this thread, we don't care about interrupts but
// we need to recalculate the allowed waiting time.
toWaitNanos = threadTimeoutNanos - (System.nanoTime() - startTime);
}
} while (toWaitNanos > 0);
} finally {
mainLock.unlock();
}
return null;
}
private void processQueue() {
QueuedItem itemToProcess = pollFromQueue();
while (itemToProcess != null) {
executeTask(itemToProcess);
itemToProcess = pollFromQueue();
}
}
@Override
public void run() {
try {
if (firstTask != null) {
executeTask(firstTask);
firstTask = null;
}
processQueue();
} catch (Throwable ex) {
writeLog(Level.SEVERE, "Unexpected exception", ex);
} finally {
finishWorking();
try {
tryTerminateAndNotify();
} finally {
restartIfNeeded();
}
}
}
}
private static class QueuedItem {
public final CancellationToken cancelToken;
public final CancellationController cancelController;
public final CancelableTask task;
public final Runnable cleanupTask;
public QueuedItem(
CancellationToken cancelToken,
CancellationController cancelController,
CancelableTask task,
Runnable cleanupTask) {
this.cancelToken = cancelToken;
this.cancelController = cancelController;
this.task = task;
this.cleanupTask = cleanupTask;
}
public QueuedItem(Runnable cleanupTask) {
this.cancelToken = CancellationSource.CANCELED_TOKEN;
this.cancelController = DummyCancellationController.INSTANCE;
this.task = DummyCancelableTask.INSTANCE;
this.cleanupTask = cleanupTask;
}
}
public enum DummyCancelableTask implements CancelableTask {
INSTANCE;
@Override
public void execute(CancellationToken cancelToken) {
}
}
public enum DummyCancellationController implements CancellationController {
INSTANCE;
@Override
public void cancel() {
}
}
private enum ExecutorState {
RUNNING(0),
SHUTTING_DOWN(1),
TERMINATING(2), // = tasks are to be canceled
TERMINATED(3);
private final int stateIndex;
private ExecutorState(int stateIndex) {
this.stateIndex = stateIndex;
}
public int getStateIndex() {
return stateIndex;
}
}
private static class AutoUnregisterListener implements Runnable {
private final AtomicReference<Runnable> listener;
private volatile ListenerRef listenerRef;
public AutoUnregisterListener(Runnable listener) {
this.listener = new AtomicReference<>(listener);
this.listenerRef = null;
}
public ListenerRef registerWith(ListenerManager<Runnable, ?> manager) {
ListenerRef currentRef = manager.registerListener(this);
this.listenerRef = currentRef;
if (listener.get() == null) {
this.listenerRef = null;
currentRef.unregister();
}
return currentRef;
}
@Override
public void run() {
Runnable currentListener = listener.getAndSet(null);
ListenerRef currentRef = listenerRef;
if (currentRef != null) {
currentRef.unregister();
}
if (currentListener != null) {
currentListener.run();
}
}
}
private enum RunnableDispatcher implements EventDispatcher<Runnable, Void> {
INSTANCE;
@Override
public void onEvent(Runnable eventListener, Void arg) {
eventListener.run();
}
}
}
| true | false | null | null |
diff --git a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/TaskListNotificationPopup.java b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/TaskListNotificationPopup.java
index 59fe5e6eb..43fc1e0da 100644
--- a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/TaskListNotificationPopup.java
+++ b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/TaskListNotificationPopup.java
@@ -1,218 +1,218 @@
/*******************************************************************************
* Copyright (c) 2004 - 2006 University Of British Columbia 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:
* University Of British Columbia - initial API and implementation
*******************************************************************************/
package org.eclipse.mylar.internal.tasks.ui;
import java.util.List;
import org.eclipse.jface.dialogs.PopupDialog;
import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.mylar.internal.tasks.ui.views.TaskListView;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.forms.events.HyperlinkAdapter;
import org.eclipse.ui.forms.events.HyperlinkEvent;
import org.eclipse.ui.forms.widgets.Form;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.Hyperlink;
import org.eclipse.ui.forms.widgets.ImageHyperlink;
import org.eclipse.ui.forms.widgets.Section;
/**
* @author Rob Elves
*/
public class TaskListNotificationPopup extends PopupDialog {
private static final String NOTIFICATIONS_HIDDEN = " more changes...";
private static final int NUM_NOTIFICATIONS_TO_DISPLAY = 3;
private static final String MYLAR_NOTIFICATION_LABEL = "Mylar Notification";
private Form form;
private Rectangle bounds;
private List<ITaskListNotification> notifications;
private Composite sectionClient;
private FormToolkit toolkit;
public TaskListNotificationPopup(Shell parent) {
super(parent, PopupDialog.INFOPOPUP_SHELLSTYLE | SWT.ON_TOP, false, false, false, false, null, null);
toolkit = new FormToolkit(parent.getDisplay());
}
public void setContents(List<ITaskListNotification> notifications) {
this.notifications = notifications;
}
@Override
protected Control createContents(Composite parent) {
getShell().setBackground(getShell().getDisplay().getSystemColor(SWT.COLOR_GRAY));
return createDialogArea(parent);
}
@Override
protected final Control createDialogArea(final Composite parent) {
getShell().setText(MYLAR_NOTIFICATION_LABEL);
form = toolkit.createForm(parent);
form.getBody().setLayout(new GridLayout());
Section section = toolkit.createSection(form.getBody(), Section.TITLE_BAR);
section.setText(MYLAR_NOTIFICATION_LABEL);
section.setLayout(new GridLayout());
sectionClient = toolkit.createComposite(section);
sectionClient.setLayout(new GridLayout(2, false));
int count = 0;
for (final ITaskListNotification notification : notifications) {
if (count < NUM_NOTIFICATIONS_TO_DISPLAY) {
Label notificationLabelIcon = toolkit.createLabel(sectionClient, "");
notificationLabelIcon.setImage(notification.getOverlayIcon());
ImageHyperlink link = toolkit.createImageHyperlink(sectionClient, SWT.BEGINNING | SWT.WRAP);
link.setText(notification.getLabel());
link.setImage(notification.getNotificationIcon());
link.addHyperlinkListener(new HyperlinkAdapter() {
@Override
public void linkActivated(HyperlinkEvent e) {
notification.openTask();
IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
if (window != null) {
Shell windowShell = window.getShell();
if (windowShell != null) {
windowShell.setMaximized(true);
windowShell.open();
}
}
}
});
String descriptionText = null;
if (notification.getDescription() != null) {
descriptionText = notification.getDescription();
}
if (descriptionText != null) {
Label descriptionLabel = toolkit.createLabel(sectionClient, descriptionText);
GridDataFactory.fillDefaults().span(2, SWT.DEFAULT).applyTo(descriptionLabel);
}
} else {
int numNotificationsRemain = notifications.size() - count;
Hyperlink remainingHyperlink = toolkit.createHyperlink(sectionClient, numNotificationsRemain
+ NOTIFICATIONS_HIDDEN, SWT.NONE);
GridDataFactory.fillDefaults().span(2, SWT.DEFAULT).applyTo(remainingHyperlink);
remainingHyperlink.addHyperlinkListener(new HyperlinkAdapter() {
@Override
public void linkActivated(HyperlinkEvent e) {
- TaskListView.getFromActivePerspective().setFocus();
+ TaskListView.openInActivePerspective().setFocus();
IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
if (window != null) {
Shell windowShell = window.getShell();
if (windowShell != null) {
windowShell.setMaximized(true);
windowShell.open();
}
}
}
});
break;
}
count++;
}
section.setClient(sectionClient);
ImageHyperlink hyperlink = new ImageHyperlink(section, SWT.NONE);
toolkit.adapt(hyperlink, true, true);
hyperlink.setBackground(null);
hyperlink.setImage(TasksUiImages.getImage(TasksUiImages.NOTIFICATION_CLOSE));
hyperlink.addHyperlinkListener(new HyperlinkAdapter() {
public void linkActivated(HyperlinkEvent e) {
close();
}
});
section.setTextClient(hyperlink);
form.pack();
return parent;
}
/**
* Initialize the shell's bounds.
*/
@Override
public void initializeBounds() {
getShell().setBounds(restoreBounds());
}
private Rectangle restoreBounds() {
bounds = form.getBounds();
Rectangle maxBounds = null;
IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
if (window != null) {
maxBounds = window.getShell().getMonitor().getClientArea();
} else {
// fallback
Display display = Display.getCurrent();
if (display == null)
display = Display.getDefault();
if (display != null && !display.isDisposed())
maxBounds = display.getPrimaryMonitor().getClientArea();
}
if (bounds.width > -1 && bounds.height > -1) {
if (maxBounds != null) {
bounds.width = Math.min(bounds.width, maxBounds.width);
bounds.height = Math.min(bounds.height, maxBounds.height);
}
// Enforce an absolute minimal size
bounds.width = Math.max(bounds.width, 30);
bounds.height = Math.max(bounds.height, 30);
}
if (bounds.x > -1 && bounds.y > -1 && maxBounds != null) {
// bounds.x = Math.max(bounds.x, maxBounds.x);
// bounds.y = Math.max(bounds.y, maxBounds.y);
if (bounds.width > -1 && bounds.height > -1) {
bounds.x = maxBounds.x + maxBounds.width - bounds.width;
bounds.y = maxBounds.y + maxBounds.height - bounds.height;
}
}
return bounds;
}
@Override
public boolean close() {
if (toolkit != null) {
if (toolkit.getColors() != null) {
toolkit.dispose();
}
}
return super.close();
}
}
| true | true | protected final Control createDialogArea(final Composite parent) {
getShell().setText(MYLAR_NOTIFICATION_LABEL);
form = toolkit.createForm(parent);
form.getBody().setLayout(new GridLayout());
Section section = toolkit.createSection(form.getBody(), Section.TITLE_BAR);
section.setText(MYLAR_NOTIFICATION_LABEL);
section.setLayout(new GridLayout());
sectionClient = toolkit.createComposite(section);
sectionClient.setLayout(new GridLayout(2, false));
int count = 0;
for (final ITaskListNotification notification : notifications) {
if (count < NUM_NOTIFICATIONS_TO_DISPLAY) {
Label notificationLabelIcon = toolkit.createLabel(sectionClient, "");
notificationLabelIcon.setImage(notification.getOverlayIcon());
ImageHyperlink link = toolkit.createImageHyperlink(sectionClient, SWT.BEGINNING | SWT.WRAP);
link.setText(notification.getLabel());
link.setImage(notification.getNotificationIcon());
link.addHyperlinkListener(new HyperlinkAdapter() {
@Override
public void linkActivated(HyperlinkEvent e) {
notification.openTask();
IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
if (window != null) {
Shell windowShell = window.getShell();
if (windowShell != null) {
windowShell.setMaximized(true);
windowShell.open();
}
}
}
});
String descriptionText = null;
if (notification.getDescription() != null) {
descriptionText = notification.getDescription();
}
if (descriptionText != null) {
Label descriptionLabel = toolkit.createLabel(sectionClient, descriptionText);
GridDataFactory.fillDefaults().span(2, SWT.DEFAULT).applyTo(descriptionLabel);
}
} else {
int numNotificationsRemain = notifications.size() - count;
Hyperlink remainingHyperlink = toolkit.createHyperlink(sectionClient, numNotificationsRemain
+ NOTIFICATIONS_HIDDEN, SWT.NONE);
GridDataFactory.fillDefaults().span(2, SWT.DEFAULT).applyTo(remainingHyperlink);
remainingHyperlink.addHyperlinkListener(new HyperlinkAdapter() {
@Override
public void linkActivated(HyperlinkEvent e) {
TaskListView.getFromActivePerspective().setFocus();
IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
if (window != null) {
Shell windowShell = window.getShell();
if (windowShell != null) {
windowShell.setMaximized(true);
windowShell.open();
}
}
}
});
break;
}
count++;
}
section.setClient(sectionClient);
ImageHyperlink hyperlink = new ImageHyperlink(section, SWT.NONE);
toolkit.adapt(hyperlink, true, true);
hyperlink.setBackground(null);
hyperlink.setImage(TasksUiImages.getImage(TasksUiImages.NOTIFICATION_CLOSE));
hyperlink.addHyperlinkListener(new HyperlinkAdapter() {
public void linkActivated(HyperlinkEvent e) {
close();
}
});
section.setTextClient(hyperlink);
form.pack();
return parent;
}
| protected final Control createDialogArea(final Composite parent) {
getShell().setText(MYLAR_NOTIFICATION_LABEL);
form = toolkit.createForm(parent);
form.getBody().setLayout(new GridLayout());
Section section = toolkit.createSection(form.getBody(), Section.TITLE_BAR);
section.setText(MYLAR_NOTIFICATION_LABEL);
section.setLayout(new GridLayout());
sectionClient = toolkit.createComposite(section);
sectionClient.setLayout(new GridLayout(2, false));
int count = 0;
for (final ITaskListNotification notification : notifications) {
if (count < NUM_NOTIFICATIONS_TO_DISPLAY) {
Label notificationLabelIcon = toolkit.createLabel(sectionClient, "");
notificationLabelIcon.setImage(notification.getOverlayIcon());
ImageHyperlink link = toolkit.createImageHyperlink(sectionClient, SWT.BEGINNING | SWT.WRAP);
link.setText(notification.getLabel());
link.setImage(notification.getNotificationIcon());
link.addHyperlinkListener(new HyperlinkAdapter() {
@Override
public void linkActivated(HyperlinkEvent e) {
notification.openTask();
IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
if (window != null) {
Shell windowShell = window.getShell();
if (windowShell != null) {
windowShell.setMaximized(true);
windowShell.open();
}
}
}
});
String descriptionText = null;
if (notification.getDescription() != null) {
descriptionText = notification.getDescription();
}
if (descriptionText != null) {
Label descriptionLabel = toolkit.createLabel(sectionClient, descriptionText);
GridDataFactory.fillDefaults().span(2, SWT.DEFAULT).applyTo(descriptionLabel);
}
} else {
int numNotificationsRemain = notifications.size() - count;
Hyperlink remainingHyperlink = toolkit.createHyperlink(sectionClient, numNotificationsRemain
+ NOTIFICATIONS_HIDDEN, SWT.NONE);
GridDataFactory.fillDefaults().span(2, SWT.DEFAULT).applyTo(remainingHyperlink);
remainingHyperlink.addHyperlinkListener(new HyperlinkAdapter() {
@Override
public void linkActivated(HyperlinkEvent e) {
TaskListView.openInActivePerspective().setFocus();
IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
if (window != null) {
Shell windowShell = window.getShell();
if (windowShell != null) {
windowShell.setMaximized(true);
windowShell.open();
}
}
}
});
break;
}
count++;
}
section.setClient(sectionClient);
ImageHyperlink hyperlink = new ImageHyperlink(section, SWT.NONE);
toolkit.adapt(hyperlink, true, true);
hyperlink.setBackground(null);
hyperlink.setImage(TasksUiImages.getImage(TasksUiImages.NOTIFICATION_CLOSE));
hyperlink.addHyperlinkListener(new HyperlinkAdapter() {
public void linkActivated(HyperlinkEvent e) {
close();
}
});
section.setTextClient(hyperlink);
form.pack();
return parent;
}
|
diff --git a/android/Common/src/com/googlecode/android_scripting/Process.java b/android/Common/src/com/googlecode/android_scripting/Process.java
index 79b10a1a..b43ad0a9 100644
--- a/android/Common/src/com/googlecode/android_scripting/Process.java
+++ b/android/Common/src/com/googlecode/android_scripting/Process.java
@@ -1,203 +1,197 @@
/*
* Copyright (C) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.googlecode.android_scripting;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.io.Reader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
public class Process {
private static final int DEFAULT_BUFFER_SIZE = 8192;
private final List<String> mArguments;
private final Map<String, String> mEnvironment;
private File mBinary;
private String mName;
private long mStartTime;
protected Integer mPid;
protected FileDescriptor mFd;
protected PrintStream mOut;
protected Reader mIn;
public Process() {
mArguments = new ArrayList<String>();
mEnvironment = new HashMap<String, String>();
}
public void addArgument(String argument) {
mArguments.add(argument);
}
public void addAllArguments(List<String> arguments) {
mArguments.addAll(arguments);
}
public void putAllEnvironmentVariables(Map<String, String> environment) {
mEnvironment.putAll(environment);
}
public void putEnvironmentVariable(String key, String value) {
mEnvironment.put(key, value);
}
public void setBinary(File binary) {
if (!binary.exists()) {
throw new RuntimeException("Binary " + binary + " does not exist!");
}
mBinary = binary;
}
public Integer getPid() {
return mPid;
}
public FileDescriptor getFd() {
return mFd;
}
public PrintStream getOut() {
return mOut;
}
public PrintStream getErr() {
return getOut();
}
public BufferedReader getIn() {
return new BufferedReader(mIn, DEFAULT_BUFFER_SIZE);
}
public void error(Object obj) {
println(obj);
}
public void print(Object obj) {
getOut().print(obj);
}
public void println(Object obj) {
getOut().println(obj);
}
public void start(final Runnable shutdownHook) {
if (isAlive()) {
throw new RuntimeException("Attempted to start process that is already running.");
}
String binaryPath = mBinary.getAbsolutePath();
Log.v("Executing " + binaryPath + " with arguments " + mArguments + " and with environment "
+ mEnvironment.toString());
- // TODO(damonkohler): Why is passing null into createSubprocess different than passing in an
- // empty array?
- String[] argumentsArray = null;
- if (mArguments.size() > 0) {
- argumentsArray = mArguments.toArray(new String[mArguments.size()]);
- }
-
int[] pid = new int[1];
+ String[] argumentsArray = mArguments.toArray(new String[mArguments.size()]);
mFd = Exec.createSubprocess(binaryPath, argumentsArray, getEnvironmentArray(), pid);
mPid = pid[0];
mOut = new PrintStream(new FileOutputStream(mFd), true /* autoflush */);
mIn = new InputStreamReader(new FileInputStream(mFd));
mStartTime = System.currentTimeMillis();
new Thread(new Runnable() {
public void run() {
int result = Exec.waitFor(mPid);
Log.v("Process " + mPid + " exited with result code " + result + ".");
mPid = null;
mOut.close();
try {
BufferedReader r = new BufferedReader(mIn);
String line = r.readLine();
while (line != null) {
Log.v(line);
line = r.readLine();
}
mIn.close();
} catch (IOException e) {
Log.e(e);
}
if (shutdownHook != null) {
shutdownHook.run();
}
}
}).start();
}
private String[] getEnvironmentArray() {
List<String> environmentVariables = new ArrayList<String>();
for (Entry<String, String> entry : mEnvironment.entrySet()) {
environmentVariables.add(entry.getKey() + "=" + entry.getValue());
}
String[] environment = environmentVariables.toArray(new String[environmentVariables.size()]);
return environment;
}
public void kill() {
if (isAlive()) {
android.os.Process.killProcess(mPid);
Log.v("Killed process " + mPid);
}
}
public boolean isAlive() {
return mPid != null;
}
public String getUptime() {
if (!isAlive()) {
return "";
}
long ms = System.currentTimeMillis() - mStartTime;
StringBuffer buffer = new StringBuffer();
int days = (int) (ms / (1000 * 60 * 60 * 24));
int hours = (int) (ms % (1000 * 60 * 60 * 24)) / 3600000;
int minutes = (int) (ms % 3600000) / 60000;
int seconds = (int) (ms % 60000) / 1000;
if (days != 0) {
buffer.append(String.format("%02d:%02d:", days, hours));
} else if (hours != 0) {
buffer.append(String.format("%02d:", hours));
}
buffer.append(String.format("%02d:%02d", minutes, seconds));
return buffer.toString();
}
public String getName() {
return mName;
}
public void setName(String name) {
mName = name;
}
}
diff --git a/android/Common/src/com/googlecode/android_scripting/interpreter/InterpreterConfiguration.java b/android/Common/src/com/googlecode/android_scripting/interpreter/InterpreterConfiguration.java
index ebfed30f..98c5e879 100644
--- a/android/Common/src/com/googlecode/android_scripting/interpreter/InterpreterConfiguration.java
+++ b/android/Common/src/com/googlecode/android_scripting/interpreter/InterpreterConfiguration.java
@@ -1,295 +1,295 @@
/*
* Copyright (C) 2009 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.googlecode.android_scripting.interpreter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ProviderInfo;
import android.content.pm.ResolveInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.Cursor;
import android.net.Uri;
import com.googlecode.android_scripting.Log;
import com.googlecode.android_scripting.interpreter.shell.ShellInterpreter;
/**
* Manages and provides access to the set of available interpreters.
*
* @author Damon Kohler ([email protected])
*/
public class InterpreterConfiguration {
private final InterpreterListener mListener;
private final Set<Interpreter> mInterpreterSet;
private final Set<ConfigurationObserver> mObserverSet;
private final Context mContext;
public interface ConfigurationObserver {
public void onConfigurationChanged();
}
private class InterpreterListener extends BroadcastReceiver {
private final PackageManager mmPackageManager;
private final ContentResolver mmResolver;
private final ExecutorService mmExecutor;
private final Map<String, Interpreter> mmDiscoveredInterpreters;
private InterpreterListener(Context context) {
mmPackageManager = context.getPackageManager();
mmResolver = context.getContentResolver();
mmExecutor = Executors.newSingleThreadExecutor();
mmDiscoveredInterpreters = new HashMap<String, Interpreter>();
}
private void discoverForType(final String mime) {
mmExecutor.submit(new Runnable() {
@Override
public void run() {
Intent intent = new Intent(InterpreterConstants.ACTION_DISCOVER_INTERPRETERS);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.setType(mime);
List<Interpreter> discoveredInterpreters = new ArrayList<Interpreter>();
List<ResolveInfo> resolveInfos = mmPackageManager.queryIntentActivities(intent, 0);
for (ResolveInfo info : resolveInfos) {
Interpreter interpreter = buildInterpreter(info.activityInfo.packageName);
if (interpreter == null) {
continue;
}
mmDiscoveredInterpreters.put(info.activityInfo.packageName, interpreter);
discoveredInterpreters.add(interpreter);
}
mInterpreterSet.addAll(discoveredInterpreters);
for (ConfigurationObserver observer : mObserverSet) {
observer.onConfigurationChanged();
}
}
});
}
private void discoverAll() {
mmExecutor.submit(new Runnable() {
@Override
public void run() {
Intent intent = new Intent(InterpreterConstants.ACTION_DISCOVER_INTERPRETERS);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.setType(InterpreterConstants.MIME + "*");
List<ResolveInfo> resolveInfos = mmPackageManager.queryIntentActivities(intent, 0);
for (ResolveInfo info : resolveInfos) {
addInterpreter(info.activityInfo.packageName);
}
}
});
}
private void addInterpreter(final String packageName) {
if (mmDiscoveredInterpreters.containsKey(packageName)) {
return;
}
mmExecutor.submit(new Runnable() {
@Override
public void run() {
Interpreter discoveredInterpreter = buildInterpreter(packageName);
mmDiscoveredInterpreters.put(packageName, discoveredInterpreter);
mInterpreterSet.add(discoveredInterpreter);
for (ConfigurationObserver observer : mObserverSet) {
observer.onConfigurationChanged();
}
Log.v("Interpreter discovered: " + packageName + "\nBinary: "
+ discoveredInterpreter.getBinary());
}
});
}
private void remove(final String packageName) {
if (!mmDiscoveredInterpreters.containsKey(packageName)) {
return;
}
mmExecutor.submit(new Runnable() {
@Override
public void run() {
Interpreter interpreter = mmDiscoveredInterpreters.get(packageName);
if (interpreter == null) {
return;
}
mInterpreterSet.remove(interpreter);
mmDiscoveredInterpreters.remove(packageName);
for (ConfigurationObserver observer : mObserverSet) {
observer.onConfigurationChanged();
}
}
});
}
- // We require that there's only one interpreter provider per APK
+ // We require that there's only one interpreter provider per APK.
private Interpreter buildInterpreter(String packageName) {
PackageInfo packInfo;
try {
packInfo = mmPackageManager.getPackageInfo(packageName, PackageManager.GET_PROVIDERS);
} catch (NameNotFoundException e) {
throw new RuntimeException("Package '" + packageName + "' not found.");
}
ProviderInfo provider = packInfo.providers[0];
Map<String, String> interpreterMap = getMap(provider, InterpreterConstants.PROVIDER_BASE);
if (interpreterMap == null) {
throw new RuntimeException("Null interpreter map for: " + packageName);
}
Map<String, String> environmentMap = getMap(provider, InterpreterConstants.PROVIDER_ENV);
if (environmentMap == null) {
throw new RuntimeException("Null environment map for: " + packageName);
}
Map<String, String> argumentsMap = getMap(provider, InterpreterConstants.PROVIDER_ARGS);
if (argumentsMap == null) {
throw new RuntimeException("Null arguments map for: " + packageName);
}
return Interpreter.buildFromMaps(interpreterMap, environmentMap, argumentsMap);
}
private Map<String, String> getMap(ProviderInfo provider, String name) {
// Use LinkedHashMap so that order is maintained (important for position CLI arguments).
Map<String, String> map = new LinkedHashMap<String, String>();
Uri uri = Uri.parse("content://" + provider.authority + "/" + name);
Cursor cursor = mmResolver.query(uri, null, null, null, null);
if (cursor == null) {
return map;
}
cursor.moveToFirst();
for (int i = 0; i < cursor.getColumnCount(); i++) {
map.put(cursor.getColumnName(i), cursor.getString(i));
}
return map;
}
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
String packageName = intent.getData().getSchemeSpecificPart();
if (action.equals(InterpreterConstants.ACTION_INTERPRETER_ADDED)) {
addInterpreter(packageName);
} else if (action.equals(InterpreterConstants.ACTION_INTERPRETER_REMOVED)
|| action.equals(Intent.ACTION_PACKAGE_REMOVED)
|| action.equals(Intent.ACTION_PACKAGE_REPLACED)
|| action.equals(Intent.ACTION_PACKAGE_DATA_CLEARED)) {
remove(packageName);
}
}
}
public InterpreterConfiguration(Context context) {
mContext = context;
mInterpreterSet = new CopyOnWriteArraySet<Interpreter>();
mInterpreterSet.add(new ShellInterpreter());
mObserverSet = new CopyOnWriteArraySet<ConfigurationObserver>();
IntentFilter filter = new IntentFilter();
filter.addAction(InterpreterConstants.ACTION_INTERPRETER_ADDED);
filter.addAction(InterpreterConstants.ACTION_INTERPRETER_REMOVED);
filter.addAction(Intent.ACTION_PACKAGE_DATA_CLEARED);
filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
filter.addAction(Intent.ACTION_PACKAGE_REPLACED);
filter.addDataScheme("package");
mListener = new InterpreterListener(mContext);
mContext.registerReceiver(mListener, filter);
}
public void startDiscovering() {
mListener.discoverAll();
}
public void startDiscovering(String mime) {
mListener.discoverForType(mime);
}
public void registerObserver(ConfigurationObserver observer) {
if (observer != null) {
mObserverSet.add(observer);
}
}
public void unregisterObserver(ConfigurationObserver observer) {
if (observer != null) {
mObserverSet.remove(observer);
}
}
/**
* Returns the list of all known interpreters.
*/
public List<? extends Interpreter> getSupportedInterpreters() {
return new ArrayList<Interpreter>(mInterpreterSet);
}
/**
* Returns the list of all installed interpreters.
*/
public List<Interpreter> getInstalledInterpreters() {
List<Interpreter> interpreters = new ArrayList<Interpreter>();
for (Interpreter i : mInterpreterSet) {
if (i.isInstalled()) {
interpreters.add(i);
}
}
return interpreters;
}
/**
* Returns the interpreter matching the provided name or null if no interpreter was found.
*/
public Interpreter getInterpreterByName(String interpreterName) {
for (Interpreter i : mInterpreterSet) {
if (i.getName().equals(interpreterName)) {
return i;
}
}
return null;
}
/**
* Returns the correct interpreter for the provided script name based on the script's extension or
* null if no interpreter was found.
*/
public Interpreter getInterpreterForScript(String scriptName) {
int dotIndex = scriptName.lastIndexOf('.');
if (dotIndex == -1) {
return null;
}
String ext = scriptName.substring(dotIndex);
for (Interpreter i : mInterpreterSet) {
if (i.getExtension().equals(ext)) {
return i;
}
}
return null;
}
}
diff --git a/android/ScriptingLayer/src/com/googlecode/android_scripting/interpreter/InterpreterProcess.java b/android/ScriptingLayer/src/com/googlecode/android_scripting/interpreter/InterpreterProcess.java
index bcaa8844..e99166ad 100644
--- a/android/ScriptingLayer/src/com/googlecode/android_scripting/interpreter/InterpreterProcess.java
+++ b/android/ScriptingLayer/src/com/googlecode/android_scripting/interpreter/InterpreterProcess.java
@@ -1,262 +1,261 @@
/*
* Copyright (C) 2009 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.googlecode.android_scripting.interpreter;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import com.googlecode.android_scripting.AndroidProxy;
import com.googlecode.android_scripting.Process;
/**
* This is a skeletal implementation of an interpreter process.
*
* @author Damon Kohler ([email protected])
*/
public class InterpreterProcess extends Process {
private static final int BUFFER_SIZE = 8192;
private final AndroidProxy mProxy;
private final StringBuffer mLog;
private final Interpreter mInterpreter;
private String mCommand;
private volatile int mLogLength = 0;
/**
* Creates a new {@link InterpreterProcess}.
*
* @param launchScript
* the absolute path to a script that should be launched with the interpreter
* @param port
* the port that the AndroidProxy is listening on
*/
public InterpreterProcess(Interpreter interpreter, AndroidProxy proxy) {
mProxy = proxy;
mLog = new StringBuffer();
mInterpreter = interpreter;
setBinary(interpreter.getBinary());
setName(interpreter.getNiceName());
setCommand(interpreter.getInteractiveCommand());
-
addAllArguments(interpreter.getArguments());
-
putAllEnvironmentVariables(System.getenv());
putEnvironmentVariable("AP_HOST", getHost());
putEnvironmentVariable("AP_PORT", Integer.toString(getPort()));
if (proxy.getSecret() != null) {
putEnvironmentVariable("AP_HANDSHAKE", getSecret());
}
putAllEnvironmentVariables(interpreter.getEnvironmentVariables());
}
protected void setCommand(String command) {
mCommand = command;
}
public Interpreter getInterpreter() {
return mInterpreter;
}
public String getHost() {
return mProxy.getAddress().getHostName();
}
public int getPort() {
return mProxy.getAddress().getPort();
}
public String getSecret() {
return mProxy.getSecret();
}
@Override
public void start(final Runnable shutdownHook) {
- addArgument(mCommand);
+ // NOTE(damonkohler): String.isEmpty() doesn't work on Cupcake.
+ if (!mCommand.equals("")) {
+ addArgument(mCommand);
+ }
super.start(shutdownHook);
}
@Override
public void kill() {
super.kill();
- if (mProxy != null) {
- mProxy.shutdown();
- }
+ mProxy.shutdown();
}
@Override
public BufferedReader getIn() {
return new LoggingBufferedReader(mIn, BUFFER_SIZE);
}
// TODO(Alexey): Add Javadoc.
private class LoggingBufferedReader extends BufferedReader {
private boolean mmSkipLF = false;
// TODO(Alexey): Use persistent storage
// replace with circular log, see ConnectBot
private int mmPos = 0;
public LoggingBufferedReader(Reader in) {
super(in);
}
public LoggingBufferedReader(Reader in, int size) {
super(in, size);
}
@Override
public int read() throws IOException {
if (mmPos == mLogLength) {
return read1();
} else {
int c = mLog.charAt(mmPos);
mmPos++;
return c;
}
}
private int read1() throws IOException {
int c;
synchronized (lock) {
// check again
if (mmPos < mLogLength) {
c = mLog.charAt(mmPos);
} else {
c = (char) super.read();
mLog.append(Character.valueOf((char) c));
mLogLength++;
}
}
mmPos++;
return c;
}
@Override
public int read(char cbuf[], int off, int len) throws IOException {
if (mmPos == mLogLength) {
return read1(cbuf, off, len);
} else {
int count = 0;
int end = Math.min(mLogLength, mmPos + len);
mLog.getChars(mmPos, end, cbuf, off);
count = end - mmPos;
len -= count;
off += count;
mmPos += count;
if (len > 0) {
int read = read1(cbuf, off, len);
if (read < 0) {
return read;
}
count += read;
}
return count;
}
}
private int read1(char cbuf[], int off, int len) throws IOException {
int count = 0;
synchronized (lock) {
if (mmPos < mLogLength) {
int end = Math.min(mLogLength, mmPos + len);
mLog.getChars(mmPos, end, cbuf, off);
count = end - mmPos;
len -= count;
off += count;
mmPos += count;
}
if (len > 0) {
int read = super.read(cbuf, off, len);
if (read < 0) {
return read;
}
mLog.append(cbuf, off, read);
mLogLength += read;
mmPos += read;
count += read;
}
}
return count;
}
@Override
public String readLine() throws IOException {
if (mmPos == mLogLength) {
return readLine1();
} else {
StringBuffer buffer = new StringBuffer();
while (mmPos < mLogLength) {
char nextChar = mLog.charAt(mmPos);
mmPos++;
if (mmSkipLF) {
mmSkipLF = false;
if (nextChar == '\n') {
continue;
}
}
buffer.append(nextChar);
if (nextChar == '\n') {
return buffer.toString();
}
if (nextChar == '\r') {
mmSkipLF = true;
return buffer.toString();
}
}
buffer.append(readLine1());
return buffer.toString();
}
}
private String readLine1() throws IOException {
StringBuffer buffer = new StringBuffer();
synchronized (lock) {
while (mmPos < mLogLength) {
char nextChar = mLog.charAt(mmPos);
mmPos++;
if (mmSkipLF) {
mmSkipLF = false;
if (nextChar == '\n') {
continue;
}
}
buffer.append(nextChar);
if (nextChar == '\n') {
return buffer.toString();
}
if (nextChar == '\r') {
mmSkipLF = true;
return buffer.toString();
}
}
String str = super.readLine();
if (mmSkipLF && str.length() == 1 && str.charAt(0) == '\n') {
mmSkipLF = false;
str = super.readLine();
}
mLog.append(str);
mLog.append('\n');
mLogLength += str.length() + 1;
mmPos += str.length() + 1;
return buffer.append(str).toString();
}
}
}
}
| false | false | null | null |
diff --git a/src/main/java/com/github/danielwegener/xjcguava/XjcGuavaPlugin.java b/src/main/java/com/github/danielwegener/xjcguava/XjcGuavaPlugin.java
index c50319b..0582c91 100644
--- a/src/main/java/com/github/danielwegener/xjcguava/XjcGuavaPlugin.java
+++ b/src/main/java/com/github/danielwegener/xjcguava/XjcGuavaPlugin.java
@@ -1,220 +1,222 @@
/*
* Copyright 2013 Daniel Wegener
*
* Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.github.danielwegener.xjcguava;
import com.sun.codemodel.*;
import com.sun.tools.xjc.BadCommandLineException;
import com.sun.tools.xjc.Options;
import com.sun.tools.xjc.Plugin;
import com.sun.tools.xjc.outline.ClassOutline;
import com.sun.tools.xjc.outline.Outline;
import org.xml.sax.ErrorHandler;
import java.io.IOException;
import java.util.*;
/**
* <p>Generates hashCode, equals and toString methods using Guavas Objects helper class.</p>
*
* @author Daniel Wegener
*/
public class XjcGuavaPlugin extends Plugin {
public static final String OPTION_NAME = "Xguava";
public static final String SKIP_TOSTRING_PARAM = "-"+OPTION_NAME + ":skipToString";
@Override
public String getOptionName() {
return OPTION_NAME;
}
@Override
public String getUsage() {
return " -" + OPTION_NAME + "\t: enable generation of guava toString, equals and hashCode methods"
+ "\n -" + SKIP_TOSTRING_PARAM + "\t: dont wrap collection parameters with Collections.unmodifiable...";
}
@Override
public int parseArgument(Options opt, String[] args, int i) throws BadCommandLineException, IOException {
final String arg = args[i].trim();
if (SKIP_TOSTRING_PARAM.equals(arg)) {
skipToString = true;
return 1;
}
return 0;
}
private boolean skipToString = false;
@Override
public boolean run(final Outline outline, final Options options, final ErrorHandler errorHandler) {
// For each defined class
final JCodeModel model = outline.getCodeModel();
for (final ClassOutline classOutline : outline.getClasses()) {
final JDefinedClass implClass = classOutline.implClass;
if (!skipToString && !implClass.isAbstract() && implClass.getMethod("toString",new JType[0]) == null) {
generateToStringMethod(model, implClass);
}
if (!implClass.isAbstract()) {
if (implClass.getMethod("hashCode",new JType[0]) == null)
generateHashCodeMethod(model, implClass);
if (implClass.getMethod("equals",new JType[]{model._ref(Object.class)}) == null) {
generateEqualsMethod(model,implClass);
}
}
}
return true;
}
protected void generateToStringMethod(JCodeModel model, JDefinedClass clazz) {
final JMethod toStringMethod = clazz.method(JMod.PUBLIC, String.class,"toString");
toStringMethod.annotate(Override.class);
final JClass objects = model.ref(com.google.common.base.Objects.class);
final Collection<JFieldVar> superClassInstanceFields = getInstanceFields(getSuperclassFields(clazz));
final Collection<JFieldVar> thisClassInstanceFields = getInstanceFields(clazz.fields().values());
final JBlock content = toStringMethod.body();
final JInvocation toStringHelperCall = objects.staticInvoke("toStringHelper");
toStringHelperCall.arg(JExpr._this());
JInvocation fluentCall = toStringHelperCall;
for (JFieldVar superField : superClassInstanceFields) {
fluentCall = fluentCall.invoke("add");
fluentCall.arg(JExpr.lit(superField.name()));
fluentCall.arg(superField);
}
for (JFieldVar thisField : thisClassInstanceFields) {
fluentCall = fluentCall.invoke("add");
fluentCall.arg(JExpr.lit(thisField.name()));
fluentCall.arg(thisField);
}
fluentCall = fluentCall.invoke("toString");
content._return(fluentCall);
}
protected void generateHashCodeMethod(JCodeModel model, JDefinedClass clazz) {
final JClass objects = model.ref(com.google.common.base.Objects.class);
final Collection<JFieldVar> thisClassInstanceFields = getInstanceFields(clazz.fields().values());
final Collection<JFieldVar> superClassInstanceFields = getInstanceFields(getSuperclassFields(clazz));
// Dont create hashCode for empty classes
if (thisClassInstanceFields.isEmpty() && superClassInstanceFields.isEmpty()) return;
final JMethod hashCodeMethod = clazz.method(JMod.PUBLIC, model.INT ,"hashCode");
final JBlock content = hashCodeMethod.body();
hashCodeMethod.annotate(Override.class);
final JInvocation hashCodeCall = objects.staticInvoke("hashCode");
for (JFieldVar superField : superClassInstanceFields) {
hashCodeCall.arg(superField);
}
for (JFieldVar thisField : thisClassInstanceFields) {
hashCodeCall.arg(thisField);
}
content._return(hashCodeCall);
}
protected void generateEqualsMethod(JCodeModel model, JDefinedClass clazz) {
final Collection<JFieldVar> superClassInstanceFields = getInstanceFields(getSuperclassFields(clazz));
final Collection<JFieldVar> thisClassInstanceFields = getInstanceFields(clazz.fields().values());
// Dont create hashCode for empty classes
if (thisClassInstanceFields.isEmpty() && superClassInstanceFields.isEmpty()) return;
final JMethod equalsMethod = clazz.method(JMod.PUBLIC, model.BOOLEAN ,"equals");
equalsMethod.annotate(Override.class);
final JVar other = equalsMethod.param(Object.class,"other");
final JClass objects = model.ref(com.google.common.base.Objects.class);
final JBlock content = equalsMethod.body();
final JConditional ifSameRef = content._if(JExpr._this().eq(other));
ifSameRef._then()._return(JExpr.TRUE);
final JConditional isOtherNull = content._if(other.eq(JExpr._null()));
isOtherNull._then()._return(JExpr.FALSE);
JExpression equalsBuilder = JExpr.TRUE;
+ final JConditional isOtherNotSameClass = content._if(JExpr.invoke("getClass").ne(other.invoke("getClass")));
+ isOtherNotSameClass._then()._return(JExpr.FALSE);
+
final JVar otherTypesafe = content.decl(JMod.FINAL, clazz, "o", JExpr.cast(clazz, other));
- content._if(otherTypesafe.eq(JExpr._null()))._then()._return(JExpr.FALSE);
for (JFieldVar superField : superClassInstanceFields) {
final JInvocation equalsInvocation = objects.staticInvoke("equal");
equalsInvocation.arg(superField);
equalsInvocation.arg(otherTypesafe.ref(superField));
equalsBuilder = equalsBuilder.cand(equalsInvocation);
}
for (JFieldVar thisField : thisClassInstanceFields) {
final JInvocation equalsInvocation = objects.staticInvoke("equal");
equalsInvocation.arg(thisField);
equalsInvocation.arg(otherTypesafe.ref(thisField));
equalsBuilder = equalsBuilder.cand(equalsInvocation);
}
content._return(equalsBuilder);
}
/**
* Takes a collection of fields, and returns a new collection containing only the instance
* (i.e. non-static) fields.
*/
protected Collection<JFieldVar> getInstanceFields(final Collection<JFieldVar> fields) {
final List<JFieldVar> instanceFields = new ArrayList<JFieldVar>();
for (final JFieldVar field : fields) {
if (!isStatic(field)) {
instanceFields.add(field);
}
}
return instanceFields;
}
protected List<JFieldVar> getSuperclassFields(final JDefinedClass implClass) {
final List<JFieldVar> fieldList = new LinkedList<JFieldVar>();
JClass superclass = implClass._extends();
while (superclass instanceof JDefinedClass) {
fieldList.addAll(0, ((JDefinedClass) superclass).fields().values());
superclass = superclass._extends();
}
return fieldList;
}
protected boolean isStatic(final JFieldVar field) {
final JMods fieldMods = field.mods();
return (fieldMods.getValue() & JMod.STATIC) > 0;
}
}
\ No newline at end of file
| false | false | null | null |
diff --git a/src/test/java/org/apache/hadoop/hbase/master/TestCatalogJanitor.java b/src/test/java/org/apache/hadoop/hbase/master/TestCatalogJanitor.java
index 57d85d88a..c8e8f7566 100644
--- a/src/test/java/org/apache/hadoop/hbase/master/TestCatalogJanitor.java
+++ b/src/test/java/org/apache/hadoop/hbase/master/TestCatalogJanitor.java
@@ -1,251 +1,251 @@
/**
* Copyright 2010 The Apache Software Foundation
*
* 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.hadoop.hbase.master;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.HBaseTestingUtility;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.HRegionInfo;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.KeyValue;
import org.apache.hadoop.hbase.NotAllMetaRegionsOnlineException;
import org.apache.hadoop.hbase.Server;
import org.apache.hadoop.hbase.catalog.CatalogTracker;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.executor.ExecutorService;
import org.apache.hadoop.hbase.io.Reference;
import org.apache.hadoop.hbase.ipc.HRegionInterface;
import org.apache.hadoop.hbase.regionserver.Store;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.util.Writables;
import org.apache.hadoop.hbase.zookeeper.ZooKeeperWatcher;
import org.junit.Test;
import org.mockito.Mockito;
public class TestCatalogJanitor {
/**
* Pseudo server for below tests.
*/
class MockServer implements Server {
private final Configuration c;
private final CatalogTracker ct;
MockServer(final HBaseTestingUtility htu)
throws NotAllMetaRegionsOnlineException, IOException {
this.c = htu.getConfiguration();
// Set hbase.rootdir into test dir.
FileSystem fs = FileSystem.get(this.c);
Path rootdir =
fs.makeQualified(HBaseTestingUtility.getTestDir(HConstants.HBASE_DIR));
this.c.set(HConstants.HBASE_DIR, rootdir.toString());
this.ct = Mockito.mock(CatalogTracker.class);
HRegionInterface hri = Mockito.mock(HRegionInterface.class);
Mockito.when(ct.waitForMetaServerConnectionDefault()).thenReturn(hri);
}
@Override
public CatalogTracker getCatalogTracker() {
return this.ct;
}
@Override
public Configuration getConfiguration() {
return this.c;
}
@Override
public String getServerName() {
- return null;
+ return "mockserver.example.org,1234,-1L";
}
@Override
public ZooKeeperWatcher getZooKeeper() {
return null;
}
@Override
public void abort(String why, Throwable e) {
//no-op
}
@Override
public boolean isStopped() {
return false;
}
@Override
public void stop(String why) {
//no-op
}
}
/**
* Mock MasterServices for tests below.
*/
class MockMasterServices implements MasterServices {
private final MasterFileSystem mfs;
MockMasterServices(final Server server) throws IOException {
this.mfs = new MasterFileSystem(server, null);
}
@Override
public void checkTableModifiable(byte[] tableName) throws IOException {
//no-op
}
@Override
public AssignmentManager getAssignmentManager() {
return null;
}
@Override
public ExecutorService getExecutorService() {
return null;
}
@Override
public MasterFileSystem getMasterFileSystem() {
return this.mfs;
}
@Override
public ServerManager getServerManager() {
return null;
}
@Override
public ZooKeeperWatcher getZooKeeper() {
return null;
}
@Override
public CatalogTracker getCatalogTracker() {
return null;
}
@Override
public Configuration getConfiguration() {
return null;
}
@Override
public String getServerName() {
return null;
}
@Override
public void abort(String why, Throwable e) {
//no-op
}
@Override
public void stop(String why) {
//no-op
}
@Override
public boolean isStopped() {
return false;
}
}
@Test
public void testGetHRegionInfo() throws IOException {
assertNull(CatalogJanitor.getHRegionInfo(new Result()));
List<KeyValue> kvs = new ArrayList<KeyValue>();
Result r = new Result(kvs);
assertNull(CatalogJanitor.getHRegionInfo(r));
byte [] f = HConstants.CATALOG_FAMILY;
// Make a key value that doesn't have the expected qualifier.
kvs.add(new KeyValue(HConstants.EMPTY_BYTE_ARRAY, f,
HConstants.SERVER_QUALIFIER, f));
r = new Result(kvs);
assertNull(CatalogJanitor.getHRegionInfo(r));
// Make a key that does not have a regioninfo value.
kvs.add(new KeyValue(HConstants.EMPTY_BYTE_ARRAY, f,
HConstants.REGIONINFO_QUALIFIER, f));
HRegionInfo hri = CatalogJanitor.getHRegionInfo(new Result(kvs));
assertTrue(hri == null);
// OK, give it what it expects
kvs.clear();
kvs.add(new KeyValue(HConstants.EMPTY_BYTE_ARRAY, f,
HConstants.REGIONINFO_QUALIFIER,
Writables.getBytes(HRegionInfo.FIRST_META_REGIONINFO)));
hri = CatalogJanitor.getHRegionInfo(new Result(kvs));
assertNotNull(hri);
assertTrue(hri.equals(HRegionInfo.FIRST_META_REGIONINFO));
}
@Test
public void testCleanParent() throws IOException {
HBaseTestingUtility htu = new HBaseTestingUtility();
Server server = new MockServer(htu);
MasterServices services = new MockMasterServices(server);
CatalogJanitor janitor = new CatalogJanitor(server, services);
// Create regions.
HTableDescriptor htd = new HTableDescriptor("table");
htd.addFamily(new HColumnDescriptor("family"));
HRegionInfo parent =
new HRegionInfo(htd, Bytes.toBytes("aaa"), Bytes.toBytes("eee"));
HRegionInfo splita =
new HRegionInfo(htd, Bytes.toBytes("aaa"), Bytes.toBytes("ccc"));
HRegionInfo splitb =
new HRegionInfo(htd, Bytes.toBytes("ccc"), Bytes.toBytes("eee"));
// Test that when both daughter regions are in place, that we do not
// remove the parent.
List<KeyValue> kvs = new ArrayList<KeyValue>();
kvs.add(new KeyValue(parent.getRegionName(), HConstants.CATALOG_FAMILY,
HConstants.SPLITA_QUALIFIER, Writables.getBytes(splita)));
kvs.add(new KeyValue(parent.getRegionName(), HConstants.CATALOG_FAMILY,
HConstants.SPLITB_QUALIFIER, Writables.getBytes(splitb)));
Result r = new Result(kvs);
// Add a reference under splitA directory so we don't clear out the parent.
Path rootdir = services.getMasterFileSystem().getRootDir();
Path tabledir =
HTableDescriptor.getTableDir(rootdir, htd.getName());
Path storedir = Store.getStoreHomedir(tabledir, splita.getEncodedName(),
htd.getColumnFamilies()[0].getName());
Reference ref = new Reference(Bytes.toBytes("ccc"), Reference.Range.top);
long now = System.currentTimeMillis();
// Reference name has this format: StoreFile#REF_NAME_PARSER
Path p = new Path(storedir, Long.toString(now) + "." + parent.getEncodedName());
FileSystem fs = services.getMasterFileSystem().getFileSystem();
ref.write(fs, p);
assertFalse(janitor.cleanParent(parent, r));
// Remove the reference file and try again.
assertTrue(fs.delete(p, true));
assertTrue(janitor.cleanParent(parent, r));
}
-}
\ No newline at end of file
+}
| false | false | null | null |
diff --git a/geoserver/analytics/src/main/java/org/opengeo/analytics/RequestMapInitializer.java b/geoserver/analytics/src/main/java/org/opengeo/analytics/RequestMapInitializer.java
index 0d7627df6..b95cabbee 100644
--- a/geoserver/analytics/src/main/java/org/opengeo/analytics/RequestMapInitializer.java
+++ b/geoserver/analytics/src/main/java/org/opengeo/analytics/RequestMapInitializer.java
@@ -1,271 +1,271 @@
package org.opengeo.analytics;
import java.io.File;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;
import org.geoserver.catalog.Catalog;
import org.geoserver.catalog.DataStoreInfo;
import org.geoserver.catalog.FeatureTypeInfo;
import org.geoserver.catalog.LayerGroupInfo;
import org.geoserver.catalog.LayerInfo;
import org.geoserver.catalog.NamespaceInfo;
import org.geoserver.catalog.ProjectionPolicy;
import org.geoserver.catalog.StyleInfo;
import org.geoserver.catalog.WorkspaceInfo;
import org.geoserver.config.GeoServer;
import org.geoserver.config.GeoServerInitializer;
import org.geoserver.data.util.IOUtils;
import org.geoserver.monitor.hib.MonitoringDataSource;
import org.geoserver.platform.GeoServerResourceLoader;
import org.geotools.data.postgis.PostgisNGDataStoreFactory;
import org.geotools.data.shapefile.ShapefileDataStoreFactory;
import org.geotools.geometry.jts.ReferencedEnvelope;
import org.geotools.jdbc.JDBCDataStoreFactory;
import org.geotools.jdbc.VirtualTable;
import org.geotools.referencing.CRS;
import org.geotools.util.logging.Logging;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import com.vividsolutions.jts.geom.Point;
import org.geotools.jdbc.RegexpValidator;
import org.geotools.jdbc.VirtualTableParameter;
public class RequestMapInitializer implements GeoServerInitializer {
static Logger LOGGER = Logging.getLogger("org.opengeo.analytics");
- static String START_END_REGEXP = "start_time > '[^();]'+ and end_time < '[^();]'+";
+ static String START_END_REGEXP = "start_time > '[^();]+' and end_time < '[^();]+'";
MonitoringDataSource dataSource;
public RequestMapInitializer(MonitoringDataSource dataSource) {
this.dataSource = dataSource;
}
public void initialize(GeoServer geoServer) throws Exception {
Catalog cat = geoServer.getCatalog();
//set up a workspace
WorkspaceInfo ws = null;
if ((ws = cat.getWorkspaceByName("analytics")) == null) {
ws = cat.getFactory().createWorkspace();
ws.setName("analytics");
cat.add(ws);
NamespaceInfo ns = cat.getFactory().createNamespace();
ns.setPrefix("analytics");
ns.setURI("http://opengeo.org/analytics");
cat.add(ns);
}
//set up the styles
addStyle(cat, "analytics_requests_agg");
//setup data files
GeoServerResourceLoader rl = cat.getResourceLoader();
// File f = rl.find("data", "monitor", "monitor_world.shp");
// if (f == null) {
// File dir = rl.findOrCreateDirectory("data", "monitor");
// IOUtils.decompress(getClass().getResourceAsStream("monitor_world.zip"), dir);
// f = rl.find("data", "monitor", "monitor_world.shp");
// }
//
// //setup a datastore for the base layer
// if (cat.getDataStoreByName("monitor", "monitor_world") == null) {
// DataStoreInfo ds = cat.getFactory().createDataStore();
// ds.setWorkspace(ws);
// ds.setName("monitor_world");
// ds.getConnectionParameters().put(ShapefileDataStoreFactory.URLP.key, f.toURL());
// ds.setEnabled(true);
// cat.add(ds);
//
// FeatureTypeInfo ft = cat.getFactory().createFeatureType();
// ft.setName("monitor_world");
// ft.setNativeName("monitor_world");
// ft.setNamespace(cat.getNamespaceByPrefix(ws.getName()));
// ft.setStore(ds);
// ft.setEnabled(true);
// setWorldBounds(ft);
//
// cat.add(ft);
//
// addLayer(cat, ft, "monitor_world");
// }
//set up a datastore for the request layer
DataStoreInfo ds = cat.getDataStoreByName("analytics", "db");
if ( ds == null) {
ds = cat.getFactory().createDataStore();
ds.setWorkspace(ws);
ds.setName("db");
ds.setEnabled(true);
updateParams(ds);
cat.add(ds);
}
else {
updateParams(ds);
cat.save(ds);
}
FeatureTypeInfo ft = cat.getFeatureTypeByDataStore(ds, "requests_agg");
if (ft == null) {
ft = cat.getFactory().createFeatureType();
ft.setName("requests_agg");
ft.setNativeName("requests_agg");
ft.setNamespace(cat.getNamespaceByPrefix(ws.getName()));
ft.setStore(ds);
ft.setEnabled(true);
setWorldBounds(ft);
VirtualTable vt = new VirtualTable("requests_agg",
"SELECT ST_SetSRID(ST_MakePoint(remote_lon,remote_lat), 4326) as \"POINT\"," +
"remote_city as \"REMOTE_CITY\", " +
"remote_country as \"REMOTE_COUNTRY\", " +
"count(*) as \"REQUESTS\"" +
" FROM request WHERE remote_lon <> 0 and remote_lat <> 0 and %query%" +
"GROUP BY \"POINT\", \"REMOTE_CITY\", \"REMOTE_COUNTRY\"");
vt.addGeometryMetadatata("POINT", Point.class, 4326);
RegexpValidator validator = new RegexpValidator(START_END_REGEXP);
vt.addParameter(new VirtualTableParameter("query","1=1",validator));
ft.getMetadata().put("JDBC_VIRTUAL_TABLE", vt);
cat.add(ft);
}
if (cat.getLayers(ft).isEmpty()) {
addLayer(cat, ft, "analytics_requests_agg");
}
ft = cat.getFeatureTypeByDataStore(ds, "requests");
if (ft == null) {
ft = cat.getFactory().createFeatureType();
ft.setName("requests");
ft.setNativeName("requests");
ft.setNamespace(cat.getNamespaceByPrefix(ws.getName()));
ft.setStore(ds);
ft.setEnabled(true);
setWorldBounds(ft);
VirtualTable vt = new VirtualTable("requests",
"SELECT ST_SetSRID(ST_MakePoint(remote_lon,remote_lat), 4326) as \"point\"," +
"id as \"ID\", " +
"id as \"REQUEST_ID\", " +
"status as \"STATUS\", " +
"category as \"CATEGORY\", " +
"path as \"PATH\", " +
"query_string as \"QUERY_STRING\", " +
"body_content_type as \"BODY_CONTENT_TYPE\", " +
"body_content_length as \"BODY_CONTENT_LENGTH\", " +
"server_host as \"SERVER_HOST\", " +
"http_method as \"HTTP_METHOD\", " +
"start_time as \"START_TIME\", " +
"end_time as \"END_TIME\", " +
"total_time as \"TOTAL_TIME\", " +
"remote_address as \"REMOTE_ADDRESS\", " +
"remote_host as \"REMOTE_HOST\", " +
"remote_user as \"REMOTE_USER\", " +
"remote_country as \"REMOTE_COUNTRY\", " +
"remote_city as \"REMOTE_CITY\", " +
"service as \"SERVICE\", " +
"operation as \"OPERATION\", " +
"sub_operation as \"SUB_OPERATION\", " +
"ows_version as \"OWS_VERSION\", " +
"content_type as \"CONTENT_TYPE\", " +
"response_length as \"RESPONSE_LENGTH\", " +
"error_message as \"ERROR_MESSAGE\"" +
" FROM request");
vt.addGeometryMetadatata("POINT", Point.class, 4326);
vt.setPrimaryKeyColumns(Arrays.asList("ID"));
ft.getMetadata().put("JDBC_VIRTUAL_TABLE", vt);
cat.add(ft);
}
if (cat.getLayers(ft).isEmpty()) {
addLayer(cat, ft, "point");
}
}
void addStyle(Catalog cat, String name) throws Exception {
GeoServerResourceLoader rl = cat.getResourceLoader();
if (cat.getStyleByName(name) == null) {
File sld = rl.find("styles", name + ".sld");
if (sld == null) {
rl.copyFromClassPath(name + ".sld",
rl.createFile("styles", name + ".sld"), getClass());
}
StyleInfo s = cat.getFactory().createStyle();
s.setName(name);
s.setFilename(name + ".sld");
cat.add(s);
}
}
void updateParams(DataStoreInfo ds) {
Map params = new HashMap();
setParamsFromURL(params, dataSource.getUrl());
params.put(JDBCDataStoreFactory.USER.key, dataSource.getUsername());
params.put(JDBCDataStoreFactory.PASSWD.key, dataSource.getPassword());
ds.getConnectionParameters().putAll(params);
}
void setParamsFromURL(Map params, String url) {
if (url.startsWith("jdbc:postgresql:")) {
//jdbc:postgresql://localhost/geotools
int i = url.indexOf("//") + 2;
int j = url.indexOf('/', i);
String host = url.substring(i, j);
int port = -1;
if (host.contains(":")) {
port = Integer.parseInt(host.substring(host.indexOf(':')+1));
host = host.substring(0, host.indexOf(':'));
}
String db = url.substring(j+1);
params.put(JDBCDataStoreFactory.DBTYPE.key, "postgis");
params.put(JDBCDataStoreFactory.HOST.key, host);
if (port != -1) {
params.put(JDBCDataStoreFactory.PORT.key, port);
}
params.put(JDBCDataStoreFactory.DATABASE.key, db);
}
else if (url.startsWith("jdbc:h2:file:")) {
//jdbc:h2:file:/path
params.put(JDBCDataStoreFactory.DBTYPE.key, "h2");
params.put(JDBCDataStoreFactory.DATABASE.key, url.substring("jdbc:h2:file:".length()));
}
else {
LOGGER.warning("Unable to configure analytics:db store from jdbc url " + url);
}
}
void setWorldBounds(FeatureTypeInfo ft) throws Exception {
CoordinateReferenceSystem crs = CRS.decode("EPSG:4326");
ft.setLatLonBoundingBox(new ReferencedEnvelope(-180, 180,-90, 90, crs));
ft.setNativeBoundingBox(new ReferencedEnvelope(-180, 180, -90, 90, crs));
ft.setNativeCRS(crs);
ft.setSRS("EPSG:4326");
ft.setProjectionPolicy(ProjectionPolicy.FORCE_DECLARED);
}
ReferencedEnvelope worldBounds() throws Exception {
return new ReferencedEnvelope(-180, 180,-90, 90, CRS.decode("EPSG:4326"));
}
void addLayer(Catalog cat, FeatureTypeInfo ft, String style) {
LayerInfo l = cat.getFactory().createLayer();
l.setResource(ft);
l.setType(LayerInfo.Type.VECTOR);
l.setEnabled(true);
l.setDefaultStyle(cat.getStyleByName(style));
cat.add(l);
}
}
diff --git a/geoserver/analytics/src/test/java/org/opengeo/analytics/RequestMapInitializerTest.java b/geoserver/analytics/src/test/java/org/opengeo/analytics/RequestMapInitializerTest.java
index 3a7c15674..49eed8501 100644
--- a/geoserver/analytics/src/test/java/org/opengeo/analytics/RequestMapInitializerTest.java
+++ b/geoserver/analytics/src/test/java/org/opengeo/analytics/RequestMapInitializerTest.java
@@ -1,19 +1,19 @@
package org.opengeo.analytics;
import junit.framework.TestCase;
import org.geotools.jdbc.RegexpValidator;
import org.geotools.validation.Validator;
/**
*
* @author Ian Schneider <[email protected]>
*/
public class RequestMapInitializerTest extends TestCase {
//@todo should have some DB tests for virtual tables?
public void testQueryRegex() {
- RegexpValidator validator = new RegexpValidator("start_time > '[^();]'+ and end_time < '[^();]'+");
+ RegexpValidator validator = new RegexpValidator(RequestMapInitializer.START_END_REGEXP);
validator.validate("start_time > '2009-08-25 13:00:00.0' and end_time < '2009-08-25 13:00:00.0'");
}
}
| false | false | null | null |
diff --git a/android/src/com/coboltforge/dontmind/multivnc/VncCanvasActivity.java b/android/src/com/coboltforge/dontmind/multivnc/VncCanvasActivity.java
index 0ea9336..c74531c 100644
--- a/android/src/com/coboltforge/dontmind/multivnc/VncCanvasActivity.java
+++ b/android/src/com/coboltforge/dontmind/multivnc/VncCanvasActivity.java
@@ -1,1016 +1,1021 @@
/*
* This 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.
*
* 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this software; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
* USA.
*/
//
// CanvasView is the Activity for showing VNC Desktop.
//
package com.coboltforge.dontmind.multivnc;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
+import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnDismissListener;
import android.content.res.Configuration;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.SystemClock;
import android.util.Log;
import android.view.Gravity;
import android.view.HapticFeedbackConstants;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.SoundEffectConstants;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;
import android.view.inputmethod.InputMethodManager;
import android.content.Context;
public class VncCanvasActivity extends Activity {
public class TouchpadInputHandler extends AbstractGestureInputHandler {
private static final String TAG = "TouchPadInputHandler";
/**
* In drag mode (entered with long press) you process mouse events
* without sending them through the gesture detector
*/
private boolean dragMode;
float dragX, dragY;
private boolean dragModeButtonDown = false;
private boolean dragModeButton2insteadof1 = false;
/*
* two-finger fling gesture stuff
*/
private long twoFingerFlingStart = -1;
private VelocityTracker twoFingerFlingVelocityTracker;
private boolean twoFingerFlingDetected = false;
private final int TWO_FINGER_FLING_UNITS = 1000;
private final float TWO_FINGER_FLING_THRESHOLD = 1000;
TouchpadInputHandler() {
super(VncCanvasActivity.this);
Log.d(TAG, "TouchpadInputHandler " + this + " created!");
}
public void init() {
twoFingerFlingVelocityTracker = VelocityTracker.obtain();
Log.d(TAG, "TouchpadInputHandler " + this + " init!");
}
public void shutdown() {
try {
twoFingerFlingVelocityTracker.recycle();
twoFingerFlingVelocityTracker = null;
}
catch (NullPointerException e) {
}
Log.d(TAG, "TouchpadInputHandler " + this + " shutdown!");
}
/**
* scale down delta when it is small. This will allow finer control
* when user is making a small movement on touch screen.
* Scale up delta when delta is big. This allows fast mouse movement when
* user is flinging.
* @param deltaX
* @return
*/
private float fineCtrlScale(float delta) {
float sign = (delta>0) ? 1 : -1;
delta = Math.abs(delta);
if (delta>=1 && delta <=3) {
delta = 1;
}else if (delta <= 10) {
delta *= 0.34;
} else if (delta <= 30 ) {
delta *= delta/30;
} else if (delta <= 90) {
delta *= (delta/30);
} else {
delta *= 3.0;
}
return sign * delta;
}
private void twoFingerFlingNotification(String str)
{
// bzzt!
vncCanvas.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY,
HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING|HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING);
// beep!
vncCanvas.playSoundEffect(SoundEffectConstants.CLICK);
VncCanvasActivity.this.notificationToast.setText(str);
VncCanvasActivity.this.notificationToast.show();
}
private void twoFingerFlingAction(Character d)
{
switch(d) {
case '←':
vncCanvas.sendMetaKey(MetaKeyBean.keyArrowLeft);
break;
case '→':
vncCanvas.sendMetaKey(MetaKeyBean.keyArrowRight);
break;
case '↑':
vncCanvas.sendMetaKey(MetaKeyBean.keyArrowUp);
break;
case '↓':
vncCanvas.sendMetaKey(MetaKeyBean.keyArrowDown);
break;
}
}
/*
* (non-Javadoc)
*
* @see android.view.GestureDetector.SimpleOnGestureListener#onLongPress(android.view.MotionEvent)
*/
@Override
public void onLongPress(MotionEvent e) {
if(Utils.DEBUG()) Log.d(TAG, "Input: long press");
showZoomer(true);
vncCanvas.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS,
HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING|HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING);
dragMode = true;
dragX = e.getX();
dragY = e.getY();
// only interpret as button down if virtual mouse buttons are disabled
if(mousebuttons.getVisibility() != View.VISIBLE)
dragModeButtonDown = true;
}
/*
* (non-Javadoc)
*
* @see android.view.GestureDetector.SimpleOnGestureListener#onScroll(android.view.MotionEvent,
* android.view.MotionEvent, float, float)
*/
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2,
float distanceX, float distanceY) {
if (e2.getPointerCount() > 1)
{
if(Utils.DEBUG()) Log.d(TAG, "Input: scroll multitouch");
if (inScaling)
return false;
// pan on 3 fingers and more
if(e2.getPointerCount() > 2) {
showZoomer(false);
return vncCanvas.pan((int) distanceX, (int) distanceY);
}
/*
* here comes the stuff that acts for two fingers
*/
// gesture start
if(twoFingerFlingStart != e1.getEventTime()) // it's a new scroll sequence
{
twoFingerFlingStart = e1.getEventTime();
twoFingerFlingDetected = false;
twoFingerFlingVelocityTracker.clear();
if(Utils.DEBUG()) Log.d(TAG, "new twoFingerFling detection started");
}
// gesture end
if(twoFingerFlingDetected == false) // not yet detected in this sequence (we only want ONE event per sequence!)
{
// update our velocity tracker
twoFingerFlingVelocityTracker.addMovement(e2);
twoFingerFlingVelocityTracker.computeCurrentVelocity(TWO_FINGER_FLING_UNITS);
float velocityX = twoFingerFlingVelocityTracker.getXVelocity();
float velocityY = twoFingerFlingVelocityTracker.getYVelocity();
// check for left/right flings
if(Math.abs(velocityX) > TWO_FINGER_FLING_THRESHOLD
&& Math.abs(velocityX) > Math.abs(2*velocityY)) {
if(velocityX < 0) {
if(Utils.DEBUG()) Log.d(TAG, "twoFingerFling LEFT detected");
twoFingerFlingNotification("←");
twoFingerFlingAction('←');
}
else {
if(Utils.DEBUG()) Log.d(TAG, "twoFingerFling RIGHT detected");
twoFingerFlingNotification("→");
twoFingerFlingAction('→');
}
twoFingerFlingDetected = true;
}
// check for left/right flings
if(Math.abs(velocityY) > TWO_FINGER_FLING_THRESHOLD
&& Math.abs(velocityY) > Math.abs(2*velocityX)) {
if(velocityY < 0) {
if(Utils.DEBUG()) Log.d(TAG, "twoFingerFling UP detected");
twoFingerFlingNotification("↑");
twoFingerFlingAction('↑');
}
else {
if(Utils.DEBUG()) Log.d(TAG, "twoFingerFling DOWN detected");
twoFingerFlingNotification("↓");
twoFingerFlingAction('↓');
}
twoFingerFlingDetected = true;
}
}
return twoFingerFlingDetected;
}
else
{
// compute the relative movement offset on the remote screen.
float deltaX = -distanceX *vncCanvas.getScale();
float deltaY = -distanceY *vncCanvas.getScale();
deltaX = fineCtrlScale(deltaX);
deltaY = fineCtrlScale(deltaY);
// compute the absolution new mouse pos on the remote site.
float newRemoteX = vncCanvas.mouseX + deltaX;
float newRemoteY = vncCanvas.mouseY + deltaY;
if(Utils.DEBUG()) Log.d(TAG, "Input: scroll single touch from "
+ vncCanvas.mouseX + "," + vncCanvas.mouseY
+ " to " + (int)newRemoteX + "," + (int)newRemoteY);
// if (dragMode) {
//
// Log.d(TAG, "dragmode in scroll!!!!");
//
// if (e2.getAction() == MotionEvent.ACTION_UP)
// dragMode = false;
// dragX = e2.getX();
// dragY = e2.getY();
// e2.setLocation(newRemoteX, newRemoteY);
// return vncCanvas.processPointerEvent(e2, true);
// }
e2.setLocation(newRemoteX, newRemoteY);
vncCanvas.processPointerEvent(e2, false);
}
return false;
}
/*
* (non-Javadoc)
*
* @see com.coboltforge.dontmind.multivnc.AbstractGestureInputHandler#onTouchEvent(android.view.MotionEvent)
*/
@Override
public boolean onTouchEvent(MotionEvent e) {
if (dragMode) {
if(Utils.DEBUG()) Log.d(TAG, "Input: touch dragMode");
// compute the relative movement offset on the remote screen.
float deltaX = (e.getX() - dragX) *vncCanvas.getScale();
float deltaY = (e.getY() - dragY) *vncCanvas.getScale();
dragX = e.getX();
dragY = e.getY();
deltaX = fineCtrlScale(deltaX);
deltaY = fineCtrlScale(deltaY);
// compute the absolution new mouse pos on the remote site.
float newRemoteX = vncCanvas.mouseX + deltaX;
float newRemoteY = vncCanvas.mouseY + deltaY;
if (e.getAction() == MotionEvent.ACTION_UP)
{
if(Utils.DEBUG()) Log.d(TAG, "Input: touch dragMode, finger up");
dragMode = false;
dragModeButtonDown = false;
dragModeButton2insteadof1 = false;
remoteMouseStayPut(e);
vncCanvas.processPointerEvent(e, false);
return super.onTouchEvent(e); // important! otherwise the gesture detector gets confused!
}
e.setLocation(newRemoteX, newRemoteY);
boolean status = false;
if(dragModeButtonDown) {
if(!dragModeButton2insteadof1) // button 1 down
status = vncCanvas.processPointerEvent(e, true, false);
else // button2 down
status = vncCanvas.processPointerEvent(e, true, true);
}
else { // dragging without any button down
status = vncCanvas.processPointerEvent(e, false);
}
return status;
}
if(Utils.DEBUG())
Log.d(TAG, "Input: touch normal: x:" + e.getX() + " y:" + e.getY() + " action:" + e.getAction());
return super.onTouchEvent(e);
}
/**
* Modify the event so that it does not move the mouse on the
* remote server.
* @param e
*/
private void remoteMouseStayPut(MotionEvent e) {
e.setLocation(vncCanvas.mouseX, vncCanvas.mouseY);
}
/*
* (non-Javadoc)
* confirmed single tap: do a left mouse down and up click on remote without moving the mouse.
* @see android.view.GestureDetector.SimpleOnGestureListener#onSingleTapConfirmed(android.view.MotionEvent)
*/
@Override
public boolean onSingleTapConfirmed(MotionEvent e) {
// disable if virtual mouse buttons are in use
if(mousebuttons.getVisibility()== View.VISIBLE)
return false;
if(Utils.DEBUG()) Log.d(TAG, "Input: single tap");
boolean multiTouch = e.getPointerCount() > 1;
remoteMouseStayPut(e);
vncCanvas.processPointerEvent(e, true, multiTouch||vncCanvas.cameraButtonDown);
e.setAction(MotionEvent.ACTION_UP);
return vncCanvas.processPointerEvent(e, false, multiTouch||vncCanvas.cameraButtonDown);
}
/*
* (non-Javadoc)
* double tap: do right mouse down and up click on remote without moving the mouse.
* @see android.view.GestureDetector.SimpleOnGestureListener#onDoubleTap(android.view.MotionEvent)
*/
@Override
public boolean onDoubleTap(MotionEvent e) {
// disable if virtual mouse buttons are in use
if(mousebuttons.getVisibility()== View.VISIBLE)
return false;
if(Utils.DEBUG()) Log.d(TAG, "Input: double tap");
dragModeButtonDown = true;
dragModeButton2insteadof1 = true;
remoteMouseStayPut(e);
vncCanvas.processPointerEvent(e, true, true);
e.setAction(MotionEvent.ACTION_UP);
return vncCanvas.processPointerEvent(e, false, true);
}
/*
* (non-Javadoc)
*
* @see android.view.GestureDetector.SimpleOnGestureListener#onDown(android.view.MotionEvent)
*/
@Override
public boolean onDown(MotionEvent e) {
return true;
}
}
private final static String TAG = "VncCanvasActivity";
VncCanvas vncCanvas;
VncDatabase database;
private ConnectionBean connection;
ZoomControls zoomer;
TouchpadInputHandler touchPad;
ViewGroup mousebuttons;
TouchPointView touchpoints;
Toast notificationToast;
private SharedPreferences prefs;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
// only do fullscreen on 2.x devices
if(Build.VERSION.SDK_INT < 11) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
prefs = getSharedPreferences(Constants.PREFSNAME, MODE_PRIVATE);
database = new VncDatabase(this);
Intent i = getIntent();
connection = new ConnectionBean();
Uri data = i.getData();
if ((data != null) && (data.getScheme().equals("vnc"))) {
String host = data.getHost();
// This should not happen according to Uri contract, but bug introduced in Froyo (2.2)
// has made this parsing of host necessary
int index = host.indexOf(':');
int port;
if (index != -1)
{
try
{
port = Integer.parseInt(host.substring(index + 1));
}
catch (NumberFormatException nfe)
{
port = 0;
}
host = host.substring(0,index);
}
else
{
port = data.getPort();
}
if (host.equals(Constants.CONNECTION))
{
if (connection.Gen_read(database.getReadableDatabase(), port))
{
MostRecentBean bean = MainMenuActivity.getMostRecent(database.getReadableDatabase());
if (bean != null)
{
bean.setConnectionId(connection.get_Id());
bean.Gen_update(database.getWritableDatabase());
}
}
}
else
{
connection.setAddress(host);
connection.setNickname(connection.getAddress());
connection.setPort(port);
List<String> path = data.getPathSegments();
if (path.size() >= 1) {
connection.setColorModel(path.get(0));
}
if (path.size() >= 2) {
connection.setPassword(path.get(1));
}
connection.save(database.getWritableDatabase());
}
} else {
Bundle extras = i.getExtras();
if (extras != null) {
connection.Gen_populate((ContentValues) extras
.getParcelable(Constants.CONNECTION));
}
if (connection.getPort() == 0)
connection.setPort(5900);
// Parse a HOST:PORT entry
String host = connection.getAddress();
if (host.indexOf(':') > -1) {
String p = host.substring(host.indexOf(':') + 1);
try {
connection.setPort(Integer.parseInt(p));
} catch (Exception e) {
}
connection.setAddress(host.substring(0, host.indexOf(':')));
}
}
setContentView(R.layout.canvas);
vncCanvas = (VncCanvas) findViewById(R.id.vnc_canvas);
zoomer = (ZoomControls) findViewById(R.id.zoomer);
vncCanvas.initializeVncCanvas(this, connection, new Runnable() {
public void run() {
setModes();
}
});
zoomer.hide();
zoomer.setOnZoomInClickListener(new View.OnClickListener() {
/*
* (non-Javadoc)
*
* @see android.view.View.OnClickListener#onClick(android.view.View)
*/
@Override
public void onClick(View v) {
try {
showZoomer(true);
vncCanvas.scaling.zoomIn(VncCanvasActivity.this);
}
catch(NullPointerException e) {
}
}
});
zoomer.setOnZoomOutClickListener(new View.OnClickListener() {
/*
* (non-Javadoc)
*
* @see android.view.View.OnClickListener#onClick(android.view.View)
*/
@Override
public void onClick(View v) {
try {
showZoomer(true);
vncCanvas.scaling.zoomOut(VncCanvasActivity.this);
}
catch(NullPointerException e) {
}
}
});
zoomer.setOnZoomKeyboardClickListener(new View.OnClickListener() {
/*
* (non-Javadoc)
*
* @see android.view.View.OnClickListener#onClick(android.view.View)
*/
@Override
public void onClick(View v) {
toggleKeyboard();
}
});
touchPad = new TouchpadInputHandler();
touchPad.init();
mousebuttons = (ViewGroup) findViewById(R.id.virtualmousebuttons);
MouseButtonView mousebutton1 = (MouseButtonView) findViewById(R.id.mousebutton1);
MouseButtonView mousebutton2 = (MouseButtonView) findViewById(R.id.mousebutton2);
MouseButtonView mousebutton3 = (MouseButtonView) findViewById(R.id.mousebutton3);
mousebutton1.init(1, vncCanvas);
mousebutton2.init(2, vncCanvas);
mousebutton3.init(3, vncCanvas);
if(! prefs.getBoolean(Constants.PREFS__KEY_MOUSEBUTTONS, true)) {
mousebutton1.setVisibility(View.GONE);
mousebutton2.setVisibility(View.GONE);
mousebutton3.setVisibility(View.GONE);
}
touchpoints = (TouchPointView) findViewById(R.id.touchpoints);
// create an empty toast. we do this do be able to cancel
notificationToast = Toast.makeText(this, "", Toast.LENGTH_SHORT);
notificationToast.setGravity(Gravity.TOP, 0, 0);
// honeycomb or newer
- if(Build.VERSION.SDK_INT >= 11) {
- // disable home button as this sometimes takes keyboard focus
- getActionBar().setDisplayShowHomeEnabled(false);
- }
+ setupActionBar();
if(! prefs.getBoolean(Constants.PREFS__KEY_POINTERHIGHLIGHT, true))
vncCanvas.setPointerHighlight(false);
}
/**
* Set modes on start to match what is specified in the ConnectionBean;
* color mode (already done), scaling
*/
void setModes() {
AbstractScaling.getByScaleType(connection.getScaleMode())
.setScaleTypeForActivity(this);
}
ConnectionBean getConnection() {
return connection;
}
/*
* (non-Javadoc)
*
* @see android.app.Activity#onCreateDialog(int)
*/
@Override
protected Dialog onCreateDialog(int id) {
// Default to meta key dialog
return new MetaKeyDialog(this);
}
/*
* (non-Javadoc)
*
* @see android.app.Activity#onPrepareDialog(int, android.app.Dialog)
*/
@Override
protected void onPrepareDialog(int id, Dialog dialog) {
super.onPrepareDialog(id, dialog);
if (dialog instanceof ConnectionSettable)
((ConnectionSettable) dialog).setConnection(connection);
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
// ignore orientation/keyboard change
super.onConfigurationChanged(newConfig);
}
@Override
protected void onStop() {
vncCanvas.disableRepaints();
super.onStop();
}
@Override
protected void onRestart() {
vncCanvas.enableRepaints();
super.onRestart();
}
@Override
protected void onPause() {
super.onPause();
// needed for the GLSurfaceView
vncCanvas.onPause();
}
@Override
protected void onResume() {
super.onResume();
// needed for the GLSurfaceView
vncCanvas.onResume();
}
/** {@inheritDoc} */
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.vnccanvasactivitymenu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
SharedPreferences.Editor ed = prefs.edit();
switch (item.getItemId()) {
case R.id.itemInfo:
vncCanvas.showConnectionInfo();
return true;
case R.id.itemSpecialKeys:
showDialog(R.layout.metakey);
return true;
case R.id.itemColorMode:
selectColorModel();
return true;
case R.id.itemToggleFramebufferUpdate:
if(vncCanvas.vncConn.toggleFramebufferUpdates()) // view enabled
{
vncCanvas.setVisibility(View.VISIBLE);
touchpoints.setVisibility(View.GONE);
}
else
{
vncCanvas.setVisibility(View.GONE);
touchpoints.setVisibility(View.VISIBLE);
}
return true;
case R.id.itemToggleMouseButtons:
if(mousebuttons.getVisibility()== View.VISIBLE) {
mousebuttons.setVisibility(View.GONE);
ed.putBoolean(Constants.PREFS__KEY_MOUSEBUTTONS, false);
}
else {
mousebuttons.setVisibility(View.VISIBLE);
ed.putBoolean(Constants.PREFS__KEY_MOUSEBUTTONS, true);
}
ed.commit();
return true;
case R.id.itemTogglePointerHighlight:
if(vncCanvas.getPointerHighlight())
vncCanvas.setPointerHighlight(false);
else
vncCanvas.setPointerHighlight(true);
ed.putBoolean(Constants.PREFS__KEY_POINTERHIGHLIGHT, vncCanvas.getPointerHighlight());
ed.commit();
return true;
case R.id.itemToggleKeyboard:
toggleKeyboard();
return true;
case R.id.itemSendKeyAgain:
sendSpecialKeyAgain();
return true;
case R.id.itemSaveBookmark:
connection.save(database.getWritableDatabase());
Toast.makeText(this, getString(R.string.bookmark_saved), Toast.LENGTH_SHORT).show();
return true;
case R.id.itemOpenDoc:
Intent intent = new Intent (this, AboutActivity.class);
this.startActivity(intent);
return true;
default:
break;
}
return super.onOptionsItemSelected(item);
}
private MetaKeyBean lastSentKey;
private void sendSpecialKeyAgain() {
if (lastSentKey == null
|| lastSentKey.get_Id() != connection.getLastMetaKeyId()) {
ArrayList<MetaKeyBean> keys = new ArrayList<MetaKeyBean>();
Cursor c = database.getReadableDatabase().rawQuery(
MessageFormat.format("SELECT * FROM {0} WHERE {1} = {2}",
MetaKeyBean.GEN_TABLE_NAME,
MetaKeyBean.GEN_FIELD__ID, connection
.getLastMetaKeyId()),
MetaKeyDialog.EMPTY_ARGS);
MetaKeyBean.Gen_populateFromCursor(c, keys, MetaKeyBean.NEW);
c.close();
if (keys.size() > 0) {
lastSentKey = keys.get(0);
} else {
lastSentKey = new MetaKeyBean();
lastSentKey.setKeySym(0xFFC6); // set F9 as default
}
}
if (lastSentKey != null)
vncCanvas.sendMetaKey(lastSentKey);
}
private void toggleKeyboard() {
InputMethodManager inputMgr = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
inputMgr.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
}
@Override
protected void onDestroy() {
super.onDestroy();
if (isFinishing()) {
touchPad.shutdown();
vncCanvas.vncConn.shutdown();
vncCanvas.onDestroy();
database.close();
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if(touchpoints.getVisibility()== View.VISIBLE)
touchpoints.handleEvent(event);
return touchPad.onTouchEvent(event);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent evt) {
if(Utils.DEBUG()) Log.d(TAG, "Input: key down: " + evt.toString());
if (keyCode == KeyEvent.KEYCODE_MENU)
return super.onKeyDown(keyCode, evt);
if(keyCode == KeyEvent.KEYCODE_BACK) {
new AlertDialog.Builder(this)
.setMessage(getString(R.string.disconnect_question))
.setPositiveButton(getString(R.string.yes), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
vncCanvas.vncConn.shutdown();
finish();
}
}).setNegativeButton(getString(R.string.no), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Do nothing.
}
}).show();
return true;
}
// use search key to toggle soft keyboard
if (keyCode == KeyEvent.KEYCODE_SEARCH)
toggleKeyboard();
if (vncCanvas.processLocalKeyEvent(keyCode, evt))
return true;
return super.onKeyDown(keyCode, evt);
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent evt) {
if(Utils.DEBUG()) Log.d(TAG, "Input: key up: " + evt.toString());
if (keyCode == KeyEvent.KEYCODE_MENU)
return super.onKeyUp(keyCode, evt);
if (vncCanvas.processLocalKeyEvent(keyCode, evt))
return true;
return super.onKeyUp(keyCode, evt);
}
// this is called for unicode symbols like €
// multiple duplicate key events have occurred in a row, or a complex string is being delivered.
// If the key code is not KEYCODE_UNKNOWN then the getRepeatCount() method returns the number of
// times the given key code should be executed.
// Otherwise, if the key code is KEYCODE_UNKNOWN, then this is a sequence of characters as returned by getCharacters().
@Override
public boolean onKeyMultiple (int keyCode, int count, KeyEvent evt) {
if(Utils.DEBUG()) Log.d(TAG, "Input: key mult: " + evt.toString());
// we only deal with the special char case for now
if(evt.getKeyCode() == KeyEvent.KEYCODE_UNKNOWN) {
if (vncCanvas.processLocalKeyEvent(keyCode, evt))
return true;
}
return super.onKeyMultiple(keyCode, count, evt);
}
private void selectColorModel() {
// Stop repainting the desktop
// because the display is composited!
vncCanvas.disableRepaints();
final String[] choices = new String[COLORMODEL.values().length];
int currentSelection = -1;
for (int i = 0; i < choices.length; i++) {
COLORMODEL cm = COLORMODEL.values()[i];
choices[i] = cm.toString();
if(cm.equals(vncCanvas.vncConn.getColorModel()))
currentSelection = i;
}
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setSingleChoiceItems(choices, currentSelection, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
dialog.dismiss();
COLORMODEL cm = COLORMODEL.values()[item];
vncCanvas.vncConn.setColorModel(cm);
connection.setColorModel(cm.nameString());
Toast.makeText(VncCanvasActivity.this,
"Updating Color Model to " + cm.toString(),
Toast.LENGTH_SHORT).show();
}
});
AlertDialog dialog = builder.create();
dialog.setOnDismissListener(new OnDismissListener() {
@Override
public void onDismiss(DialogInterface arg0) {
Log.i(TAG, "Color Model Selector dismissed");
// Restore desktop repaints
vncCanvas.enableRepaints();
}
});
dialog.show();
}
float panTouchX, panTouchY;
/**
* Pan based on touch motions
*
* @param event
*/
private boolean pan(MotionEvent event) {
float curX = event.getX();
float curY = event.getY();
int dX = (int) (panTouchX - curX);
int dY = (int) (panTouchY - curY);
return vncCanvas.pan(dX, dY);
}
boolean touchPan(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
panTouchX = event.getX();
panTouchY = event.getY();
break;
case MotionEvent.ACTION_MOVE:
pan(event);
panTouchX = event.getX();
panTouchY = event.getY();
break;
case MotionEvent.ACTION_UP:
pan(event);
break;
}
return true;
}
long hideZoomAfterMs;
static final long ZOOM_HIDE_DELAY_MS = 2500;
HideZoomRunnable hideZoomInstance = new HideZoomRunnable();
private void showZoomer(boolean force) {
if (force || zoomer.getVisibility() != View.VISIBLE) {
zoomer.show();
hideZoomAfterMs = SystemClock.uptimeMillis() + ZOOM_HIDE_DELAY_MS;
vncCanvas.handler
.postAtTime(hideZoomInstance, hideZoomAfterMs + 10);
}
}
private class HideZoomRunnable implements Runnable {
public void run() {
if (SystemClock.uptimeMillis() >= hideZoomAfterMs) {
zoomer.hide();
}
}
}
public void showScaleToast()
{
// show scale
notificationToast.setText(getString(R.string.scale_msg) + " " + (int)(100*vncCanvas.getScale()) + "%");
notificationToast.show();
}
+ @SuppressLint("NewApi")
public void setTitle(String text) {
-
if(Build.VERSION.SDK_INT >= 11)
getActionBar().setTitle(text);
-
+ }
+
+ @SuppressLint("NewApi")
+ private void setupActionBar() {
+ if(Build.VERSION.SDK_INT >= 11) {
+ // disable home button as this sometimes takes keyboard focus
+ getActionBar().setDisplayShowHomeEnabled(false);
+ }
}
}
| false | false | null | null |
diff --git a/ecologylab/generic/NewPorterStemmer.java b/ecologylab/generic/NewPorterStemmer.java
index 5032a5b0..4174dc7b 100644
--- a/ecologylab/generic/NewPorterStemmer.java
+++ b/ecologylab/generic/NewPorterStemmer.java
@@ -1,564 +1,561 @@
package cm.media.text;
/*
Porter stemmer in Java. The original paper is in
Porter, 1980, An algorithm for suffix stripping, Program, Vol. 14,
no. 3, pp 130-137,
See also http://www.tartarus.org/~martin/PorterStemmer
History:
Release 1
Bug 1 (reported by Gonzalo Parra 16/10/99) fixed as marked below.
The words 'aed', 'eed', 'oed' leave k at 'a' for step 3, and b[k-1]
is then out outside the bounds of b.
Release 2
Similarly,
Bug 2 (reported by Steve Dyrdahl 22/2/00) fixed as marked below.
'ion' by itself leaves j = -1 in the test for 'ion' in step 5, and
b[j] is then outside the bounds of b.
Release 3
Considerably revised 4/9/00 in the light of many helpful suggestions
from Brian Goetz of Quiotix Corporation ([email protected]).
Release 4
Modification
This version is derived from Release 4, modified by Jin Wang to use
StringBuffer instead of char array.
*/
import java.io.*;
import java.lang.StringBuffer;
+import cm.generic.*;
/**
* Stemmer, implementing the Porter Stemming Algorithm
*
* The Stemmer class transforms a word into its root form. The input
* word can be provided a character at time (by calling add()), or at once
* by calling one of the various stem(something) methods.
*
* New version of PorterStemmer implemented with StringBuffer.
*/
public class NewPorterStemmer
+extends Debug
{
//private char[] b;
private StringBuffer b;
private int i, /* offset into b */
i_end, /* offset to end of stemmed word */
j, k;
private boolean dirty = false;
private static final int INC = 100;
/* unit of size whereby b is increased */
public NewPorterStemmer()
{
b = new StringBuffer(INC);
i = 0;
i_end = 0;
}
/**
* reset() resets the stemmer so it can stem another word. If you invoke
* the stemmer by calling add(char) and then stem(), you must call reset()
* before starting another word.
*/
public void reset()
{
i = 0;
dirty = false;
}
/**
* Add a character to the word being stemmed. When you are finished
* adding characters, you can call stem(void) to stem the word.
*/
public void add(char ch)
{
if (i == b.length())
b.setLength(i+INC);
b.setCharAt(i++, ch);
}
/** Adds wLen characters to the word being stemmed contained in a portion
* of a char[] array. This is like repeated calls of add(char ch), but
* faster.
*/
public void add(char[] w, int wLen)
{
if (i+wLen >= b.length())
b.setLength(i+wLen+INC);
for (int c = 0; c < wLen; c++)
b.setCharAt(i++, w[c]);
}
public void add(String s)
{
reset();
int wLen = s.length();
- int last = wLen - 1;
-
- if (s.charAt(last) == 's')
- wLen--; // drop ending s -- get rid of plural
-
b.setLength(wLen);
for (int c = 0; c < wLen; c++)
b.setCharAt(i++, s.charAt(c));
}
/*
public void add(String s)
{
add(s.toCharArray(), s.length());
}
*/
/**
* After a word has been stemmed, it can be retrieved by toString(),
* or a reference to the internal buffer can be retrieved by getResultBuffer
* and getResultLength (which is generally more efficient.)
*/
public String toString()
{
// force ArrayCopy here, otherwise StringBuffer gets shared and SLOW
return b.substring(0, i_end);
// return new String(b,0,i_end);
}
public String stem(String s)
{
/*
NewPorterStemmer stemmer = new NewPorterStemmer();
stemmer.add(s);
stemmer.stem();
return stemmer.toString();
*/
add(s);
stem();
return toString();
}
/**
* Returns the length of the word resulting from the stemming process.
*/
public int getResultLength() { return i_end; }
/**
* Returns a reference to a character buffer containing the results of
* the stemming process. You also need to consult getResultLength()
* to determine the length of the result.
*/
public StringBuffer getResultBuffer() { return b; }
/* cons(i) is true <=> b[i] is a consonant. */
private final boolean cons(int i)
{ switch (b.charAt(i))
{ case 'a': case 'e': case 'i': case 'o': case 'u': return false;
case 'y': return (i==0) ? true : !cons(i-1);
default: return true;
}
}
/* m() measures the number of consonant sequences between 0 and j. if c is
a consonant sequence and v a vowel sequence, and <..> indicates arbitrary
presence,
<c><v> gives 0
<c>vc<v> gives 1
<c>vcvc<v> gives 2
<c>vcvcvc<v> gives 3
....
*/
private final int m()
{ int n = 0;
int i = 0;
while(true)
{ if (i > j) return n;
if (! cons(i)) break; i++;
}
i++;
while(true)
{ while(true)
{ if (i > j) return n;
if (cons(i)) break;
i++;
}
i++;
n++;
while(true)
{ if (i > j) return n;
if (! cons(i)) break;
i++;
}
i++;
}
}
/* vowelinstem() is true <=> 0,...j contains a vowel */
private final boolean vowelinstem()
{ int i; for (i = 0; i <= j; i++) if (! cons(i)) return true;
return false;
}
/* doublec(j) is true <=> j,(j-1) contain a double consonant. */
private final boolean doublec(int j)
{ if (j < 1) return false;
if (b.charAt(j) != b.charAt(j-1)) return false;
return cons(j);
}
/* cvc(i) is true <=> i-2,i-1,i has the form consonant - vowel - consonant
and also if the second c is not w,x or y. this is used when trying to
restore an e at the end of a short word. e.g.
cav(e), lov(e), hop(e), crim(e), but
snow, box, tray.
*/
private final boolean cvc(int i)
{ if (i < 2 || !cons(i) || cons(i-1) || !cons(i-2)) return false;
{ int ch = b.charAt(i);
if (ch == 'w' || ch == 'x' || ch == 'y') return false;
}
return true;
}
private final boolean ends(String s)
{ int l = s.length();
int o = k-l+1;
if (o < 0) return false;
for (int i = 0; i < l; i++) if (b.charAt(o+i) != s.charAt(i)) return false;
j = k-l;
return true;
}
/* setto(s) sets (j+1),...k to the characters in the string s, readjusting
k. */
private final void setto(String s)
{ int l = s.length();
int o = j+1;
for (int i = 0; i < l; i++) b.setCharAt(o+i, s.charAt(i));
k = j+l;
dirty = true;
}
/* r(s) is used further down. */
private final void r(String s) { if (m() > 0) setto(s); }
/* step1() gets rid of plurals and -ed or -ing. e.g.
caresses -> caress
ponies -> poni
ties -> ti
caress -> caress
cats -> cat
feed -> feed
agreed -> agree
disabled -> disable
matting -> mat
mating -> mate
meeting -> meet
milling -> mill
messing -> mess
meetings -> meet
*/
private final void step1()
{ if (b.charAt(k) == 's')
{ if (ends("sses")) k -= 2; else
if (ends("ies")) setto("i"); else
if (b.charAt(k-1) != 's') k--;
}
if (ends("eed")) { if (m() > 0) k--; } else
if ((ends("ed") || ends("ing")) && vowelinstem())
{ k = j;
if (ends("at")) setto("ate"); else
if (ends("bl")) setto("ble"); else
if (ends("iz")) setto("ize"); else
if (doublec(k))
{ k--;
{ int ch = b.charAt(k);
if (ch == 'l' || ch == 's' || ch == 'z') k++;
}
}
else if (m() == 1 && cvc(k)) setto("e");
}
}
/* step2() turns terminal y to i when there is another vowel in the stem. */
private final void step2()
{
if (ends("y") && vowelinstem())
b.setCharAt(k,'i');
dirty = true;
}
/* step3() maps double suffices to single ones. so -ization ( = -ize plus
-ation) maps to -ize etc. note that the string before the suffix must give
m() > 0. */
private final void step3()
{
if (k == 0)
return; /* For Bug 1 */
switch (b.charAt(k-1))
{
case 'a': if (ends("ational")) { r("ate"); break; }
if (ends("tional")) { r("tion"); break; }
break;
case 'c': if (ends("enci")) { r("ence"); break; }
if (ends("anci")) { r("ance"); break; }
break;
case 'e': if (ends("izer")) { r("ize"); break; }
break;
case 'l': if (ends("bli")) { r("ble"); break; }
if (ends("alli")) { r("al"); break; }
if (ends("entli")) { r("ent"); break; }
if (ends("eli")) { r("e"); break; }
if (ends("ousli")) { r("ous"); break; }
break;
case 'o': if (ends("ization")) { r("ize"); break; }
if (ends("ation")) { r("ate"); break; }
if (ends("ator")) { r("ate"); break; }
break;
case 's': if (ends("alism")) { r("al"); break; }
if (ends("iveness")) { r("ive"); break; }
if (ends("fulness")) { r("ful"); break; }
if (ends("ousness")) { r("ous"); break; }
break;
case 't': if (ends("aliti")) { r("al"); break; }
if (ends("iviti")) { r("ive"); break; }
if (ends("biliti")) { r("ble"); break; }
break;
case 'g': if (ends("logi")) { r("log"); break; }
}
}
/* step4() deals with -ic-, -full, -ness etc. similar strategy to step3. */
private final void step4()
{
switch (b.charAt(k))
{
case 'e': if (ends("icate")) { r("ic"); break; }
if (ends("ative")) { r(""); break; }
if (ends("alize")) { r("al"); break; }
break;
case 'i': if (ends("iciti")) { r("ic"); break; }
break;
case 'l': if (ends("ical")) { r("ic"); break; }
if (ends("ful")) { r(""); break; }
break;
case 's': if (ends("ness")) { r(""); break; }
break;
}
}
/* step5() takes off -ant, -ence etc., in context <c>vcvc<v>. */
private final void step5()
{
if (k == 0)
return; /* for Bug 1 */
switch (b.charAt(k-1))
{
case 'a':
if (ends("al"))
break;
return;
case 'c':
if (ends("ance"))
break;
if (ends("ence"))
break;
return;
case 'e':
if (ends("er"))
break;
return;
case 'i':
if (ends("ic"))
break;
return;
case 'l':
if (ends("able"))
break;
if (ends("ible"))
break;
return;
case 'n':
if (ends("ant"))
break;
if (ends("ement"))
break;
if (ends("ment"))
break;
/* element etc. not stripped before the m */
if (ends("ent"))
break;
return;
case 'o':
if (ends("ion") && j >= 0 &&
(b.charAt(j) == 's' || b.charAt(j) == 't'))
break; /* j >= 0 fixes Bug 2 */
if (ends("ou"))
break;
return;
/* takes care of -ous */
case 's':
if (ends("ism"))
break;
return;
case 't':
if (ends("ate"))
break;
if (ends("iti"))
break;
return;
case 'u':
if (ends("ous"))
break;
return;
case 'v':
if (ends("ive"))
break;
return;
case 'z':
if (ends("ize"))
break;
return;
default: return;
}
if (m() > 1)
k = j;
}
/* step6() removes a final -e if m() > 1. */
private final void step6()
{
j = k;
if (b.charAt(k) == 'e')
{ int a = m();
if (a > 1 || a == 1 && !cvc(k-1))
k--;
}
if (b.charAt(k) == 'l' && doublec(k) && m() > 1)
k--;
}
/** Stem the word placed into the Stemmer buffer through calls to add().
* Returns true if the stemming process resulted in a word different
* from the input. You can retrieve the result with
* getResultLength()/getResultBuffer() or toString().
*/
public void stem()
{ k = i - 1;
if (k > 1) {
step1();
step2();
step3();
step4();
step5();
step6(); }
i_end = k+1; i = 0;
}
/** Test program for demonstrating the PorterStemmer. It reads text from a
* a list of files, stems each word, and writes the result to standard
* output. Note that the word stemmed is expected to be in lower case:
* forcing lower case must be done outside the PorterStemmer class.
* Usage: PorterStemmer file-name file-name ...
*/
public static void main(String[] args)
{
char[] w = new char[501];
NewPorterStemmer s = new NewPorterStemmer();
//String test = "computers";
//System.out.println("testString is " + s.stem(test));
for (int i = 0; i < args.length; i++)
try
{
FileInputStream in = new FileInputStream(args[i]);
try
{ while(true)
{ int ch = in.read();
if (Character.isLetter((char) ch))
{
int j = 0;
while(true)
{ ch = Character.toLowerCase((char) ch);
w[j] = (char) ch;
if (j < 500) j++;
ch = in.read();
if (!Character.isLetter((char) ch))
{
/* to test add(char ch) */
for (int c = 0; c < j; c++)
s.add(w[c]);
//System.out.println(s.toString());
/* or, to test add(char[] w, int j) */
//s.add(w, j);
s.stem();
{ String u;
/* and now, to test toString() : */
u = s.toString();
/* to test getResultBuffer(), getResultLength() : */
/* u = new String(s.getResultBuffer(), 0, s.getResultLength()); */
System.out.print(u);
}
break;
}
}
}
if (ch < 0) break;
System.out.print((char)ch);
}
}
catch (IOException e)
{ System.out.println("error reading " + args[i]);
break;
}
}
catch (FileNotFoundException e)
{ System.out.println("file " + args[i] + " not found");
break;
}
}
}
| false | false | null | null |
diff --git a/src/com/massivecraft/factions/integration/LWCFeatures.java b/src/com/massivecraft/factions/integration/LWCFeatures.java
index 9cacb807..2f62b7bc 100644
--- a/src/com/massivecraft/factions/integration/LWCFeatures.java
+++ b/src/com/massivecraft/factions/integration/LWCFeatures.java
@@ -1,86 +1,88 @@
package com.massivecraft.factions.integration;
import java.util.LinkedList;
import java.util.List;
import org.bukkit.Bukkit;
import org.bukkit.Chunk;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.BlockState;
import com.griefcraft.lwc.LWC;
import com.griefcraft.lwc.LWCPlugin;
import com.massivecraft.factions.Conf;
import com.massivecraft.factions.FLocation;
import com.massivecraft.factions.FPlayers;
import com.massivecraft.factions.Faction;
import com.massivecraft.factions.P;
public class LWCFeatures
{
private static LWC lwc;
public static void integrateLWC(LWCPlugin test)
{
lwc = test.getLWC();
P.p.log("Successfully hooked into LWC!"+(Conf.lwcIntegration ? "" : " Integration is currently disabled, though (\"lwcIntegration\")."));
}
+ public static boolean getEnabled()
+ {
+ return Conf.lwcIntegration && lwc != null;
+ }
+
public static void clearOtherChests(FLocation flocation, Faction faction)
{
Location location = new Location(Bukkit.getWorld(flocation.getWorldName()), flocation.getX() * 16, 5, flocation.getZ() * 16);
+ if (location.getWorld() == null) return; // world not loaded or something? cancel out to prevent error
Chunk chunk = location.getChunk();
BlockState[] blocks = chunk.getTileEntities();
List<Block> chests = new LinkedList<Block>();
for(int x = 0; x < blocks.length; x++)
{
if(blocks[x].getType() == Material.CHEST)
{
chests.add(blocks[x].getBlock());
}
}
for(int x = 0; x < chests.size(); x++)
{
if(lwc.findProtection(chests.get(x)) != null)
{
if(!faction.getFPlayers().contains(FPlayers.i.get(lwc.findProtection(chests.get(x)).getOwner())))
lwc.findProtection(chests.get(x)).remove();
}
}
}
public static void clearAllChests(FLocation flocation)
{
Location location = new Location(Bukkit.getWorld(flocation.getWorldName()), flocation.getX() * 16, 5, flocation.getZ() * 16);
+ if (location.getWorld() == null) return; // world not loaded or something? cancel out to prevent error
Chunk chunk = location.getChunk();
BlockState[] blocks = chunk.getTileEntities();
List<Block> chests = new LinkedList<Block>();
for(int x = 0; x < blocks.length; x++)
{
if(blocks[x].getType() == Material.CHEST)
{
chests.add(blocks[x].getBlock());
}
}
for(int x = 0; x < chests.size(); x++)
{
if(lwc.findProtection(chests.get(x)) != null)
{
lwc.findProtection(chests.get(x)).remove();
}
}
}
-
- public static boolean getEnabled()
- {
- return Conf.lwcIntegration && lwc != null;
- }
}
| false | false | null | null |
diff --git a/core/src/com/google/zxing/common/CroppedMonochromeBitmapSource.java b/core/src/com/google/zxing/common/CroppedMonochromeBitmapSource.java
index a3adf57f..f78cc38a 100644
--- a/core/src/com/google/zxing/common/CroppedMonochromeBitmapSource.java
+++ b/core/src/com/google/zxing/common/CroppedMonochromeBitmapSource.java
@@ -1,110 +1,110 @@
/*
* Copyright 2009 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.zxing.common;
import com.google.zxing.BlackPointEstimationMethod;
import com.google.zxing.MonochromeBitmapSource;
import com.google.zxing.ReaderException;
/**
* Encapulates a cropped region of another {@link com.google.zxing.MonochromeBitmapSource}.
*
* @author Sean Owen
*/
public final class CroppedMonochromeBitmapSource implements MonochromeBitmapSource {
private final MonochromeBitmapSource delegate;
private final int left;
private final int top;
private final int right;
private final int bottom;
/**
* Creates an instance that uses only a region of the given image as a source of pixels to decode.
*
* @param delegate image to decode a region of
* @param left x coordinate of leftmost pixels to decode
* @param top y coordinate of topmost pixels to decode
* @param right one more than the x coordinate of rightmost pixels to decode, i.e. we will decode
* pixels whose x coordinate is in [left,right)
* @param bottom likewise, one more than the y coordinate of the bottommost pixels to decode
*/
public CroppedMonochromeBitmapSource(MonochromeBitmapSource delegate,
int left, int top, int right, int bottom) {
this.delegate = delegate;
this.left = left;
this.top = top;
this.right = right;
this.bottom = bottom;
}
public boolean isBlack(int x, int y) {
return delegate.isBlack(left + x, top + y);
}
public BitArray getBlackRow(int y, BitArray row, int startX, int getWidth) {
return delegate.getBlackRow(top + y, row, left + startX, getWidth);
}
public BitArray getBlackColumn(int x, BitArray column, int startY, int getHeight) {
return delegate.getBlackColumn(left + x, column, top + startY, getHeight);
}
public int getHeight() {
return bottom - top;
}
public int getWidth() {
return right - left;
}
public void estimateBlackPoint(BlackPointEstimationMethod method, int argument)
throws ReaderException {
// Hmm, the delegate will probably base this on the whole image though...
delegate.estimateBlackPoint(method, argument);
}
public BlackPointEstimationMethod getLastEstimationMethod() {
return delegate.getLastEstimationMethod();
}
public MonochromeBitmapSource rotateCounterClockwise() {
MonochromeBitmapSource rotated = delegate.rotateCounterClockwise();
return new CroppedMonochromeBitmapSource(rotated,
top,
delegate.getWidth() - right,
- delegate.getHeight() - bottom,
- left);
+ bottom,
+ delegate.getWidth() - left);
}
public boolean isRotateSupported() {
return delegate.isRotateSupported();
}
public int getLuminance(int x, int y) {
return delegate.getLuminance(x, y);
}
public int[] getLuminanceRow(int y, int[] row) {
return delegate.getLuminanceRow(y, row);
}
public int[] getLuminanceColumn(int x, int[] column) {
return delegate.getLuminanceColumn(x, column);
}
}
| true | false | null | null |
diff --git a/closure/closure-compiler/src/com/google/javascript/rhino/Node.java b/closure/closure-compiler/src/com/google/javascript/rhino/Node.java
index 3561b0a46..9837231c0 100644
--- a/closure/closure-compiler/src/com/google/javascript/rhino/Node.java
+++ b/closure/closure-compiler/src/com/google/javascript/rhino/Node.java
@@ -1,2363 +1,2371 @@
/*
*
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* 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.
*
* The Original Code is Rhino code, released
* May 6, 1999.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1997-1999
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Norris Boyd
* Roger Lawrence
* Mike McCabe
*
* Alternatively, the contents of this file may be used under the terms of
* the GNU General Public License Version 2 or later (the "GPL"), in which
* case the provisions of the GPL are applicable instead of those above. If
* you wish to allow use of your version of this file only under the terms of
* the GPL and not to allow others to use your version of this file under the
* MPL, indicate your decision by deleting the provisions above and replacing
* them with the notice and other provisions required by the GPL. If you do
* not delete the provisions above, a recipient may use your version of this
* file under either the MPL or the GPL.
*
* ***** END LICENSE BLOCK ***** */
package com.google.javascript.rhino;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Objects;
import com.google.common.base.Preconditions;
import com.google.javascript.rhino.jstype.JSType;
import com.google.javascript.rhino.jstype.SimpleSourceFile;
import com.google.javascript.rhino.jstype.StaticSourceFile;
import java.io.IOException;
import java.io.Serializable;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Set;
/**
* This class implements the root of the intermediate representation.
*
*/
public class Node implements Cloneable, Serializable {
private static final long serialVersionUID = 1L;
public static final int
// TODO(nicksantos): Remove this prop.
SOURCENAME_PROP = 16,
JSDOC_INFO_PROP = 29, // contains a TokenStream.JSDocInfo object
VAR_ARGS_NAME = 30, // the name node is a variable length
// argument placeholder.
INCRDECR_PROP = 32, // pre or post type of increment/decrement
PARENTHESIZED_PROP = 35, // expression is parenthesized
QUOTED_PROP = 36, // set to indicate a quoted object lit key
OPT_ARG_NAME = 37, // The name node is an optional argument.
SYNTHETIC_BLOCK_PROP = 38, // A synthetic block. Used to make
// processing simpler, and does not
// represent a real block in the source.
EMPTY_BLOCK = 39, // Used to indicate BLOCK that replaced
// EMPTY nodes.
ORIGINALNAME_PROP = 40, // The original name of the node, before
// renaming.
BRACELESS_TYPE = 41, // The type syntax without curly braces.
SIDE_EFFECT_FLAGS = 42, // Function or constructor call side effect
// flags
// Coding convention props
IS_CONSTANT_NAME = 43, // The variable or property is constant.
IS_OPTIONAL_PARAM = 44, // The parameter is optional.
IS_VAR_ARGS_PARAM = 45, // The parameter is a var_args.
IS_NAMESPACE = 46, // The variable creates a namespace.
IS_DISPATCHER = 47, // The function is a dispatcher function,
// probably generated from Java code, and
// should be resolved to the proper
// overload if possible.
DIRECTIVES = 48, // The ES5 directives on this node.
DIRECT_EVAL = 49, // ES5 distinguishes between direct and
// indirect calls to eval.
FREE_CALL = 50, // A CALL without an explicit "this" value.
STATIC_SOURCE_FILE = 51, // A StaticSourceFile indicating the file
// where this node lives.
LENGTH = 52, // The length of the code represented by
// this node.
INPUT_ID = 53, // The id of the input associated with this
// node.
SLASH_V = 54, // Whether a STRING node contains a \v
// vertical tab escape. This is a total hack.
// See comments in IRFactory about this.
LAST_PROP = 54;
public static final int // flags for INCRDECR_PROP
DECR_FLAG = 0x1,
POST_FLAG = 0x2;
private static final String propToString(int propType) {
switch (propType) {
case BRACELESS_TYPE: return "braceless_type";
case VAR_ARGS_NAME: return "var_args_name";
case SOURCENAME_PROP: return "sourcename";
case JSDOC_INFO_PROP: return "jsdoc_info";
case INCRDECR_PROP: return "incrdecr";
case PARENTHESIZED_PROP: return "parenthesized";
case QUOTED_PROP: return "quoted";
case OPT_ARG_NAME: return "opt_arg";
case SYNTHETIC_BLOCK_PROP: return "synthetic";
case EMPTY_BLOCK: return "empty_block";
case ORIGINALNAME_PROP: return "originalname";
case SIDE_EFFECT_FLAGS: return "side_effect_flags";
case IS_CONSTANT_NAME: return "is_constant_name";
case IS_OPTIONAL_PARAM: return "is_optional_param";
case IS_VAR_ARGS_PARAM: return "is_var_args_param";
case IS_NAMESPACE: return "is_namespace";
case IS_DISPATCHER: return "is_dispatcher";
case DIRECTIVES: return "directives";
case DIRECT_EVAL: return "direct_eval";
case FREE_CALL: return "free_call";
case STATIC_SOURCE_FILE: return "source_file";
case INPUT_ID: return "input_id";
case LENGTH: return "length";
default:
throw new IllegalStateException("unexpect prop id " + propType);
}
}
private static class NumberNode extends Node {
private static final long serialVersionUID = 1L;
NumberNode(double number) {
super(Token.NUMBER);
this.number = number;
}
public NumberNode(double number, int lineno, int charno) {
super(Token.NUMBER, lineno, charno);
this.number = number;
}
@Override
public double getDouble() {
return this.number;
}
@Override
public void setDouble(double d) {
this.number = d;
}
@Override
boolean isEquivalentTo(Node node, boolean compareJsType, boolean recurse) {
- return (super.isEquivalentTo(node, compareJsType, recurse)
- && getDouble() == ((NumberNode) node).getDouble());
+ boolean equivalent = super.isEquivalentTo(node, compareJsType, recurse);
+ if (equivalent) {
+ double thisValue = getDouble();
+ double thatValue = ((NumberNode) node).getDouble();
+ if (thisValue == thatValue) {
+ // detect the difference between 0.0 and -0.0.
+ return (thisValue != 0.0) || (1/thisValue == 1/thatValue);
+ }
+ }
+ return false;
}
private double number;
}
private static class StringNode extends Node {
private static final long serialVersionUID = 1L;
StringNode(int type, String str) {
super(type);
if (null == str) {
throw new IllegalArgumentException("StringNode: str is null");
}
this.str = str;
}
StringNode(int type, String str, int lineno, int charno) {
super(type, lineno, charno);
if (null == str) {
throw new IllegalArgumentException("StringNode: str is null");
}
this.str = str;
}
/**
* returns the string content.
* @return non null.
*/
@Override
public String getString() {
return this.str;
}
/**
* sets the string content.
* @param str the new value. Non null.
*/
@Override
public void setString(String str) {
if (null == str) {
throw new IllegalArgumentException("StringNode: str is null");
}
this.str = str;
}
@Override
boolean isEquivalentTo(Node node, boolean compareJsType, boolean recurse) {
return (super.isEquivalentTo(node, compareJsType, recurse)
&& this.str.equals(((StringNode) node).str));
}
/**
* If the property is not defined, this was not a quoted key. The
* QUOTED_PROP int property is only assigned to STRING tokens used as
* object lit keys.
* @return true if this was a quoted string key in an object literal.
*/
@Override
public boolean isQuotedString() {
return getBooleanProp(QUOTED_PROP);
}
/**
* This should only be called for STRING nodes created in object lits.
*/
@Override
public void setQuotedString() {
putBooleanProp(QUOTED_PROP, true);
}
private String str;
}
// PropListItems must be immutable so that they can be shared.
private interface PropListItem {
int getType();
PropListItem getNext();
PropListItem chain(PropListItem next);
Object getObjectValue();
int getIntValue();
}
private static abstract class AbstractPropListItem
implements PropListItem, Serializable {
private static final long serialVersionUID = 1L;
private final PropListItem next;
private final int propType;
AbstractPropListItem(int propType, PropListItem next) {
this.propType = propType;
this.next = next;
}
@Override
public int getType() {
return propType;
}
@Override
public PropListItem getNext() {
return next;
}
@Override
public abstract PropListItem chain(PropListItem next);
}
// A base class for Object storing props
private static class ObjectPropListItem
extends AbstractPropListItem {
private static final long serialVersionUID = 1L;
private final Object objectValue;
ObjectPropListItem(int propType, Object objectValue, PropListItem next) {
super(propType, next);
this.objectValue = objectValue;
}
@Override
public int getIntValue() {
throw new UnsupportedOperationException();
}
@Override
public Object getObjectValue() {
return objectValue;
}
@Override
public String toString() {
return objectValue == null ? "null" : objectValue.toString();
}
@Override
public PropListItem chain(PropListItem next) {
return new ObjectPropListItem(getType(), objectValue, next);
}
}
// A base class for int storing props
private static class IntPropListItem extends AbstractPropListItem {
private static final long serialVersionUID = 1L;
final int intValue;
IntPropListItem(int propType, int intValue, PropListItem next) {
super(propType, next);
this.intValue = intValue;
}
@Override
public int getIntValue() {
return intValue;
}
@Override
public Object getObjectValue() {
throw new UnsupportedOperationException();
}
@Override
public String toString() {
return String.valueOf(intValue);
}
@Override
public PropListItem chain(PropListItem next) {
return new IntPropListItem(getType(), intValue, next);
}
}
public Node(int nodeType) {
type = nodeType;
parent = null;
sourcePosition = -1;
}
public Node(int nodeType, Node child) {
Preconditions.checkArgument(child.parent == null,
"new child has existing parent");
Preconditions.checkArgument(child.next == null,
"new child has existing sibling");
type = nodeType;
parent = null;
first = last = child;
child.next = null;
child.parent = this;
sourcePosition = -1;
}
public Node(int nodeType, Node left, Node right) {
Preconditions.checkArgument(left.parent == null,
"first new child has existing parent");
Preconditions.checkArgument(left.next == null,
"first new child has existing sibling");
Preconditions.checkArgument(right.parent == null,
"second new child has existing parent");
Preconditions.checkArgument(right.next == null,
"second new child has existing sibling");
type = nodeType;
parent = null;
first = left;
last = right;
left.next = right;
left.parent = this;
right.next = null;
right.parent = this;
sourcePosition = -1;
}
public Node(int nodeType, Node left, Node mid, Node right) {
Preconditions.checkArgument(left.parent == null);
Preconditions.checkArgument(left.next == null);
Preconditions.checkArgument(mid.parent == null);
Preconditions.checkArgument(mid.next == null);
Preconditions.checkArgument(right.parent == null);
Preconditions.checkArgument(right.next == null);
type = nodeType;
parent = null;
first = left;
last = right;
left.next = mid;
left.parent = this;
mid.next = right;
mid.parent = this;
right.next = null;
right.parent = this;
sourcePosition = -1;
}
public Node(int nodeType, Node left, Node mid, Node mid2, Node right) {
Preconditions.checkArgument(left.parent == null);
Preconditions.checkArgument(left.next == null);
Preconditions.checkArgument(mid.parent == null);
Preconditions.checkArgument(mid.next == null);
Preconditions.checkArgument(mid2.parent == null);
Preconditions.checkArgument(mid2.next == null);
Preconditions.checkArgument(right.parent == null);
Preconditions.checkArgument(right.next == null);
type = nodeType;
parent = null;
first = left;
last = right;
left.next = mid;
left.parent = this;
mid.next = mid2;
mid.parent = this;
mid2.next = right;
mid2.parent = this;
right.next = null;
right.parent = this;
sourcePosition = -1;
}
public Node(int nodeType, int lineno, int charno) {
type = nodeType;
parent = null;
sourcePosition = mergeLineCharNo(lineno, charno);
}
public Node(int nodeType, Node child, int lineno, int charno) {
this(nodeType, child);
sourcePosition = mergeLineCharNo(lineno, charno);
}
public Node(int nodeType, Node left, Node right, int lineno, int charno) {
this(nodeType, left, right);
sourcePosition = mergeLineCharNo(lineno, charno);
}
public Node(int nodeType, Node left, Node mid, Node right,
int lineno, int charno) {
this(nodeType, left, mid, right);
sourcePosition = mergeLineCharNo(lineno, charno);
}
public Node(int nodeType, Node left, Node mid, Node mid2, Node right,
int lineno, int charno) {
this(nodeType, left, mid, mid2, right);
sourcePosition = mergeLineCharNo(lineno, charno);
}
public Node(int nodeType, Node[] children, int lineno, int charno) {
this(nodeType, children);
sourcePosition = mergeLineCharNo(lineno, charno);
}
public Node(int nodeType, Node[] children) {
this.type = nodeType;
parent = null;
if (children.length != 0) {
this.first = children[0];
this.last = children[children.length - 1];
for (int i = 1; i < children.length; i++) {
if (null != children[i - 1].next) {
// fail early on loops. implies same node in array twice
throw new IllegalArgumentException("duplicate child");
}
children[i - 1].next = children[i];
Preconditions.checkArgument(children[i - 1].parent == null);
children[i - 1].parent = this;
}
Preconditions.checkArgument(children[children.length - 1].parent == null);
children[children.length - 1].parent = this;
if (null != this.last.next) {
// fail early on loops. implies same node in array twice
throw new IllegalArgumentException("duplicate child");
}
}
}
public static Node newNumber(double number) {
return new NumberNode(number);
}
public static Node newNumber(double number, int lineno, int charno) {
return new NumberNode(number, lineno, charno);
}
public static Node newString(String str) {
return new StringNode(Token.STRING, str);
}
public static Node newString(int type, String str) {
return new StringNode(type, str);
}
public static Node newString(String str, int lineno, int charno) {
return new StringNode(Token.STRING, str, lineno, charno);
}
public static Node newString(int type, String str, int lineno, int charno) {
return new StringNode(type, str, lineno, charno);
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public boolean hasChildren() {
return first != null;
}
public Node getFirstChild() {
return first;
}
public Node getLastChild() {
return last;
}
public Node getNext() {
return next;
}
public Node getChildBefore(Node child) {
if (child == first) {
return null;
}
Node n = first;
while (n.next != child) {
n = n.next;
if (n == null) {
throw new RuntimeException("node is not a child");
}
}
return n;
}
public Node getChildAtIndex(int i) {
Node n = first;
while (i > 0) {
n = n.next;
i--;
}
return n;
}
public int getIndexOfChild(Node child) {
Node n = first;
int i = 0;
while (n != null) {
if (child == n) {
return i;
}
n = n.next;
i++;
}
return -1;
}
public Node getLastSibling() {
Node n = this;
while (n.next != null) {
n = n.next;
}
return n;
}
public void addChildToFront(Node child) {
Preconditions.checkArgument(child.parent == null);
Preconditions.checkArgument(child.next == null);
child.parent = this;
child.next = first;
first = child;
if (last == null) {
last = child;
}
}
public void addChildToBack(Node child) {
Preconditions.checkArgument(child.parent == null);
Preconditions.checkArgument(child.next == null);
child.parent = this;
child.next = null;
if (last == null) {
first = last = child;
return;
}
last.next = child;
last = child;
}
public void addChildrenToFront(Node children) {
for (Node child = children; child != null; child = child.next) {
Preconditions.checkArgument(child.parent == null);
child.parent = this;
}
Node lastSib = children.getLastSibling();
lastSib.next = first;
first = children;
if (last == null) {
last = lastSib;
}
}
public void addChildrenToBack(Node children) {
for (Node child = children; child != null; child = child.next) {
Preconditions.checkArgument(child.parent == null);
child.parent = this;
}
if (last != null) {
last.next = children;
}
last = children.getLastSibling();
if (first == null) {
first = children;
}
}
/**
* Add 'child' before 'node'.
*/
public void addChildBefore(Node newChild, Node node) {
Preconditions.checkArgument(node != null,
"The existing child node of the parent should not be null.");
Preconditions.checkArgument(newChild.next == null,
"The new child node has siblings.");
Preconditions.checkArgument(newChild.parent == null,
"The new child node already has a parent.");
if (first == node) {
newChild.parent = this;
newChild.next = first;
first = newChild;
return;
}
Node prev = getChildBefore(node);
addChildAfter(newChild, prev);
}
/**
* Add 'child' after 'node'.
*/
public void addChildAfter(Node newChild, Node node) {
Preconditions.checkArgument(newChild.next == null,
"The new child node has siblings.");
Preconditions.checkArgument(newChild.parent == null,
"The new child node already has a parent.");
newChild.parent = this;
newChild.next = node.next;
node.next = newChild;
if (last == node) {
last = newChild;
}
}
/**
* Detach a child from its parent and siblings.
*/
public void removeChild(Node child) {
Node prev = getChildBefore(child);
if (prev == null)
first = first.next;
else
prev.next = child.next;
if (child == last) last = prev;
child.next = null;
child.parent = null;
}
/**
* Detaches child from Node and replaces it with newChild.
*/
public void replaceChild(Node child, Node newChild) {
Preconditions.checkArgument(newChild.next == null,
"The new child node has siblings.");
Preconditions.checkArgument(newChild.parent == null,
"The new child node already has a parent.");
// Copy over important information.
newChild.copyInformationFrom(child);
newChild.next = child.next;
newChild.parent = this;
if (child == first) {
first = newChild;
} else {
Node prev = getChildBefore(child);
prev.next = newChild;
}
if (child == last)
last = newChild;
child.next = null;
child.parent = null;
}
public void replaceChildAfter(Node prevChild, Node newChild) {
Preconditions.checkArgument(prevChild.parent == this,
"prev is not a child of this node.");
Preconditions.checkArgument(newChild.next == null,
"The new child node has siblings.");
Preconditions.checkArgument(newChild.parent == null,
"The new child node already has a parent.");
// Copy over important information.
newChild.copyInformationFrom(prevChild);
Node child = prevChild.next;
newChild.next = child.next;
newChild.parent = this;
prevChild.next = newChild;
if (child == last)
last = newChild;
child.next = null;
child.parent = null;
}
@VisibleForTesting
PropListItem lookupProperty(int propType) {
PropListItem x = propListHead;
while (x != null && propType != x.getType()) {
x = x.getNext();
}
return x;
}
/**
* Clone the properties from the provided node without copying
* the property object. The recieving node may not have any
* existing properties.
* @param other The node to clone properties from.
* @return this node.
*/
public Node clonePropsFrom(Node other) {
Preconditions.checkState(this.propListHead == null,
"Node has existing properties.");
this.propListHead = other.propListHead;
return this;
}
public void removeProp(int propType) {
PropListItem result = removeProp(propListHead, propType);
if (result != propListHead) {
propListHead = result;
}
}
/**
* @param item The item to inspect
* @param propType The property to look for
* @return The replacement list if the property was removed, or
* 'item' otherwise.
*/
private PropListItem removeProp(PropListItem item, int propType) {
if (item == null) {
return null;
} else if (item.getType() == propType) {
return item.getNext();
} else {
PropListItem result = removeProp(item.getNext(), propType);
if (result != item.getNext()) {
return item.chain(result);
} else {
return item;
}
}
}
public Object getProp(int propType) {
if (propType == SOURCENAME_PROP) {
return getSourceFileName();
}
PropListItem item = lookupProperty(propType);
if (item == null) {
return null;
}
return item.getObjectValue();
}
public boolean getBooleanProp(int propType) {
return getIntProp(propType) != 0;
}
/**
* Returns the integer value for the property, or 0 if the property
* is not defined.
*/
public int getIntProp(int propType) {
PropListItem item = lookupProperty(propType);
if (item == null) {
return 0;
}
return item.getIntValue();
}
public int getExistingIntProp(int propType) {
PropListItem item = lookupProperty(propType);
if (item == null) {
throw new IllegalStateException("missing prop: " + propType);
}
return item.getIntValue();
}
public void putProp(int propType, Object value) {
if (propType == SOURCENAME_PROP) {
putProp(
STATIC_SOURCE_FILE, new SimpleSourceFile((String) value, false));
return;
}
removeProp(propType);
if (value != null) {
propListHead = createProp(propType, value, propListHead);
}
}
public void putBooleanProp(int propType, boolean value) {
putIntProp(propType, value ? 1 : 0);
}
public void putIntProp(int propType, int value) {
removeProp(propType);
if (value != 0) {
propListHead = createProp(propType, value, propListHead);
}
}
PropListItem createProp(int propType, Object value, PropListItem next) {
return new ObjectPropListItem(propType, value, next);
}
PropListItem createProp(int propType, int value, PropListItem next) {
return new IntPropListItem(propType, value, next);
}
// Gets all the property types, in sorted order.
private int[] getSortedPropTypes() {
int count = 0;
for (PropListItem x = propListHead; x != null; x = x.getNext()) {
count++;
}
int[] keys = new int[count];
for (PropListItem x = propListHead; x != null; x = x.getNext()) {
count--;
keys[count] = x.getType();
}
Arrays.sort(keys);
return keys;
}
/** Can only be called when <tt>getType() == TokenStream.NUMBER</tt> */
public double getDouble() throws UnsupportedOperationException {
if (this.getType() == Token.NUMBER) {
throw new IllegalStateException(
"Number node not created with Node.newNumber");
} else {
throw new UnsupportedOperationException(this + " is not a number node");
}
}
/** Can only be called when <tt>getType() == TokenStream.NUMBER</tt> */
public void setDouble(double s) throws UnsupportedOperationException {
if (this.getType() == Token.NUMBER) {
throw new IllegalStateException(
"Number node not created with Node.newNumber");
} else {
throw new UnsupportedOperationException(this + " is not a string node");
}
}
/** Can only be called when node has String context. */
public String getString() throws UnsupportedOperationException {
if (this.getType() == Token.STRING) {
throw new IllegalStateException(
"String node not created with Node.newString");
} else {
throw new UnsupportedOperationException(this + " is not a string node");
}
}
/** Can only be called when node has String context. */
public void setString(String s) throws UnsupportedOperationException {
if (this.getType() == Token.STRING) {
throw new IllegalStateException(
"String node not created with Node.newString");
} else {
throw new UnsupportedOperationException(this + " is not a string node");
}
}
@Override
public String toString() {
return toString(true, true, true);
}
public String toString(
boolean printSource,
boolean printAnnotations,
boolean printType) {
StringBuilder sb = new StringBuilder();
toString(sb, printSource, printAnnotations, printType);
return sb.toString();
}
private void toString(
StringBuilder sb,
boolean printSource,
boolean printAnnotations,
boolean printType) {
sb.append(Token.name(type));
if (this instanceof StringNode) {
sb.append(' ');
sb.append(getString());
} else if (type == Token.FUNCTION) {
sb.append(' ');
// In the case of JsDoc trees, the first child is often not a string
// which causes exceptions to be thrown when calling toString or
// toStringTree.
if (first == null || first.getType() != Token.NAME) {
sb.append("<invalid>");
} else {
sb.append(first.getString());
}
} else if (type == Token.NUMBER) {
sb.append(' ');
sb.append(getDouble());
}
if (printSource) {
int lineno = getLineno();
if (lineno != -1) {
sb.append(' ');
sb.append(lineno);
}
}
if (printAnnotations) {
int[] keys = getSortedPropTypes();
for (int i = 0; i < keys.length; i++) {
int type = keys[i];
PropListItem x = lookupProperty(type);
sb.append(" [");
sb.append(propToString(type));
sb.append(": ");
String value;
switch (type) {
default:
value = x.toString();
break;
}
sb.append(value);
sb.append(']');
}
}
if (printType) {
if (jsType != null) {
String jsTypeString = jsType.toString();
if (jsTypeString != null) {
sb.append(" : ");
sb.append(jsTypeString);
}
}
}
}
public String toStringTree() {
return toStringTreeImpl();
}
private String toStringTreeImpl() {
try {
StringBuilder s = new StringBuilder();
appendStringTree(s);
return s.toString();
} catch (IOException e) {
throw new RuntimeException("Should not happen\n" + e);
}
}
public void appendStringTree(Appendable appendable) throws IOException {
toStringTreeHelper(this, 0, appendable);
}
private static void toStringTreeHelper(Node n, int level, Appendable sb)
throws IOException {
for (int i = 0; i != level; ++i) {
sb.append(" ");
}
sb.append(n.toString());
sb.append('\n');
for (Node cursor = n.getFirstChild();
cursor != null;
cursor = cursor.getNext()) {
toStringTreeHelper(cursor, level + 1, sb);
}
}
int type; // type of the node; Token.NAME for example
Node next; // next sibling
private Node first; // first element of a linked list of children
private Node last; // last element of a linked list of children
/**
* Linked list of properties. Since vast majority of nodes would have
* no more then 2 properties, linked list saves memory and provides
* fast lookup. If this does not holds, propListHead can be replaced
* by UintMap.
*/
private PropListItem propListHead;
/**
* COLUMN_BITS represents how many of the lower-order bits of
* sourcePosition are reserved for storing the column number.
* Bits above these store the line number.
* This gives us decent position information for everything except
* files already passed through a minimizer, where lines might
* be longer than 4096 characters.
*/
public static final int COLUMN_BITS = 12;
/**
* MAX_COLUMN_NUMBER represents the maximum column number that can
* be represented. JSCompiler's modifications to Rhino cause all
* tokens located beyond the maximum column to MAX_COLUMN_NUMBER.
*/
public static final int MAX_COLUMN_NUMBER = (1 << COLUMN_BITS) - 1;
/**
* COLUMN_MASK stores a value where bits storing the column number
* are set, and bits storing the line are not set. It's handy for
* separating column number from line number.
*/
public static final int COLUMN_MASK = MAX_COLUMN_NUMBER;
/**
* Source position of this node. The position is encoded with the
* column number in the low 12 bits of the integer, and the line
* number in the rest. Create some handy constants so we can change this
* size if we want.
*/
private int sourcePosition;
private JSType jsType;
private Node parent;
//==========================================================================
// Source position management
public void setStaticSourceFile(StaticSourceFile file) {
this.putProp(STATIC_SOURCE_FILE, file);
}
/** Sets the source file to a non-extern file of the given name. */
public void setSourceFileForTesting(String name) {
this.putProp(STATIC_SOURCE_FILE, new SimpleSourceFile(name, false));
}
public String getSourceFileName() {
StaticSourceFile file = getStaticSourceFile();
return file == null ? null : file.getName();
}
/** Returns the source file associated with this input. May be null */
public StaticSourceFile getStaticSourceFile() {
return ((StaticSourceFile) this.getProp(STATIC_SOURCE_FILE));
}
/**
* @param inputId
*/
public void setInputId(InputId inputId) {
this.putProp(INPUT_ID, inputId);
}
/**
* @return The Id of the CompilerInput associated with this Node.
*/
public InputId getInputId() {
return ((InputId) this.getProp(INPUT_ID));
}
public boolean isFromExterns() {
StaticSourceFile file = getStaticSourceFile();
return file == null ? false : file.isExtern();
}
public int getLength() {
return getIntProp(LENGTH);
}
public void setLength(int length) {
putIntProp(LENGTH, length);
}
public int getLineno() {
return extractLineno(sourcePosition);
}
public int getCharno() {
return extractCharno(sourcePosition);
}
public int getSourceOffset() {
StaticSourceFile file = getStaticSourceFile();
int lineOffset = file == null ?
Integer.MIN_VALUE : file.getLineOffset(getLineno());
return lineOffset + getCharno();
}
public int getSourcePosition() {
return sourcePosition;
}
public void setLineno(int lineno) {
int charno = getCharno();
if (charno == -1) {
charno = 0;
}
sourcePosition = mergeLineCharNo(lineno, charno);
}
public void setCharno(int charno) {
sourcePosition = mergeLineCharNo(getLineno(), charno);
}
public void setSourceEncodedPosition(int sourcePosition) {
this.sourcePosition = sourcePosition;
}
public void setSourceEncodedPositionForTree(int sourcePosition) {
this.sourcePosition = sourcePosition;
for (Node child = getFirstChild();
child != null; child = child.getNext()) {
child.setSourceEncodedPositionForTree(sourcePosition);
}
}
/**
* Merges the line number and character number in one integer. The Character
* number takes the first 12 bits and the line number takes the rest. If
* the character number is greater than <code>2<sup>12</sup>-1</code> it is
* adjusted to <code>2<sup>12</sup>-1</code>.
*/
protected static int mergeLineCharNo(int lineno, int charno) {
if (lineno < 0 || charno < 0) {
return -1;
} else if ((charno & ~COLUMN_MASK) != 0) {
return lineno << COLUMN_BITS | COLUMN_MASK;
} else {
return lineno << COLUMN_BITS | (charno & COLUMN_MASK);
}
}
/**
* Extracts the line number and character number from a merged line char
* number (see {@link #mergeLineCharNo(int, int)}).
*/
protected static int extractLineno(int lineCharNo) {
if (lineCharNo == -1) {
return -1;
} else {
return lineCharNo >>> COLUMN_BITS;
}
}
/**
* Extracts the character number and character number from a merged line
* char number (see {@link #mergeLineCharNo(int, int)}).
*/
protected static int extractCharno(int lineCharNo) {
if (lineCharNo == -1) {
return -1;
} else {
return lineCharNo & COLUMN_MASK;
}
}
//==========================================================================
// Iteration
/**
* <p>Return an iterable object that iterates over this nodes's children.
* The iterator does not support the optional operation
* {@link Iterator#remove()}.</p>
*
* <p>To iterate over a node's siblings, one can write</p>
* <pre>Node n = ...;
* for (Node child : n.children()) { ...</pre>
*/
public Iterable<Node> children() {
if (first == null) {
return Collections.emptySet();
} else {
return new SiblingNodeIterable(first);
}
}
/**
* <p>Return an iterable object that iterates over this nodes's siblings.
* The iterator does not support the optional operation
* {@link Iterator#remove()}.</p>
*
* <p>To iterate over a node's siblings, one can write</p>
* <pre>Node n = ...;
* for (Node sibling : n.siblings()) { ...</pre>
*/
public Iterable<Node> siblings() {
return new SiblingNodeIterable(this);
}
/**
* @see Node#siblings()
*/
private static final class SiblingNodeIterable
implements Iterable<Node>, Iterator<Node> {
private final Node start;
private Node current;
private boolean used;
SiblingNodeIterable(Node start) {
this.start = start;
this.current = start;
this.used = false;
}
@Override
public Iterator<Node> iterator() {
if (!used) {
used = true;
return this;
} else {
// We have already used the current object as an iterator;
// we must create a new SiblingNodeIterable based on this
// iterable's start node.
//
// Since the primary use case for Node.children is in for
// loops, this branch is extremely unlikely.
return (new SiblingNodeIterable(start)).iterator();
}
}
@Override
public boolean hasNext() {
return current != null;
}
@Override
public Node next() {
if (current == null) {
throw new NoSuchElementException();
}
try {
return current;
} finally {
current = current.getNext();
}
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
// ==========================================================================
// Accessors
PropListItem getPropListHeadForTesting() {
return propListHead;
}
public Node getParent() {
return parent;
}
/**
* Gets the ancestor node relative to this.
*
* @param level 0 = this, 1 = the parent, etc.
*/
public Node getAncestor(int level) {
Preconditions.checkArgument(level >= 0);
Node node = this;
while (node != null && level-- > 0) {
node = node.getParent();
}
return node;
}
/**
* Iterates all of the node's ancestors excluding itself.
*/
public AncestorIterable getAncestors() {
return new AncestorIterable(this.getParent());
}
/**
* Iterator to go up the ancestor tree.
*/
public static class AncestorIterable implements Iterable<Node> {
private Node cur;
/**
* @param cur The node to start.
*/
AncestorIterable(Node cur) {
this.cur = cur;
}
@Override
public Iterator<Node> iterator() {
return new Iterator<Node>() {
@Override
public boolean hasNext() {
return cur != null;
}
@Override
public Node next() {
if (!hasNext()) throw new NoSuchElementException();
Node n = cur;
cur = cur.getParent();
return n;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
}
/**
* Check for one child more efficiently than by iterating over all the
* children as is done with Node.getChildCount().
*
* @return Whether the node has exactly one child.
*/
public boolean hasOneChild() {
return first != null && first == last;
}
/**
* Check for more than one child more efficiently than by iterating over all
* the children as is done with Node.getChildCount().
*
* @return Whether the node more than one child.
*/
public boolean hasMoreThanOneChild() {
return first != null && first != last;
}
public int getChildCount() {
int c = 0;
for (Node n = first; n != null; n = n.next)
c++;
return c;
}
// Intended for testing and verification only.
public boolean hasChild(Node child) {
for (Node n = first; n != null; n = n.getNext()) {
if (child == n) {
return true;
}
}
return false;
}
/**
* Checks if the subtree under this node is the same as another subtree.
* Returns null if it's equal, or a message describing the differences.
*/
public String checkTreeEquals(Node node2) {
NodeMismatch diff = checkTreeEqualsImpl(node2);
if (diff != null) {
return "Node tree inequality:" +
"\nTree1:\n" + toStringTree() +
"\n\nTree2:\n" + node2.toStringTree() +
"\n\nSubtree1: " + diff.nodeA.toStringTree() +
"\n\nSubtree2: " + diff.nodeB.toStringTree();
}
return null;
}
/**
* Compare this node to node2 recursively and return the first pair of nodes
* that differs doing a preorder depth-first traversal. Package private for
* testing. Returns null if the nodes are equivalent.
*/
NodeMismatch checkTreeEqualsImpl(Node node2) {
if (!isEquivalentTo(node2, false, false)) {
return new NodeMismatch(this, node2);
}
NodeMismatch res = null;
Node n, n2;
for (n = first, n2 = node2.first;
res == null && n != null;
n = n.next, n2 = n2.next) {
if (node2 == null) {
throw new IllegalStateException();
}
res = n.checkTreeEqualsImpl(n2);
if (res != null) {
return res;
}
}
return res;
}
/**
* Compare this node to node2 recursively and return the first pair of nodes
* that differs doing a preorder depth-first traversal. Package private for
* testing. Returns null if the nodes are equivalent.
*/
NodeMismatch checkTreeTypeAwareEqualsImpl(Node node2) {
// Do a non-recursive equivalents check.
if (!isEquivalentTo(node2, true, false)) {
return new NodeMismatch(this, node2);
}
NodeMismatch res = null;
Node n, n2;
for (n = first, n2 = node2.first;
res == null && n != null;
n = n.next, n2 = n2.next) {
res = n.checkTreeTypeAwareEqualsImpl(n2);
if (res != null) {
return res;
}
}
return res;
}
/** Returns true if this node is equivalent semantically to another */
public boolean isEquivalentTo(Node node) {
return isEquivalentTo(node, false, true);
}
/**
* Returns true if this node is equivalent semantically to another and
* the types are equivalent.
*/
public boolean isEquivalentToTyped(Node node) {
return isEquivalentTo(node, true, true);
}
/**
* @param compareJsType Whether to compare the JSTypes of the nodes.
* @param recurse Whether to compare the children of the current node, if
* not only the the count of the children are compared.
* @return Whether this node is equivalent semantically to the provided node.
*/
boolean isEquivalentTo(Node node, boolean compareJsType, boolean recurse) {
if (type != node.getType()
|| getChildCount() != node.getChildCount()
|| this.getClass() != node.getClass()) {
return false;
}
if (compareJsType && !JSType.isEquivalent(jsType, node.getJSType())) {
return false;
}
if (type == Token.INC || type == Token.DEC) {
int post1 = this.getIntProp(INCRDECR_PROP);
int post2 = node.getIntProp(INCRDECR_PROP);
if (post1 != post2) {
return false;
}
} else if (type == Token.STRING) {
int quoted1 = this.getIntProp(QUOTED_PROP);
int quoted2 = node.getIntProp(QUOTED_PROP);
if (quoted1 != quoted2) {
return false;
}
int slashV1 = this.getIntProp(SLASH_V);
int slashV2 = node.getIntProp(SLASH_V);
if (slashV1 != slashV2) {
return false;
}
} else if (type == Token.CALL) {
if (this.getBooleanProp(FREE_CALL) != node.getBooleanProp(FREE_CALL)) {
return false;
}
}
if (recurse) {
Node n, n2;
for (n = first, n2 = node.first;
n != null;
n = n.next, n2 = n2.next) {
if (!n.isEquivalentTo(n2, compareJsType, true)) {
return false;
}
}
}
return true;
}
/**
* This function takes a set of GETPROP nodes and produces a string that is
* each property separated by dots. If the node ultimately under the left
* sub-tree is not a simple name, this is not a valid qualified name.
*
* @return a null if this is not a qualified name, or a dot-separated string
* of the name and properties.
*/
public String getQualifiedName() {
if (type == Token.NAME) {
return getString();
} else if (type == Token.GETPROP) {
String left = getFirstChild().getQualifiedName();
if (left == null) {
return null;
}
return left + "." + getLastChild().getString();
} else if (type == Token.THIS) {
return "this";
} else {
return null;
}
}
/**
* Returns whether a node corresponds to a simple or a qualified name, such as
* <code>x</code> or <code>a.b.c</code> or <code>this.a</code>.
*/
public boolean isQualifiedName() {
switch (getType()) {
case Token.NAME:
case Token.THIS:
return true;
case Token.GETPROP:
return getFirstChild().isQualifiedName();
default:
return false;
}
}
/**
* Returns whether a node corresponds to a simple or a qualified name without
* a "this" reference, such as <code>a.b.c</code>, but not <code>this.a</code>
* .
*/
public boolean isUnscopedQualifiedName() {
switch (getType()) {
case Token.NAME:
return true;
case Token.GETPROP:
return getFirstChild().isUnscopedQualifiedName();
default:
return false;
}
}
// ==========================================================================
// Mutators
/**
* Removes this node from its parent. Equivalent to:
* node.getParent().removeChild();
*/
public Node detachFromParent() {
Preconditions.checkState(parent != null);
parent.removeChild(this);
return this;
}
/**
* Removes the first child of Node. Equivalent to:
* node.removeChild(node.getFirstChild());
*
* @return The removed Node.
*/
public Node removeFirstChild() {
Node child = first;
if (child != null) {
removeChild(child);
}
return child;
}
/**
* @return A Node that is the head of the list of children.
*/
public Node removeChildren() {
Node children = first;
for (Node child = first; child != null; child = child.getNext()) {
child.parent = null;
}
first = null;
last = null;
return children;
}
/**
* Removes all children from this node and isolates the children from each
* other.
*/
public void detachChildren() {
for (Node child = first; child != null;) {
Node nextChild = child.getNext();
child.parent = null;
child.next = null;
child = nextChild;
}
first = null;
last = null;
}
public Node removeChildAfter(Node prev) {
Preconditions.checkArgument(prev.parent == this,
"prev is not a child of this node.");
Preconditions.checkArgument(prev.next != null,
"no next sibling.");
Node child = prev.next;
prev.next = child.next;
if (child == last) last = prev;
child.next = null;
child.parent = null;
return child;
}
/**
* @return A detached clone of the Node, specifically excluding its children.
*/
public Node cloneNode() {
Node result;
try {
result = (Node) super.clone();
// PropListItem lists are immutable and can be shared so there is no
// need to clone them here.
result.next = null;
result.first = null;
result.last = null;
result.parent = null;
} catch (CloneNotSupportedException e) {
throw new RuntimeException(e.getMessage());
}
return result;
}
/**
* @return A detached clone of the Node and all its children.
*/
public Node cloneTree() {
Node result = cloneNode();
for (Node n2 = getFirstChild(); n2 != null; n2 = n2.getNext()) {
Node n2clone = n2.cloneTree();
n2clone.parent = result;
if (result.last != null) {
result.last.next = n2clone;
}
if (result.first == null) {
result.first = n2clone;
}
result.last = n2clone;
}
return result;
}
/**
* Copies source file and name information from the other
* node given to the current node. Used for maintaining
* debug information across node append and remove operations.
* @return this
*/
// TODO(nicksantos): The semantics of this method are ill-defined. Delete it.
public Node copyInformationFrom(Node other) {
if (getProp(ORIGINALNAME_PROP) == null) {
putProp(ORIGINALNAME_PROP, other.getProp(ORIGINALNAME_PROP));
}
if (getProp(STATIC_SOURCE_FILE) == null) {
putProp(STATIC_SOURCE_FILE, other.getProp(STATIC_SOURCE_FILE));
sourcePosition = other.sourcePosition;
} else if (getProp(SOURCENAME_PROP) == null) {
putProp(SOURCENAME_PROP, other.getProp(SOURCENAME_PROP));
sourcePosition = other.sourcePosition;
}
return this;
}
/**
* Copies source file and name information from the other node to the
* entire tree rooted at this node.
* @return this
*/
// TODO(nicksantos): The semantics of this method are ill-defined. Delete it.
public Node copyInformationFromForTree(Node other) {
copyInformationFrom(other);
for (Node child = getFirstChild();
child != null; child = child.getNext()) {
child.copyInformationFromForTree(other);
}
return this;
}
/**
* Overwrite all the source information in this node with
* that of {@code other}.
*/
public Node useSourceInfoFrom(Node other) {
putProp(ORIGINALNAME_PROP, other.getProp(ORIGINALNAME_PROP));
putProp(STATIC_SOURCE_FILE, other.getProp(STATIC_SOURCE_FILE));
sourcePosition = other.sourcePosition;
return this;
}
public Node srcref(Node other) {
return useSourceInfoFrom(other);
}
/**
* Overwrite all the source information in this node and its subtree with
* that of {@code other}.
*/
public Node useSourceInfoFromForTree(Node other) {
useSourceInfoFrom(other);
for (Node child = getFirstChild();
child != null; child = child.getNext()) {
child.useSourceInfoFromForTree(other);
}
return this;
}
public Node srcrefTree(Node other) {
return useSourceInfoFromForTree(other);
}
/**
* Overwrite all the source information in this node with
* that of {@code other} iff the source info is missing.
*/
public Node useSourceInfoIfMissingFrom(Node other) {
if (getProp(ORIGINALNAME_PROP) == null) {
putProp(ORIGINALNAME_PROP, other.getProp(ORIGINALNAME_PROP));
}
if (getProp(STATIC_SOURCE_FILE) == null) {
putProp(STATIC_SOURCE_FILE, other.getProp(STATIC_SOURCE_FILE));
sourcePosition = other.sourcePosition;
}
return this;
}
/**
* Overwrite all the source information in this node and its subtree with
* that of {@code other} iff the source info is missing.
*/
public Node useSourceInfoIfMissingFromForTree(Node other) {
useSourceInfoIfMissingFrom(other);
for (Node child = getFirstChild();
child != null; child = child.getNext()) {
child.useSourceInfoIfMissingFromForTree(other);
}
return this;
}
//==========================================================================
// Custom annotations
public JSType getJSType() {
return jsType;
}
public void setJSType(JSType jsType) {
this.jsType = jsType;
}
public FileLevelJsDocBuilder getJsDocBuilderForNode() {
return new FileLevelJsDocBuilder();
}
/**
* An inner class that provides back-door access to the license
* property of the JSDocInfo property for this node. This is only
* meant to be used for top level script nodes where the
* {@link com.google.javascript.jscomp.parsing.JsDocInfoParser} needs to
* be able to append directly to the top level node, not just the
* current node.
*/
public class FileLevelJsDocBuilder {
public void append(String fileLevelComment) {
JSDocInfo jsDocInfo = getJSDocInfo();
if (jsDocInfo == null) {
// TODO(user): Is there a way to determine whether to
// parse the JsDoc documentation from here?
jsDocInfo = new JSDocInfo(false);
}
String license = jsDocInfo.getLicense();
if (license == null) {
license = "";
}
jsDocInfo.setLicense(license + fileLevelComment);
setJSDocInfo(jsDocInfo);
}
}
/**
* Get the {@link JSDocInfo} attached to this node.
* @return the information or {@code null} if no JSDoc is attached to this
* node
*/
public JSDocInfo getJSDocInfo() {
return (JSDocInfo) getProp(JSDOC_INFO_PROP);
}
/**
* Sets the {@link JSDocInfo} attached to this node.
*/
public void setJSDocInfo(JSDocInfo info) {
putProp(JSDOC_INFO_PROP, info);
}
/**
* Sets whether this node is a variable length argument node. This
* method is meaningful only on {@link Token#NAME} nodes
* used to define a {@link Token#FUNCTION}'s argument list.
*/
public void setVarArgs(boolean varArgs) {
putBooleanProp(VAR_ARGS_NAME, varArgs);
}
/**
* Returns whether this node is a variable length argument node. This
* method's return value is meaningful only on {@link Token#NAME} nodes
* used to define a {@link Token#FUNCTION}'s argument list.
*/
public boolean isVarArgs() {
return getBooleanProp(VAR_ARGS_NAME);
}
/**
* Sets whether this node is an optional argument node. This
* method is meaningful only on {@link Token#NAME} nodes
* used to define a {@link Token#FUNCTION}'s argument list.
*/
public void setOptionalArg(boolean optionalArg) {
putBooleanProp(OPT_ARG_NAME, optionalArg);
}
/**
* Returns whether this node is an optional argument node. This
* method's return value is meaningful only on {@link Token#NAME} nodes
* used to define a {@link Token#FUNCTION}'s argument list.
*/
public boolean isOptionalArg() {
return getBooleanProp(OPT_ARG_NAME);
}
/**
* Sets whether this is a synthetic block that should not be considered
* a real source block.
*/
public void setIsSyntheticBlock(boolean val) {
putBooleanProp(SYNTHETIC_BLOCK_PROP, val);
}
/**
* Returns whether this is a synthetic block that should not be considered
* a real source block.
*/
public boolean isSyntheticBlock() {
return getBooleanProp(SYNTHETIC_BLOCK_PROP);
}
/**
* Sets the ES5 directives on this node.
*/
public void setDirectives(Set<String> val) {
putProp(DIRECTIVES, val);
}
/**
* Returns the set of ES5 directives for this node.
*/
@SuppressWarnings("unchecked")
public Set<String> getDirectives() {
return (Set<String>) getProp(DIRECTIVES);
}
/**
* Adds a warning to be suppressed. This is indistinguishable
* from having a {@code @suppress} tag in the code.
*/
public void addSuppression(String warning) {
if (getJSDocInfo() == null) {
setJSDocInfo(new JSDocInfo(false));
}
getJSDocInfo().addSuppression(warning);
}
/**
* Sets whether this is a synthetic block that should not be considered
* a real source block.
*/
public void setWasEmptyNode(boolean val) {
putBooleanProp(EMPTY_BLOCK, val);
}
/**
* Returns whether this is a synthetic block that should not be considered
* a real source block.
*/
public boolean wasEmptyNode() {
return getBooleanProp(EMPTY_BLOCK);
}
// There are four values of interest:
// global state changes
// this state changes
// arguments state changes
// whether the call throws an exception
// locality of the result
// We want a value of 0 to mean "global state changes and
// unknown locality of result".
final public static int FLAG_GLOBAL_STATE_UNMODIFIED = 1;
final public static int FLAG_THIS_UNMODIFIED = 2;
final public static int FLAG_ARGUMENTS_UNMODIFIED = 4;
final public static int FLAG_NO_THROWS = 8;
final public static int FLAG_LOCAL_RESULTS = 16;
final public static int SIDE_EFFECTS_FLAGS_MASK = 31;
final public static int SIDE_EFFECTS_ALL = 0;
final public static int NO_SIDE_EFFECTS =
FLAG_GLOBAL_STATE_UNMODIFIED
| FLAG_THIS_UNMODIFIED
| FLAG_ARGUMENTS_UNMODIFIED
| FLAG_NO_THROWS;
/**
* Marks this function or constructor call's side effect flags.
* This property is only meaningful for {@link Token#CALL} and
* {@link Token#NEW} nodes.
*/
public void setSideEffectFlags(int flags) {
Preconditions.checkArgument(
getType() == Token.CALL || getType() == Token.NEW,
"setIsNoSideEffectsCall only supports CALL and NEW nodes, got " +
Token.name(getType()));
putIntProp(SIDE_EFFECT_FLAGS, flags);
}
public void setSideEffectFlags(SideEffectFlags flags) {
setSideEffectFlags(flags.valueOf());
}
/**
* Returns the side effects flags for this node.
*/
public int getSideEffectFlags() {
return getIntProp(SIDE_EFFECT_FLAGS);
}
/**
* A helper class for getting and setting the side-effect flags.
* @author [email protected] (John Lenz)
*/
public static class SideEffectFlags {
private int value = Node.SIDE_EFFECTS_ALL;
public SideEffectFlags() {
}
public SideEffectFlags(int value) {
this.value = value;
}
public int valueOf() {
return value;
}
/** All side-effect occur and the returned results are non-local. */
public void setAllFlags() {
value = Node.SIDE_EFFECTS_ALL;
}
/** No side-effects occur and the returned results are local. */
public void clearAllFlags() {
value = Node.NO_SIDE_EFFECTS | Node.FLAG_LOCAL_RESULTS;
}
public boolean areAllFlagsSet() {
return value == Node.SIDE_EFFECTS_ALL;
}
/**
* Preserve the return result flag, but clear the others:
* no global state change, no throws, no this change, no arguments change
*/
public void clearSideEffectFlags() {
value |= Node.NO_SIDE_EFFECTS;
}
public void setMutatesGlobalState() {
// Modify global means everything must be assumed to be modified.
removeFlag(Node.FLAG_GLOBAL_STATE_UNMODIFIED);
removeFlag(Node.FLAG_ARGUMENTS_UNMODIFIED);
removeFlag(Node.FLAG_THIS_UNMODIFIED);
}
public void setThrows() {
removeFlag(Node.FLAG_NO_THROWS);
}
public void setMutatesThis() {
removeFlag(Node.FLAG_THIS_UNMODIFIED);
}
public void setMutatesArguments() {
removeFlag(Node.FLAG_ARGUMENTS_UNMODIFIED);
}
public void setReturnsTainted() {
removeFlag(Node.FLAG_LOCAL_RESULTS);
}
private void removeFlag(int flag) {
value &= ~flag;
}
}
/**
* @return Whether the only side-effect is "modifies this"
*/
public boolean isOnlyModifiesThisCall() {
return areBitFlagsSet(
getSideEffectFlags() & Node.NO_SIDE_EFFECTS,
Node.FLAG_GLOBAL_STATE_UNMODIFIED
| Node.FLAG_ARGUMENTS_UNMODIFIED
| Node.FLAG_NO_THROWS);
}
/**
* Returns true if this node is a function or constructor call that
* has no side effects.
*/
public boolean isNoSideEffectsCall() {
return areBitFlagsSet(getSideEffectFlags(), NO_SIDE_EFFECTS);
}
/**
* Returns true if this node is a function or constructor call that
* returns a primitive or a local object (an object that has no other
* references).
*/
public boolean isLocalResultCall() {
return areBitFlagsSet(getSideEffectFlags(), FLAG_LOCAL_RESULTS);
}
/**
* returns true if all the flags are set in value.
*/
private boolean areBitFlagsSet(int value, int flags) {
return (value & flags) == flags;
}
/**
* This should only be called for STRING nodes children of OBJECTLIT.
*/
public boolean isQuotedString() {
return false;
}
/**
* This should only be called for STRING nodes children of OBJECTLIT.
*/
public void setQuotedString() {
throw new IllegalStateException("not a StringNode");
}
static class NodeMismatch {
final Node nodeA;
final Node nodeB;
NodeMismatch(Node nodeA, Node nodeB) {
this.nodeA = nodeA;
this.nodeB = nodeB;
}
@Override
public boolean equals(Object object) {
if (object instanceof NodeMismatch) {
NodeMismatch that = (NodeMismatch) object;
return that.nodeA.equals(this.nodeA) && that.nodeB.equals(this.nodeB);
}
return false;
}
@Override
public int hashCode() {
return Objects.hashCode(nodeA, nodeB);
}
}
/*** AST type check methods ***/
public boolean isAdd() {
return this.getType() == Token.ADD;
}
public boolean isAnd() {
return this.getType() == Token.AND;
}
public boolean isArrayLit() {
return this.getType() == Token.ARRAYLIT;
}
public boolean isAssign() {
return this.getType() == Token.ASSIGN;
}
public boolean isAssignAdd() {
return this.getType() == Token.ASSIGN_ADD;
}
public boolean isBlock() {
return this.getType() == Token.BLOCK;
}
public boolean isBreak() {
return this.getType() == Token.BREAK;
}
public boolean isCall() {
return this.getType() == Token.CALL;
}
public boolean isCase() {
return this.getType() == Token.CASE;
}
public boolean isCatch() {
return this.getType() == Token.CATCH;
}
public boolean isComma() {
return this.getType() == Token.COMMA;
}
public boolean isContinue() {
return this.getType() == Token.CONTINUE;
}
public boolean isDebugger() {
return this.getType() == Token.DEBUGGER;
}
public boolean isDec() {
return this.getType() == Token.DEC;
}
public boolean isDefaultCase() {
return this.getType() == Token.DEFAULT_CASE;
}
public boolean isDelProp() {
return this.getType() == Token.DELPROP;
}
public boolean isDo() {
return this.getType() == Token.DO;
}
public boolean isEmpty() {
return this.getType() == Token.EMPTY;
}
public boolean isExprResult() {
return this.getType() == Token.EXPR_RESULT;
}
public boolean isFalse() {
return this.getType() == Token.FALSE;
}
public boolean isFor() {
return this.getType() == Token.FOR;
}
public boolean isFunction() {
return this.getType() == Token.FUNCTION;
}
public boolean isGetterDef() {
return this.getType() == Token.GETTER_DEF;
}
public boolean isGetElem() {
return this.getType() == Token.GETELEM;
}
public boolean isGetProp() {
return this.getType() == Token.GETPROP;
}
public boolean isHook() {
return this.getType() == Token.HOOK;
}
public boolean isIf() {
return this.getType() == Token.IF;
}
public boolean isIn() {
return this.getType() == Token.IN;
}
public boolean isInc() {
return this.getType() == Token.INC;
}
public boolean isInstanceOf() {
return this.getType() == Token.INSTANCEOF;
}
public boolean isLabel() {
return this.getType() == Token.LABEL;
}
public boolean isLabelName() {
return this.getType() == Token.LABEL_NAME;
}
public boolean isName() {
return this.getType() == Token.NAME;
}
public boolean isNE() {
return this.getType() == Token.NE;
}
public boolean isNew() {
return this.getType() == Token.NEW;
}
public boolean isNot() {
return this.getType() == Token.NOT;
}
public boolean isNull() {
return this.getType() == Token.NULL;
}
public boolean isNumber() {
return this.getType() == Token.NUMBER;
}
public boolean isObjectLit() {
return this.getType() == Token.OBJECTLIT;
}
public boolean isOr() {
return this.getType() == Token.OR;
}
public boolean isParamList() {
return this.getType() == Token.PARAM_LIST;
}
public boolean isRegExp() {
return this.getType() == Token.REGEXP;
}
public boolean isReturn() {
return this.getType() == Token.RETURN;
}
public boolean isScript() {
return this.getType() == Token.SCRIPT;
}
public boolean isSetterDef() {
return this.getType() == Token.SETTER_DEF;
}
public boolean isString() {
return this.getType() == Token.STRING;
}
public boolean isSwitch() {
return this.getType() == Token.SWITCH;
}
public boolean isThis() {
return this.getType() == Token.THIS;
}
public boolean isThrow() {
return this.getType() == Token.THROW;
}
public boolean isTrue() {
return this.getType() == Token.TRUE;
}
public boolean isTry() {
return this.getType() == Token.TRY;
}
public boolean isTypeOf() {
return this.getType() == Token.TYPEOF;
}
public boolean isVar() {
return this.getType() == Token.VAR;
}
public boolean isVoid() {
return this.getType() == Token.VOID;
}
public boolean isWhile() {
return this.getType() == Token.WHILE;
}
public boolean isWith() {
return this.getType() == Token.WITH;
}
}
diff --git a/closure/closure-compiler/test/com/google/javascript/jscomp/IntegrationTest.java b/closure/closure-compiler/test/com/google/javascript/jscomp/IntegrationTest.java
index da89a21ec..33a446226 100644
--- a/closure/closure-compiler/test/com/google/javascript/jscomp/IntegrationTest.java
+++ b/closure/closure-compiler/test/com/google/javascript/jscomp/IntegrationTest.java
@@ -1,2049 +1,2061 @@
/*
* Copyright 2009 The Closure Compiler Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.javascript.jscomp;
import com.google.common.base.Joiner;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Sets;
import com.google.javascript.jscomp.CompilerOptions.LanguageMode;
import com.google.javascript.rhino.Node;
import com.google.javascript.rhino.Token;
import junit.framework.TestCase;
/**
* Tests for {@link PassFactory}.
*
* @author [email protected] (Nick Santos)
*/
public class IntegrationTest extends TestCase {
/** Externs for the test */
private final JSSourceFile[] DEFAULT_EXTERNS = new JSSourceFile[] {
JSSourceFile.fromCode("externs",
"var arguments;\n"
+ "/** @constructor */ function Window() {}\n"
+ "/** @type {string} */ Window.prototype.name;\n"
+ "/** @type {string} */ Window.prototype.offsetWidth;\n"
+ "/** @type {Window} */ var window;\n"
+ "/** @nosideeffects */ function noSideEffects() {}\n"
+ "/** @constructor\n * @nosideeffects */ function Widget() {}\n"
+ "/** @modifies {this} */ Widget.prototype.go = function() {};\n"
+ "/** @return {string} */ var widgetToken = function() {};\n")
};
private JSSourceFile[] externs = DEFAULT_EXTERNS;
private static final String CLOSURE_BOILERPLATE =
"/** @define {boolean} */ var COMPILED = false; var goog = {};" +
"goog.exportSymbol = function() {};";
private static final String CLOSURE_COMPILED =
"var COMPILED = true; var goog$exportSymbol = function() {};";
// The most recently used compiler.
private Compiler lastCompiler;
@Override
public void setUp() {
externs = DEFAULT_EXTERNS;
lastCompiler = null;
}
public void testBug1949424() {
CompilerOptions options = createCompilerOptions();
options.collapseProperties = true;
options.closurePass = true;
test(options, CLOSURE_BOILERPLATE + "goog.provide('FOO'); FOO.bar = 3;",
CLOSURE_COMPILED + "var FOO$bar = 3;");
}
public void testBug1949424_v2() {
CompilerOptions options = createCompilerOptions();
options.collapseProperties = true;
options.closurePass = true;
test(options, CLOSURE_BOILERPLATE + "goog.provide('FOO.BAR'); FOO.BAR = 3;",
CLOSURE_COMPILED + "var FOO$BAR = 3;");
}
public void testBug1956277() {
CompilerOptions options = createCompilerOptions();
options.collapseProperties = true;
options.inlineVariables = true;
test(options, "var CONST = {}; CONST.bar = null;" +
"function f(url) { CONST.bar = url; }",
"var CONST$bar = null; function f(url) { CONST$bar = url; }");
}
public void testBug1962380() {
CompilerOptions options = createCompilerOptions();
options.collapseProperties = true;
options.inlineVariables = true;
options.generateExports = true;
test(options,
CLOSURE_BOILERPLATE + "/** @export */ goog.CONSTANT = 1;" +
"var x = goog.CONSTANT;",
"(function() {})('goog.CONSTANT', 1);" +
"var x = 1;");
}
public void testBug2410122() {
CompilerOptions options = createCompilerOptions();
options.generateExports = true;
options.closurePass = true;
test(options,
"var goog = {};" +
"function F() {}" +
"/** @export */ function G() { goog.base(this); } " +
"goog.inherits(G, F);",
"var goog = {};" +
"function F() {}" +
"function G() { F.call(this); } " +
"goog.inherits(G, F); goog.exportSymbol('G', G);");
}
public void testIssue90() {
CompilerOptions options = createCompilerOptions();
options.foldConstants = true;
options.inlineVariables = true;
options.removeDeadCode = true;
test(options,
"var x; x && alert(1);",
"");
}
public void testClosurePassOff() {
CompilerOptions options = createCompilerOptions();
options.closurePass = false;
testSame(
options,
"var goog = {}; goog.require = function(x) {}; goog.require('foo');");
testSame(
options,
"var goog = {}; goog.getCssName = function(x) {};" +
"goog.getCssName('foo');");
}
public void testClosurePassOn() {
CompilerOptions options = createCompilerOptions();
options.closurePass = true;
test(
options,
"var goog = {}; goog.require = function(x) {}; goog.require('foo');",
ProcessClosurePrimitives.MISSING_PROVIDE_ERROR);
test(
options,
"/** @define {boolean} */ var COMPILED = false;" +
"var goog = {}; goog.getCssName = function(x) {};" +
"goog.getCssName('foo');",
"var COMPILED = true;" +
"var goog = {}; goog.getCssName = function(x) {};" +
"'foo';");
}
public void testCssNameCheck() {
CompilerOptions options = createCompilerOptions();
options.closurePass = true;
options.checkMissingGetCssNameLevel = CheckLevel.ERROR;
options.checkMissingGetCssNameBlacklist = "foo";
test(options, "var x = 'foo';",
CheckMissingGetCssName.MISSING_GETCSSNAME);
}
public void testBug2592659() {
CompilerOptions options = createCompilerOptions();
options.closurePass = true;
options.checkTypes = true;
options.checkMissingGetCssNameLevel = CheckLevel.WARNING;
options.checkMissingGetCssNameBlacklist = "foo";
test(options,
"var goog = {};\n" +
"/**\n" +
" * @param {string} className\n" +
" * @param {string=} opt_modifier\n" +
" * @return {string}\n" +
"*/\n" +
"goog.getCssName = function(className, opt_modifier) {}\n" +
"var x = goog.getCssName(123, 'a');",
TypeValidator.TYPE_MISMATCH_WARNING);
}
public void testTypedefBeforeOwner1() {
CompilerOptions options = createCompilerOptions();
options.closurePass = true;
test(options,
"goog.provide('foo.Bar.Type');\n" +
"goog.provide('foo.Bar');\n" +
"/** @typedef {number} */ foo.Bar.Type;\n" +
"foo.Bar = function() {};",
"var foo = {}; foo.Bar.Type; foo.Bar = function() {};");
}
public void testTypedefBeforeOwner2() {
CompilerOptions options = createCompilerOptions();
options.closurePass = true;
options.collapseProperties = true;
test(options,
"goog.provide('foo.Bar.Type');\n" +
"goog.provide('foo.Bar');\n" +
"/** @typedef {number} */ foo.Bar.Type;\n" +
"foo.Bar = function() {};",
"var foo$Bar$Type; var foo$Bar = function() {};");
}
public void testExportedNames() {
CompilerOptions options = createCompilerOptions();
options.closurePass = true;
options.variableRenaming = VariableRenamingPolicy.ALL;
test(options,
"/** @define {boolean} */ var COMPILED = false;" +
"var goog = {}; goog.exportSymbol('b', goog);",
"var a = true; var c = {}; c.exportSymbol('b', c);");
test(options,
"/** @define {boolean} */ var COMPILED = false;" +
"var goog = {}; goog.exportSymbol('a', goog);",
"var b = true; var c = {}; c.exportSymbol('a', c);");
}
public void testCheckGlobalThisOn() {
CompilerOptions options = createCompilerOptions();
options.checkSuspiciousCode = true;
options.checkGlobalThisLevel = CheckLevel.ERROR;
test(options, "function f() { this.y = 3; }", CheckGlobalThis.GLOBAL_THIS);
}
public void testSusiciousCodeOff() {
CompilerOptions options = createCompilerOptions();
options.checkSuspiciousCode = false;
options.checkGlobalThisLevel = CheckLevel.ERROR;
test(options, "function f() { this.y = 3; }", CheckGlobalThis.GLOBAL_THIS);
}
public void testCheckGlobalThisOff() {
CompilerOptions options = createCompilerOptions();
options.checkSuspiciousCode = true;
options.checkGlobalThisLevel = CheckLevel.OFF;
testSame(options, "function f() { this.y = 3; }");
}
public void testCheckRequiresAndCheckProvidesOff() {
testSame(createCompilerOptions(), new String[] {
"/** @constructor */ function Foo() {}",
"new Foo();"
});
}
public void testCheckRequiresOn() {
CompilerOptions options = createCompilerOptions();
options.checkRequires = CheckLevel.ERROR;
test(options, new String[] {
"/** @constructor */ function Foo() {}",
"new Foo();"
}, CheckRequiresForConstructors.MISSING_REQUIRE_WARNING);
}
public void testCheckProvidesOn() {
CompilerOptions options = createCompilerOptions();
options.checkProvides = CheckLevel.ERROR;
test(options, new String[] {
"/** @constructor */ function Foo() {}",
"new Foo();"
}, CheckProvides.MISSING_PROVIDE_WARNING);
}
public void testGenerateExportsOff() {
testSame(createCompilerOptions(), "/** @export */ function f() {}");
}
public void testGenerateExportsOn() {
CompilerOptions options = createCompilerOptions();
options.generateExports = true;
test(options, "/** @export */ function f() {}",
"/** @export */ function f() {} goog.exportSymbol('f', f);");
}
public void testExportTestFunctionsOff() {
testSame(createCompilerOptions(), "function testFoo() {}");
}
public void testExportTestFunctionsOn() {
CompilerOptions options = createCompilerOptions();
options.exportTestFunctions = true;
test(options, "function testFoo() {}",
"/** @export */ function testFoo() {}" +
"goog.exportSymbol('testFoo', testFoo);");
}
public void testCheckSymbolsOff() {
CompilerOptions options = createCompilerOptions();
testSame(options, "x = 3;");
}
public void testCheckSymbolsOn() {
CompilerOptions options = createCompilerOptions();
options.checkSymbols = true;
test(options, "x = 3;", VarCheck.UNDEFINED_VAR_ERROR);
}
public void testCheckReferencesOff() {
CompilerOptions options = createCompilerOptions();
testSame(options, "x = 3; var x = 5;");
}
public void testCheckReferencesOn() {
CompilerOptions options = createCompilerOptions();
options.aggressiveVarCheck = CheckLevel.ERROR;
test(options, "x = 3; var x = 5;",
VariableReferenceCheck.UNDECLARED_REFERENCE);
}
public void testInferTypes() {
CompilerOptions options = createCompilerOptions();
options.inferTypes = true;
options.checkTypes = false;
options.closurePass = true;
test(options,
CLOSURE_BOILERPLATE +
"goog.provide('Foo'); /** @enum */ Foo = {a: 3};",
TypeCheck.ENUM_NOT_CONSTANT);
assertTrue(lastCompiler.getErrorManager().getTypedPercent() == 0);
// This does not generate a warning.
test(options, "/** @type {number} */ var n = window.name;",
"var n = window.name;");
assertTrue(lastCompiler.getErrorManager().getTypedPercent() == 0);
}
public void testTypeCheckAndInference() {
CompilerOptions options = createCompilerOptions();
options.checkTypes = true;
test(options, "/** @type {number} */ var n = window.name;",
TypeValidator.TYPE_MISMATCH_WARNING);
assertTrue(lastCompiler.getErrorManager().getTypedPercent() > 0);
}
public void testTypeNameParser() {
CompilerOptions options = createCompilerOptions();
options.checkTypes = true;
test(options, "/** @type {n} */ var n = window.name;",
RhinoErrorReporter.TYPE_PARSE_ERROR);
}
// This tests that the TypedScopeCreator is memoized so that it only creates a
// Scope object once for each scope. If, when type inference requests a scope,
// it creates a new one, then multiple JSType objects end up getting created
// for the same local type, and ambiguate will rename the last statement to
// o.a(o.a, o.a), which is bad.
public void testMemoizedTypedScopeCreator() {
CompilerOptions options = createCompilerOptions();
options.checkTypes = true;
options.ambiguateProperties = true;
options.propertyRenaming = PropertyRenamingPolicy.ALL_UNQUOTED;
test(options, "function someTest() {\n"
+ " /** @constructor */\n"
+ " function Foo() { this.instProp = 3; }\n"
+ " Foo.prototype.protoProp = function(a, b) {};\n"
+ " /** @constructor\n @extends Foo */\n"
+ " function Bar() {}\n"
+ " goog.inherits(Bar, Foo);\n"
+ " var o = new Bar();\n"
+ " o.protoProp(o.protoProp, o.instProp);\n"
+ "}",
"function someTest() {\n"
+ " function Foo() { this.b = 3; }\n"
+ " Foo.prototype.a = function(a, b) {};\n"
+ " function Bar() {}\n"
+ " goog.c(Bar, Foo);\n"
+ " var o = new Bar();\n"
+ " o.a(o.a, o.b);\n"
+ "}");
}
public void testCheckTypes() {
CompilerOptions options = createCompilerOptions();
options.checkTypes = true;
test(options, "var x = x || {}; x.f = function() {}; x.f(3);",
TypeCheck.WRONG_ARGUMENT_COUNT);
}
public void testReplaceCssNames() {
CompilerOptions options = createCompilerOptions();
options.closurePass = true;
options.gatherCssNames = true;
test(options, "/** @define {boolean} */\n"
+ "var COMPILED = false;\n"
+ "goog.setCssNameMapping({'foo':'bar'});\n"
+ "function getCss() {\n"
+ " return goog.getCssName('foo');\n"
+ "}",
"var COMPILED = true;\n"
+ "function getCss() {\n"
+ " return \"bar\";"
+ "}");
assertEquals(
ImmutableMap.of("foo", new Integer(1)),
lastCompiler.getPassConfig().getIntermediateState().cssNames);
}
public void testRemoveClosureAsserts() {
CompilerOptions options = createCompilerOptions();
options.closurePass = true;
testSame(options,
"var goog = {};"
+ "goog.asserts.assert(goog);");
options.removeClosureAsserts = true;
test(options,
"var goog = {};"
+ "goog.asserts.assert(goog);",
"var goog = {};");
}
public void testDeprecation() {
String code = "/** @deprecated */ function f() { } function g() { f(); }";
CompilerOptions options = createCompilerOptions();
testSame(options, code);
options.setWarningLevel(DiagnosticGroups.DEPRECATED, CheckLevel.ERROR);
testSame(options, code);
options.checkTypes = true;
test(options, code, CheckAccessControls.DEPRECATED_NAME);
}
public void testVisibility() {
String[] code = {
"/** @private */ function f() { }",
"function g() { f(); }"
};
CompilerOptions options = createCompilerOptions();
testSame(options, code);
options.setWarningLevel(DiagnosticGroups.VISIBILITY, CheckLevel.ERROR);
testSame(options, code);
options.checkTypes = true;
test(options, code, CheckAccessControls.BAD_PRIVATE_GLOBAL_ACCESS);
}
public void testUnreachableCode() {
String code = "function f() { return \n 3; }";
CompilerOptions options = createCompilerOptions();
testSame(options, code);
options.checkUnreachableCode = CheckLevel.ERROR;
test(options, code, CheckUnreachableCode.UNREACHABLE_CODE);
}
public void testMissingReturn() {
String code =
"/** @return {number} */ function f() { if (f) { return 3; } }";
CompilerOptions options = createCompilerOptions();
testSame(options, code);
options.checkMissingReturn = CheckLevel.ERROR;
testSame(options, code);
options.checkTypes = true;
test(options, code, CheckMissingReturn.MISSING_RETURN_STATEMENT);
}
public void testIdGenerators() {
String code = "function f() {} f('id');";
CompilerOptions options = createCompilerOptions();
testSame(options, code);
options.idGenerators = Sets.newHashSet("f");
test(options, code, "function f() {} 'a';");
}
public void testOptimizeArgumentsArray() {
String code = "function f() { return arguments[0]; }";
CompilerOptions options = createCompilerOptions();
testSame(options, code);
options.optimizeArgumentsArray = true;
String argName = "JSCompiler_OptimizeArgumentsArray_p0";
test(options, code,
"function f(" + argName + ") { return " + argName + "; }");
}
public void testOptimizeParameters() {
String code = "function f(a) { return a; } f(true);";
CompilerOptions options = createCompilerOptions();
testSame(options, code);
options.optimizeParameters = true;
test(options, code, "function f() { var a = true; return a;} f();");
}
public void testOptimizeReturns() {
String code = "function f(a) { return a; } f(true);";
CompilerOptions options = createCompilerOptions();
testSame(options, code);
options.optimizeReturns = true;
test(options, code, "function f(a) {return;} f(true);");
}
public void testRemoveAbstractMethods() {
String code = CLOSURE_BOILERPLATE +
"var x = {}; x.foo = goog.abstractMethod; x.bar = 3;";
CompilerOptions options = createCompilerOptions();
testSame(options, code);
options.closurePass = true;
options.collapseProperties = true;
test(options, code, CLOSURE_COMPILED + " var x$bar = 3;");
}
public void testCollapseProperties1() {
String code =
"var x = {}; x.FOO = 5; x.bar = 3;";
CompilerOptions options = createCompilerOptions();
testSame(options, code);
options.collapseProperties = true;
test(options, code, "var x$FOO = 5; var x$bar = 3;");
}
public void testCollapseProperties2() {
String code =
"var x = {}; x.FOO = 5; x.bar = 3;";
CompilerOptions options = createCompilerOptions();
testSame(options, code);
options.collapseProperties = true;
options.collapseObjectLiterals = true;
test(options, code, "var x$FOO = 5; var x$bar = 3;");
}
public void testCollapseObjectLiteral1() {
// Verify collapseObjectLiterals does nothing in global scope
String code = "var x = {}; x.FOO = 5; x.bar = 3;";
CompilerOptions options = createCompilerOptions();
testSame(options, code);
options.collapseObjectLiterals = true;
testSame(options, code);
}
public void testCollapseObjectLiteral2() {
String code =
"function f() {var x = {}; x.FOO = 5; x.bar = 3;}";
CompilerOptions options = createCompilerOptions();
testSame(options, code);
options.collapseObjectLiterals = true;
test(options, code,
"function f(){" +
"var JSCompiler_object_inline_FOO_0;" +
"var JSCompiler_object_inline_bar_1;" +
"JSCompiler_object_inline_FOO_0=5;" +
"JSCompiler_object_inline_bar_1=3}");
}
public void testTightenTypesWithoutTypeCheck() {
CompilerOptions options = createCompilerOptions();
options.tightenTypes = true;
test(options, "", DefaultPassConfig.TIGHTEN_TYPES_WITHOUT_TYPE_CHECK);
}
public void testDisambiguateProperties() {
String code =
"/** @constructor */ function Foo(){} Foo.prototype.bar = 3;" +
"/** @constructor */ function Baz(){} Baz.prototype.bar = 3;";
CompilerOptions options = createCompilerOptions();
testSame(options, code);
options.disambiguateProperties = true;
options.checkTypes = true;
test(options, code,
"function Foo(){} Foo.prototype.Foo_prototype$bar = 3;" +
"function Baz(){} Baz.prototype.Baz_prototype$bar = 3;");
}
public void testMarkPureCalls() {
String testCode = "function foo() {} foo();";
CompilerOptions options = createCompilerOptions();
options.removeDeadCode = true;
testSame(options, testCode);
options.computeFunctionSideEffects = true;
test(options, testCode, "function foo() {}");
}
public void testMarkNoSideEffects() {
String testCode = "noSideEffects();";
CompilerOptions options = createCompilerOptions();
options.removeDeadCode = true;
testSame(options, testCode);
options.markNoSideEffectCalls = true;
test(options, testCode, "");
}
public void testChainedCalls() {
CompilerOptions options = createCompilerOptions();
options.chainCalls = true;
test(
options,
"/** @constructor */ function Foo() {} " +
"Foo.prototype.bar = function() { return this; }; " +
"var f = new Foo();" +
"f.bar(); " +
"f.bar(); ",
"function Foo() {} " +
"Foo.prototype.bar = function() { return this; }; " +
"var f = new Foo();" +
"f.bar().bar();");
}
public void testExtraAnnotationNames() {
CompilerOptions options = createCompilerOptions();
options.setExtraAnnotationNames(Sets.newHashSet("TagA", "TagB"));
test(
options,
"/** @TagA */ var f = new Foo(); /** @TagB */ f.bar();",
"var f = new Foo(); f.bar();");
}
public void testDevirtualizePrototypeMethods() {
CompilerOptions options = createCompilerOptions();
options.devirtualizePrototypeMethods = true;
test(
options,
"/** @constructor */ var Foo = function() {}; " +
"Foo.prototype.bar = function() {};" +
"(new Foo()).bar();",
"var Foo = function() {};" +
"var JSCompiler_StaticMethods_bar = " +
" function(JSCompiler_StaticMethods_bar$self) {};" +
"JSCompiler_StaticMethods_bar(new Foo());");
}
public void testCheckConsts() {
CompilerOptions options = createCompilerOptions();
options.inlineConstantVars = true;
test(options, "var FOO = true; FOO = false",
ConstCheck.CONST_REASSIGNED_VALUE_ERROR);
}
public void testAllChecksOn() {
CompilerOptions options = createCompilerOptions();
options.checkSuspiciousCode = true;
options.checkControlStructures = true;
options.checkRequires = CheckLevel.ERROR;
options.checkProvides = CheckLevel.ERROR;
options.generateExports = true;
options.exportTestFunctions = true;
options.closurePass = true;
options.checkMissingGetCssNameLevel = CheckLevel.ERROR;
options.checkMissingGetCssNameBlacklist = "goog";
options.syntheticBlockStartMarker = "synStart";
options.syntheticBlockEndMarker = "synEnd";
options.checkSymbols = true;
options.aggressiveVarCheck = CheckLevel.ERROR;
options.processObjectPropertyString = true;
options.collapseProperties = true;
test(options, CLOSURE_BOILERPLATE, CLOSURE_COMPILED);
}
public void testTypeCheckingWithSyntheticBlocks() {
CompilerOptions options = createCompilerOptions();
options.syntheticBlockStartMarker = "synStart";
options.syntheticBlockEndMarker = "synEnd";
options.checkTypes = true;
// We used to have a bug where the CFG drew an
// edge straight from synStart to f(progress).
// If that happens, then progress will get type {number|undefined}.
testSame(
options,
"/** @param {number} x */ function f(x) {}" +
"function g() {" +
" synStart('foo');" +
" var progress = 1;" +
" f(progress);" +
" synEnd('foo');" +
"}");
}
public void testCompilerDoesNotBlowUpIfUndefinedSymbols() {
CompilerOptions options = createCompilerOptions();
options.checkSymbols = true;
// Disable the undefined variable check.
options.setWarningLevel(
DiagnosticGroup.forType(VarCheck.UNDEFINED_VAR_ERROR),
CheckLevel.OFF);
// The compiler used to throw an IllegalStateException on this.
testSame(options, "var x = {foo: y};");
}
// Make sure that if we change variables which are constant to have
// $$constant appended to their names, we remove that tag before
// we finish.
public void testConstantTagsMustAlwaysBeRemoved() {
CompilerOptions options = createCompilerOptions();
options.variableRenaming = VariableRenamingPolicy.LOCAL;
String originalText = "var G_GEO_UNKNOWN_ADDRESS=1;\n" +
"function foo() {" +
" var localVar = 2;\n" +
" if (G_GEO_UNKNOWN_ADDRESS == localVar) {\n" +
" alert(\"A\"); }}";
String expectedText = "var G_GEO_UNKNOWN_ADDRESS=1;" +
"function foo(){var a=2;if(G_GEO_UNKNOWN_ADDRESS==a){alert(\"A\")}}";
test(options, originalText, expectedText);
}
public void testClosurePassPreservesJsDoc() {
CompilerOptions options = createCompilerOptions();
options.checkTypes = true;
options.closurePass = true;
test(options,
CLOSURE_BOILERPLATE +
"goog.provide('Foo'); /** @constructor */ Foo = function() {};" +
"var x = new Foo();",
"var COMPILED=true;var goog={};goog.exportSymbol=function(){};" +
"var Foo=function(){};var x=new Foo");
test(options,
CLOSURE_BOILERPLATE +
"goog.provide('Foo'); /** @enum */ Foo = {a: 3};",
TypeCheck.ENUM_NOT_CONSTANT);
}
public void testProvidedNamespaceIsConst() {
CompilerOptions options = createCompilerOptions();
options.closurePass = true;
options.inlineConstantVars = true;
options.collapseProperties = true;
test(options,
"var goog = {}; goog.provide('foo'); " +
"function f() { foo = {};}",
"var foo = {}; function f() { foo = {}; }",
ConstCheck.CONST_REASSIGNED_VALUE_ERROR);
}
public void testProvidedNamespaceIsConst2() {
CompilerOptions options = createCompilerOptions();
options.closurePass = true;
options.inlineConstantVars = true;
options.collapseProperties = true;
test(options,
"var goog = {}; goog.provide('foo.bar'); " +
"function f() { foo.bar = {};}",
"var foo$bar = {};" +
"function f() { foo$bar = {}; }",
ConstCheck.CONST_REASSIGNED_VALUE_ERROR);
}
public void testProvidedNamespaceIsConst3() {
CompilerOptions options = createCompilerOptions();
options.closurePass = true;
options.inlineConstantVars = true;
options.collapseProperties = true;
test(options,
"var goog = {}; " +
"goog.provide('foo.bar'); goog.provide('foo.bar.baz'); " +
"/** @constructor */ foo.bar = function() {};" +
"/** @constructor */ foo.bar.baz = function() {};",
"var foo$bar = function(){};" +
"var foo$bar$baz = function(){};");
}
public void testProvidedNamespaceIsConst4() {
CompilerOptions options = createCompilerOptions();
options.closurePass = true;
options.inlineConstantVars = true;
options.collapseProperties = true;
test(options,
"var goog = {}; goog.provide('foo.Bar'); " +
"var foo = {}; foo.Bar = {};",
"var foo = {}; var foo = {}; foo.Bar = {};");
}
public void testProvidedNamespaceIsConst5() {
CompilerOptions options = createCompilerOptions();
options.closurePass = true;
options.inlineConstantVars = true;
options.collapseProperties = true;
test(options,
"var goog = {}; goog.provide('foo.Bar'); " +
"foo = {}; foo.Bar = {};",
"var foo = {}; foo = {}; foo.Bar = {};");
}
public void testProcessDefinesAlwaysOn() {
test(createCompilerOptions(),
"/** @define {boolean} */ var HI = true; HI = false;",
"var HI = false;false;");
}
public void testProcessDefinesAdditionalReplacements() {
CompilerOptions options = createCompilerOptions();
options.setDefineToBooleanLiteral("HI", false);
test(options,
"/** @define {boolean} */ var HI = true;",
"var HI = false;");
}
public void testReplaceMessages() {
CompilerOptions options = createCompilerOptions();
String prefix = "var goog = {}; goog.getMsg = function() {};";
testSame(options, prefix + "var MSG_HI = goog.getMsg('hi');");
options.messageBundle = new EmptyMessageBundle();
test(options,
prefix + "/** @desc xyz */ var MSG_HI = goog.getMsg('hi');",
prefix + "var MSG_HI = 'hi';");
}
public void testCheckGlobalNames() {
CompilerOptions options = createCompilerOptions();
options.checkGlobalNamesLevel = CheckLevel.ERROR;
test(options, "var x = {}; var y = x.z;",
CheckGlobalNames.UNDEFINED_NAME_WARNING);
}
public void testInlineGetters() {
CompilerOptions options = createCompilerOptions();
String code =
"function Foo() {} Foo.prototype.bar = function() { return 3; };" +
"var x = new Foo(); x.bar();";
testSame(options, code);
options.inlineGetters = true;
test(options, code,
"function Foo() {} Foo.prototype.bar = function() { return 3 };" +
"var x = new Foo(); 3;");
}
public void testInlineGettersWithAmbiguate() {
CompilerOptions options = createCompilerOptions();
String code =
"/** @constructor */" +
"function Foo() {}" +
"/** @type {number} */ Foo.prototype.field;" +
"Foo.prototype.getField = function() { return this.field; };" +
"/** @constructor */" +
"function Bar() {}" +
"/** @type {string} */ Bar.prototype.field;" +
"Bar.prototype.getField = function() { return this.field; };" +
"new Foo().getField();" +
"new Bar().getField();";
testSame(options, code);
options.inlineGetters = true;
test(options, code,
"function Foo() {}" +
"Foo.prototype.field;" +
"Foo.prototype.getField = function() { return this.field; };" +
"function Bar() {}" +
"Bar.prototype.field;" +
"Bar.prototype.getField = function() { return this.field; };" +
"new Foo().field;" +
"new Bar().field;");
options.checkTypes = true;
options.ambiguateProperties = true;
// Propagating the wrong type information may cause ambiguate properties
// to generate bad code.
testSame(options, code);
}
public void testInlineVariables() {
CompilerOptions options = createCompilerOptions();
String code = "function foo() {} var x = 3; foo(x);";
testSame(options, code);
options.inlineVariables = true;
test(options, code, "(function foo() {})(3);");
options.propertyRenaming = PropertyRenamingPolicy.HEURISTIC;
test(options, code, DefaultPassConfig.CANNOT_USE_PROTOTYPE_AND_VAR);
}
public void testInlineConstants() {
CompilerOptions options = createCompilerOptions();
String code = "function foo() {} var x = 3; foo(x); var YYY = 4; foo(YYY);";
testSame(options, code);
options.inlineConstantVars = true;
test(options, code, "function foo() {} var x = 3; foo(x); foo(4);");
}
public void testMinimizeExits() {
CompilerOptions options = createCompilerOptions();
String code =
"function f() {" +
" if (window.foo) return; window.h(); " +
"}";
testSame(options, code);
options.foldConstants = true;
test(
options, code,
"function f() {" +
" window.foo || window.h(); " +
"}");
}
public void testFoldConstants() {
CompilerOptions options = createCompilerOptions();
String code = "if (true) { window.foo(); }";
testSame(options, code);
options.foldConstants = true;
test(options, code, "window.foo();");
}
public void testRemoveUnreachableCode() {
CompilerOptions options = createCompilerOptions();
String code = "function f() { return; f(); }";
testSame(options, code);
options.removeDeadCode = true;
test(options, code, "function f() {}");
}
public void testRemoveUnusedPrototypeProperties1() {
CompilerOptions options = createCompilerOptions();
String code = "function Foo() {} " +
"Foo.prototype.bar = function() { return new Foo(); };";
testSame(options, code);
options.removeUnusedPrototypeProperties = true;
test(options, code, "function Foo() {}");
}
public void testRemoveUnusedPrototypeProperties2() {
CompilerOptions options = createCompilerOptions();
String code = "function Foo() {} " +
"Foo.prototype.bar = function() { return new Foo(); };" +
"function f(x) { x.bar(); }";
testSame(options, code);
options.removeUnusedPrototypeProperties = true;
testSame(options, code);
options.removeUnusedVars = true;
test(options, code, "");
}
public void testSmartNamePass() {
CompilerOptions options = createCompilerOptions();
String code = "function Foo() { this.bar(); } " +
"Foo.prototype.bar = function() { return Foo(); };";
testSame(options, code);
options.smartNameRemoval = true;
test(options, code, "");
}
public void testDeadAssignmentsElimination() {
CompilerOptions options = createCompilerOptions();
String code = "function f() { var x = 3; 4; x = 5; return x; } f(); ";
testSame(options, code);
options.deadAssignmentElimination = true;
testSame(options, code);
options.removeUnusedVars = true;
test(options, code, "function f() { var x = 3; 4; x = 5; return x; } f();");
}
public void testInlineFunctions() {
CompilerOptions options = createCompilerOptions();
String code = "function f() { return 3; } f(); ";
testSame(options, code);
options.inlineFunctions = true;
test(options, code, "3;");
}
public void testRemoveUnusedVars1() {
CompilerOptions options = createCompilerOptions();
String code = "function f(x) {} f();";
testSame(options, code);
options.removeUnusedVars = true;
test(options, code, "function f() {} f();");
}
public void testRemoveUnusedVars2() {
CompilerOptions options = createCompilerOptions();
String code = "(function f(x) {})();var g = function() {}; g();";
testSame(options, code);
options.removeUnusedVars = true;
test(options, code, "(function() {})();var g = function() {}; g();");
options.anonymousFunctionNaming = AnonymousFunctionNamingPolicy.UNMAPPED;
test(options, code, "(function f() {})();var g = function $g$() {}; g();");
}
public void testCrossModuleCodeMotion() {
CompilerOptions options = createCompilerOptions();
String[] code = new String[] {
"var x = 1;",
"x;",
};
testSame(options, code);
options.crossModuleCodeMotion = true;
test(options, code, new String[] {
"",
"var x = 1; x;",
});
}
public void testCrossModuleMethodMotion() {
CompilerOptions options = createCompilerOptions();
String[] code = new String[] {
"var Foo = function() {}; Foo.prototype.bar = function() {};" +
"var x = new Foo();",
"x.bar();",
};
testSame(options, code);
options.crossModuleMethodMotion = true;
test(options, code, new String[] {
CrossModuleMethodMotion.STUB_DECLARATIONS +
"var Foo = function() {};" +
"Foo.prototype.bar=JSCompiler_stubMethod(0); var x=new Foo;",
"Foo.prototype.bar=JSCompiler_unstubMethod(0,function(){}); x.bar()",
});
}
public void testFlowSensitiveInlineVariables1() {
CompilerOptions options = createCompilerOptions();
String code = "function f() { var x = 3; x = 5; return x; }";
testSame(options, code);
options.flowSensitiveInlineVariables = true;
test(options, code, "function f() { var x = 3; return 5; }");
String unusedVar = "function f() { var x; x = 5; return x; } f()";
test(options, unusedVar, "function f() { var x; return 5; } f()");
options.removeUnusedVars = true;
test(options, unusedVar, "function f() { return 5; } f()");
}
public void testFlowSensitiveInlineVariables2() {
CompilerOptions options = createCompilerOptions();
CompilationLevel.SIMPLE_OPTIMIZATIONS
.setOptionsForCompilationLevel(options);
test(options,
"function f () {\n" +
" var ab = 0;\n" +
" ab += '-';\n" +
" alert(ab);\n" +
"}",
"function f () {\n" +
" alert('0-');\n" +
"}");
}
public void testCollapseAnonymousFunctions() {
CompilerOptions options = createCompilerOptions();
String code = "var f = function() {};";
testSame(options, code);
options.collapseAnonymousFunctions = true;
test(options, code, "function f() {}");
}
public void testMoveFunctionDeclarations() {
CompilerOptions options = createCompilerOptions();
String code = "var x = f(); function f() { return 3; }";
testSame(options, code);
options.moveFunctionDeclarations = true;
test(options, code, "function f() { return 3; } var x = f();");
}
public void testNameAnonymousFunctions() {
CompilerOptions options = createCompilerOptions();
String code = "var f = function() {};";
testSame(options, code);
options.anonymousFunctionNaming = AnonymousFunctionNamingPolicy.MAPPED;
test(options, code, "var f = function $() {}");
assertNotNull(lastCompiler.getResult().namedAnonFunctionMap);
options.anonymousFunctionNaming = AnonymousFunctionNamingPolicy.UNMAPPED;
test(options, code, "var f = function $f$() {}");
assertNull(lastCompiler.getResult().namedAnonFunctionMap);
}
public void testExtractPrototypeMemberDeclarations() {
CompilerOptions options = createCompilerOptions();
String code = "var f = function() {};";
String expected = "var a; var b = function() {}; a = b.prototype;";
for (int i = 0; i < 10; i++) {
code += "f.prototype.a = " + i + ";";
expected += "a.a = " + i + ";";
}
testSame(options, code);
options.extractPrototypeMemberDeclarations = true;
options.variableRenaming = VariableRenamingPolicy.ALL;
test(options, code, expected);
options.propertyRenaming = PropertyRenamingPolicy.HEURISTIC;
options.variableRenaming = VariableRenamingPolicy.OFF;
testSame(options, code);
}
public void testDevirtualizationAndExtractPrototypeMemberDeclarations() {
CompilerOptions options = createCompilerOptions();
options.devirtualizePrototypeMethods = true;
options.collapseAnonymousFunctions = true;
options.extractPrototypeMemberDeclarations = true;
options.variableRenaming = VariableRenamingPolicy.ALL;
String code = "var f = function() {};";
String expected = "var a; function b() {} a = b.prototype;";
for (int i = 0; i < 10; i++) {
code += "f.prototype.argz = function() {arguments};";
code += "f.prototype.devir" + i + " = function() {};";
char letter = (char) ('d' + i);
expected += "a.argz = function() {arguments};";
expected += "function " + letter + "(c){}";
}
code += "var F = new f(); F.argz();";
expected += "var n = new b(); n.argz();";
for (int i = 0; i < 10; i++) {
code += "F.devir" + i + "();";
char letter = (char) ('d' + i);
expected += letter + "(n);";
}
test(options, code, expected);
}
public void testCoalesceVariableNames() {
CompilerOptions options = createCompilerOptions();
String code = "function f() {var x = 3; var y = x; var z = y; return z;}";
testSame(options, code);
options.coalesceVariableNames = true;
test(options, code,
"function f() {var x = 3; x = x; x = x; return x;}");
}
public void testPropertyRenaming() {
CompilerOptions options = createCompilerOptions();
options.propertyAffinity = true;
String code =
"function f() { return this.foo + this['bar'] + this.Baz; }" +
"f.prototype.bar = 3; f.prototype.Baz = 3;";
String heuristic =
"function f() { return this.foo + this['bar'] + this.a; }" +
"f.prototype.bar = 3; f.prototype.a = 3;";
String aggHeuristic =
"function f() { return this.foo + this['b'] + this.a; } " +
"f.prototype.b = 3; f.prototype.a = 3;";
String all =
"function f() { return this.b + this['bar'] + this.a; }" +
"f.prototype.c = 3; f.prototype.a = 3;";
testSame(options, code);
options.propertyRenaming = PropertyRenamingPolicy.HEURISTIC;
test(options, code, heuristic);
options.propertyRenaming = PropertyRenamingPolicy.AGGRESSIVE_HEURISTIC;
test(options, code, aggHeuristic);
options.propertyRenaming = PropertyRenamingPolicy.ALL_UNQUOTED;
test(options, code, all);
}
public void testConvertToDottedProperties() {
CompilerOptions options = createCompilerOptions();
String code =
"function f() { return this['bar']; } f.prototype.bar = 3;";
String expected =
"function f() { return this.bar; } f.prototype.a = 3;";
testSame(options, code);
options.convertToDottedProperties = true;
options.propertyRenaming = PropertyRenamingPolicy.ALL_UNQUOTED;
test(options, code, expected);
}
public void testRewriteFunctionExpressions() {
CompilerOptions options = createCompilerOptions();
String code = "var a = function() {};";
String expected = "function JSCompiler_emptyFn(){return function(){}} " +
"var a = JSCompiler_emptyFn();";
for (int i = 0; i < 10; i++) {
code += "a = function() {};";
expected += "a = JSCompiler_emptyFn();";
}
testSame(options, code);
options.rewriteFunctionExpressions = true;
test(options, code, expected);
}
public void testAliasAllStrings() {
CompilerOptions options = createCompilerOptions();
String code = "function f() { return 'a'; }";
String expected = "var $$S_a = 'a'; function f() { return $$S_a; }";
testSame(options, code);
options.aliasAllStrings = true;
test(options, code, expected);
}
public void testAliasExterns() {
CompilerOptions options = createCompilerOptions();
String code = "function f() { return window + window + window + window; }";
String expected = "var GLOBAL_window = window;" +
"function f() { return GLOBAL_window + GLOBAL_window + " +
" GLOBAL_window + GLOBAL_window; }";
testSame(options, code);
options.aliasExternals = true;
test(options, code, expected);
}
public void testAliasKeywords() {
CompilerOptions options = createCompilerOptions();
String code =
"function f() { return true + true + true + true + true + true; }";
String expected = "var JSCompiler_alias_TRUE = true;" +
"function f() { return JSCompiler_alias_TRUE + " +
" JSCompiler_alias_TRUE + JSCompiler_alias_TRUE + " +
" JSCompiler_alias_TRUE + JSCompiler_alias_TRUE + " +
" JSCompiler_alias_TRUE; }";
testSame(options, code);
options.aliasKeywords = true;
test(options, code, expected);
}
public void testRenameVars1() {
CompilerOptions options = createCompilerOptions();
String code =
"var abc = 3; function f() { var xyz = 5; return abc + xyz; }";
String local = "var abc = 3; function f() { var a = 5; return abc + a; }";
String all = "var a = 3; function c() { var b = 5; return a + b; }";
testSame(options, code);
options.variableRenaming = VariableRenamingPolicy.LOCAL;
test(options, code, local);
options.variableRenaming = VariableRenamingPolicy.ALL;
test(options, code, all);
options.reserveRawExports = true;
}
public void testRenameVars2() {
CompilerOptions options = createCompilerOptions();
options.variableRenaming = VariableRenamingPolicy.ALL;
String code = "var abc = 3; function f() { window['a'] = 5; }";
String noexport = "var a = 3; function b() { window['a'] = 5; }";
String export = "var b = 3; function c() { window['a'] = 5; }";
options.reserveRawExports = false;
test(options, code, noexport);
options.reserveRawExports = true;
test(options, code, export);
}
public void testShadowVaribles() {
CompilerOptions options = createCompilerOptions();
options.variableRenaming = VariableRenamingPolicy.LOCAL;
options.shadowVariables = true;
String code = "var f = function(x) { return function(y) {}}";
String expected = "var f = function(a) { return function(a) {}}";
test(options, code, expected);
}
public void testRenameLabels() {
CompilerOptions options = createCompilerOptions();
String code = "longLabel: while (true) { break longLabel; }";
String expected = "a: while (true) { break a; }";
testSame(options, code);
options.labelRenaming = true;
test(options, code, expected);
}
public void testBadBreakStatementInIdeMode() {
// Ensure that type-checking doesn't crash, even if the CFG is malformed.
// This can happen in IDE mode.
CompilerOptions options = createCompilerOptions();
options.ideMode = true;
options.checkTypes = true;
test(options,
"function f() { try { } catch(e) { break; } }",
RhinoErrorReporter.PARSE_ERROR);
}
public void testIssue63SourceMap() {
CompilerOptions options = createCompilerOptions();
String code = "var a;";
options.skipAllPasses = true;
options.sourceMapOutputPath = "./src.map";
Compiler compiler = compile(options, code);
compiler.toSource();
}
public void testRegExp1() {
CompilerOptions options = createCompilerOptions();
options.foldConstants = true;
String code = "/(a)/.test(\"a\");";
testSame(options, code);
options.computeFunctionSideEffects = true;
String expected = "";
test(options, code, expected);
}
public void testRegExp2() {
CompilerOptions options = createCompilerOptions();
options.foldConstants = true;
String code = "/(a)/.test(\"a\");var a = RegExp.$1";
testSame(options, code);
options.computeFunctionSideEffects = true;
test(options, code, CheckRegExp.REGEXP_REFERENCE);
options.setWarningLevel(DiagnosticGroups.CHECK_REGEXP, CheckLevel.OFF);
testSame(options, code);
}
public void testFoldLocals1() {
CompilerOptions options = createCompilerOptions();
options.foldConstants = true;
// An external object, whose constructor has no side-effects,
// and whose method "go" only modifies the object.
String code = "new Widget().go();";
testSame(options, code);
options.computeFunctionSideEffects = true;
test(options, code, "");
}
public void testFoldLocals2() {
CompilerOptions options = createCompilerOptions();
options.foldConstants = true;
options.checkTypes = true;
// An external function that returns a local object that the
// method "go" that only modifies the object.
String code = "widgetToken().go();";
testSame(options, code);
options.computeFunctionSideEffects = true;
test(options, code, "widgetToken()");
}
public void testFoldLocals3() {
CompilerOptions options = createCompilerOptions();
options.foldConstants = true;
// A function "f" who returns a known local object, and a method that
// modifies only modifies that.
String definition = "function f(){return new Widget()}";
String call = "f().go();";
String code = definition + call;
testSame(options, code);
options.computeFunctionSideEffects = true;
// BROKEN
//test(options, code, definition);
testSame(options, code);
}
public void testFoldLocals4() {
CompilerOptions options = createCompilerOptions();
options.foldConstants = true;
String code = "/** @constructor */\n"
+ "function InternalWidget(){this.x = 1;}"
+ "InternalWidget.prototype.internalGo = function (){this.x = 2};"
+ "new InternalWidget().internalGo();";
testSame(options, code);
options.computeFunctionSideEffects = true;
String optimized = ""
+ "function InternalWidget(){this.x = 1;}"
+ "InternalWidget.prototype.internalGo = function (){this.x = 2};";
test(options, code, optimized);
}
public void testFoldLocals5() {
CompilerOptions options = createCompilerOptions();
options.foldConstants = true;
String code = ""
+ "function fn(){var a={};a.x={};return a}"
+ "fn().x.y = 1;";
// "fn" returns a unescaped local object, we should be able to fold it,
// but we don't currently.
String result = ""
+ "function fn(){var a={x:{}};return a}"
+ "fn().x.y = 1;";
test(options, code, result);
options.computeFunctionSideEffects = true;
test(options, code, result);
}
public void testFoldLocals6() {
CompilerOptions options = createCompilerOptions();
options.foldConstants = true;
String code = ""
+ "function fn(){return {}}"
+ "fn().x.y = 1;";
testSame(options, code);
options.computeFunctionSideEffects = true;
testSame(options, code);
}
public void testFoldLocals7() {
CompilerOptions options = createCompilerOptions();
options.foldConstants = true;
String code = ""
+ "function InternalWidget(){return [];}"
+ "Array.prototype.internalGo = function (){this.x = 2};"
+ "InternalWidget().internalGo();";
testSame(options, code);
options.computeFunctionSideEffects = true;
String optimized = ""
+ "function InternalWidget(){return [];}"
+ "Array.prototype.internalGo = function (){this.x = 2};";
test(options, code, optimized);
}
public void testVarDeclarationsIntoFor() {
CompilerOptions options = createCompilerOptions();
options.collapseVariableDeclarations = false;
String code = "var a = 1; for (var b = 2; ;) {}";
testSame(options, code);
options.collapseVariableDeclarations = false;
test(options, code, "for (var a = 1, b = 2; ;) {}");
}
public void testExploitAssigns() {
CompilerOptions options = createCompilerOptions();
options.collapseVariableDeclarations = false;
String code = "a = 1; b = a; c = b";
testSame(options, code);
options.collapseVariableDeclarations = true;
test(options, code, "c=b=a=1");
}
public void testRecoverOnBadExterns() throws Exception {
// This test is for a bug in a very narrow set of circumstances:
// 1) externs validation has to be off.
// 2) aliasExternals has to be on.
// 3) The user has to reference a "normal" variable in externs.
// This case is handled at checking time by injecting a
// synthetic extern variable, and adding a "@suppress {duplicate}" to
// the normal code at compile time. But optimizations may remove that
// annotation, so we need to make sure that the variable declarations
// are de-duped before that happens.
CompilerOptions options = createCompilerOptions();
options.aliasExternals = true;
externs = new JSSourceFile[] {
JSSourceFile.fromCode("externs", "extern.foo")
};
test(options,
"var extern; " +
"function f() { return extern + extern + extern + extern; }",
"var extern; " +
"function f() { return extern + extern + extern + extern; }",
VarCheck.UNDEFINED_EXTERN_VAR_ERROR);
}
public void testDuplicateVariablesInExterns() {
CompilerOptions options = createCompilerOptions();
options.checkSymbols = true;
externs = new JSSourceFile[] {
JSSourceFile.fromCode("externs",
"var externs = {}; /** @suppress {duplicate} */ var externs = {};")
};
testSame(options, "");
}
public void testLanguageMode() {
CompilerOptions options = createCompilerOptions();
options.setLanguageIn(LanguageMode.ECMASCRIPT3);
String code = "var a = {get f(){}}";
Compiler compiler = compile(options, code);
checkUnexpectedErrorsOrWarnings(compiler, 1);
assertEquals(
"JSC_PARSE_ERROR. Parse error. " +
"getters are not supported in Internet Explorer " +
"at i0 line 1 : 0",
compiler.getErrors()[0].toString());
options.setLanguageIn(LanguageMode.ECMASCRIPT5);
testSame(options, code);
options.setLanguageIn(LanguageMode.ECMASCRIPT5_STRICT);
testSame(options, code);
}
public void testLanguageMode2() {
CompilerOptions options = createCompilerOptions();
options.setLanguageIn(LanguageMode.ECMASCRIPT3);
options.setWarningLevel(DiagnosticGroups.ES5_STRICT, CheckLevel.OFF);
String code = "var a = 2; delete a;";
testSame(options, code);
options.setLanguageIn(LanguageMode.ECMASCRIPT5);
testSame(options, code);
options.setLanguageIn(LanguageMode.ECMASCRIPT5_STRICT);
test(options,
code,
code,
StrictModeCheck.DELETE_VARIABLE);
}
public void testIssue598() {
CompilerOptions options = createCompilerOptions();
options.setLanguageIn(LanguageMode.ECMASCRIPT5_STRICT);
WarningLevel.VERBOSE.setOptionsForWarningLevel(options);
options.setLanguageIn(LanguageMode.ECMASCRIPT5);
String code =
"'use strict';\n" +
"function App() {}\n" +
"App.prototype = {\n" +
" get appData() { return this.appData_; },\n" +
" set appData(data) { this.appData_ = data; }\n" +
"};";
Compiler compiler = compile(options, code);
testSame(options, code);
}
public void testCoaleseVariables() {
CompilerOptions options = createCompilerOptions();
options.foldConstants = false;
options.coalesceVariableNames = true;
String code =
"function f(a) {" +
" if (a) {" +
" return a;" +
" } else {" +
" var b = a;" +
" return b;" +
" }" +
" return a;" +
"}";
String expected =
"function f(a) {" +
" if (a) {" +
" return a;" +
" } else {" +
" a = a;" +
" return a;" +
" }" +
" return a;" +
"}";
test(options, code, expected);
options.foldConstants = true;
options.coalesceVariableNames = false;
code =
"function f(a) {" +
" if (a) {" +
" return a;" +
" } else {" +
" var b = a;" +
" return b;" +
" }" +
" return a;" +
"}";
expected =
"function f(a) {" +
" if (!a) {" +
" var b = a;" +
" return b;" +
" }" +
" return a;" +
"}";
test(options, code, expected);
options.foldConstants = true;
options.coalesceVariableNames = true;
expected =
"function f(a) {" +
" return a;" +
"}";
test(options, code, expected);
}
public void testLateStatementFusion() {
CompilerOptions options = createCompilerOptions();
options.foldConstants = true;
test(options,
"while(a){a();if(b){b();b()}}",
"for(;a;)a(),b&&(b(),b())");
}
public void testLateConstantReordering() {
CompilerOptions options = createCompilerOptions();
options.foldConstants = true;
test(options,
"if (x < 1 || x > 1 || 1 < x || 1 > x) { alert(x) }",
" (1 > x || 1 < x || 1 < x || 1 > x) && alert(x) ");
}
public void testsyntheticBlockOnDeadAssignments() {
CompilerOptions options = createCompilerOptions();
options.deadAssignmentElimination = true;
options.removeUnusedVars = true;
options.syntheticBlockStartMarker = "START";
options.syntheticBlockEndMarker = "END";
test(options, "var x; x = 1; START(); x = 1;END();x()",
"var x; x = 1;{START();{x = 1}END()}x()");
}
public void testBug4152835() {
CompilerOptions options = createCompilerOptions();
options.foldConstants = true;
options.syntheticBlockStartMarker = "START";
options.syntheticBlockEndMarker = "END";
test(options, "START();END()", "{START();{}END()}");
}
public void testBug5786871() {
CompilerOptions options = createCompilerOptions();
options.ideMode = true;
test(options, "function () {}", RhinoErrorReporter.PARSE_ERROR);
}
public void testIssue378() {
CompilerOptions options = createCompilerOptions();
options.inlineVariables = true;
options.flowSensitiveInlineVariables = true;
testSame(options, "function f(c) {var f = c; arguments[0] = this;" +
" f.apply(this, arguments); return this;}");
}
public void testIssue550() {
CompilerOptions options = createCompilerOptions();
CompilationLevel.SIMPLE_OPTIMIZATIONS
.setOptionsForCompilationLevel(options);
options.foldConstants = true;
options.inlineVariables = true;
options.flowSensitiveInlineVariables = true;
test(options,
"function f(h) {\n" +
" var a = h;\n" +
" a = a + 'x';\n" +
" a = a + 'y';\n" +
" return a;\n" +
"}",
"function f(a) {return a + 'xy'}");
}
public void testCodingConvention() {
Compiler compiler = new Compiler();
compiler.initOptions(new CompilerOptions());
assertEquals(
compiler.getCodingConvention().getClass().toString(),
ClosureCodingConvention.class.toString());
}
public void testJQueryStringSplitLoops() {
CompilerOptions options = createCompilerOptions();
options.foldConstants = true;
test(options,
"var x=['1','2','3','4','5','6','7']",
"var x='1,2,3,4,5,6,7'.split(',')");
options = createCompilerOptions();
options.foldConstants = true;
options.computeFunctionSideEffects = false;
options.removeUnusedVars = true;
// If we do splits too early, it would add a sideeffect to x.
test(options,
"var x=['1','2','3','4','5','6','7']",
"");
}
public void testAlwaysRunSafetyCheck() {
CompilerOptions options = createCompilerOptions();
options.checkSymbols = false;
options.customPasses = ArrayListMultimap.create();
options.customPasses.put(
CustomPassExecutionTime.BEFORE_OPTIMIZATIONS,
new CompilerPass() {
@Override public void process(Node externs, Node root) {
Node var = root.getLastChild().getFirstChild();
assertEquals(Token.VAR, var.getType());
var.detachFromParent();
}
});
try {
test(options,
"var x = 3; function f() { return x + z; }",
"function f() { return x + z; }");
fail("Expected runtime exception");
} catch (RuntimeException e) {
assertTrue(e.getMessage().indexOf("Unexpected variable x") != -1);
}
}
public void testSuppressEs5StrictWarning() {
CompilerOptions options = createCompilerOptions();
options.setWarningLevel(DiagnosticGroups.ES5_STRICT, CheckLevel.WARNING);
testSame(options,
"/** @suppress{es5Strict} */\n" +
"function f() { var arguments; }");
}
public void testCheckProvidesWarning() {
CompilerOptions options = createCompilerOptions();
options.setWarningLevel(DiagnosticGroups.CHECK_PROVIDES, CheckLevel.WARNING);
options.setCheckProvides(CheckLevel.WARNING);
test(options,
"/** @constructor */\n" +
"function f() { var arguments; }",
DiagnosticType.warning("JSC_MISSING_PROVIDE", "missing goog.provide(''{0}'')"));
}
public void testSuppressCheckProvidesWarning() {
CompilerOptions options = createCompilerOptions();
options.setWarningLevel(DiagnosticGroups.CHECK_PROVIDES, CheckLevel.WARNING);
options.setCheckProvides(CheckLevel.WARNING);
testSame(options,
"/** @constructor\n" +
" * @suppress{checkProvides} */\n" +
"function f() { var arguments; }");
}
public void testRenamePrefixNamespace() {
String code =
"var x = {}; x.FOO = 5; x.bar = 3;";
CompilerOptions options = createCompilerOptions();
testSame(options, code);
options.collapseProperties = true;
options.renamePrefixNamespace = "_";
test(options, code, "_.x$FOO = 5; _.x$bar = 3;");
}
public void testRenamePrefixNamespaceActivatesMoveFunctionDeclarations() {
CompilerOptions options = createCompilerOptions();
String code = "var x = f; function f() { return 3; }";
testSame(options, code);
assertFalse(options.moveFunctionDeclarations);
options.renamePrefixNamespace = "_";
test(options, code, "_.f = function() { return 3; }; _.x = _.f;");
}
public void testBrokenNameSpace() {
CompilerOptions options = createCompilerOptions();
String code = "var goog; goog.provide('i.am.on.a.Horse');" +
"i.am.on.a.Horse = function() {};" +
"i.am.on.a.Horse.prototype.x = function() {};" +
"i.am.on.a.Boat.prototype.y = function() {}";
options.closurePass = true;
options.collapseProperties = true;
options.smartNameRemoval = true;
test(options, code, "");
}
public void testNamelessParameter() {
CompilerOptions options = createCompilerOptions();
CompilationLevel.ADVANCED_OPTIMIZATIONS
.setOptionsForCompilationLevel(options);
String code =
"var impl_0;" +
"$load($init());" +
"function $load(){" +
" window['f'] = impl_0;" +
"}" +
"function $init() {" +
" impl_0 = {};" +
"}";
String result =
"window.f = {};";
test(options, code, result);
}
public void testHiddenSideEffect() {
CompilerOptions options = createCompilerOptions();
CompilationLevel.ADVANCED_OPTIMIZATIONS
.setOptionsForCompilationLevel(options);
options.setAliasExternals(true);
String code =
"window.offsetWidth;";
String result =
"window.offsetWidth;";
test(options, code, result);
}
+ public void testNegativeZero() {
+ CompilerOptions options = createCompilerOptions();
+ CompilationLevel.ADVANCED_OPTIMIZATIONS
+ .setOptionsForCompilationLevel(options);
+ test(options,
+ "function bar(x) { return x; }\n" +
+ "function foo(x) { print(x / bar(0));\n" +
+ " print(x / bar(-0)); }\n" +
+ "foo(3);",
+ "print(3/0);print(3/-0);");
+ }
+
private void testSame(CompilerOptions options, String original) {
testSame(options, new String[] { original });
}
private void testSame(CompilerOptions options, String[] original) {
test(options, original, original);
}
/**
* Asserts that when compiling with the given compiler options,
* {@code original} is transformed into {@code compiled}.
*/
private void test(CompilerOptions options,
String original, String compiled) {
test(options, new String[] { original }, new String[] { compiled });
}
/**
* Asserts that when compiling with the given compiler options,
* {@code original} is transformed into {@code compiled}.
*/
private void test(CompilerOptions options,
String[] original, String[] compiled) {
Compiler compiler = compile(options, original);
assertEquals("Expected no warnings or errors\n" +
"Errors: \n" + Joiner.on("\n").join(compiler.getErrors()) +
"Warnings: \n" + Joiner.on("\n").join(compiler.getWarnings()),
0, compiler.getErrors().length + compiler.getWarnings().length);
Node root = compiler.getRoot().getLastChild();
Node expectedRoot = parse(compiled, options);
String explanation = expectedRoot.checkTreeEquals(root);
assertNull("\nExpected: " + compiler.toSource(expectedRoot) +
"\nResult: " + compiler.toSource(root) +
"\n" + explanation, explanation);
}
/**
* Asserts that when compiling with the given compiler options,
* there is an error or warning.
*/
private void test(CompilerOptions options,
String original, DiagnosticType warning) {
test(options, new String[] { original }, warning);
}
private void test(CompilerOptions options,
String original, String compiled, DiagnosticType warning) {
test(options, new String[] { original }, new String[] { compiled },
warning);
}
private void test(CompilerOptions options,
String[] original, DiagnosticType warning) {
test(options, original, null, warning);
}
/**
* Asserts that when compiling with the given compiler options,
* there is an error or warning.
*/
private void test(CompilerOptions options,
String[] original, String[] compiled, DiagnosticType warning) {
Compiler compiler = compile(options, original);
checkUnexpectedErrorsOrWarnings(compiler, 1);
assertEquals("Expected exactly one warning or error",
1, compiler.getErrors().length + compiler.getWarnings().length);
if (compiler.getErrors().length > 0) {
assertEquals(warning, compiler.getErrors()[0].getType());
} else {
assertEquals(warning, compiler.getWarnings()[0].getType());
}
if (compiled != null) {
Node root = compiler.getRoot().getLastChild();
Node expectedRoot = parse(compiled, options);
String explanation = expectedRoot.checkTreeEquals(root);
assertNull("\nExpected: " + compiler.toSource(expectedRoot) +
"\nResult: " + compiler.toSource(root) +
"\n" + explanation, explanation);
}
}
private void checkUnexpectedErrorsOrWarnings(
Compiler compiler, int expected) {
int actual = compiler.getErrors().length + compiler.getWarnings().length;
if (actual != expected) {
String msg = "";
for (JSError err : compiler.getErrors()) {
msg += "Error:" + err.toString() + "\n";
}
for (JSError err : compiler.getWarnings()) {
msg += "Warning:" + err.toString() + "\n";
}
assertEquals("Unexpected warnings or errors.\n "+ msg,
expected, actual);
}
}
private Compiler compile(CompilerOptions options, String original) {
return compile(options, new String[] { original });
}
private Compiler compile(CompilerOptions options, String[] original) {
Compiler compiler = lastCompiler = new Compiler();
JSSourceFile[] inputs = new JSSourceFile[original.length];
for (int i = 0; i < original.length; i++) {
inputs[i] = JSSourceFile.fromCode("input" + i, original[i]);
}
compiler.compile(
externs, CompilerTestCase.createModuleChain(original), options);
return compiler;
}
private Node parse(String[] original, CompilerOptions options) {
Compiler compiler = new Compiler();
JSSourceFile[] inputs = new JSSourceFile[original.length];
for (int i = 0; i < inputs.length; i++) {
inputs[i] = JSSourceFile.fromCode("input" + i, original[i]);
}
compiler.init(externs, inputs, options);
checkUnexpectedErrorsOrWarnings(compiler, 0);
Node all = compiler.parseInputs();
checkUnexpectedErrorsOrWarnings(compiler, 0);
Node n = all.getLastChild();
Node externs = all.getFirstChild();
(new CreateSyntheticBlocks(
compiler, "synStart", "synEnd")).process(externs, n);
(new Normalize(compiler, false)).process(externs, n);
(MakeDeclaredNamesUnique.getContextualRenameInverter(compiler)).process(
externs, n);
(new Denormalize(compiler)).process(externs, n);
return n;
}
/** Creates a CompilerOptions object with google coding conventions. */
private CompilerOptions createCompilerOptions() {
CompilerOptions options = new CompilerOptions();
options.setCodingConvention(new GoogleCodingConvention());
return options;
}
}
diff --git a/closure/closure-compiler/test/com/google/javascript/jscomp/PeepholeFoldConstantsTest.java b/closure/closure-compiler/test/com/google/javascript/jscomp/PeepholeFoldConstantsTest.java
index 62adce266..d666483ce 100644
--- a/closure/closure-compiler/test/com/google/javascript/jscomp/PeepholeFoldConstantsTest.java
+++ b/closure/closure-compiler/test/com/google/javascript/jscomp/PeepholeFoldConstantsTest.java
@@ -1,1284 +1,1285 @@
/*
* Copyright 2004 The Closure Compiler Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.javascript.jscomp;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.javascript.rhino.Node;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Tests for {@link PeepholeFoldConstants} in isolation. Tests for
* the interaction of multiple peephole passes are in
* {@link PeepholeIntegrationTest}.
*/
public class PeepholeFoldConstantsTest extends CompilerTestCase {
private boolean late;
// TODO(user): Remove this when we no longer need to do string comparison.
private PeepholeFoldConstantsTest(boolean compareAsTree) {
super("", compareAsTree);
}
public PeepholeFoldConstantsTest() {
super("");
}
@Override
public void setUp() {
late = false;
enableLineNumberCheck(true);
}
@Override
public CompilerPass getProcessor(final Compiler compiler) {
CompilerPass peepholePass = new PeepholeOptimizationsPass(compiler,
new PeepholeFoldConstants(late));
return peepholePass;
}
@Override
protected int getNumRepetitions() {
// Reduce this to 2 if we get better expression evaluators.
return 2;
}
private void foldSame(String js) {
testSame(js);
}
private void fold(String js, String expected) {
test(js, expected);
}
private void fold(String js, String expected, DiagnosticType warning) {
test(js, expected, warning);
}
// TODO(user): This is same as fold() except it uses string comparison. Any
// test that needs tell us where a folding is constructing an invalid AST.
private void assertResultString(String js, String expected) {
PeepholeFoldConstantsTest scTest = new PeepholeFoldConstantsTest(false);
scTest.test(js, expected);
}
public void testUndefinedComparison1() {
fold("undefined == undefined", "true");
fold("undefined == null", "true");
fold("undefined == void 0", "true");
fold("undefined == 0", "false");
fold("undefined == 1", "false");
fold("undefined == 'hi'", "false");
fold("undefined == true", "false");
fold("undefined == false", "false");
fold("undefined === undefined", "true");
fold("undefined === null", "false");
fold("undefined === void 0", "true");
foldSame("undefined == this");
foldSame("undefined == x");
fold("undefined != undefined", "false");
fold("undefined != null", "false");
fold("undefined != void 0", "false");
fold("undefined != 0", "true");
fold("undefined != 1", "true");
fold("undefined != 'hi'", "true");
fold("undefined != true", "true");
fold("undefined != false", "true");
fold("undefined !== undefined", "false");
fold("undefined !== void 0", "false");
fold("undefined !== null", "true");
foldSame("undefined != this");
foldSame("undefined != x");
fold("undefined < undefined", "false");
fold("undefined > undefined", "false");
fold("undefined >= undefined", "false");
fold("undefined <= undefined", "false");
fold("0 < undefined", "false");
fold("true > undefined", "false");
fold("'hi' >= undefined", "false");
fold("null <= undefined", "false");
fold("undefined < 0", "false");
fold("undefined > true", "false");
fold("undefined >= 'hi'", "false");
fold("undefined <= null", "false");
fold("null == undefined", "true");
fold("0 == undefined", "false");
fold("1 == undefined", "false");
fold("'hi' == undefined", "false");
fold("true == undefined", "false");
fold("false == undefined", "false");
fold("null === undefined", "false");
fold("void 0 === undefined", "true");
fold("undefined == NaN", "false");
fold("NaN == undefined", "false");
fold("undefined == Infinity", "false");
fold("Infinity == undefined", "false");
fold("undefined == -Infinity", "false");
fold("-Infinity == undefined", "false");
fold("({}) == undefined", "false");
fold("undefined == ({})", "false");
fold("([]) == undefined", "false");
fold("undefined == ([])", "false");
fold("(/a/g) == undefined", "false");
fold("undefined == (/a/g)", "false");
fold("(function(){}) == undefined", "false");
fold("undefined == (function(){})", "false");
fold("undefined != NaN", "true");
fold("NaN != undefined", "true");
fold("undefined != Infinity", "true");
fold("Infinity != undefined", "true");
fold("undefined != -Infinity", "true");
fold("-Infinity != undefined", "true");
fold("({}) != undefined", "true");
fold("undefined != ({})", "true");
fold("([]) != undefined", "true");
fold("undefined != ([])", "true");
fold("(/a/g) != undefined", "true");
fold("undefined != (/a/g)", "true");
fold("(function(){}) != undefined", "true");
fold("undefined != (function(){})", "true");
foldSame("this == undefined");
foldSame("x == undefined");
}
public void testUndefinedComparison2() {
fold("\"123\" !== void 0", "true");
fold("\"123\" === void 0", "false");
fold("void 0 !== \"123\"", "true");
fold("void 0 === \"123\"", "false");
}
public void testUndefinedComparison3() {
fold("\"123\" !== undefined", "true");
fold("\"123\" === undefined", "false");
fold("undefined !== \"123\"", "true");
fold("undefined === \"123\"", "false");
}
public void testUndefinedComparison4() {
fold("1 !== void 0", "true");
fold("1 === void 0", "false");
fold("null !== void 0", "true");
fold("null === void 0", "false");
fold("undefined !== void 0", "false");
fold("undefined === void 0", "true");
}
public void testNullComparison1() {
fold("null == undefined", "true");
fold("null == null", "true");
fold("null == void 0", "true");
fold("null == 0", "false");
fold("null == 1", "false");
fold("null == 'hi'", "false");
fold("null == true", "false");
fold("null == false", "false");
fold("null === undefined", "false");
fold("null === null", "true");
fold("null === void 0", "false");
foldSame("null == this");
foldSame("null == x");
fold("null != undefined", "false");
fold("null != null", "false");
fold("null != void 0", "false");
fold("null != 0", "true");
fold("null != 1", "true");
fold("null != 'hi'", "true");
fold("null != true", "true");
fold("null != false", "true");
fold("null !== undefined", "true");
fold("null !== void 0", "true");
fold("null !== null", "false");
foldSame("null != this");
foldSame("null != x");
fold("null < null", "false");
fold("null > null", "false");
fold("null >= null", "true");
fold("null <= null", "true");
foldSame("0 < null"); // foldable
fold("true > null", "true");
foldSame("'hi' >= null"); // foldable
fold("null <= null", "true");
foldSame("null < 0"); // foldable
fold("null > true", "false");
foldSame("null >= 'hi'"); // foldable
fold("null <= null", "true");
fold("null == null", "true");
fold("0 == null", "false");
fold("1 == null", "false");
fold("'hi' == null", "false");
fold("true == null", "false");
fold("false == null", "false");
fold("null === null", "true");
fold("void 0 === null", "false");
fold("null == NaN", "false");
fold("NaN == null", "false");
fold("null == Infinity", "false");
fold("Infinity == null", "false");
fold("null == -Infinity", "false");
fold("-Infinity == null", "false");
fold("({}) == null", "false");
fold("null == ({})", "false");
fold("([]) == null", "false");
fold("null == ([])", "false");
fold("(/a/g) == null", "false");
fold("null == (/a/g)", "false");
fold("(function(){}) == null", "false");
fold("null == (function(){})", "false");
fold("null != NaN", "true");
fold("NaN != null", "true");
fold("null != Infinity", "true");
fold("Infinity != null", "true");
fold("null != -Infinity", "true");
fold("-Infinity != null", "true");
fold("({}) != null", "true");
fold("null != ({})", "true");
fold("([]) != null", "true");
fold("null != ([])", "true");
fold("(/a/g) != null", "true");
fold("null != (/a/g)", "true");
fold("(function(){}) != null", "true");
fold("null != (function(){})", "true");
foldSame("({a:f()}) == null");
foldSame("null == ({a:f()})");
foldSame("([f()]) == null");
foldSame("null == ([f()])");
foldSame("this == null");
foldSame("x == null");
}
public void testUnaryOps() {
// These cases are handled by PeepholeRemoveDeadCode.
foldSame("!foo()");
foldSame("~foo()");
foldSame("-foo()");
// These cases are handled here.
fold("a=!true", "a=false");
fold("a=!10", "a=false");
fold("a=!false", "a=true");
fold("a=!foo()", "a=!foo()");
- fold("a=-0", "a=0");
+ fold("a=-0", "a=-0.0");
+ fold("a=-(0)", "a=-0.0");
fold("a=-Infinity", "a=-Infinity");
fold("a=-NaN", "a=NaN");
fold("a=-foo()", "a=-foo()");
fold("a=~~0", "a=0");
fold("a=~~10", "a=10");
fold("a=~-7", "a=6");
fold("a=+true", "a=1");
fold("a=+10", "a=10");
fold("a=+false", "a=0");
foldSame("a=+foo()");
foldSame("a=+f");
fold("a=+(f?true:false)", "a=+(f?1:0)"); // TODO(johnlenz): foldable
fold("a=+0", "a=0");
fold("a=+Infinity", "a=Infinity");
fold("a=+NaN", "a=NaN");
fold("a=+-7", "a=-7");
fold("a=+.5", "a=.5");
fold("a=~0x100000000", "a=~0x100000000",
PeepholeFoldConstants.BITWISE_OPERAND_OUT_OF_RANGE);
fold("a=~-0x100000000", "a=~-0x100000000",
PeepholeFoldConstants.BITWISE_OPERAND_OUT_OF_RANGE);
fold("a=~.5", "~.5", PeepholeFoldConstants.FRACTIONAL_BITWISE_OPERAND);
}
public void testUnaryOpsStringCompare() {
// Negatives are folded into a single number node.
assertResultString("a=-1", "a=-1");
assertResultString("a=~0", "a=-1");
assertResultString("a=~1", "a=-2");
assertResultString("a=~101", "a=-102");
}
public void testFoldLogicalOp() {
fold("x = true && x", "x = x");
foldSame("x = [foo()] && x");
fold("x = false && x", "x = false");
fold("x = true || x", "x = true");
fold("x = false || x", "x = x");
fold("x = 0 && x", "x = 0");
fold("x = 3 || x", "x = 3");
fold("x = false || 0", "x = 0");
// unfoldable, because the right-side may be the result
fold("a = x && true", "a=x&&true");
fold("a = x && false", "a=x&&false");
fold("a = x || 3", "a=x||3");
fold("a = x || false", "a=x||false");
fold("a = b ? c : x || false", "a=b?c:x||false");
fold("a = b ? x || false : c", "a=b?x||false:c");
fold("a = b ? c : x && true", "a=b?c:x&&true");
fold("a = b ? x && true : c", "a=b?x&&true:c");
// folded, but not here.
foldSame("a = x || false ? b : c");
foldSame("a = x && true ? b : c");
fold("x = foo() || true || bar()", "x = foo()||true");
fold("x = foo() || false || bar()", "x = foo()||bar()");
fold("x = foo() || true && bar()", "x = foo()||bar()");
fold("x = foo() || false && bar()", "x = foo()||false");
fold("x = foo() && false && bar()", "x = foo()&&false");
fold("x = foo() && true && bar()", "x = foo()&&bar()");
fold("x = foo() && false || bar()", "x = foo()&&false||bar()");
fold("1 && b()", "b()");
fold("a() && (1 && b())", "a() && b()");
// TODO(johnlenz): Consider folding the following to:
// "(a(),1) && b();
fold("(a() && 1) && b()", "(a() && 1) && b()");
// Really not foldable, because it would change the type of the
// expression if foo() returns something equivalent, but not
// identical, to true. Cf. FoldConstants.tryFoldAndOr().
foldSame("x = foo() && true || bar()");
foldSame("foo() && true || bar()");
}
public void testFoldBitwiseOp() {
fold("x = 1 & 1", "x = 1");
fold("x = 1 & 2", "x = 0");
fold("x = 3 & 1", "x = 1");
fold("x = 3 & 3", "x = 3");
fold("x = 1 | 1", "x = 1");
fold("x = 1 | 2", "x = 3");
fold("x = 3 | 1", "x = 3");
fold("x = 3 | 3", "x = 3");
fold("x = 1 ^ 1", "x = 0");
fold("x = 1 ^ 2", "x = 3");
fold("x = 3 ^ 1", "x = 2");
fold("x = 3 ^ 3", "x = 0");
fold("x = -1 & 0", "x = 0");
fold("x = 0 & -1", "x = 0");
fold("x = 1 & 4", "x = 0");
fold("x = 2 & 3", "x = 2");
// make sure we fold only when we are supposed to -- not when doing so would
// lose information or when it is performed on nonsensical arguments.
fold("x = 1 & 1.1", "x = 1");
fold("x = 1.1 & 1", "x = 1");
fold("x = 1 & 3000000000", "x = 0");
fold("x = 3000000000 & 1", "x = 0");
// Try some cases with | as well
fold("x = 1 | 4", "x = 5");
fold("x = 1 | 3", "x = 3");
fold("x = 1 | 1.1", "x = 1");
foldSame("x = 1 | 3E9");
fold("x = 1 | 3000000001", "x = -1294967295");
}
public void testFoldBitwiseOp2() {
fold("x = y & 1 & 1", "x = y & 1");
fold("x = y & 1 & 2", "x = y & 0");
fold("x = y & 3 & 1", "x = y & 1");
fold("x = 3 & y & 1", "x = y & 1");
fold("x = y & 3 & 3", "x = y & 3");
fold("x = 3 & y & 3", "x = y & 3");
fold("x = y | 1 | 1", "x = y | 1");
fold("x = y | 1 | 2", "x = y | 3");
fold("x = y | 3 | 1", "x = y | 3");
fold("x = 3 | y | 1", "x = y | 3");
fold("x = y | 3 | 3", "x = y | 3");
fold("x = 3 | y | 3", "x = y | 3");
fold("x = y ^ 1 ^ 1", "x = y ^ 0");
fold("x = y ^ 1 ^ 2", "x = y ^ 3");
fold("x = y ^ 3 ^ 1", "x = y ^ 2");
fold("x = 3 ^ y ^ 1", "x = y ^ 2");
fold("x = y ^ 3 ^ 3", "x = y ^ 0");
fold("x = 3 ^ y ^ 3", "x = y ^ 0");
fold("x = Infinity | NaN", "x=0");
fold("x = 12 | NaN", "x=12");
}
public void testFoldingMixTypesLate() {
late = true;
fold("x = x + '2'", "x+='2'");
fold("x = +x + +'2'", "x = +x + 2");
fold("x = x - '2'", "x-=2");
fold("x = x ^ '2'", "x^=2");
fold("x = '2' ^ x", "x^=2");
fold("x = '2' & x", "x&=2");
fold("x = '2' | x", "x|=2");
fold("x = '2' | y", "x=2|y");
fold("x = y | '2'", "x=y|2");
fold("x = y | (a && '2')", "x=y|(a&&2)");
fold("x = y | (a,'2')", "x=y|(a,2)");
fold("x = y | (a?'1':'2')", "x=y|(a?1:2)");
fold("x = y | ('x'?'1':'2')", "x=y|('x'?1:2)");
}
public void testFoldingMixTypesEarly() {
late = false;
foldSame("x = x + '2'");
fold("x = +x + +'2'", "x = +x + 2");
fold("x = x - '2'", "x = x - 2");
fold("x = x ^ '2'", "x = x ^ 2");
fold("x = '2' ^ x", "x = 2 ^ x");
fold("x = '2' & x", "x = 2 & x");
fold("x = '2' | x", "x = 2 | x");
fold("x = '2' | y", "x=2|y");
fold("x = y | '2'", "x=y|2");
fold("x = y | (a && '2')", "x=y|(a&&2)");
fold("x = y | (a,'2')", "x=y|(a,2)");
fold("x = y | (a?'1':'2')", "x=y|(a?1:2)");
fold("x = y | ('x'?'1':'2')", "x=y|('x'?1:2)");
}
public void testFoldingAdd() {
fold("x = null + true", "x=1");
foldSame("x = a + true");
}
public void testFoldBitwiseOpStringCompare() {
assertResultString("x = -1 | 0", "x=-1");
// EXPR_RESULT case is in in PeepholeIntegrationTest
}
public void testFoldBitShifts() {
fold("x = 1 << 0", "x = 1");
fold("x = -1 << 0", "x = -1");
fold("x = 1 << 1", "x = 2");
fold("x = 3 << 1", "x = 6");
fold("x = 1 << 8", "x = 256");
fold("x = 1 >> 0", "x = 1");
fold("x = -1 >> 0", "x = -1");
fold("x = 1 >> 1", "x = 0");
fold("x = 2 >> 1", "x = 1");
fold("x = 5 >> 1", "x = 2");
fold("x = 127 >> 3", "x = 15");
fold("x = 3 >> 1", "x = 1");
fold("x = 3 >> 2", "x = 0");
fold("x = 10 >> 1", "x = 5");
fold("x = 10 >> 2", "x = 2");
fold("x = 10 >> 5", "x = 0");
fold("x = 10 >>> 1", "x = 5");
fold("x = 10 >>> 2", "x = 2");
fold("x = 10 >>> 5", "x = 0");
fold("x = -1 >>> 1", "x = 2147483647"); // 0x7fffffff
fold("x = -1 >>> 0", "x = 4294967295"); // 0xffffffff
fold("x = -2 >>> 0", "x = 4294967294"); // 0xfffffffe
fold("3000000000 << 1", "3000000000<<1",
PeepholeFoldConstants.BITWISE_OPERAND_OUT_OF_RANGE);
fold("1 << 32", "1<<32",
PeepholeFoldConstants.SHIFT_AMOUNT_OUT_OF_BOUNDS);
fold("1 << -1", "1<<32",
PeepholeFoldConstants.SHIFT_AMOUNT_OUT_OF_BOUNDS);
fold("3000000000 >> 1", "3000000000>>1",
PeepholeFoldConstants.BITWISE_OPERAND_OUT_OF_RANGE);
fold("1 >> 32", "1>>32",
PeepholeFoldConstants.SHIFT_AMOUNT_OUT_OF_BOUNDS);
fold("1.5 << 0", "1.5<<0",
PeepholeFoldConstants.FRACTIONAL_BITWISE_OPERAND);
fold("1 << .5", "1.5<<0",
PeepholeFoldConstants.FRACTIONAL_BITWISE_OPERAND);
fold("1.5 >>> 0", "1.5>>>0",
PeepholeFoldConstants.FRACTIONAL_BITWISE_OPERAND);
fold("1 >>> .5", "1.5>>>0",
PeepholeFoldConstants.FRACTIONAL_BITWISE_OPERAND);
fold("1.5 >> 0", "1.5>>0",
PeepholeFoldConstants.FRACTIONAL_BITWISE_OPERAND);
fold("1 >> .5", "1.5>>0",
PeepholeFoldConstants.FRACTIONAL_BITWISE_OPERAND);
}
public void testFoldBitShiftsStringCompare() {
// Negative numbers.
assertResultString("x = -1 << 1", "x=-2");
assertResultString("x = -1 << 8", "x=-256");
assertResultString("x = -1 >> 1", "x=-1");
assertResultString("x = -2 >> 1", "x=-1");
assertResultString("x = -1 >> 0", "x=-1");
}
public void testStringAdd() {
fold("x = 'a' + \"bc\"", "x = \"abc\"");
fold("x = 'a' + 5", "x = \"a5\"");
fold("x = 5 + 'a'", "x = \"5a\"");
fold("x = 'a' + ''", "x = \"a\"");
fold("x = \"a\" + foo()", "x = \"a\"+foo()");
fold("x = foo() + 'a' + 'b'", "x = foo()+\"ab\"");
fold("x = (foo() + 'a') + 'b'", "x = foo()+\"ab\""); // believe it!
fold("x = foo() + 'a' + 'b' + 'cd' + bar()", "x = foo()+\"abcd\"+bar()");
fold("x = foo() + 2 + 'b'", "x = foo()+2+\"b\""); // don't fold!
fold("x = foo() + 'a' + 2", "x = foo()+\"a2\"");
fold("x = '' + null", "x = \"null\"");
fold("x = true + '' + false", "x = \"truefalse\"");
fold("x = '' + []", "x = ''"); // cannot fold (but nice if we can)
}
public void testFoldConstructor() {
fold("x = this[new String('a')]", "x = this['a']");
fold("x = ob[new String(12)]", "x = ob['12']");
fold("x = ob[new String(false)]", "x = ob['false']");
fold("x = ob[new String(null)]", "x = ob['null']");
fold("x = 'a' + new String('b')", "x = 'ab'");
fold("x = 'a' + new String(23)", "x = 'a23'");
fold("x = 2 + new String(1)", "x = '21'");
foldSame("x = ob[new String(a)]");
foldSame("x = new String('a')");
foldSame("x = (new String('a'))[3]");
}
public void testFoldArithmetic() {
fold("x = 10 + 20", "x = 30");
fold("x = 2 / 4", "x = 0.5");
fold("x = 2.25 * 3", "x = 6.75");
fold("z = x * y", "z = x * y");
fold("x = y * 5", "x = y * 5");
fold("x = 1 / 0", "x = 1 / 0");
fold("x = 3 % 2", "x = 1");
fold("x = 3 % -2", "x = 1");
fold("x = -1 % 3", "x = -1");
fold("x = 1 % 0", "x = 1 % 0");
}
public void testFoldArithmetic2() {
foldSame("x = y + 10 + 20");
foldSame("x = y / 2 / 4");
fold("x = y * 2.25 * 3", "x = y * 6.75");
fold("z = x * y", "z = x * y");
fold("x = y * 5", "x = y * 5");
fold("x = y + (z * 24 * 60 * 60 * 1000)", "x = y + z * 864E5");
}
public void testFoldArithmetic3() {
fold("x = null * undefined", "x = NaN");
fold("x = null * 1", "x = 0");
fold("x = (null - 1) * 2", "x = -2");
fold("x = (null + 1) * 2", "x = 2");
}
public void testFoldArithmeticInfinity() {
fold("x=-Infinity-2", "x=-Infinity");
fold("x=Infinity-2", "x=Infinity");
fold("x=Infinity*5", "x=Infinity");
}
public void testFoldArithmeticStringComp() {
// Negative Numbers.
assertResultString("x = 10 - 20", "x=-10");
}
public void testFoldComparison() {
fold("x = 0 == 0", "x = true");
fold("x = 1 == 2", "x = false");
fold("x = 'abc' == 'def'", "x = false");
fold("x = 'abc' == 'abc'", "x = true");
fold("x = \"\" == ''", "x = true");
fold("x = foo() == bar()", "x = foo()==bar()");
fold("x = 1 != 0", "x = true");
fold("x = 'abc' != 'def'", "x = true");
fold("x = 'a' != 'a'", "x = false");
fold("x = 1 < 20", "x = true");
fold("x = 3 < 3", "x = false");
fold("x = 10 > 1.0", "x = true");
fold("x = 10 > 10.25", "x = false");
fold("x = y == y", "x = y==y");
fold("x = y < y", "x = false");
fold("x = y > y", "x = false");
fold("x = 1 <= 1", "x = true");
fold("x = 1 <= 0", "x = false");
fold("x = 0 >= 0", "x = true");
fold("x = -1 >= 9", "x = false");
fold("x = true == true", "x = true");
fold("x = false == false", "x = true");
fold("x = false == null", "x = false");
fold("x = false == true", "x = false");
fold("x = true == null", "x = false");
fold("0 == 0", "true");
fold("1 == 2", "false");
fold("'abc' == 'def'", "false");
fold("'abc' == 'abc'", "true");
fold("\"\" == ''", "true");
foldSame("foo() == bar()");
fold("1 != 0", "true");
fold("'abc' != 'def'", "true");
fold("'a' != 'a'", "false");
fold("1 < 20", "true");
fold("3 < 3", "false");
fold("10 > 1.0", "true");
fold("10 > 10.25", "false");
foldSame("x == x");
fold("x < x", "false");
fold("x > x", "false");
fold("1 <= 1", "true");
fold("1 <= 0", "false");
fold("0 >= 0", "true");
fold("-1 >= 9", "false");
fold("true == true", "true");
fold("false == null", "false");
fold("false == true", "false");
fold("true == null", "false");
}
// ===, !== comparison tests
public void testFoldComparison2() {
fold("x = 0 === 0", "x = true");
fold("x = 1 === 2", "x = false");
fold("x = 'abc' === 'def'", "x = false");
fold("x = 'abc' === 'abc'", "x = true");
fold("x = \"\" === ''", "x = true");
fold("x = foo() === bar()", "x = foo()===bar()");
fold("x = 1 !== 0", "x = true");
fold("x = 'abc' !== 'def'", "x = true");
fold("x = 'a' !== 'a'", "x = false");
fold("x = y === y", "x = y===y");
fold("x = true === true", "x = true");
fold("x = false === false", "x = true");
fold("x = false === null", "x = false");
fold("x = false === true", "x = false");
fold("x = true === null", "x = false");
fold("0 === 0", "true");
fold("1 === 2", "false");
fold("'abc' === 'def'", "false");
fold("'abc' === 'abc'", "true");
fold("\"\" === ''", "true");
foldSame("foo() === bar()");
// TODO(johnlenz): It would be nice to handle these cases as well.
foldSame("1 === '1'");
foldSame("1 === true");
foldSame("1 !== '1'");
foldSame("1 !== true");
fold("1 !== 0", "true");
fold("'abc' !== 'def'", "true");
fold("'a' !== 'a'", "false");
foldSame("x === x");
fold("true === true", "true");
fold("false === null", "false");
fold("false === true", "false");
fold("true === null", "false");
}
public void testFoldComparison3() {
fold("x = !1 == !0", "x = false");
fold("x = !0 == !0", "x = true");
fold("x = !1 == !1", "x = true");
fold("x = !1 == null", "x = false");
fold("x = !1 == !0", "x = false");
fold("x = !0 == null", "x = false");
fold("!0 == !0", "true");
fold("!1 == null", "false");
fold("!1 == !0", "false");
fold("!0 == null", "false");
fold("x = !0 === !0", "x = true");
fold("x = !1 === !1", "x = true");
fold("x = !1 === null", "x = false");
fold("x = !1 === !0", "x = false");
fold("x = !0 === null", "x = false");
fold("!0 === !0", "true");
fold("!1 === null", "false");
fold("!1 === !0", "false");
fold("!0 === null", "false");
}
public void testFoldGetElem() {
fold("x = [,10][0]", "x = void 0");
fold("x = [10, 20][0]", "x = 10");
fold("x = [10, 20][1]", "x = 20");
fold("x = [10, 20][0.5]", "",
PeepholeFoldConstants.INVALID_GETELEM_INDEX_ERROR);
fold("x = [10, 20][-1]", "",
PeepholeFoldConstants.INDEX_OUT_OF_BOUNDS_ERROR);
fold("x = [10, 20][2]", "",
PeepholeFoldConstants.INDEX_OUT_OF_BOUNDS_ERROR);
}
public void testFoldComplex() {
fold("x = (3 / 1.0) + (1 * 2)", "x = 5");
fold("x = (1 == 1.0) && foo() && true", "x = foo()&&true");
fold("x = 'abc' + 5 + 10", "x = \"abc510\"");
}
public void testFoldLeft() {
foldSame("(+x - 1) + 2"); // not yet
fold("(+x + 1) + 2", "+x + 3");
}
public void testFoldArrayLength() {
// Can fold
fold("x = [].length", "x = 0");
fold("x = [1,2,3].length", "x = 3");
fold("x = [a,b].length", "x = 2");
// Not handled yet
fold("x = [,,1].length", "x = 3");
// Cannot fold
fold("x = [foo(), 0].length", "x = [foo(),0].length");
fold("x = y.length", "x = y.length");
}
public void testFoldStringLength() {
// Can fold basic strings.
fold("x = ''.length", "x = 0");
fold("x = '123'.length", "x = 3");
// Test unicode escapes are accounted for.
fold("x = '123\u01dc'.length", "x = 4");
}
public void testFoldTypeof() {
fold("x = typeof 1", "x = \"number\"");
fold("x = typeof 'foo'", "x = \"string\"");
fold("x = typeof true", "x = \"boolean\"");
fold("x = typeof false", "x = \"boolean\"");
fold("x = typeof null", "x = \"object\"");
fold("x = typeof undefined", "x = \"undefined\"");
fold("x = typeof void 0", "x = \"undefined\"");
fold("x = typeof []", "x = \"object\"");
fold("x = typeof [1]", "x = \"object\"");
fold("x = typeof [1,[]]", "x = \"object\"");
fold("x = typeof {}", "x = \"object\"");
fold("x = typeof function() {}", "x = 'function'");
foldSame("x = typeof[1,[foo()]]");
foldSame("x = typeof{bathwater:baby()}");
}
public void testFoldInstanceOf() {
// Non object types are never instances of anything.
fold("64 instanceof Object", "false");
fold("64 instanceof Number", "false");
fold("'' instanceof Object", "false");
fold("'' instanceof String", "false");
fold("true instanceof Object", "false");
fold("true instanceof Boolean", "false");
fold("!0 instanceof Object", "false");
fold("!0 instanceof Boolean", "false");
fold("false instanceof Object", "false");
fold("null instanceof Object", "false");
fold("undefined instanceof Object", "false");
fold("NaN instanceof Object", "false");
fold("Infinity instanceof Object", "false");
// Array and object literals are known to be objects.
fold("[] instanceof Object", "true");
fold("({}) instanceof Object", "true");
// These cases is foldable, but no handled currently.
foldSame("new Foo() instanceof Object");
// These would require type information to fold.
foldSame("[] instanceof Foo");
foldSame("({}) instanceof Foo");
fold("(function() {}) instanceof Object", "true");
// An unknown value should never be folded.
foldSame("x instanceof Foo");
}
public void testDivision() {
// Make sure the 1/3 does not expand to 0.333333
fold("print(1/3)", "print(1/3)");
// Decimal form is preferable to fraction form when strings are the
// same length.
fold("print(1/2)", "print(0.5)");
}
public void testAssignOpsLate() {
late = true;
fold("x=x+y", "x+=y");
foldSame("x=y+x");
fold("x=x*y", "x*=y");
fold("x=y*x", "x*=y");
fold("x.y=x.y+z", "x.y+=z");
foldSame("next().x = next().x + 1");
fold("x=x-y", "x-=y");
foldSame("x=y-x");
fold("x=x|y", "x|=y");
fold("x=y|x", "x|=y");
fold("x=x*y", "x*=y");
fold("x=y*x", "x*=y");
fold("x.y=x.y+z", "x.y+=z");
foldSame("next().x = next().x + 1");
// This is ok, really.
fold("({a:1}).a = ({a:1}).a + 1", "({a:1}).a = 2");
}
public void testAssignOpsEarly() {
late = false;
foldSame("x=x+y");
foldSame("x=y+x");
foldSame("x=x*y");
foldSame("x=y*x");
foldSame("x.y=x.y+z");
foldSame("next().x = next().x + 1");
foldSame("x=x-y");
foldSame("x=y-x");
foldSame("x=x|y");
foldSame("x=y|x");
foldSame("x=x*y");
foldSame("x=y*x");
foldSame("x.y=x.y+z");
foldSame("next().x = next().x + 1");
// This is ok, really.
fold("({a:1}).a = ({a:1}).a + 1", "({a:1}).a = 2");
}
public void testFoldAdd1() {
fold("x=false+1","x=1");
fold("x=true+1","x=2");
fold("x=1+false","x=1");
fold("x=1+true","x=2");
}
public void testFoldLiteralNames() {
foldSame("NaN == NaN");
foldSame("Infinity == Infinity");
foldSame("Infinity == NaN");
fold("undefined == NaN", "false");
fold("undefined == Infinity", "false");
foldSame("Infinity >= Infinity");
foldSame("NaN >= NaN");
}
public void testFoldLiteralsTypeMismatches() {
fold("true == true", "true");
fold("true == false", "false");
fold("true == null", "false");
fold("false == null", "false");
// relational operators convert its operands
fold("null <= null", "true"); // 0 = 0
fold("null >= null", "true");
fold("null > null", "false");
fold("null < null", "false");
fold("false >= null", "true"); // 0 = 0
fold("false <= null", "true");
fold("false > null", "false");
fold("false < null", "false");
fold("true >= null", "true"); // 1 > 0
fold("true <= null", "false");
fold("true > null", "true");
fold("true < null", "false");
fold("true >= false", "true"); // 1 > 0
fold("true <= false", "false");
fold("true > false", "true");
fold("true < false", "false");
}
public void testFoldLeftChildConcat() {
foldSame("x +5 + \"1\"");
fold("x+\"5\" + \"1\"", "x + \"51\"");
// fold("\"a\"+(c+\"b\")","\"a\"+c+\"b\"");
fold("\"a\"+(\"b\"+c)","\"ab\"+c");
}
public void testFoldLeftChildOp() {
fold("x * Infinity * 2", "x * Infinity");
foldSame("x - Infinity - 2"); // want "x-Infinity"
foldSame("x - 1 + Infinity");
foldSame("x - 2 + 1");
foldSame("x - 2 + 3");
foldSame("1 + x - 2 + 1");
foldSame("1 + x - 2 + 3");
foldSame("1 + x - 2 + 3 - 1");
foldSame("f(x)-0");
foldSame("x-0-0");
foldSame("x+2-2+2");
foldSame("x+2-2+2-2");
foldSame("x-2+2");
foldSame("x-2+2-2");
foldSame("x-2+2-2+2");
foldSame("1+x-0-NaN");
foldSame("1+f(x)-0-NaN");
foldSame("1+x-0+NaN");
foldSame("1+f(x)-0+NaN");
foldSame("1+x+NaN"); // unfoldable
foldSame("x+2-2"); // unfoldable
foldSame("x+2"); // nothing to do
foldSame("x-2"); // nothing to do
}
public void testFoldSimpleArithmeticOp() {
foldSame("x*NaN");
foldSame("NaN/y");
foldSame("f(x)-0");
foldSame("f(x)*1");
foldSame("1*f(x)");
foldSame("0+a+b");
foldSame("0-a-b");
foldSame("a+b-0");
foldSame("(1+x)*NaN");
foldSame("(1+f(x))*NaN"); // don't fold side-effects
}
public void testFoldLiteralsAsNumbers() {
fold("x/'12'","x/12");
fold("x/('12'+'6')", "x/126");
fold("true*x", "1*x");
fold("x/false", "x/0"); // should we add an error check? :)
}
public void testNotFoldBackToTrueFalse() {
late = false;
fold("!0", "true");
fold("!1", "false");
fold("!3", "false");
late = true;
foldSame("!0");
foldSame("!1");
fold("!3", "false");
foldSame("false");
foldSame("true");
}
public void testFoldBangConstants() {
fold("1 + !0", "2");
fold("1 + !1", "1");
fold("'a ' + !1", "'a false'");
fold("'a ' + !0", "'a true'");
}
public void testFoldMixed() {
fold("''+[1]", "'1'");
foldSame("false+[]"); // would like: "\"false\""
}
public void testFoldVoid() {
foldSame("void 0");
fold("void 1", "void 0");
fold("void x", "void 0");
fold("void x()", "void x()");
}
public void testObjectLiteral() {
test("(!{})", "false");
test("(!{a:1})", "false");
testSame("(!{a:foo()})");
testSame("(!{'a':foo()})");
}
public void testArrayLiteral() {
test("(![])", "false");
test("(![1])", "false");
test("(![a])", "false");
testSame("(![foo()])");
}
public void testIssue601() {
testSame("'\\v' == 'v'");
testSame("'v' == '\\v'");
testSame("'\\u000B' == '\\v'");
}
public void testFoldObjectLiteralRef1() {
// Leave extra side-effects in place
testSame("var x = ({a:foo(),b:bar()}).a");
testSame("var x = ({a:1,b:bar()}).a");
testSame("function f() { return {b:foo(), a:2}.a; }");
// on the LHS the object act as a temporary leave it in place.
testSame("({a:x}).a = 1");
test("({a:x}).a += 1", "({a:x}).a = x + 1");
testSame("({a:x}).a ++");
testSame("({a:x}).a --");
// functions can't reference the object through 'this'.
testSame("({a:function(){return this}}).a");
testSame("({get a() {return this}}).a");
testSame("({set a(b) {return this}}).a");
// Leave unknown props alone, the might be on the prototype
testSame("({}).a");
// setters by themselves don't provide a definition
testSame("({}).a");
testSame("({set a(b) {}}).a");
// sets don't hide other definitions.
test("({a:1,set a(b) {}}).a", "1");
// get is transformed to a call (gets don't have self referential names)
test("({get a() {}}).a", "(function (){})()");
// sets don't hide other definitions.
test("({get a() {},set a(b) {}}).a", "(function (){})()");
// a function remains a function not a call.
test("var x = ({a:function(){return 1}}).a",
"var x = function(){return 1}");
test("var x = ({a:1}).a", "var x = 1");
test("var x = ({a:1, a:2}).a", "var x = 2");
test("var x = ({a:1, a:foo()}).a", "var x = foo()");
test("var x = ({a:foo()}).a", "var x = foo()");
test("function f() { return {a:1, b:2}.a; }",
"function f() { return 1; }");
// GETELEM is handled the same way.
test("var x = ({'a':1})['a']", "var x = 1");
}
public void testFoldObjectLiteralRef2() {
late = false;
test("({a:x}).a += 1", "({a:x}).a = x + 1");
late = true;
testSame("({a:x}).a += 1");
}
public void testIEString() {
testSame("!+'\\v1'");
}
public void testIssue522() {
testSame("[][1] = 1;");
}
private static final List<String> LITERAL_OPERANDS =
ImmutableList.of(
"null",
"undefined",
"void 0",
"true",
"false",
"!0",
"!1",
"0",
"1",
"''",
"'123'",
"'abc'",
"'def'",
"NaN",
"Infinity"
// TODO(nicksantos): Add more literals
// "-Infinity",
//"({})",
// "[]"
//"[0]",
//"Object",
//"(function() {})"
);
public void testInvertibleOperators() {
Map<String, String> inverses = ImmutableMap.<String, String>builder()
.put("==", "!=")
.put("===", "!==")
.put("<=", ">")
.put("<", ">=")
.put(">=", "<")
.put(">", "<=")
.put("!=", "==")
.put("!==", "===")
.build();
Set<String> comparators = ImmutableSet.of("<=", "<", ">=", ">");
Set<String> equalitors = ImmutableSet.of("==", "===");
Set<String> uncomparables = ImmutableSet.of("undefined", "void 0");
List<String> operators = ImmutableList.copyOf(inverses.values());
for (int iOperandA = 0; iOperandA < LITERAL_OPERANDS.size(); iOperandA++) {
for (int iOperandB = 0;
iOperandB < LITERAL_OPERANDS.size();
iOperandB++) {
for (int iOp = 0; iOp < operators.size(); iOp++) {
String a = LITERAL_OPERANDS.get(iOperandA);
String b = LITERAL_OPERANDS.get(iOperandB);
String op = operators.get(iOp);
String inverse = inverses.get(op);
// Test invertability.
if (comparators.contains(op) &&
(uncomparables.contains(a) || uncomparables.contains(b))) {
assertSameResults(join(a, op, b), "false");
assertSameResults(join(a, inverse, b), "false");
} else if (a.equals(b) && equalitors.contains(op)) {
if (a.equals("NaN") || a.equals("Infinity")) {
foldSame(join(a, op, b));
foldSame(join(a, inverse, b));
} else {
assertSameResults(join(a, op, b), "true");
assertSameResults(join(a, inverse, b), "false");
}
} else {
assertNotSameResults(join(a, op, b), join(a, inverse, b));
}
}
}
}
}
public void testCommutativeOperators() {
late = true;
List<String> operators =
ImmutableList.of(
"==",
"!=",
"===",
"!==",
"*",
"|",
"&",
"^");
for (int iOperandA = 0; iOperandA < LITERAL_OPERANDS.size(); iOperandA++) {
for (int iOperandB = iOperandA;
iOperandB < LITERAL_OPERANDS.size();
iOperandB++) {
for (int iOp = 0; iOp < operators.size(); iOp++) {
String a = LITERAL_OPERANDS.get(iOperandA);
String b = LITERAL_OPERANDS.get(iOperandB);
String op = operators.get(iOp);
// Test commutativity.
// TODO(nicksantos): Eventually, all cases should be collapsed.
assertSameResultsOrUncollapsed(join(a, op, b), join(b, op, a));
}
}
}
}
private String join(String operandA, String op, String operandB) {
return operandA + " " + op + " " + operandB;
}
private void assertSameResultsOrUncollapsed(String exprA, String exprB) {
String resultA = process(exprA);
String resultB = process(exprB); // TODO: why is nothing done with this?
if (resultA.equals(print(exprA))) {
foldSame(exprA);
foldSame(exprB);
} else {
assertSameResults(exprA, exprB);
}
}
private void assertSameResults(String exprA, String exprB) {
assertEquals(
"Expressions did not fold the same\nexprA: " +
exprA + "\nexprB: " + exprB,
process(exprA), process(exprB));
}
private void assertNotSameResults(String exprA, String exprB) {
assertFalse(
"Expressions folded the same\nexprA: " +
exprA + "\nexprB: " + exprB,
process(exprA).equals(process(exprB)));
}
private String process(String js) {
return printHelper(js, true);
}
private String print(String js) {
return printHelper(js, false);
}
private String printHelper(String js, boolean runProcessor) {
Compiler compiler = createCompiler();
CompilerOptions options = getOptions();
compiler.init(
new JSSourceFile[] {},
new JSSourceFile[] { JSSourceFile.fromCode("testcode", js) },
options);
Node root = compiler.parseInputs();
assertTrue("Unexpected parse error(s): " +
Joiner.on("\n").join(compiler.getErrors()) +
"\nEXPR: " + js,
root != null);
Node externsRoot = root.getFirstChild();
Node mainRoot = externsRoot.getNext();
if (runProcessor) {
getProcessor(compiler).process(externsRoot, mainRoot);
}
return compiler.toSource(mainRoot);
}
}
| false | false | null | null |
diff --git a/Libraries/ReikaPacketHelper.java b/Libraries/ReikaPacketHelper.java
index a412d102..65b11241 100644
--- a/Libraries/ReikaPacketHelper.java
+++ b/Libraries/ReikaPacketHelper.java
@@ -1,207 +1,208 @@
/*******************************************************************************
* @author Reika Kalseki
*
* Copyright 2013
*
* All rights reserved.
* Distribution of the software in any form is only allowed with
* explicit, prior permission from the owner.
******************************************************************************/
package Reika.DragonAPI.Libraries;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.util.List;
import net.minecraft.client.entity.EntityClientPlayerMP;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.network.packet.Packet;
import net.minecraft.network.packet.Packet250CustomPayload;
import net.minecraft.tileentity.TileEntity;
import Reika.DragonAPI.DragonAPICore;
import Reika.DragonAPI.Auxiliary.PacketTypes;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.network.PacketDispatcher;
import cpw.mods.fml.relauncher.Side;
public final class ReikaPacketHelper extends DragonAPICore {
public static void sendDataPacket(String ch, int id, TileEntity te, EntityPlayer player, List<Integer> data) {
int x = te.xCoord;
int y = te.yCoord;
int z = te.zCoord;
String name = te.getBlockType().getLocalizedName();
int npars;
if (data == null)
npars = 4;
else
npars = data.size()+4;
ByteArrayOutputStream bos = new ByteArrayOutputStream(npars*4); //4 bytes an int
DataOutputStream outputStream = new DataOutputStream(bos);
try {
outputStream.writeInt(PacketTypes.DATA.ordinal());
outputStream.writeInt(id);
if (data != null)
for (int i = 0; i < data.size(); i++) {
outputStream.writeInt(data.get(i));
}
outputStream.writeInt(x);
outputStream.writeInt(y);
outputStream.writeInt(z);
}
catch (Exception ex) {
ex.printStackTrace();
throw new RuntimeException("TileEntity "+name+" threw a packet exception! Null data: "+(data == null)+"; Npars: "+npars);
}
Packet250CustomPayload packet = new Packet250CustomPayload();
packet.channel = ch;
packet.data = bos.toByteArray();
packet.length = bos.size();
Side side = FMLCommonHandler.instance().getEffectiveSide();
if (side == Side.SERVER) {
// We are on the server side.
EntityPlayerMP player2 = (EntityPlayerMP) player;
PacketDispatcher.sendPacketToServer(packet);
PacketDispatcher.sendPacketToAllInDimension(packet, te.worldObj.provider.dimensionId);
}
else if (side == Side.CLIENT) {
// We are on the client side.
EntityClientPlayerMP player2 = (EntityClientPlayerMP) player;
PacketDispatcher.sendPacketToServer(packet);
+ //PacketDispatcher.sendPacketToAllInDimension(packet, te.worldObj.provider.dimensionId);
}
else {
// We are on the Bukkit server.
}
}
public static void sendLongDataPacket(String ch, int id, TileEntity te, EntityPlayer player, List<Long> data) {
int x = te.xCoord;
int y = te.yCoord;
int z = te.zCoord;
String name = te.getBlockType().getLocalizedName();
int npars;
if (data == null)
npars = 4;
else
npars = data.size()+4;
ByteArrayOutputStream bos = new ByteArrayOutputStream(((npars-4)*8)+2*4); //4 bytes an int + 8 bytes a long
DataOutputStream outputStream = new DataOutputStream(bos);
try {
outputStream.writeInt(PacketTypes.DATA.ordinal());
outputStream.writeInt(id);
if (data != null)
for (int i = 0; i < data.size(); i++) {
outputStream.writeLong(data.get(i));
}
outputStream.writeInt(x);
outputStream.writeInt(y);
outputStream.writeInt(z);
}
catch (Exception ex) {
ex.printStackTrace();
throw new RuntimeException("TileEntity "+name+" threw a long packet exception! Null data: "+(data == null)+"; Npars: "+npars);
}
Packet250CustomPayload packet = new Packet250CustomPayload();
packet.channel = ch;
packet.data = bos.toByteArray();
packet.length = bos.size();
Side side = FMLCommonHandler.instance().getEffectiveSide();
if (side == Side.SERVER) {
// We are on the server side.
EntityPlayerMP player2 = (EntityPlayerMP) player;
}
else if (side == Side.CLIENT) {
// We are on the client side.
EntityClientPlayerMP player2 = (EntityClientPlayerMP) player;
PacketDispatcher.sendPacketToServer(packet);
}
else {
// We are on the Bukkit server.
}
}
public static void sendDataPacket(String ch, int id, TileEntity te, EntityPlayer player, int data) {
sendDataPacket(ch, id, te, player, ReikaJavaLibrary.makeListFrom(data));
}
public static void sendLongDataPacket(String ch, int id, TileEntity te, EntityPlayer player, long data) {
sendLongDataPacket(ch, id, te, player, ReikaJavaLibrary.makeListFrom(data));
}
public static void sendDataPacket(String ch, int id, TileEntity te, EntityPlayer player, int data1, int data2) {
sendDataPacket(ch, id, te, player, ReikaJavaLibrary.makeListFromArray(new Object[]{data1, data2}));
}
public static void sendDataPacket(String ch, int id, TileEntity te, EntityPlayer player, int data1, int data2, int data3) {
sendDataPacket(ch, id, te, player, ReikaJavaLibrary.makeListFromArray(new Object[]{data1, data2, data3}));
}
public static void sendDataPacket(String ch, int id, TileEntity te, EntityPlayer player, int data1, int data2, int data3, int data4) {
sendDataPacket(ch, id, te, player, ReikaJavaLibrary.makeListFromArray(new Object[]{data1, data2, data3, data4}));
}
public static void sendDataPacket(String ch, int id, TileEntity te, EntityPlayer player, long data) {
sendLongDataPacket(ch, id, te, player, ReikaJavaLibrary.makeListFrom(data));
}
public static void sendDataPacket(String ch, int id, TileEntity te, EntityPlayer player) {
sendDataPacket(ch, id, te, player, null);
}
public static void sendDataPacket(String ch, int id, TileEntity te) {
sendDataPacket(ch, id, te, null, null);
}
public static void sendSoundPacket(String ch, String path, double x, double y, double z, float vol, float pitch) {
int length = 0;
ByteArrayOutputStream bos = new ByteArrayOutputStream(length);
DataOutputStream outputStream = new DataOutputStream(bos);
try {
outputStream.writeInt(PacketTypes.SOUND.ordinal());
Packet.writeString(path, outputStream);
outputStream.writeDouble(x);
outputStream.writeDouble(y);
outputStream.writeDouble(z);
outputStream.writeFloat(vol);
outputStream.writeFloat(pitch);
}
catch (Exception ex) {
ex.printStackTrace();
throw new RuntimeException("Sound Packet for "+path+" threw a packet exception!");
}
Packet250CustomPayload packet = new Packet250CustomPayload();
packet.channel = ch;
packet.data = bos.toByteArray();
packet.length = bos.size();
Side side = FMLCommonHandler.instance().getEffectiveSide();
if (side == Side.SERVER) {
// We are on the server side.
//EntityPlayerMP player2 = (EntityPlayerMP) player;
PacketDispatcher.sendPacketToAllPlayers(packet);
}
else if (side == Side.CLIENT) {
// We are on the client side.
//EntityClientPlayerMP player2 = (EntityClientPlayerMP) player;
//PacketDispatcher.sendPacketToServer(packet);
}
else {
// We are on the Bukkit server.
}
}
}
diff --git a/Libraries/ReikaWorldHelper.java b/Libraries/ReikaWorldHelper.java
index 0f65921d..d9af0e88 100644
--- a/Libraries/ReikaWorldHelper.java
+++ b/Libraries/ReikaWorldHelper.java
@@ -1,1226 +1,1230 @@
/*******************************************************************************
* @author Reika Kalseki
*
* Copyright 2013
*
* All rights reserved.
* Distribution of the software in any form is only allowed with
* explicit, prior permission from the owner.
******************************************************************************/
package Reika.DragonAPI.Libraries;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.entity.Entity;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.item.EntityXPOrb;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.util.MathHelper;
import net.minecraft.util.MovingObjectPosition;
import net.minecraft.util.Vec3;
import net.minecraft.world.World;
import net.minecraft.world.biome.BiomeGenBase;
import Reika.DragonAPI.DragonAPICore;
import Reika.DragonAPI.Auxiliary.BlockProperties;
public final class ReikaWorldHelper extends DragonAPICore {
public static boolean softBlocks(int id) {
BlockProperties.setSoft();
return (BlockProperties.softBlocksArray[id]);
}
public static boolean flammable(int id) {
BlockProperties.setFlammable();
return (BlockProperties.flammableArray[id]);
}
public static boolean nonSolidBlocks(int id) {
BlockProperties.setNonSolid();
return (BlockProperties.nonSolidArray[id]);
}
/** Converts the given block ID to a hex color. Renders ores (or disguises as stone) as requested.
* Args: Block ID, Ore Rendering */
public static int blockColors(int id, boolean renderOres) {
BlockProperties.setBlockColors(renderOres);
if (BlockProperties.blockColorArray[id] == 0)
return 0xffD47EFF;
return BlockProperties.blockColorArray[id];
}
/** Converts the given coordinates to an RGB representation of those coordinates' biome's color, for the given material type.
* Args: World, x, z, material (String) */
public static int[] biomeToRGB(World world, int x, int z, String material) {
BiomeGenBase biome = world.getBiomeGenForCoords(x, z);
int color = ReikaWorldHelper.biomeToHex(biome, material);
return ReikaGuiAPI.HexToRGB(color);
}
/** Converts the given coordinates to a hex representation of those coordinates' biome's color, for the given material type.
* Args: World, x, z, material (String) */
public static int biomeToHexColor(World world, int x, int z, String material) {
BiomeGenBase biome = world.getBiomeGenForCoords(x, z);
int color = ReikaWorldHelper.biomeToHex(biome, material);
return color;
}
private static int biomeToHex(BiomeGenBase biome, String mat) {
int color = 0;
if (mat == "Leaves")
color = biome.getBiomeFoliageColor();
if (mat == "Grass")
color = biome.getBiomeGrassColor();
if (mat == "Water")
color = biome.getWaterColorMultiplier();
if (mat == "Sky")
color = biome.getSkyColorByTemp(biome.getIntTemperature());
return color;
}
/** Caps the metadata at a certain value (eg, for leaves, metas are from 0-11, but there are only 4 types, and each type has 3 metas).
* Args: Initial metadata, cap (# of types) */
public static int capMetadata(int meta, int cap) {
while (meta >= cap)
meta -= cap;
return meta;
}
/** Finds the top edge of the top solid (nonair) block in the column. Args: World, this.x,y,z */
public static double findSolidSurface(World world, double x, double y, double z) { //Returns double y-coord of top surface of top block
int xp = (int)x;
int zp = (int)z;
boolean lowestsolid = false;
boolean solidup = false;
boolean soliddown = false;
while (!(!solidup && soliddown)) {
solidup = (world.getBlockMaterial(xp, (int)y, zp) != Material.air);
soliddown = (world.getBlockMaterial(xp, (int)y-1, zp) != Material.air);
if (solidup && soliddown) //Both blocks are solid -> below surface
y++;
if (solidup && !soliddown) //Upper only is solid -> should never happen
y += 2; // Fix attempt
if (!solidup && soliddown) // solid lower only
; // the case we want
if (!solidup && !soliddown) //Neither solid -> above surface
y--;
}
return y;
}
/** Finds the top edge of the top water block in the column. Args: World, this.x,y,z */
public static double findWaterSurface(World world, double x, double y, double z) { //Returns double y-coord of top surface of top block
int xp = (int)x;
int zp = (int)z;
boolean lowestwater = false;
boolean waterup = false;
boolean waterdown = false;
while (!(!waterup && waterdown)) {
waterup = (world.getBlockMaterial(xp, (int)y, zp) == Material.water);
waterdown = (world.getBlockMaterial(xp, (int)y-1, zp) == Material.water);
if (waterup && waterdown) //Both blocks are water -> below surface
y++;
if (waterup && !waterdown) //Upper only is water -> should never happen
return 255; //Return top of chunk and exit function
if (!waterup && waterdown) // Water lower only
; // the case we want
if (!waterup && !waterdown) //Neither water -> above surface
y--;
}
return y;
}
/** Search for a specific block in a range. Returns true if found. Cannot identify if
* found more than one, or where the found one(s) is/are. May be CPU-intensive. Args: World, this.x,y,z, search range, target id */
public static boolean findNearBlock(World world, int x, int y, int z, int range, int id) {
x -= range/2;
y -= range/2;
z -= range/2;
for (int i = 0; i < range; i++) {
for (int j = 0; j < range; j++) {
for (int k = 0; k < range; k++) {
if (world.getBlockId(x+i, y+j, z+k) == id)
return true;
}
}
}
return false;
}
/** Search for a specific block in a range. Returns number found. Cannot identify where they
* are. May be CPU-intensive. Args: World, this.x,y,z, search range, target id */
public static int findNearBlocks(World world, int x, int y, int z, int range, int id) {
int count = 0;
x -= range/2;
y -= range/2;
z -= range/2;
for (int i = 0; i < range; i++) {
for (int j = 0; j < range; j++) {
for (int k = 0; k < range; k++) {
if (world.getBlockId(x+i, y+j, z+k) == id)
count++;
}
}
}
return count;
}
/** Tests for if a block of a certain id is in the "sights" of a directional block (eg dispenser).
* Returns the number of blocks away it is. If not found, returns 0 (an impossibility).
* Args: World, this.x,y,z, search range, target id, direction "f" */
public static int isLookingAt(World world, int x, int y, int z, int range, int id, int f) {
int idfound = 0;
switch (f) {
case 0: //facing north (-z);
for (int i = 0; i < range; i++) {
idfound = world.getBlockId(x, y, z-i);
if (idfound == id)
return i;
}
break;
case 1: //facing east (-x);
for (int i = 0; i < range; i++) {
idfound = world.getBlockId(x-i, y, z);
if (idfound == id)
return i;
}
break;
case 2: //facing south (+z);
for (int i = 0; i < range; i++) {
idfound = world.getBlockId(x, y, z+i);
if (idfound == id)
return i;
}
break;
case 3: //facing west (+x);
for (int i = 0; i < range; i++) {
idfound = world.getBlockId(x+i, y, z);
if (idfound == id)
return i;
}
break;
}
return 0;
}
/** Returns the direction in which a block of the specified ID was found.
* Returns -1 if not found. Args: World, x,y,z, id to search.
* Convention: 0 up 1 down 2 x+ 3 x- 4 z+ 5 z- */
public static int checkForAdjBlock(World world, int x, int y, int z, int id) {
if (world.getBlockId(x,y+1,z) == id)
return 0;
if (world.getBlockId(x,y-1,z) == id)
return 1;
if (world.getBlockId(x+1,y,z) == id)
return 2;
if (world.getBlockId(x-1,y,z) == id)
return 3;
if (world.getBlockId(x,y,z+1) == id)
return 4;
if (world.getBlockId(x,y,z-1) == id)
return 5;
return -1;
}
/** Returns the direction in which a block of the specified material was found.
* Returns -1 if not found. Args: World, x,y,z, material to search.
* Convention: 0 up 1 down 2 x+ 3 x- 4 z+ 5 z- */
public static int checkForAdjMaterial(World world, int x, int y, int z, Material mat) {
if (world.getBlockMaterial(x,y+1,z) == mat)
return 0;
if (world.getBlockMaterial(x,y-1,z) == mat)
return 1;
if (world.getBlockMaterial(x+1,y,z) == mat)
return 2;
if (world.getBlockMaterial(x-1,y,z) == mat)
return 3;
if (world.getBlockMaterial(x,y,z+1) == mat)
return 4;
if (world.getBlockMaterial(x,y,z-1) == mat)
return 5;
return -1;
}
/** Returns the direction in which a source block of the specified liquid was found.
* Returns -1 if not found. Args: World, x,y,z, material (water/lava) to search.
* Convention: 0 up 1 down 2 x+ 3 x- 4 z+ 5 z- */
public static int checkForAdjSourceBlock(World world, int x, int y, int z, Material mat) {
if (world.getBlockMaterial(x, y+1, z) == mat && world.getBlockMetadata(x, y+1, z) == 0)
return 0;
if (world.getBlockMaterial(x, y-1, z) == mat && world.getBlockMetadata(x, y-1, z) == 0)
return 1;
if (world.getBlockMaterial(x+1, y, z) == mat && world.getBlockMetadata(x+1, y, z) == 0)
return 2;
if (world.getBlockMaterial(x-1, y, z) == mat && world.getBlockMetadata(x-1, y, z) == 0)
return 3;
if (world.getBlockMaterial(x, y, z+1) == mat && world.getBlockMetadata(x, y, z+1) == 0)
return 4;
if (world.getBlockMaterial(x, y, z-1) == mat && world.getBlockMetadata(x, y, z-1) == 0)
return 5;
return -1;
}
/** Edits a block adjacent to the passed arguments, on the specified side.
* Args: World, x, y, z, side, id to change to */
public static void changeAdjBlock(World world, int x, int y, int z, int side, int id) {
switch(side) {
case 0:
legacySetBlockWithNotify(world, x, y+1, z, id);
break;
case 1:
legacySetBlockWithNotify(world, x, y-1, z, id);
break;
case 2:
legacySetBlockWithNotify(world, x+1, y, z, id);
break;
case 3:
legacySetBlockWithNotify(world, x-1, y, z, id);
break;
case 4:
legacySetBlockWithNotify(world, x, y, z+1, id);
break;
case 5:
legacySetBlockWithNotify(world, x, y, z-1, id);
break;
}
}
/** Returns true if the passed biome is a snow biome. Args: Biome*/
public static boolean isSnowBiome(BiomeGenBase biome) {
if (biome == BiomeGenBase.frozenOcean)
return true;
if (biome == BiomeGenBase.frozenRiver)
return true;
if (biome == BiomeGenBase.iceMountains)
return true;
if (biome == BiomeGenBase.icePlains)
return true;
if (biome == BiomeGenBase.taiga)
return true;
if (biome == BiomeGenBase.taigaHills)
return true;
return false;
}
/** Returns true if the passed biome is a hot biome. Args: Biome*/
public static boolean isHotBiome(BiomeGenBase biome) {
if (biome == BiomeGenBase.desert)
return true;
if (biome == BiomeGenBase.desertHills)
return true;
if (biome == BiomeGenBase.hell)
return true;
if (biome == BiomeGenBase.jungle)
return true;
if (biome == BiomeGenBase.jungleHills)
return true;
return false;
}
/** Applies temperature effects to the environment. Args: World, x, y, z, temperature */
public static void temperatureEnvironment(World world, int x, int y, int z, int temperature) {
if (temperature < 0) {
for (int i = 0; i < 6; i++) {
int side = (ReikaWorldHelper.checkForAdjMaterial(world, x, y, z, Material.water));
if (side != -1)
ReikaWorldHelper.changeAdjBlock(world, x, y, z, side, Block.ice.blockID);
}
}
if (temperature > 450) { // Wood autoignition
for (int i = 0; i < 4; i++) {
if (world.getBlockMaterial(x-i, y, z) == Material.wood)
ignite(world, x-i, y, z);
if (world.getBlockMaterial(x+i, y, z) == Material.wood)
ignite(world, x+i, y, z);
if (world.getBlockMaterial(x, y-i, z) == Material.wood)
ignite(world, x, y-i, z);
if (world.getBlockMaterial(x, y+i, z) == Material.wood)
ignite(world, x, y+i, z);
if (world.getBlockMaterial(x, y, z-i) == Material.wood)
ignite(world, x, y, z-i);
if (world.getBlockMaterial(x, y, z+i) == Material.wood)
ignite(world, x, y, z+i);
}
}
if (temperature > 600) { // Wool autoignition
for (int i = 0; i < 4; i++) {
if (world.getBlockMaterial(x-i, y, z) == Material.cloth)
ignite(world, x-i, y, z);
if (world.getBlockMaterial(x+i, y, z) == Material.cloth)
ignite(world, x+i, y, z);
if (world.getBlockMaterial(x, y-i, z) == Material.cloth)
ignite(world, x, y-i, z);
if (world.getBlockMaterial(x, y+i, z) == Material.cloth)
ignite(world, x, y+i, z);
if (world.getBlockMaterial(x, y, z-i) == Material.cloth)
ignite(world, x, y, z-i);
if (world.getBlockMaterial(x, y, z+i) == Material.cloth)
ignite(world, x, y, z+i);
}
}
if (temperature > 300) { // TNT autoignition
for (int i = 0; i < 4; i++) {
if (world.getBlockMaterial(x-i, y, z) == Material.tnt)
ignite(world, x-i, y, z);
if (world.getBlockMaterial(x+i, y, z) == Material.tnt)
ignite(world, x+i, y, z);
if (world.getBlockMaterial(x, y-i, z) == Material.tnt)
ignite(world, x, y-i, z);
if (world.getBlockMaterial(x, y+i, z) == Material.tnt)
ignite(world, x, y+i, z);
if (world.getBlockMaterial(x, y, z-i) == Material.tnt)
ignite(world, x, y, z-i);
if (world.getBlockMaterial(x, y, z+i) == Material.tnt)
ignite(world, x, y, z+i);
}
}
if (temperature > 230) { // Grass/leaves/plant autoignition
for (int i = 0; i < 4; i++) {
if (world.getBlockMaterial(x-i, y, z) == Material.leaves || world.getBlockMaterial(x-i, y, z) == Material.vine || world.getBlockMaterial(x-i, y, z) == Material.plants || world.getBlockMaterial(x-i, y, z) == Material.web)
ignite(world, x-i, y, z);
if (world.getBlockMaterial(x+i, y, z) == Material.leaves || world.getBlockMaterial(x+i, y, z) == Material.vine || world.getBlockMaterial(x+i, y, z) == Material.plants || world.getBlockMaterial(x+i, y, z) == Material.web)
ignite(world, x+i, y, z);
if (world.getBlockMaterial(x, y-i, z) == Material.leaves || world.getBlockMaterial(x, y-i, z) == Material.vine || world.getBlockMaterial(x, y-i, z) == Material.plants || world.getBlockMaterial(x, y-i, z) == Material.web)
ignite(world, x, y-i, z);
if (world.getBlockMaterial(x, y+i, z) == Material.leaves || world.getBlockMaterial(x, y+i, z) == Material.vine || world.getBlockMaterial(x, y+i, z) == Material.plants || world.getBlockMaterial(x, y+i, z) == Material.web)
ignite(world, x, y+i, z);
if (world.getBlockMaterial(x, y, z-i) == Material.leaves || world.getBlockMaterial(x, y, z-i) == Material.vine || world.getBlockMaterial(x, y, z-i) == Material.plants || world.getBlockMaterial(x, y, z-i) == Material.web)
ignite(world, x, y, z-i);
if (world.getBlockMaterial(x, y, z+i) == Material.leaves || world.getBlockMaterial(x, y, z+i) == Material.vine || world.getBlockMaterial(x, y, z+i) == Material.plants || world.getBlockMaterial(x, y, z+i) == Material.web)
ignite(world, x, y, z+i);
}
}
if (temperature > 0) { // Melting snow/ice
for (int i = 0; i < 3; i++) {
if (world.getBlockMaterial(x-i, y, z) == Material.ice)
legacySetBlockWithNotify(world, x-i, y, z, Block.waterMoving.blockID);
if (world.getBlockMaterial(x+i, y, z) == Material.ice)
legacySetBlockWithNotify(world, x+i, y, z, Block.waterMoving.blockID);
if (world.getBlockMaterial(x, y-i, z) == Material.ice)
legacySetBlockWithNotify(world, x, y-i, z, Block.waterMoving.blockID);
if (world.getBlockMaterial(x, y+i, z) == Material.ice)
legacySetBlockWithNotify(world, x, y+i, z, Block.waterMoving.blockID);
if (world.getBlockMaterial(x, y, z-i) == Material.ice)
legacySetBlockWithNotify(world, x, y, z-i, Block.waterMoving.blockID);
if (world.getBlockMaterial(x, y, z+i) == Material.ice)
legacySetBlockWithNotify(world, x, y, z+i, Block.waterMoving.blockID);
}
}
if (temperature > 0) { // Melting snow/ice
for (int i = 0; i < 3; i++) {
if (world.getBlockMaterial(x-i, y, z) == Material.snow)
legacySetBlockWithNotify(world, x-i, y, z, 0);
if (world.getBlockMaterial(x+i, y, z) == Material.snow)
legacySetBlockWithNotify(world, x+i, y, z, 0);
if (world.getBlockMaterial(x, y-i, z) == Material.snow)
legacySetBlockWithNotify(world, x, y-i, z, 0);
if (world.getBlockMaterial(x, y+i, z) == Material.snow)
legacySetBlockWithNotify(world, x, y+i, z, 0);
if (world.getBlockMaterial(x, y, z-i) == Material.snow)
legacySetBlockWithNotify(world, x, y, z-i, 0);
if (world.getBlockMaterial(x, y, z+i) == Material.snow)
legacySetBlockWithNotify(world, x, y, z+i, 0);
if (world.getBlockMaterial(x-i, y, z) == Material.craftedSnow)
legacySetBlockWithNotify(world, x-i, y, z, 0);
if (world.getBlockMaterial(x+i, y, z) == Material.craftedSnow)
legacySetBlockWithNotify(world, x+i, y, z, 0);
if (world.getBlockMaterial(x, y-i, z) == Material.craftedSnow)
legacySetBlockWithNotify(world, x, y-i, z, 0);
if (world.getBlockMaterial(x, y+i, z) == Material.craftedSnow)
legacySetBlockWithNotify(world, x, y+i, z, 0);
if (world.getBlockMaterial(x, y, z-i) == Material.craftedSnow)
legacySetBlockWithNotify(world, x, y, z-i, 0);
if (world.getBlockMaterial(x, y, z+i) == Material.craftedSnow)
legacySetBlockWithNotify(world, x, y, z+i, 0);
}
}
if (temperature > 900) { // Melting sand, ground
for (int i = 0; i < 3; i++) {
if (world.getBlockMaterial(x-i, y, z) == Material.sand)
legacySetBlockWithNotify(world, x-i, y, z, Block.glass.blockID);
if (world.getBlockMaterial(x+i, y, z) == Material.sand)
legacySetBlockWithNotify(world, x+i, y, z, Block.glass.blockID);
if (world.getBlockMaterial(x, y-i, z) == Material.sand)
legacySetBlockWithNotify(world, x, y-i, z, Block.glass.blockID);
if (world.getBlockMaterial(x, y+i, z) == Material.sand)
legacySetBlockWithNotify(world, x, y+i, z, Block.glass.blockID);
if (world.getBlockMaterial(x, y, z-i) == Material.sand)
legacySetBlockWithNotify(world, x, y, z-i, Block.glass.blockID);
if (world.getBlockMaterial(x, y, z+i) == Material.sand)
legacySetBlockWithNotify(world, x, y, z+i, Block.glass.blockID);
if (world.getBlockMaterial(x-i, y, z) == Material.ground)
legacySetBlockWithNotify(world, x-i, y, z, Block.glass.blockID);
if (world.getBlockMaterial(x+i, y, z) == Material.ground)
legacySetBlockWithNotify(world, x+i, y, z, Block.glass.blockID);
if (world.getBlockMaterial(x, y-i, z) == Material.ground)
legacySetBlockWithNotify(world, x, y-i, z, Block.glass.blockID);
if (world.getBlockMaterial(x, y+i, z) == Material.ground)
legacySetBlockWithNotify(world, x, y+i, z, Block.glass.blockID);
if (world.getBlockMaterial(x, y, z-i) == Material.ground)
legacySetBlockWithNotify(world, x, y, z-i, Block.glass.blockID);
if (world.getBlockMaterial(x, y, z+i) == Material.ground)
legacySetBlockWithNotify(world, x, y, z+i, Block.glass.blockID);
}
}
if (temperature > 1700) { // Melting rock
for (int i = 0; i < 3; i++) {
if (world.getBlockMaterial(x-i, y, z) == Material.rock)
legacySetBlockWithNotify(world, x-i, y, z, Block.lavaMoving.blockID);
if (world.getBlockMaterial(x+i, y, z) == Material.rock)
legacySetBlockWithNotify(world, x+i, y, z, Block.lavaMoving.blockID);
if (world.getBlockMaterial(x, y-i, z) == Material.rock)
legacySetBlockWithNotify(world, x, y-i, z, Block.lavaMoving.blockID);
if (world.getBlockMaterial(x, y+i, z) == Material.rock)
legacySetBlockWithNotify(world, x, y+i, z, Block.lavaMoving.blockID);
if (world.getBlockMaterial(x, y, z-i) == Material.rock)
legacySetBlockWithNotify(world, x, y, z-i, Block.lavaMoving.blockID);
if (world.getBlockMaterial(x, y, z+i) == Material.rock)
legacySetBlockWithNotify(world, x, y, z+i, Block.lavaMoving.blockID);
}
}
}
/** Surrounds the block with fire. Args: World, x, y, z */
public static void ignite(World world, int x, int y, int z) {
if (world.getBlockId (x-1, y, z) == 0)
legacySetBlockWithNotify(world, x-1, y, z, Block.fire.blockID);
if (world.getBlockId (x+1, y, z) == 0)
legacySetBlockWithNotify(world, x+1, y, z, Block.fire.blockID);
if (world.getBlockId (x, y-1, z) == 0)
legacySetBlockWithNotify(world, x, y-1, z, Block.fire.blockID);
if (world.getBlockId (x, y+1, z) == 0)
legacySetBlockWithNotify(world, x, y+1, z, Block.fire.blockID);
if (world.getBlockId (x, y, z-1) == 0)
legacySetBlockWithNotify(world, x, y, z-1, Block.fire.blockID);
if (world.getBlockId (x, y, z+1) == 0)
legacySetBlockWithNotify(world, x, y, z+1, Block.fire.blockID);
}
/** Returns the number of water blocks directly and continuously above the passed coordinates.
* Returns -1 if invalid liquid specified. Args: World, x, y, z */
public static int getDepth(World world, int x, int y, int z, String liq) {
int i = 1;
if (liq == "water") {
while (world.getBlockId(x, y+i, z) == Block.waterMoving.blockID || world.getBlockId(x, y+i, z) == Block.waterStill.blockID) {
i++;
}
return (i-1);
}
if (liq == "lava") {
while (world.getBlockId(x, y+i, z) == Block.lavaMoving.blockID || world.getBlockId(x, y+i, z) == Block.lavaStill.blockID) {
i++;
}
return (i-1);
}
return -1;
}
/** Returns true if the block ID is one associated with caves, like air, cobwebs,
* spawners, mushrooms, etc. Args: Block ID */
public static boolean caveBlock(int id) {
if (id == 0 || id == Block.waterMoving.blockID || id == Block.waterStill.blockID || id == Block.lavaMoving.blockID ||
id == Block.lavaStill.blockID || id == Block.web.blockID || id == Block.mobSpawner.blockID || id == Block.mushroomRed.blockID ||
id == Block.mushroomBrown.blockID)
return true;
return false;
}
/** Returns a broad-stroke biome temperature in degrees centigrade.
* Args: biome */
public static int getBiomeTemp(BiomeGenBase biome) {
int Tamb = 25; //Most biomes = 25C
if (ReikaWorldHelper.isSnowBiome(biome))
Tamb = -20; //-20C
if (ReikaWorldHelper.isHotBiome(biome))
Tamb = 40;
if (biome == BiomeGenBase.hell)
Tamb = 300; //boils water, so 300C (3 x 100)
return Tamb;
}
/** Returns a broad-stroke biome temperature in degrees centigrade.
* Args: World, x, z */
public static int getBiomeTemp(World world, int x, int z) {
int Tamb = 25; //Most biomes = 25C
BiomeGenBase biome = world.getBiomeGenForCoords(x, z);
if (ReikaWorldHelper.isSnowBiome(biome))
Tamb = -20; //-20C
if (ReikaWorldHelper.isHotBiome(biome))
Tamb = 40;
if (biome == BiomeGenBase.hell)
Tamb = 300; //boils water, so 300C (3 x 100)
return Tamb;
}
/** Performs machine overheat effects (primarily intended for RotaryCraft).
* Args: World, x, y, z, item drop id, item drop metadata, min drops, max drops,
* spark particles yes/no, number-of-sparks multiplier (default 20-40),
* flaming explosion yes/no, smoking explosion yes/no, explosion force (0 for none) */
public static void overheat(World world, int x, int y, int z, int id, int meta, int mindrops, int maxdrops, boolean sparks, float sparkmultiplier, boolean flaming, boolean smoke, float force) {
if (force > 0 && !world.isRemote) {
if (flaming)
world.newExplosion(null, x, y, z, force, true, smoke);
else
world.createExplosion(null, x, y, z, force, smoke);
}
int numsparks = rand.nextInt(20)+20;
numsparks *= sparkmultiplier;
if (sparks)
for (int i = 0; i < numsparks; i++)
world.spawnParticle("lava", x+rand.nextFloat(), y+1, z+rand.nextFloat(), 0, 0, 0);
ItemStack scrap = new ItemStack(id, 1, meta);
int numdrops = rand.nextInt(maxdrops)+mindrops;
if (!world.isRemote || id <= 0) {
for (int i = 0; i < numdrops; i++) {
EntityItem ent = new EntityItem(world, x+rand.nextFloat(), y+0.5, z+rand.nextFloat(), scrap);
- ent.setVelocity(-0.2+0.4*rand.nextFloat(), 0.5*rand.nextFloat(), -0.2+0.4*rand.nextFloat());
+ ent.motionX = -0.2+0.4*rand.nextFloat();
+ ent.motionY = 0.5*rand.nextFloat();
+ ent.motionZ = -0.2+0.4*rand.nextFloat();
world.spawnEntityInWorld(ent);
ent.velocityChanged = true;
}
}
}
/** Takes a specified amount of XP and splits it randomly among a bunch of orbs.
* Args: World, x, y, z, amount */
public static void splitAndSpawnXP(World world, float x, float y, float z, int xp) {
int max = xp/5+1;
while (xp > 0) {
int value = rand.nextInt(max)+1;
while (value > xp)
value = rand.nextInt(max)+1;
xp -= value;
EntityXPOrb orb = new EntityXPOrb(world, x, y, z, value);
- orb.setVelocity(-0.2+0.4*rand.nextFloat(), 0.3*rand.nextFloat(), -0.2+0.4*rand.nextFloat());
+ orb.motionX = -0.2+0.4*rand.nextFloat();
+ orb.motionY = 0.3*rand.nextFloat();
+ orb.motionZ = -0.2+0.4*rand.nextFloat();
if (world.isRemote)
return;
orb.velocityChanged = true;
world.spawnEntityInWorld(orb);
}
}
/** Returns true if the coordinate specified is a lava source block and would be recreated according to the lava-duplication rules
* that existed for a short time in Beta 1.9. Args: World, x, y, z */
public static boolean is1p9InfiniteLava(World world, int x, int y, int z) {
if (world.getBlockMaterial(x, y, z) != Material.lava || world.getBlockMetadata(x, y, z) != 0)
return false;
if (world.getBlockMaterial(x+1, y, z) != Material.lava || world.getBlockMetadata(x+1, y, z) != 0)
return false;
if (world.getBlockMaterial(x, y, z+1) != Material.lava || world.getBlockMetadata(x, y, z+1) != 0)
return false;
if (world.getBlockMaterial(x-1, y, z) != Material.lava || world.getBlockMetadata(x-1, y, z) != 0)
return false;
if (world.getBlockMaterial(x, y, z-1) != Material.lava || world.getBlockMetadata(x, y, z-1) != 0)
return false;
return true;
}
/** Returns the y-coordinate of the top non-air block at the given xz coordinates, at or
* below the specified y-coordinate. Returns -1 if none. Args: World, x, z, y */
public static int findTopBlockBelowY(World world, int x, int z, int y) {
int id = world.getBlockId(x, y, z);
while ((id == 0) && y >= 0) {
y--;
id = world.getBlockId(x, y, z);
}
return y;
}
/** Returns true if the coordinate is a liquid source block. Args: World, x, y, z */
public static boolean isLiquidSourceBlock(World world, int x, int y, int z) {
if (world.getBlockMetadata(x, y, z) != 0)
return false;
if (world.getBlockMaterial(x, y, z) != Material.lava && world.getBlockMaterial(x, y, z) != Material.water)
return false;
return true;
}
/** Breaks a contiguous area of blocks recursively (akin to a fill tool in image editors).
* Args: World, start x, start y, start z, id, metadata (-1 for any) */
public static void recursiveBreak(World world, int x, int y, int z, int id, int meta) {
if (id == 0)
return;
if (world.getBlockId(x, y, z) != id)
return;
if (meta != world.getBlockMetadata(x, y, z) && meta != -1)
return;
int metad = world.getBlockMetadata(x, y, z);
Block.blocksList[id].dropBlockAsItem(world, x, y, z, id, metad);
legacySetBlockWithNotify(world, x, y, z, 0);
world.markBlockForUpdate(x, y, z);
recursiveBreak(world, x+1, y, z, id, meta);
recursiveBreak(world, x-1, y, z, id, meta);
recursiveBreak(world, x, y+1, z, id, meta);
recursiveBreak(world, x, y-1, z, id, meta);
recursiveBreak(world, x, y, z+1, id, meta);
recursiveBreak(world, x, y, z-1, id, meta);
}
/** Like the ordinary recursive break but with a spherical bounded volume. Args: World, x, y, z,
* id to replace, metadata to replace (-1 for any), origin x,y,z, max radius */
public static void recursiveBreakWithinSphere(World world, int x, int y, int z, int id, int meta, int x0, int y0, int z0, double r) {
if (id == 0)
return;
if (world.getBlockId(x, y, z) != id)
return;
if (meta != world.getBlockMetadata(x, y, z) && meta != -1)
return;
if (ReikaMathLibrary.py3d(x-x0, y-y0, z-z0) > r)
return;
int metad = capMetadata(world.getBlockMetadata(x, y, z), 4);
Block.blocksList[id].dropBlockAsItem(world, x, y, z, metad, 0);
legacySetBlockWithNotify(world, x, y, z, 0);
world.markBlockForUpdate(x, y, z);
recursiveBreakWithinSphere(world, x+1, y, z, id, meta, x0, y0, z0, r);
recursiveBreakWithinSphere(world, x-1, y, z, id, meta, x0, y0, z0, r);
recursiveBreakWithinSphere(world, x, y+1, z, id, meta, x0, y0, z0, r);
recursiveBreakWithinSphere(world, x, y-1, z, id, meta, x0, y0, z0, r);
recursiveBreakWithinSphere(world, x, y, z+1, id, meta, x0, y0, z0, r);
recursiveBreakWithinSphere(world, x, y, z-1, id, meta, x0, y0, z0, r);
}
/** Like the ordinary recursive break but with a bounded volume. Args: World, x, y, z,
* id to replace, metadata to replace (-1 for any), min x,y,z, max x,y,z */
public static void recursiveBreakWithBounds(World world, int x, int y, int z, int id, int meta, int x1, int y1, int z1, int x2, int y2, int z2) {
if (id == 0)
return;
if (x < x1 || y < y1 || z < z1 || x > x2 || y > y2 || z > z2)
return;
if (world.getBlockId(x, y, z) != id)
return;
if (meta != world.getBlockMetadata(x, y, z) && meta != -1)
return;
int metad = world.getBlockMetadata(x, y, z);
Block.blocksList[id].dropBlockAsItem(world, x, y, z, id, metad);
legacySetBlockWithNotify(world, x, y, z, 0);
world.markBlockForUpdate(x, y, z);
recursiveBreakWithBounds(world, x+1, y, z, id, meta, x1, y1, z1, x2, y2, z2);
recursiveBreakWithBounds(world, x-1, y, z, id, meta, x1, y1, z1, x2, y2, z2);
recursiveBreakWithBounds(world, x, y+1, z, id, meta, x1, y1, z1, x2, y2, z2);
recursiveBreakWithBounds(world, x, y-1, z, id, meta, x1, y1, z1, x2, y2, z2);
recursiveBreakWithBounds(world, x, y, z+1, id, meta, x1, y1, z1, x2, y2, z2);
recursiveBreakWithBounds(world, x, y, z-1, id, meta, x1, y1, z1, x2, y2, z2);
}
/** Recursively fills a contiguous area of one block type with another, akin to a fill tool.
* Args: World, start x, start y, start z, id to replace, id to fill with,
* metadata to replace (-1 for any), metadata to fill with */
public static void recursiveFill(World world, int x, int y, int z, int id, int idto, int meta, int metato) {
if (world.getBlockId(x, y, z) != id)
return;
if (meta != world.getBlockMetadata(x, y, z) && meta != -1)
return;
int metad = world.getBlockMetadata(x, y, z);
legacySetBlockAndMetadataWithNotify(world, x, y, z, idto, metato);
world.markBlockForUpdate(x, y, z);
recursiveFill(world, x+1, y, z, id, idto, meta, metato);
recursiveFill(world, x-1, y, z, id, idto, meta, metato);
recursiveFill(world, x, y+1, z, id, idto, meta, metato);
recursiveFill(world, x, y-1, z, id, idto, meta, metato);
recursiveFill(world, x, y, z+1, id, idto, meta, metato);
recursiveFill(world, x, y, z-1, id, idto, meta, metato);
}
/** Like the ordinary recursive fill but with a bounded volume. Args: World, x, y, z,
* id to replace, id to fill with, metadata to replace (-1 for any),
* metadata to fill with, min x,y,z, max x,y,z */
public static void recursiveFillWithBounds(World world, int x, int y, int z, int id, int idto, int meta, int metato, int x1, int y1, int z1, int x2, int y2, int z2) {
if (x < x1 || y < y1 || z < z1 || x > x2 || y > y2 || z > z2)
return;
if (world.getBlockId(x, y, z) != id)
return;
if (meta != world.getBlockMetadata(x, y, z) && meta != -1)
return;
int metad = world.getBlockMetadata(x, y, z);
legacySetBlockAndMetadataWithNotify(world, x, y, z, idto, metato);
world.markBlockForUpdate(x, y, z);
recursiveFillWithBounds(world, x+1, y, z, id, idto, meta, metato, x1, y1, z1, x2, y2, z2);
recursiveFillWithBounds(world, x-1, y, z, id, idto, meta, metato, x1, y1, z1, x2, y2, z2);
recursiveFillWithBounds(world, x, y+1, z, id, idto, meta, metato, x1, y1, z1, x2, y2, z2);
recursiveFillWithBounds(world, x, y-1, z, id, idto, meta, metato, x1, y1, z1, x2, y2, z2);
recursiveFillWithBounds(world, x, y, z+1, id, idto, meta, metato, x1, y1, z1, x2, y2, z2);
recursiveFillWithBounds(world, x, y, z-1, id, idto, meta, metato, x1, y1, z1, x2, y2, z2);
}
/** Like the ordinary recursive fill but with a spherical bounded volume. Args: World, x, y, z,
* id to replace, id to fill with, metadata to replace (-1 for any),
* metadata to fill with, origin x,y,z, max radius */
public static void recursiveFillWithinSphere(World world, int x, int y, int z, int id, int idto, int meta, int metato, int x0, int y0, int z0, double r) {
//ReikaGuiAPI.write(world.getBlockId(x, y, z)+" & "+id+" @ "+x0+", "+y0+", "+z0);
if (world.getBlockId(x, y, z) != id)
return;
if (meta != world.getBlockMetadata(x, y, z) && meta != -1)
return;
if (ReikaMathLibrary.py3d(x-x0, y-y0, z-z0) > r)
return;
int metad = world.getBlockMetadata(x, y, z);
legacySetBlockAndMetadataWithNotify(world, x, y, z, idto, metato);
world.markBlockForUpdate(x, y, z);
recursiveFillWithinSphere(world, x+1, y, z, id, idto, meta, metato, x0, y0, z0, r);
recursiveFillWithinSphere(world, x-1, y, z, id, idto, meta, metato, x0, y0, z0, r);
recursiveFillWithinSphere(world, x, y+1, z, id, idto, meta, metato, x0, y0, z0, r);
recursiveFillWithinSphere(world, x, y-1, z, id, idto, meta, metato, x0, y0, z0, r);
recursiveFillWithinSphere(world, x, y, z+1, id, idto, meta, metato, x0, y0, z0, r);
recursiveFillWithinSphere(world, x, y, z-1, id, idto, meta, metato, x0, y0, z0, r);
}
/** Returns true if there is a clear line of sight between two points. Args: World, Start x,y,z, End x,y,z
* NOTE: If one point is a block, use canBlockSee instead, as this method will always return false. */
public static boolean lineOfSight(World world, double x1, double y1, double z1, double x2, double y2, double z2) {
if (world.isRemote)
return false;
Vec3 v1 = Vec3.fakePool.getVecFromPool(x1, y1, z1);
Vec3 v2 = Vec3.fakePool.getVecFromPool(x2, y2, z2);
return (world.rayTraceBlocks(v1, v2) == null);
}
/** Returns true if there is a clear line of sight between two entites. Args: World, Entity 1, Entity 2 */
public static boolean lineOfSight(World world, Entity e1, Entity e2) {
if (world.isRemote)
return false;
Vec3 v1 = Vec3.fakePool.getVecFromPool(e1.posX, e1.posY+e1.getEyeHeight(), e1.posZ);
Vec3 v2 = Vec3.fakePool.getVecFromPool(e2.posX, e2.posY+e2.getEyeHeight(), e2.posZ);
return (world.rayTraceBlocks(v1, v2) == null);
}
/** Returns true if a block can see an point. Args: World, block x,y,z, Point x,y,z, Max Range */
public static boolean canBlockSee(World world, int x, int y, int z, double x0, double y0, double z0, double range) {
int locid = world.getBlockId(x, y, z);
range += 2;
for (int k = 0; k < 10; k++) {
float a = 0; float b = 0; float c = 0;
switch(k) {
case 1:
a = 1;
break;
case 2:
b = 1;
break;
case 3:
a = 1;
b = 1;
break;
case 4:
c = 1;
break;
case 5:
a = 1;
c = 1;
break;
case 6:
b = 1;
c = 1;
break;
case 7:
a = 1;
b = 1;
c = 1;
break;
case 8:
a = 0.5F;
b = 0.5F;
c = 0.5F;
break;
case 9:
b = 0.5F;
break;
}
for (float i = 0; i <= range; i += 0.25) {
Vec3 vec2 = ReikaVectorHelper.getVec2Pt(x+a, y+b, z+c, x0, y0, z0).normalize();
vec2.xCoord *= i;
vec2.yCoord *= i;
vec2.zCoord *= i;
vec2.xCoord += x0;
vec2.yCoord += y0;
vec2.zCoord += z0;
//ReikaGuiAPI.write(String.format("%f --> %.3f, %.3f, %.3f", i, vec2.xCoord, vec2.yCoord, vec2.zCoord));
int id = world.getBlockId((int)vec2.xCoord, (int)vec2.yCoord, (int)vec2.zCoord);
if ((int)vec2.xCoord == x && (int)vec2.yCoord == y && (int)vec2.zCoord == z) {
//ReikaGuiAPI.writeCoords(world, (int)vec2.xCoord, (int)vec2.yCoord, (int)vec2.zCoord);
return true;
}
else if (id != 0 && id != locid && (isCollideable(world, (int)vec2.xCoord, (int)vec2.yCoord, (int)vec2.zCoord) && !softBlocks(id))) {
i = (float)(range + 1); //Hard loop break
}
}
}
return false;
}
/** Returns true if the entity can see a block, or if it could be moved to a position where it could see the block.
* Args: World, Block x,y,z, Entity, Max Move Distance
* DO NOT USE THIS - CPU INTENSIVE TO ALL HELL! */
public static boolean canSeeOrMoveToSeeBlock(World world, int x, int y, int z, Entity ent, double r) {
double d = 4;//+ReikaMathLibrary.py3d(x-ent.posX, y-ent.posY, z-ent.posZ);
if (canBlockSee(world, x, y, z, ent.posX, ent.posY, ent.posZ, d))
return true;
double xmin; double ymin; double zmin;
double xmax; double ymax; double zmax;
double[] pos = new double[3];
boolean[] signs = new boolean[3];
boolean[] signs2 = new boolean[3];
signs[0] = (ReikaMathLibrary.isSameSign(ent.posX, x));
signs[1] = (ReikaMathLibrary.isSameSign(ent.posY, y));
signs[2] = (ReikaMathLibrary.isSameSign(ent.posZ, z));
for (double i = ent.posX-r; i <= ent.posX+r; i += 0.5) {
for (double j = ent.posY-r; j <= ent.posY+r; j += 0.5) {
for (double k = ent.posZ-r; k <= ent.posZ+r; k += 0.5) {
if (canBlockSee(world, x, y, z, ent.posX+i, ent.posY+j, ent.posZ+k, d))
return true;
}
}
}
/*
for (double i = ent.posX; i > ent.posX-r; i -= 0.5) {
int id = world.getBlockId((int)i, (int)ent.posY, (int)ent.posZ);
if (isCollideable(world, (int)i, (int)ent.posY, (int)ent.posZ)) {
xmin = i+Block.blocksList[id].getBlockBoundsMaxX();
}
}
for (double i = ent.posX; i < ent.posX+r; i += 0.5) {
int id = world.getBlockId((int)i, (int)ent.posY, (int)ent.posZ);
if (isCollideable(world, (int)i, (int)ent.posY, (int)ent.posZ)) {
xmax = i+Block.blocksList[id].getBlockBoundsMinX();
}
}
for (double i = ent.posY; i > ent.posY-r; i -= 0.5) {
int id = world.getBlockId((int)ent.posX, (int)i, (int)ent.posZ);
if (isCollideable(world, (int)ent.posX, (int)i, (int)ent.posZ)) {
ymin = i+Block.blocksList[id].getBlockBoundsMaxX();
}
}
for (double i = ent.posY; i < ent.posY+r; i += 0.5) {
int id = world.getBlockId((int)ent.posX, (int)i, (int)ent.posZ);
if (isCollideable(world, (int)ent.posX, (int)i, (int)ent.posZ)) {
ymax = i+Block.blocksList[id].getBlockBoundsMinX();
}
}
for (double i = ent.posZ; i > ent.posZ-r; i -= 0.5) {
int id = world.getBlockId((int)ent.posX, (int)ent.posY, (int)i);
if (isCollideable(world, (int)ent.posX, (int)ent.posY, (int)i)) {
zmin = i+Block.blocksList[id].getBlockBoundsMaxX();
}
}
for (double i = ent.posZ; i < ent.posZ+r; i += 0.5) {
int id = world.getBlockId((int)ent.posX, (int)ent.posY, (int)i);
if (isCollideable(world, (int)ent.posX, (int)ent.posY, (int)i)) {
zmax = i+Block.blocksList[id].getBlockBoundsMinX();
}
}*/
signs2[0] = (ReikaMathLibrary.isSameSign(pos[0], x));
signs2[1] = (ReikaMathLibrary.isSameSign(pos[1], y));
signs2[2] = (ReikaMathLibrary.isSameSign(pos[2], z));
if (signs[0] != signs2[0] || signs[1] != signs2[1] || signs[2] != signs2[2]) //Cannot pull the item "Across" (so that it moves away)
return false;
return false;
}
public static boolean lenientSeeThrough(World world, double x, double y, double z, double x0, double y0, double z0) {
MovingObjectPosition pos;
Vec3 par1Vec3 = Vec3.fakePool.getVecFromPool(x, y, z);
Vec3 par2Vec3 = Vec3.fakePool.getVecFromPool(x0, y0, z0);
if (!Double.isNaN(par1Vec3.xCoord) && !Double.isNaN(par1Vec3.yCoord) && !Double.isNaN(par1Vec3.zCoord)) {
if (!Double.isNaN(par2Vec3.xCoord) && !Double.isNaN(par2Vec3.yCoord) && !Double.isNaN(par2Vec3.zCoord)) {
int var5 = MathHelper.floor_double(par2Vec3.xCoord);
int var6 = MathHelper.floor_double(par2Vec3.yCoord);
int var7 = MathHelper.floor_double(par2Vec3.zCoord);
int var8 = MathHelper.floor_double(par1Vec3.xCoord);
int var9 = MathHelper.floor_double(par1Vec3.yCoord);
int var10 = MathHelper.floor_double(par1Vec3.zCoord);
int var11 = world.getBlockId(var8, var9, var10);
int var12 = world.getBlockMetadata(var8, var9, var10);
Block var13 = Block.blocksList[var11];
//ReikaGuiAPI.write(var11);
if (var13 != null && (var11 > 0 && !ReikaWorldHelper.softBlocks(var11) && (var11 != Block.leaves.blockID) && (var11 != Block.web.blockID)) && var13.canCollideCheck(var12, false)) {
MovingObjectPosition var14 = var13.collisionRayTrace(world, var8, var9, var10, par1Vec3, par2Vec3);
if (var14 != null)
pos = var14;
}
var11 = 200;
while (var11-- >= 0) {
if (Double.isNaN(par1Vec3.xCoord) || Double.isNaN(par1Vec3.yCoord) || Double.isNaN(par1Vec3.zCoord))
pos = null;
if (var8 == var5 && var9 == var6 && var10 == var7)
pos = null;
boolean var39 = true;
boolean var40 = true;
boolean var41 = true;
double var15 = 999.0D;
double var17 = 999.0D;
double var19 = 999.0D;
if (var5 > var8)
var15 = var8 + 1.0D;
else if (var5 < var8)
var15 = var8 + 0.0D;
else
var39 = false;
if (var6 > var9)
var17 = var9 + 1.0D;
else if (var6 < var9)
var17 = var9 + 0.0D;
else
var40 = false;
if (var7 > var10)
var19 = var10 + 1.0D;
else if (var7 < var10)
var19 = var10 + 0.0D;
else
var41 = false;
double var21 = 999.0D;
double var23 = 999.0D;
double var25 = 999.0D;
double var27 = par2Vec3.xCoord - par1Vec3.xCoord;
double var29 = par2Vec3.yCoord - par1Vec3.yCoord;
double var31 = par2Vec3.zCoord - par1Vec3.zCoord;
if (var39)
var21 = (var15 - par1Vec3.xCoord) / var27;
if (var40)
var23 = (var17 - par1Vec3.yCoord) / var29;
if (var41)
var25 = (var19 - par1Vec3.zCoord) / var31;
boolean var33 = false;
byte var42;
if (var21 < var23 && var21 < var25) {
if (var5 > var8)
var42 = 4;
else
var42 = 5;
par1Vec3.xCoord = var15;
par1Vec3.yCoord += var29 * var21;
par1Vec3.zCoord += var31 * var21;
}
else if (var23 < var25) {
if (var6 > var9)
var42 = 0;
else
var42 = 1;
par1Vec3.xCoord += var27 * var23;
par1Vec3.yCoord = var17;
par1Vec3.zCoord += var31 * var23;
}
else {
if (var7 > var10)
var42 = 2;
else
var42 = 3;
par1Vec3.xCoord += var27 * var25;
par1Vec3.yCoord += var29 * var25;
par1Vec3.zCoord = var19;
}
Vec3 var34 = world.getWorldVec3Pool().getVecFromPool(par1Vec3.xCoord, par1Vec3.yCoord, par1Vec3.zCoord);
var8 = (int)(var34.xCoord = MathHelper.floor_double(par1Vec3.xCoord));
if (var42 == 5) {
--var8;
++var34.xCoord;
}
var9 = (int)(var34.yCoord = MathHelper.floor_double(par1Vec3.yCoord));
if (var42 == 1) {
--var9;
++var34.yCoord;
}
var10 = (int)(var34.zCoord = MathHelper.floor_double(par1Vec3.zCoord));
if (var42 == 3) {
--var10;
++var34.zCoord;
}
int var35 = world.getBlockId(var8, var9, var10);
int var36 = world.getBlockMetadata(var8, var9, var10);
Block var37 = Block.blocksList[var35];
if (var35 > 0 && var37.canCollideCheck(var36, false)) {
MovingObjectPosition var38 = var37.collisionRayTrace(world, var8, var9, var10, par1Vec3, par2Vec3);
if (var38 != null)
pos = var38;
}
}
pos = null;
}
else
pos = null;
}
else
pos = null;
return (pos == null);
}
/** Returns true if the block has a hitbox. Args: World, x, y, z */
public static boolean isCollideable(World world, int x, int y, int z) {
if (world.getBlockId(x, y, z) == 0)
return false;
Block b = Block.blocksList[world.getBlockId(x, y, z)];
return (b.getCollisionBoundingBoxFromPool(world, x, y, z) != null);
}
public static boolean legacySetBlockMetadataWithNotify(World world, int x, int y, int z, int meta) {
return world.setBlockMetadataWithNotify(x, y, z, meta, 3);
}
public static boolean legacySetBlockAndMetadataWithNotify(World world, int x, int y, int z, int id, int meta) {
return world.setBlock(x, y, z, id, meta, 3);
}
public static boolean legacySetBlockWithNotify(World world, int x, int y, int z, int id) {
return world.setBlock(x, y, z, id, 0, 3);
}
/** Returns true if the specified corner has at least one air block adjacent to it,
* but is not surrounded by air on all sides or in the void. Args: World, x, y, z */
public static boolean cornerHasAirAdjacent(World world, int x, int y, int z) {
if (y <= 0)
return false;
int airs = 0;
if (world.getBlockId(x, y, z) == 0)
airs++;
if (world.getBlockId(x-1, y, z) == 0)
airs++;
if (world.getBlockId(x, y, z-1) == 0)
airs++;
if (world.getBlockId(x-1, y, z-1) == 0)
airs++;
if (world.getBlockId(x, y-1, z) == 0)
airs++;
if (world.getBlockId(x-1, y-1, z) == 0)
airs++;
if (world.getBlockId(x, y-1, z-1) == 0)
airs++;
if (world.getBlockId(x-1, y-1, z-1) == 0)
airs++;
return (airs > 0 && airs != 8);
}
/** Returns true if the specified corner has at least one nonopaque block adjacent to it,
* but is not surrounded by air on all sides or in the void. Args: World, x, y, z */
public static boolean cornerHasTransAdjacent(World world, int x, int y, int z) {
if (y <= 0)
return false;
int id;
int airs = 0;
boolean nonopq = false;
id = world.getBlockId(x, y, z);
if (id == 0)
airs++;
else if (!Block.blocksList[id].isOpaqueCube())
nonopq = true;
id = world.getBlockId(x-1, y, z);
if (id == 0)
airs++;
else if (!Block.blocksList[id].isOpaqueCube())
nonopq = true;
id = world.getBlockId(x, y, z-1);
if (id == 0)
airs++;
else if (!Block.blocksList[id].isOpaqueCube())
nonopq = true;
id = world.getBlockId(x-1, y, z-1);
if (id == 0)
airs++;
else if (!Block.blocksList[id].isOpaqueCube())
nonopq = true;
id = world.getBlockId(x, y-1, z);
if (id == 0)
airs++;
else if (!Block.blocksList[id].isOpaqueCube())
nonopq = true;
id = world.getBlockId(x-1, y-1, z);
if (id == 0)
airs++;
else if (!Block.blocksList[id].isOpaqueCube())
nonopq = true;
id = world.getBlockId(x, y-1, z-1);
if (id == 0)
airs++;
else if (!Block.blocksList[id].isOpaqueCube())
nonopq = true;
id = world.getBlockId(x-1, y-1, z-1);
if (id == 0)
airs++;
else if (!Block.blocksList[id].isOpaqueCube())
nonopq = true;
return (airs != 8 && nonopq);
}
/** Spills the entire inventory of an ItemStack[] at the specified coordinates with a 1-block spread.
* Args: World, x, y, z, inventory */
public static void spillAndEmptyInventory(World world, int x, int y, int z, ItemStack[] inventory) {
EntityItem ei;
ItemStack is;
for (int i = 0; i < inventory.length; i++) {
is = inventory[i];
inventory[i] = null;
if (is != null && !world.isRemote) {
ei = new EntityItem(world, x+rand.nextFloat(), y+rand.nextFloat(), z+rand.nextFloat(), is);
ReikaEntityHelper.addRandomDirVelocity(ei, 0.2);
world.spawnEntityInWorld(ei);
}
}
}
/** Spills the entire inventory of an ItemStack[] at the specified coordinates with a 1-block spread.
* Args: World, x, y, z, IInventory */
public static void spillAndEmptyInventory(World world, int x, int y, int z, IInventory ii) {
int size = ii.getSizeInventory();
for (int i = 0; i < size; i++) {
ItemStack s = ii.getStackInSlot(i);
if (s != null) {
ii.setInventorySlotContents(i, null);
EntityItem ei = new EntityItem(world, x+rand.nextFloat(), y+rand.nextFloat(), z+rand.nextFloat(), s);
ReikaEntityHelper.addRandomDirVelocity(ei, 0.2);
ei.delayBeforeCanPickup = 10;
if (!world.isRemote)
world.spawnEntityInWorld(ei);
}
}
}
/** Spawns a line of particles between two points. Args: World, start x,y,z, end x,y,z, particle type, particle speed x,y,z, number of particles */
public static void spawnParticleLine(World world, double x1, double y1, double z1, double x2, double y2, double z2, String name, double vx, double vy, double vz, int spacing) {
double dx = x2-x1;
double dy = y2-y1;
double dz = z2-z1;
double sx = dx/spacing;
double sy = dy/spacing;
double sz = dy/spacing;
double[][] parts = new double[spacing+1][3];
for (int i = 0; i <= spacing; i++) {
parts[i][0] = i*sx+x1;
parts[i][1] = i*sy+y1;
parts[i][2] = i*sz+z1;
}
for (int i = 0; i < parts.length; i++) {
world.spawnParticle(name, parts[i][0], parts[i][1], parts[i][2], vx, vy, vz);
}
}
/** Checks if a liquid block is part of a column (has same liquid above and below and none of them are source blocks).
* Args: World, x, y, z */
public static boolean isLiquidAColumn(World world, int x, int y, int z) {
Material mat = world.getBlockMaterial(x, y, z);
if (isLiquidSourceBlock(world, x, y, z))
return false;
if (world.getBlockMaterial(x, y+1, z) != mat)
return false;
if (isLiquidSourceBlock(world, x, y+1, z))
return false;
if (world.getBlockMaterial(x, y-1, z) != mat)
return false;
if (isLiquidSourceBlock(world, x, y-1, z))
return false;
return true;
}
public static void causeAdjacentUpdates(World world, int x, int y, int z) {
int id = world.getBlockId(x, y, z);
world.notifyBlocksOfNeighborChange(x, y, z, id);
}
}
| false | false | null | null |
diff --git a/restnet-db/src/main/java/net/idea/restnet/db/QueryResource.java b/restnet-db/src/main/java/net/idea/restnet/db/QueryResource.java
index 977c908..9979314 100644
--- a/restnet-db/src/main/java/net/idea/restnet/db/QueryResource.java
+++ b/restnet-db/src/main/java/net/idea/restnet/db/QueryResource.java
@@ -1,734 +1,741 @@
package net.idea.restnet.db;
import java.io.File;
import java.io.FileOutputStream;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import java.util.UUID;
import net.idea.modbcum.i.IDBProcessor;
import net.idea.modbcum.i.IQueryObject;
import net.idea.modbcum.i.IQueryRetrieval;
import net.idea.modbcum.i.exceptions.AmbitException;
import net.idea.modbcum.i.exceptions.NotFoundException;
import net.idea.modbcum.i.processors.IProcessor;
import net.idea.modbcum.i.reporter.Reporter;
import net.idea.restnet.c.AbstractResource;
import net.idea.restnet.c.PageParams;
import net.idea.restnet.c.RepresentationConvertor;
import net.idea.restnet.c.TaskApplication;
import net.idea.restnet.c.exception.RResourceException;
import net.idea.restnet.c.task.CallableProtectedTask;
import net.idea.restnet.c.task.FactoryTaskConvertor;
import net.idea.restnet.c.task.TaskCreator;
import net.idea.restnet.c.task.TaskCreatorFile;
import net.idea.restnet.c.task.TaskCreatorForm;
import net.idea.restnet.c.task.TaskCreatorMultiPartForm;
import net.idea.restnet.i.task.ICallableTask;
import net.idea.restnet.i.task.ITaskStorage;
import net.idea.restnet.i.task.Task;
+import net.idea.restnet.i.task.TaskResult;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.restlet.Context;
import org.restlet.Request;
import org.restlet.data.CharacterSet;
import org.restlet.data.CookieSetting;
import org.restlet.data.Form;
import org.restlet.data.MediaType;
import org.restlet.data.Method;
import org.restlet.data.Reference;
import org.restlet.data.Status;
import org.restlet.ext.fileupload.RestletFileUpload;
import org.restlet.representation.ObjectRepresentation;
import org.restlet.representation.Representation;
import org.restlet.representation.Variant;
import org.restlet.resource.ResourceException;
/**
* Abstract parent class for all resources , which retrieves something from the database
* @author nina
*
* @param <Q>
* @param <T>
*/
public abstract class QueryResource<Q extends IQueryRetrieval<T>,T extends Serializable> extends AbstractResource<Q,T,IProcessor<Q,Representation>> {
protected enum RDF_WRITER {
jena,
stax
}
protected RDF_WRITER rdfwriter = RDF_WRITER.jena;
protected boolean dataset_prefixed_compound_uri = false;
public final static String query_resource = "/query";
protected String configFile= "conf/restnet-db.pref";
public String getConfigFile() {
return configFile;
}
public void setConfigFile(String configFile) {
this.configFile = configFile;
}
/**TODO
* http://markmail.org/search/?q=restlet+statusservice+variant#query:restlet%20statusservice%20variant+page:1+mid:2qrzgzbendopxg5t+state:results
an alternate design where you would leverage the new RepresentationInfo class added to Restlet 2.0
by overriding the "ServerResource#getInfo(Variant)" method.
This would allow you to support content negotiation and conditional processing
without having to connect to your database.
Then, when the "get(Variant)" method calls you back,
you would connect to your database, throw any exception that occurs and return a verified representation.
*/
protected int maxRetry = 3;
@Override
protected void doInit() throws ResourceException {
super.doInit();
customizeVariants(new MediaType[] {
MediaType.TEXT_HTML,
MediaType.TEXT_PLAIN,
MediaType.TEXT_URI_LIST,
MediaType.TEXT_CSV,
MediaType.APPLICATION_RDF_XML,
MediaType.APPLICATION_RDF_TURTLE,
MediaType.TEXT_RDF_N3,
MediaType.TEXT_RDF_NTRIPLES,
MediaType.APPLICATION_JSON,
MediaType.APPLICATION_JAVA_OBJECT,
MediaType.APPLICATION_WADL
});
if (queryObject!=null) {
Form form = getParams();
setPaging(form, queryObject);
}
}
protected Form getParams() {
return getRequest().getResourceRef().getQueryAsForm();
}
/*
protected Connection getConnection() throws SQLException , AmbitException {
Connection connection = ((AmbitApplication)getApplication()).getConnection(getRequest());
if (connection.isClosed()) connection = ((AmbitApplication)getApplication()).getConnection(getRequest());
return connection;
}
*/
protected Q returnQueryObject() {
return queryObject;
}
public void configureDatasetMembersPrefixOption(boolean prefix) {
dataset_prefixed_compound_uri = prefix;
}
protected void configureRDFWriterOption(String defaultWriter) {
try {
Object jenaOption = getRequest().getResourceRef().getQueryAsForm().getFirstValue("rdfwriter");
//if no option ?rdfwriter=jena|stax , then take from properties rdf.writer
//if not defined there, use jena
rdfwriter = RDF_WRITER.valueOf(jenaOption==null?defaultWriter:jenaOption.toString().toLowerCase());
} catch (Exception x) {
rdfwriter = RDF_WRITER.jena;
}
}
@Override
protected Representation get(Variant variant) throws ResourceException {
try {
CookieSetting cS = new CookieSetting(0, "subjectid", getToken());
cS.setPath("/");
this.getResponse().getCookieSettings().add(cS);
/*
if (variant.getMediaType().equals(MediaType.APPLICATION_WADL)) {
return new WadlRepresentation();
} else
*/
if (MediaType.APPLICATION_JAVA_OBJECT.equals(variant.getMediaType())) {
if ((queryObject!=null) && (queryObject instanceof Serializable))
return new ObjectRepresentation((Serializable)returnQueryObject(),MediaType.APPLICATION_JAVA_OBJECT);
else throw new ResourceException(Status.CLIENT_ERROR_NOT_ACCEPTABLE);
}
if (queryObject != null) {
IProcessor<Q, Representation> convertor = null;
Connection connection = null;
int retry=0;
while (retry <maxRetry) {
try {
DBConnection dbc = new DBConnection(getContext(),getConfigFile());
configureRDFWriterOption(dbc.rdfWriter());
configureDatasetMembersPrefixOption(dbc.dataset_prefixed_compound_uri());
convertor = createConvertor(variant);
if (convertor instanceof RepresentationConvertor)
((RepresentationConvertor)convertor).setLicenseURI(getLicenseURI());
connection = dbc.getConnection(getRequest());
Reporter reporter = ((RepresentationConvertor)convertor).getReporter();
if (reporter instanceof IDBProcessor)
((IDBProcessor)reporter).setConnection(connection);
Representation r = convertor.process(queryObject);
r.setCharacterSet(CharacterSet.UTF_8);
return r;
} catch (ResourceException x) {
throw x;
} catch (NotFoundException x) {
Representation r = processNotFound(x,retry);
if (r!=null) return r;
} catch (SQLException x) {
Representation r = processSQLError(x,retry,variant);
if (r==null) continue; else return r;
} catch (Exception x) {
Context.getCurrentLogger().severe(x.getMessage());
throw new RResourceException(Status.SERVER_ERROR_INTERNAL,x,variant);
} finally {
//try { if (connection !=null) connection.close(); } catch (Exception x) {};
//try { if ((convertor !=null) && (convertor.getReporter() !=null)) convertor.getReporter().close(); } catch (Exception x) {}
}
}
return null;
} else {
if (variant.getMediaType().equals(MediaType.TEXT_HTML)) try {
IProcessor<Q, Representation> convertor = createConvertor(variant);
Representation r = convertor.process(null);
return r;
} catch (Exception x) {
throw new RResourceException(Status.CLIENT_ERROR_BAD_REQUEST,x,variant);
} else {
throw new RResourceException(Status.CLIENT_ERROR_BAD_REQUEST,error,variant);
}
}
} catch (RResourceException x) {
throw x;
} catch (ResourceException x) {
throw new RResourceException(x.getStatus(),x,variant);
} catch (Exception x) {
throw new RResourceException(Status.SERVER_ERROR_INTERNAL,x,variant);
}
}
protected Representation processNotFound(NotFoundException x, int retry) throws Exception {
throw new ResourceException(Status.CLIENT_ERROR_NOT_FOUND,String.format("Query returns no results! %s",x.getMessage()));
}
protected Representation processSQLError(SQLException x, int retry,Variant variant) throws Exception {
Context.getCurrentLogger().severe(x.getMessage());
if (retry <maxRetry) {
retry++;
getResponse().setStatus(Status.SERVER_ERROR_SERVICE_UNAVAILABLE,x,String.format("Retry %d ",retry));
return null;
}
else {
throw new RResourceException(Status.SERVER_ERROR_SERVICE_UNAVAILABLE,x,variant);
}
}
/**
* POST - create entity based on parameters in http header, creates a new entry in the databaseand returns an url to it
*
public void executeUpdate(Representation entity, T entry, AbstractUpdate updateObject) throws ResourceException {
Connection c = null;
//TODO it is inefficient to instantiate executor in all classes
UpdateExecutor executor = new UpdateExecutor();
try {
DBConnection dbc = new DBConnection(getContext(),getConfigFile());
c = dbc.getConnection(getRequest());
executor.setConnection(c);
executor.open();
executor.process(updateObject);
customizeEntry(entry, c);
QueryURIReporter<T,Q> uriReporter = getURUReporter(getRequest());
if (uriReporter!=null) {
getResponse().setLocationRef(uriReporter.getURI(entry));
getResponse().setEntity(uriReporter.getURI(entry),MediaType.TEXT_HTML);
}
getResponse().setStatus(Status.SUCCESS_OK);
} catch (SQLException x) {
Context.getCurrentLogger().severe(x.getMessage());
getResponse().setStatus(Status.CLIENT_ERROR_FORBIDDEN,x,x.getMessage());
getResponse().setEntity(null);
} catch (ProcessorException x) {
Context.getCurrentLogger().severe(x.getMessage());
getResponse().setStatus((x.getCause() instanceof SQLException)?Status.CLIENT_ERROR_FORBIDDEN:Status.SERVER_ERROR_INTERNAL,
x,x.getMessage());
getResponse().setEntity(null);
} catch (Exception x) {
Context.getCurrentLogger().severe(x.getMessage());
getResponse().setStatus(Status.SERVER_ERROR_INTERNAL,x,x.getMessage());
getResponse().setEntity(null);
} finally {
try {executor.close();} catch (Exception x) {}
try {if(c != null) c.close();} catch (Exception x) {}
}
}
/**
* POST - create entity based on parameters in the query, creates a new entry in the databaseand returns an url to it
* TODO Refactor to allow multiple objects
public void createNewObject(Representation entity) throws ResourceException {
T entry = createObjectFromHeaders(null, entity);
executeUpdate(entity,
entry,
createUpdateObject(entry));
}
*/
/**
* DELETE - create entity based on parameters in the query, creates a new entry in the database and returns an url to it
public void deleteObject(Representation entity) throws ResourceException {
Form queryForm = getRequest().getResourceRef().getQueryAsForm();
T entry = createObjectFromHeaders(queryForm, entity);
executeUpdate(entity,
entry,
createDeleteObject(entry));
}
*/
/*
protected Representation delete(Variant variant) throws ResourceException {
Representation entity = getRequestEntity();
Form queryForm = null;
if (MediaType.APPLICATION_WWW_FORM.equals(entity.getMediaType()))
queryForm = new Form(entity);
T entry = createObjectFromHeaders(queryForm, entity);
executeUpdate(entity,
entry,
createDeleteObject(entry));
getResponse().setStatus(Status.SUCCESS_OK);
return new EmptyRepresentation();
};
*/
protected QueryURIReporter<T, Q> getURUReporter(Request baseReference) throws ResourceException {
throw new ResourceException(Status.SERVER_ERROR_NOT_IMPLEMENTED,String.format("%s getURUReporter()", getClass().getName()) );
}
/*
protected AbstractUpdate createUpdateObject(T entry) throws ResourceException {
throw new ResourceException(Status.SERVER_ERROR_NOT_IMPLEMENTED,String.format("%s createUpdateObject()", getClass().getName()));
}
protected AbstractUpdate createDeleteObject(T entry) throws ResourceException {
throw new ResourceException(Status.SERVER_ERROR_NOT_IMPLEMENTED,String.format("%s createDeleteObject()", getClass().getName()));
}
protected RDFObjectIterator<T> createObjectIterator(Reference reference, MediaType mediaType) throws ResourceException {
throw new ResourceException(Status.SERVER_ERROR_NOT_IMPLEMENTED,String.format("%s createObjectIterator()", getClass().getName()));
}
protected RDFObjectIterator<T> createObjectIterator(Representation entity) throws ResourceException {
throw new ResourceException(Status.SERVER_ERROR_NOT_IMPLEMENTED,String.format("%s createObjectIterator", getClass().getName()));
}
*/
/**
* Return this object if can't parse source_uri
* @param uri
* @return
*/
protected T onError(String uri) {
return null;
}
/*
protected T createObjectFromHeaders(Form queryForm, Representation entity) throws ResourceException {
RDFObjectIterator<T> iterator = null;
if (!entity.isAvailable()) { //using URI
throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST,"Empty content");
} else
if (MediaType.TEXT_URI_LIST.equals(entity.getMediaType())) {
return createObjectFromURIlist(entity);
} else if (MediaType.APPLICATION_WWW_FORM.equals(entity.getMediaType())) {
return createObjectFromWWWForm(entity);
} else if (MediaType.MULTIPART_FORM_DATA.equals(entity.getMediaType())) {
return createObjectFromMultiPartForm(entity);
} else // assume RDF
try {
iterator = createObjectIterator(entity);
iterator.setCloseModel(true);
iterator.setBaseReference(getRequest().getRootRef());
while (iterator.hasNext()) {
T nextObject = iterator.next();
if (accept(nextObject)) return nextObject;
}
throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST,"Nothing to write! "+getRequest().getRootRef() );
} catch (ResourceException x) {
throw x;
} catch (Exception x) {
throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST,x.getMessage(),x);
} finally {
try { iterator.close(); } catch (Exception x) {}
}
}
protected boolean accept(T object) throws ResourceException {
return true;
}
protected T createObjectFromWWWForm(Representation entity) throws ResourceException {
Form queryForm = new Form(entity);
String sourceURI = getObjectURI(queryForm);
RDFObjectIterator<T> iterator = null;
try {
iterator = createObjectIterator(new Reference(sourceURI),entity.getMediaType()==null?MediaType.APPLICATION_RDF_XML:entity.getMediaType());
iterator.setCloseModel(true);
iterator.setBaseReference(getRequest().getRootRef());
while (iterator.hasNext()) {
return iterator.next();
}
//if none
return onError(sourceURI);
} catch (Exception x) {
return onError(sourceURI);
} finally {
try { iterator.close(); } catch (Exception x) {}
}
}
protected T createObjectFromMultiPartForm(Representation entity) throws ResourceException {
throw new ResourceException(Status.SERVER_ERROR_NOT_IMPLEMENTED);
}
protected T createObjectFromURIlist(Representation entity) throws ResourceException {
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(entity.getStream()));
String line = null;
while ((line = reader.readLine())!= null)
return onError(line);
throw new ResourceException(Status.CLIENT_ERROR_NOT_FOUND);
} catch (Exception x) {
throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST,x.getMessage(),x);
} finally {
try { reader.close();} catch (Exception x) {}
}
}
*/
protected String getObjectURI(Form queryForm) throws ResourceException {
return getParameter(queryForm,
PageParams.params.source_uri.toString(),
PageParams.params.source_uri.getDescription(),
true);
}
@Override
protected Representation processAndGenerateTask(final Method method,
Representation entity, Variant variant, boolean async)
throws ResourceException {
Connection conn = null;
try {
IQueryRetrieval<T> query = createUpdateQuery(method,getContext(),getRequest(),getResponse());
TaskCreator taskCreator = getTaskCreator(entity, variant, method, async);
List<UUID> r = null;
if (query==null) { //no db querying, just return the task
r = taskCreator.process(null);
} else {
DBConnection dbc = new DBConnection(getApplication().getContext(),getConfigFile());
conn = dbc.getConnection(getRequest());
try {
taskCreator.setConnection(conn);
r = taskCreator.process(query);
} finally {
try {
taskCreator.setConnection(null);
taskCreator.close();
} catch (Exception x) {}
try { conn.close(); conn=null;} catch (Exception x) {}
}
}
if ((r==null) || (r.size()==0)) throw new ResourceException(Status.CLIENT_ERROR_NOT_FOUND);
else {
ITaskStorage storage = ((TaskApplication)getApplication()).getTaskStorage();
FactoryTaskConvertor<Object> tc = getFactoryTaskConvertor(storage);
if (r.size()==1) {
- Task<Reference,Object> task = storage.findTask(r.get(0));
+ Task<TaskResult,Object> task = storage.findTask(r.get(0));
task.update();
- setStatus(task.isDone()?Status.SUCCESS_OK:Status.SUCCESS_ACCEPTED);
- return tc.createTaskRepresentation(r.get(0), variant,getRequest(), getResponse(),getDocumentation());
+ if (variant.getMediaType().equals(MediaType.TEXT_HTML)) {
+ getResponse().redirectSeeOther(task.getUri().getUri());
+ return null;
+ } else {
+ setStatus(task.isDone()?Status.SUCCESS_OK:Status.SUCCESS_ACCEPTED);
+ return tc.createTaskRepresentation(r.get(0), variant,getRequest(), getResponse(),getDocumentation());
+ }
} else
return tc.createTaskRepresentation(r.iterator(), variant,getRequest(), getResponse(),getDocumentation());
+
}
} catch (RResourceException x) {
throw x;
} catch (ResourceException x) {
throw new RResourceException(x.getStatus(),x, variant);
} catch (AmbitException x) {
throw new RResourceException(new Status(Status.SERVER_ERROR_INTERNAL,x),variant);
} catch (SQLException x) {
throw new RResourceException(new Status(Status.SERVER_ERROR_INTERNAL,x),variant);
} catch (Exception x) {
throw new RResourceException(new Status(Status.SERVER_ERROR_INTERNAL,x),variant);
} finally {
try { if (conn != null) conn.close(); } catch (Exception x) {}
}
}
protected TaskCreator getTaskCreator(Representation entity, Variant variant, Method method, boolean async) throws Exception {
if (entity==null) {
return getTaskCreator(null, method,async,null);
} else if (MediaType.APPLICATION_WWW_FORM.equals(entity.getMediaType())) {
Form form = new Form(entity);
final Reference reference = new Reference(getObjectURI(form));
return getTaskCreator(form, method,async,reference);
} else if (MediaType.MULTIPART_FORM_DATA.equals(entity.getMediaType(),true)) {
DiskFileItemFactory factory = new DiskFileItemFactory();
//factory.setSizeThreshold(100);
RestletFileUpload upload = new RestletFileUpload(factory);
List<FileItem> items = upload.parseRequest((Request)getRequest());
return getTaskCreator(items, method,async);
} else if (isAllowedMediaType(entity.getMediaType())) {
return getTaskCreator(downloadRepresentation(entity, variant), entity.getMediaType(), method,async);
} else throw new ResourceException(Status.CLIENT_ERROR_UNSUPPORTED_MEDIA_TYPE);
}
protected File downloadRepresentation(Representation entity, Variant variant) throws Exception{
String extension = getExtension(entity.getMediaType());
File file = null;
if (entity.getDownloadName() == null) {
file = File.createTempFile(String.format("_download_%s",UUID.randomUUID()), extension);
file.deleteOnExit();
} else
file = new File(String
.format("%s/%s", System.getProperty("java.io.tmpdir"),
entity.getDownloadName()));
FileOutputStream out = new FileOutputStream(file);
entity.write(out);
out.flush();
out.close();
return file;
}
protected String getExtension(MediaType mediaType) {
if (MediaType.APPLICATION_RDF_XML.equals(mediaType))
return ".rdf";
else if (MediaType.APPLICATION_RDF_TURTLE.equals(mediaType))
return ".turtle";
else if (MediaType.TEXT_RDF_N3.equals(mediaType))
return ".n3";
else if (MediaType.APPLICATION_EXCEL.equals(mediaType))
return ".xls";
else if (MediaType.TEXT_CSV.equals(mediaType))
return ".csv";
else if (MediaType.TEXT_PLAIN.equals(mediaType))
return ".txt";
else if (MediaType.APPLICATION_EXCEL.equals(mediaType))
return ".xls";
else if (MediaType.APPLICATION_PDF.equals(mediaType))
return ".pdf";
else
return null;
}
/**
* Create a task, given a file
* @param form
* @param method
* @param async
* @param reference
* @return
* @throws Exception
*/
protected TaskCreator getTaskCreator(File file, MediaType mediaType, final Method method, boolean async) throws Exception {
return new TaskCreatorFile<Object,T>(file,mediaType,async) {
protected ICallableTask getCallable(File file, T item) throws ResourceException {
return createCallable(method,file,mediaType,item);
}
@Override
protected Task<Reference, Object> createTask(
ICallableTask callable,
T item) throws ResourceException {
return addTask(callable, item,null);
}
};
}
/**
* Create a task, given a web form
* @param form
* @param method
* @param async
* @param reference
* @return
* @throws Exception
*/
protected TaskCreator getTaskCreator(Form form, final Method method, boolean async, final Reference reference) throws Exception {
return new TaskCreatorForm<Object,T>(form,async) {
@Override
protected ICallableTask getCallable(Form form,
T item) throws ResourceException {
return createCallable(method,form,item);
}
@Override
protected Task<Reference, Object> createTask(
ICallableTask callable,
T item) throws ResourceException {
return addTask(callable, item,reference);
}
};
}
/**
* Create task, given multipart web form (file uploads)
* @param fileItems
* @param method
* @param async
* @param reference
* @return
* @throws Exception
*/
protected TaskCreator getTaskCreator(List<FileItem> fileItems, final Method method, boolean async) throws Exception {
return new TaskCreatorMultiPartForm<Object,T>(fileItems,async) {
protected ICallableTask getCallable(java.util.List<FileItem> input, T item) throws ResourceException {
return createCallable(method,input,item);
};
@Override
protected Task createTask(ICallableTask callable, T item)
throws ResourceException {
return addTask(callable, item, (Reference)null);
}
};
}
protected Task<Reference, Object> addTask(
ICallableTask callable,
T item,
Reference reference) throws ResourceException {
return ((TaskApplication)getApplication()).addTask(
String.format("Apply %s %s %s",
item==null?"":item.toString(),
reference==null?"":"to",reference==null?"":reference),
callable,
getRequest().getRootRef(),
getToken());
}
protected CallableProtectedTask<String> createCallable(Method method,File file,MediaType mediaType,T item) throws ResourceException {
throw new ResourceException(Status.SERVER_ERROR_NOT_IMPLEMENTED);
}
protected CallableProtectedTask<String> createCallable(Method method,Form form,T item) throws ResourceException {
throw new ResourceException(Status.SERVER_ERROR_NOT_IMPLEMENTED);
}
protected CallableProtectedTask<String> createCallable(Method method,List<FileItem> input,T item) throws ResourceException {
throw new ResourceException(Status.SERVER_ERROR_NOT_IMPLEMENTED);
}
protected void setPaging(Form form, IQueryObject queryObject) {
String max = form.getFirstValue(max_hits);
String page = form.getFirstValue(PageParams.params.page.toString());
String pageSize = form.getFirstValue(PageParams.params.pagesize.toString());
if (max != null)
try {
queryObject.setPage(0);
queryObject.setPageSize(Long.parseLong(form.getFirstValue(max_hits).toString()));
return;
} catch (Exception x) {
}
try {
queryObject.setPage(Integer.parseInt(page));
} catch (Exception x) {
}
try {
queryObject.setPageSize(Long.parseLong(pageSize));
} catch (Exception x) {
}
}
/*
protected Template createTemplate(Form form) throws ResourceException {
String[] featuresURI = OpenTox.params.feature_uris.getValuesArray(form);
return createTemplate(getContext(),getRequest(),getResponse(), featuresURI);
}
protected Template createTemplate(Context context, Request request,
Response response,String[] featuresURI) throws ResourceException {
try {
Template profile = new Template(null);
profile.setId(-1);
ProfileReader reader = new ProfileReader(getRequest().getRootRef(),profile);
reader.setCloseConnection(false);
DBConnection dbc = new DBConnection(getContext());
Connection conn = dbc.getConnection(getRequest());
try {
for (String featureURI:featuresURI) {
if (featureURI == null) continue;
reader.setConnection(conn);
profile = reader.process(new Reference(featureURI));
reader.setProfile(profile);
}
// readFeatures(featureURI, profile);
if (profile.size() == 0) {
reader.setConnection(conn);
String templateuri = getDefaultTemplateURI(context,request,response);
if (templateuri!= null) profile = reader.process(new Reference(templateuri));
reader.setProfile(profile);
}
} catch (Exception x) {
System.out.println(getRequest().getResourceRef());
//x.printStackTrace();
} finally {
//the reader closes the connection
reader.setCloseConnection(true);
try { reader.close();} catch (Exception x) {}
//try { conn.close();} catch (Exception x) {}
}
return profile;
} catch (Exception x) {
getLogger().info(x.getMessage());
throw new ResourceException(Status.SERVER_ERROR_INTERNAL,x);
}
}
protected String getDefaultTemplateURI(Context context, Request request,Response response) {
return null;
}
*/
protected String getLicenseURI() {
return null;
}
protected boolean isAllowedMediaType(MediaType mediaType) throws ResourceException {
throw new ResourceException(Status.SERVER_ERROR_NOT_IMPLEMENTED);
}
}
| false | false | null | null |
diff --git a/src/me/guillaumin/android/osmtracker/layout/UserDefinedLayout.java b/src/me/guillaumin/android/osmtracker/layout/UserDefinedLayout.java
index 5420e3a..ace7235 100644
--- a/src/me/guillaumin/android/osmtracker/layout/UserDefinedLayout.java
+++ b/src/me/guillaumin/android/osmtracker/layout/UserDefinedLayout.java
@@ -1,123 +1,128 @@
package me.guillaumin.android.osmtracker.layout;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Stack;
import me.guillaumin.android.osmtracker.OSMTracker;
import me.guillaumin.android.osmtracker.R;
import me.guillaumin.android.osmtracker.activity.TrackLogger;
import me.guillaumin.android.osmtracker.service.resources.AppResourceIconResolver;
import me.guillaumin.android.osmtracker.service.resources.ExternalDirectoryIconResolver;
import me.guillaumin.android.osmtracker.util.UserDefinedLayoutReader;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
+import android.content.Context;
import android.view.ViewGroup;
import android.widget.LinearLayout;
/**
* Manages user-definable layout. User can define his own buttons
* and pages of buttons in an XML file.
*
* @author Nicolas Guillaumin
*
*/
public class UserDefinedLayout extends LinearLayout {
@SuppressWarnings("unused")
private static final String TAG = UserDefinedLayout.class.getSimpleName();
/**
* Name of the root layout.
*/
private static final String ROOT_LAYOUT_NAME = "root";
/**
* List of layouts (button pages) read from XML
*/
private HashMap<String, ViewGroup> layouts = new HashMap<String, ViewGroup>();
/**
* Stack for keeping track of user navigation in pages
*/
private Stack<String> layoutStack = new Stack<String>();
+
+ public UserDefinedLayout(Context ctx) {
+ super(ctx);
+ }
public UserDefinedLayout(TrackLogger activity, long trackId, File xmlLayout) throws XmlPullParserException, IOException {
super(activity);
// Set default presentation parameters
setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT, 1));
UserDefinedLayoutReader udlr;
XmlPullParser parser;
if (xmlLayout == null) {
// No user file, use default file
parser = getResources().getXml(R.xml.default_buttons_layout);
udlr = new UserDefinedLayoutReader(this, getContext(), activity, trackId, parser, new AppResourceIconResolver(getResources(), OSMTracker.class.getPackage().getName()));
} else {
// User file specified, parse it
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
parser = factory.newPullParser();
parser.setInput(new FileReader(xmlLayout));
udlr = new UserDefinedLayoutReader(this, getContext(), activity, trackId, parser, new ExternalDirectoryIconResolver(xmlLayout.getParentFile()));
}
layouts = udlr.parseLayout();
if (layouts == null || layouts.isEmpty() || layouts.get(ROOT_LAYOUT_NAME) == null) {
throw new IOException("Error in layout file. Is there a layout name '" + ROOT_LAYOUT_NAME + "' defined ?");
}
// XML file parsed, push the root layout on the view
push(ROOT_LAYOUT_NAME);
}
/**
* Push the specified layout on top of the view
* @param s Name of layout to push.
*/
public void push(String s) {
if (layouts.get(s) != null) {
layoutStack.push(s);
if (this.getChildCount() > 0) {
this.removeAllViews();
}
this.addView(layouts.get(layoutStack.peek()));
}
}
/**
* Pops the current top-layout, and set the view to
* the new top-layout.
* @return The name of the popped layout
*/
public String pop() {
String out = layoutStack.pop();
if (this.getChildCount() > 0) {
this.removeAllViews();
}
this.addView(layouts.get(layoutStack.peek()));
return out;
}
/**
* @return the number of layouts stacked
*/
public int getStackSize() {
return layoutStack.size();
}
@Override
public void setEnabled(boolean enabled) {
super.setEnabled(enabled);
this.getChildAt(0).setEnabled(enabled);
}
}
diff --git a/src/me/guillaumin/android/osmtracker/view/DisplayTrackView.java b/src/me/guillaumin/android/osmtracker/view/DisplayTrackView.java
index 6e09f4e..4105156 100644
--- a/src/me/guillaumin/android/osmtracker/view/DisplayTrackView.java
+++ b/src/me/guillaumin/android/osmtracker/view/DisplayTrackView.java
@@ -1,326 +1,330 @@
package me.guillaumin.android.osmtracker.view;
import java.text.DecimalFormat;
import me.guillaumin.android.osmtracker.R;
import me.guillaumin.android.osmtracker.db.TrackContentProvider;
import me.guillaumin.android.osmtracker.db.TrackContentProvider.Schema;
import me.guillaumin.android.osmtracker.util.ArrayUtils;
import me.guillaumin.android.osmtracker.util.MercatorProjection;
import android.content.Context;
import android.database.ContentObserver;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.os.Handler;
import android.util.Log;
import android.widget.TextView;
public class DisplayTrackView extends TextView {
private static final String TAG = DisplayTrackView.class.getSimpleName();
/**
* Padding (in pixels) for drawing track, to prevent touching the borders.
*/
private static final int PADDING = 5;
/**
* Width of the scale bar, in pixels.
*/
private static final int SCALE_WIDTH = 50;
/**
* Height of left & right small lines to delimit scale (pixels)
*/
private static final int SCALE_DELIM_HEIGHT = 10;
/**
* Formatter for scale information
*/
private static final DecimalFormat SCALE_FORMAT = new DecimalFormat("0");
/**
* Coordinates to draw (before projection)
*/
private double[][] coords;
/**
* Array of pixels coordinates to display track
*/
private int[][] pixels;
/**
* Coordinates of waypoints
*/
private double[][] wayPointsCoords;
/**
* Pixels coordinates to display waypoints
*/
private int[][] wayPointsPixels;
/**
* The projection used to convert coordinates to pixels.
*/
private MercatorProjection projection;
/**
* Paint used for drawing track.
*/
private Paint trackPaint = new Paint();
/**
* Compass bitmap
*/
private Bitmap compass;
/**
* Position marker bitmap
*/
private Bitmap marker;
/**
* Way point marker Bitmap
*/
private Bitmap wayPointMarker;
/**
* Letter to use for meter unit (taken from resources)
*/
private String meterLabel;
/**
* Letter to use for indicating North (taken from resources)
*/
private String northLabel;
/**
* Current track id
*/
private long currentTrackId;
/**
* ContentObserver to be notified about any new trackpoint and
* redraw screen
*/
private class TrackPointContentObserver extends ContentObserver {
public TrackPointContentObserver(Handler handler) {
super(handler);
}
@Override
public void onChange(boolean selfChange) {
// width & height could be = 0 if the view had
// not been attached to window & measured when onChange()
// is fired.
if (getWidth() > 0 && getHeight() > 0) {
// Populate new data, and recompute projection
populateCoords();
projectData(getWidth(), getHeight());
// Force view redraw
invalidate();
}
}
}
/**
* Instance of TrackpointContentObserver
*/
private TrackPointContentObserver trackpointContentObserver;
+ public DisplayTrackView(Context context) {
+ super(context);
+ }
+
public DisplayTrackView(Context context, long trackId) {
super(context);
currentTrackId = trackId;
// Set text align to center
getPaint().setTextAlign(Align.CENTER);
// Setup track drawing paint
trackPaint.setColor(getCurrentTextColor());
trackPaint.setStyle(Paint.Style.FILL_AND_STROKE);
// Retrieve some resources that will be used in drawing
meterLabel = getResources().getString(R.string.various_unit_meters);
northLabel = getResources().getString(R.string.displaytrack_north);
marker = BitmapFactory.decodeResource(getResources(), R.drawable.marker);
compass = BitmapFactory.decodeResource(getResources(), android.R.drawable.ic_menu_compass);
wayPointMarker = BitmapFactory.decodeResource(getResources(), R.drawable.star);
trackpointContentObserver = new TrackPointContentObserver(new Handler());
context.getContentResolver().registerContentObserver(
TrackContentProvider.trackPointsUri(currentTrackId),
true, trackpointContentObserver);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
Log.v(TAG, "onSizeChanged: " + w + "," + h + ". Old: " + oldw + "," + oldh);
// Populate data from content provider
populateCoords();
// Project coordinates into 2D screen
projectData(w, h);
super.onSizeChanged(w, h, oldw, oldh);
}
@Override
protected void onDetachedFromWindow() {
// Unregister content observer
getContext().getContentResolver().unregisterContentObserver(trackpointContentObserver);
super.onDetachedFromWindow();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// If we have data to paint
if (pixels != null && pixels.length > 0) {
int length = pixels.length;
for (int i = 1; i < length; i++) {
// Draw a line between each point
canvas.drawLine(
PADDING + pixels[i - 1][MercatorProjection.X],
PADDING + pixels[i - 1][MercatorProjection.Y],
PADDING + pixels[i][MercatorProjection.X],
PADDING + pixels[i][MercatorProjection.Y], trackPaint);
}
// Draw a marker for each waypoint
if (wayPointsPixels != null && wayPointsPixels.length > 0) {
int wpLength = wayPointsPixels.length;
for (int i = 0; i < wpLength; i++) {
canvas.drawBitmap(wayPointMarker,
PADDING + wayPointsPixels[i][MercatorProjection.X],
PADDING + wayPointsPixels[i][MercatorProjection.Y],
this.getPaint());
}
}
// Draw current position marker
canvas.drawBitmap(marker, pixels[length - 1][MercatorProjection.X],
pixels[length - 1][MercatorProjection.Y], this.getPaint());
// Draw scale information
drawScale(canvas);
}
// Draw static resources
drawStatic(canvas);
}
/**
* Draw scale information.
*
* @param canvas
* Canvas used to draw
*/
private void drawScale(Canvas canvas) {
double scale = projection.getScale();
Log.v(TAG, "Scale is: " + scale);
// Draw horizontal line
canvas.drawLine(getWidth() - PADDING - SCALE_WIDTH, PADDING+SCALE_DELIM_HEIGHT/2, getWidth() - PADDING, PADDING+SCALE_DELIM_HEIGHT/2, this.getPaint());
// Draw 2 small vertical lines for the bounds
canvas.drawLine(getWidth() - PADDING - SCALE_WIDTH, PADDING, getWidth() - PADDING - SCALE_WIDTH,
PADDING + SCALE_DELIM_HEIGHT, this.getPaint());
canvas.drawLine(getWidth() - PADDING, PADDING, getWidth() - PADDING, PADDING + SCALE_DELIM_HEIGHT, this.getPaint());
// Draw scale
canvas.drawText(SCALE_FORMAT.format(100*1000*scale*SCALE_WIDTH) + meterLabel, getWidth() - PADDING - SCALE_WIDTH / 2,
PADDING + SCALE_DELIM_HEIGHT + getPaint().getTextSize(), this.getPaint());
}
/**
* Draw various static gfx (Compass ...)
*
* @param canvas
* Canvas used to draw
*/
private void drawStatic(Canvas canvas) {
canvas.drawBitmap(compass, PADDING, getHeight() - PADDING - compass.getHeight(), null);
canvas.drawText(northLabel, PADDING + compass.getWidth() / 2, getHeight() - PADDING - compass.getHeight() - 5,
this.getPaint());
}
/**
* Populate coordinates from a cursor to current track Database
*/
public void populateCoords() {
Cursor c = getContext().getContentResolver().query(
TrackContentProvider.trackPointsUri(currentTrackId),
null, null, null, TrackContentProvider.Schema.COL_TIMESTAMP + " asc");
coords = new double[c.getCount()][2];
int i=0;
for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext(), i++) {
coords[i][MercatorProjection.LONGITUDE] = c.getDouble(c.getColumnIndex(Schema.COL_LONGITUDE));
coords[i][MercatorProjection.LATITUDE] = c.getDouble(c.getColumnIndex(Schema.COL_LATITUDE));
}
c.close();
Log.v(TAG, "Extracted " + coords.length + " track points from DB.");
c = getContext().getContentResolver().query(
TrackContentProvider.waypointsUri(currentTrackId),
null, null, null, TrackContentProvider.Schema.COL_TIMESTAMP + " asc");
wayPointsCoords = new double[c.getCount()][2];
for(c.moveToFirst(), i=0; !c.isAfterLast(); c.moveToNext(), i++) {
wayPointsCoords[i][MercatorProjection.LONGITUDE] = c.getDouble(c.getColumnIndex(Schema.COL_LONGITUDE));
wayPointsCoords[i][MercatorProjection.LATITUDE] = c.getDouble(c.getColumnIndex(Schema.COL_LATITUDE));
}
c.close();
Log.v(TAG, "Extracted " + wayPointsCoords.length + " way points from DB.");
}
/**
* Project current coordinates into a 2D screen
* @param width Width of the display screen
* @param height Height of the display screen
*/
public void projectData(int width, int height) {
// If we got coordinates, start projecting.
if (coords != null && coords.length > 0) {
projection = new MercatorProjection(
ArrayUtils.findMin(coords, MercatorProjection.LATITUDE),
ArrayUtils.findMin(coords, MercatorProjection.LONGITUDE),
ArrayUtils.findMax(coords, MercatorProjection.LATITUDE),
ArrayUtils.findMax(coords, MercatorProjection.LONGITUDE),
width - PADDING * 2, height - PADDING * 2);
// Project each coordinate into pixels.
pixels = new int[coords.length][2];
int length = pixels.length;
for (int i = 0; i < length; i++) {
pixels[i] = projection.project(coords[i][MercatorProjection.LONGITUDE],
coords[i][MercatorProjection.LATITUDE]);
}
// Same thing for way points, using same projection
if (wayPointsCoords != null && wayPointsCoords.length > 0) {
// Project each coordinate into pixels.
wayPointsPixels = new int[wayPointsCoords.length][2];
length = wayPointsPixels.length;
for (int i = 0; i < length; i++) {
wayPointsPixels[i] = projection.project(wayPointsCoords[i][MercatorProjection.LONGITUDE],
wayPointsCoords[i][MercatorProjection.LATITUDE]);
}
}
}
}
}
| false | false | null | null |
diff --git a/org.sonar.ide.eclipse/src/org/sonar/ide/eclipse/jobs/RefreshViolationsJob.java b/org.sonar.ide.eclipse/src/org/sonar/ide/eclipse/jobs/RefreshViolationsJob.java
index 605fcf24..2e851517 100644
--- a/org.sonar.ide.eclipse/src/org/sonar/ide/eclipse/jobs/RefreshViolationsJob.java
+++ b/org.sonar.ide.eclipse/src/org/sonar/ide/eclipse/jobs/RefreshViolationsJob.java
@@ -1,149 +1,144 @@
/*
* Sonar, open source software quality management tool.
* Copyright (C) 2010 SonarSource
* mailto:contact AT sonarsource DOT com
*
* Sonar 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.
*
* Sonar 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 Sonar; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
*/
package org.sonar.ide.eclipse.jobs;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.IFileEditorInput;
-import org.eclipse.ui.IPartListener2;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.IWorkbenchPart;
-import org.eclipse.ui.IWorkbenchPartReference;
+import org.eclipse.ui.*;
import org.eclipse.ui.progress.UIJob;
import org.sonar.ide.eclipse.SonarPlugin;
import org.sonar.ide.eclipse.core.ISonarConstants;
+import org.sonar.ide.eclipse.core.ISonarResource;
import org.sonar.ide.eclipse.internal.EclipseSonar;
+import org.sonar.ide.eclipse.utils.PlatformUtils;
import org.sonar.ide.shared.violations.ViolationUtils;
import org.sonar.wsclient.services.Violation;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
+import java.util.*;
/**
* This class load violations in background.
*
* @link http://jira.codehaus.org/browse/SONARIDE-27
*
* @author Jérémie Lagarde
*/
public class RefreshViolationsJob extends AbstractRefreshModelJob<Violation> {
public RefreshViolationsJob(final List<IResource> resources) {
super(resources, ISonarConstants.MARKER_ID);
}
@Override
protected Collection<Violation> retrieveDatas(EclipseSonar sonar, IResource resource) {
return sonar.search(resource).getViolations();
}
@Override
protected Integer getLine(final Violation violation) {
return violation.getLine();
}
@Override
protected String getMessage(final Violation violation) {
return ViolationUtils.getDescription(violation);
}
@Override
protected Integer getPriority(final Violation violation) {
if (ViolationUtils.PRIORITY_BLOCKER.equalsIgnoreCase(violation.getPriority())) {
return new Integer(IMarker.PRIORITY_HIGH);
}
if (ViolationUtils.PRIORITY_CRITICAL.equalsIgnoreCase(violation.getPriority())) {
return new Integer(IMarker.PRIORITY_HIGH);
}
if (ViolationUtils.PRIORITY_MAJOR.equalsIgnoreCase(violation.getPriority())) {
return new Integer(IMarker.PRIORITY_NORMAL);
}
return new Integer(IMarker.PRIORITY_LOW);
}
@Override
protected Integer getSeverity(final Violation violation) {
return new Integer(IMarker.SEVERITY_WARNING);
}
@Override
protected Map<String, Object> getExtraInfos(final Violation violation) {
final Map<String, Object> extraInfos = new HashMap<String, Object>();
extraInfos.put("rulekey", violation.getRuleKey());
extraInfos.put("rulename", violation.getRuleName());
extraInfos.put("rulepriority", violation.getPriority());
return extraInfos;
}
public static void setupViolationsUpdater() {
new UIJob("Prepare violations updater") {
@Override
public IStatus runInUIThread(IProgressMonitor monitor) {
final IWorkbenchPage page = SonarPlugin.getDefault().getWorkbench().getActiveWorkbenchWindow().getActivePage();
page.addPartListener(new ViolationsUpdater());
return Status.OK_STATUS;
}
}.schedule();
}
private static class ViolationsUpdater implements IPartListener2 {
public void partOpened(IWorkbenchPartReference partRef) {
IWorkbenchPart part = partRef.getPart(true);
if (part instanceof IEditorPart) {
IEditorInput input = ((IEditorPart) part).getEditorInput();
if (input instanceof IFileEditorInput) {
IResource resource = ((IFileEditorInput) input).getFile();
- new RefreshViolationsJob(Collections.singletonList(resource)).schedule();
+ ISonarResource sonarResource = PlatformUtils.adapt(resource, ISonarResource.class);
+ if (sonarResource != null) {
+ new RefreshViolationsJob(Collections.singletonList(resource)).schedule();
+ }
}
}
}
public void partVisible(IWorkbenchPartReference partRef) {
}
public void partInputChanged(IWorkbenchPartReference partRef) {
}
public void partHidden(IWorkbenchPartReference partRef) {
}
public void partDeactivated(IWorkbenchPartReference partRef) {
}
public void partClosed(IWorkbenchPartReference partRef) {
}
public void partBroughtToTop(IWorkbenchPartReference partRef) {
}
public void partActivated(IWorkbenchPartReference partRef) {
}
}
}
| false | false | null | null |
diff --git a/src/com/fsck/k9/mail/store/ImapStore.java b/src/com/fsck/k9/mail/store/ImapStore.java
index 19fc8729..fff7710d 100644
--- a/src/com/fsck/k9/mail/store/ImapStore.java
+++ b/src/com/fsck/k9/mail/store/ImapStore.java
@@ -1,1302 +1,1302 @@
package com.fsck.k9.mail.store;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.security.GeneralSecurityException;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.SSLException;
import android.util.Config;
import android.util.Log;
import com.fsck.k9.k9;
import com.fsck.k9.PeekableInputStream;
import com.fsck.k9.Utility;
import com.fsck.k9.mail.AuthenticationFailedException;
import com.fsck.k9.mail.FetchProfile;
import com.fsck.k9.mail.Flag;
import com.fsck.k9.mail.Folder;
import com.fsck.k9.mail.Message;
import com.fsck.k9.mail.MessageRetrievalListener;
import com.fsck.k9.mail.MessagingException;
import com.fsck.k9.mail.Part;
import com.fsck.k9.mail.Store;
import com.fsck.k9.mail.CertificateValidationException;
import com.fsck.k9.mail.internet.MimeBodyPart;
import com.fsck.k9.mail.internet.MimeHeader;
import com.fsck.k9.mail.internet.MimeMessage;
import com.fsck.k9.mail.internet.MimeMultipart;
import com.fsck.k9.mail.internet.MimeUtility;
import com.fsck.k9.mail.store.ImapResponseParser.ImapList;
import com.fsck.k9.mail.store.ImapResponseParser.ImapResponse;
import com.fsck.k9.mail.transport.CountingOutputStream;
import com.fsck.k9.mail.transport.EOLConvertingOutputStream;
import com.beetstra.jutf7.CharsetProvider;
/**
* <pre>
* TODO Need to start keeping track of UIDVALIDITY
* TODO Need a default response handler for things like folder updates
* TODO In fetch(), if we need a ImapMessage and were given
* something else we can try to do a pre-fetch first.
*
* ftp://ftp.isi.edu/in-notes/rfc2683.txt When a client asks for
* certain information in a FETCH command, the server may return the requested
* information in any order, not necessarily in the order that it was requested.
* Further, the server may return the information in separate FETCH responses
* and may also return information that was not explicitly requested (to reflect
* to the client changes in the state of the subject message).
* </pre>
*/
public class ImapStore extends Store {
public static final int CONNECTION_SECURITY_NONE = 0;
public static final int CONNECTION_SECURITY_TLS_OPTIONAL = 1;
public static final int CONNECTION_SECURITY_TLS_REQUIRED = 2;
public static final int CONNECTION_SECURITY_SSL_REQUIRED = 3;
public static final int CONNECTION_SECURITY_SSL_OPTIONAL = 4;
private static final Flag[] PERMANENT_FLAGS = { Flag.DELETED, Flag.SEEN };
private String mHost;
private int mPort;
private String mUsername;
private String mPassword;
private int mConnectionSecurity;
private String mPathPrefix;
private LinkedList<ImapConnection> mConnections =
new LinkedList<ImapConnection>();
/**
* Charset used for converting folder names to and from UTF-7 as defined by RFC 3501.
*/
private Charset mModifiedUtf7Charset;
/**
* Cache of ImapFolder objects. ImapFolders are attached to a given folder on the server
* and as long as their associated connection remains open they are reusable between
* requests. This cache lets us make sure we always reuse, if possible, for a given
* folder name.
*/
private HashMap<String, ImapFolder> mFolderCache = new HashMap<String, ImapFolder>();
/**
* imap://user:password@server:port CONNECTION_SECURITY_NONE
* imap+tls://user:password@server:port CONNECTION_SECURITY_TLS_OPTIONAL
* imap+tls+://user:password@server:port CONNECTION_SECURITY_TLS_REQUIRED
* imap+ssl+://user:password@server:port CONNECTION_SECURITY_SSL_REQUIRED
* imap+ssl://user:password@server:port CONNECTION_SECURITY_SSL_OPTIONAL
*
* @param _uri
*/
public ImapStore(String _uri) throws MessagingException {
URI uri;
try {
uri = new URI(_uri);
} catch (URISyntaxException use) {
throw new MessagingException("Invalid ImapStore URI", use);
}
String scheme = uri.getScheme();
if (scheme.equals("imap")) {
mConnectionSecurity = CONNECTION_SECURITY_NONE;
mPort = 143;
} else if (scheme.equals("imap+tls")) {
mConnectionSecurity = CONNECTION_SECURITY_TLS_OPTIONAL;
mPort = 143;
} else if (scheme.equals("imap+tls+")) {
mConnectionSecurity = CONNECTION_SECURITY_TLS_REQUIRED;
mPort = 143;
} else if (scheme.equals("imap+ssl+")) {
mConnectionSecurity = CONNECTION_SECURITY_SSL_REQUIRED;
mPort = 993;
} else if (scheme.equals("imap+ssl")) {
mConnectionSecurity = CONNECTION_SECURITY_SSL_OPTIONAL;
mPort = 993;
} else {
throw new MessagingException("Unsupported protocol");
}
mHost = uri.getHost();
if (uri.getPort() != -1) {
mPort = uri.getPort();
}
if (uri.getUserInfo() != null) {
String[] userInfoParts = uri.getUserInfo().split(":", 2);
mUsername = userInfoParts[0];
if (userInfoParts.length > 1) {
mPassword = userInfoParts[1];
}
}
if ((uri.getPath() != null) && (uri.getPath().length() > 0)) {
mPathPrefix = uri.getPath().substring(1);
}
mModifiedUtf7Charset = new CharsetProvider().charsetForName("X-RFC-3501");
}
@Override
public Folder getFolder(String name) throws MessagingException {
ImapFolder folder;
synchronized (mFolderCache) {
folder = mFolderCache.get(name);
if (folder == null) {
folder = new ImapFolder(name);
mFolderCache.put(name, folder);
}
}
return folder;
}
@Override
public Folder[] getPersonalNamespaces() throws MessagingException {
ImapConnection connection = getConnection();
try {
ArrayList<Folder> folders = new ArrayList<Folder>();
if(mPathPrefix == null){ mPathPrefix = ""; }
List<ImapResponse> responses =
connection.executeSimpleCommand(String.format("LIST \"\" \"%s*\"",
mPathPrefix));
for (ImapResponse response : responses) {
if (response.get(0).equals("LIST")) {
boolean includeFolder = true;
String folder = decodeFolderName(response.getString(3));
if (folder.equalsIgnoreCase(k9.INBOX)) {
continue;
}else{
if(mPathPrefix.length() > 0){
if(folder.length() >= mPathPrefix.length() + 1){
folder = folder.substring(mPathPrefix.length() + 1);
}
}
}
ImapList attributes = response.getList(1);
for (int i = 0, count = attributes.size(); i < count; i++) {
String attribute = attributes.getString(i);
if (attribute.equalsIgnoreCase("\\NoSelect")) {
includeFolder = false;
}
}
if (includeFolder) {
folders.add(getFolder(folder));
}
}
}
folders.add(getFolder("INBOX"));
return folders.toArray(new Folder[] {});
} catch (IOException ioe) {
connection.close();
throw new MessagingException("Unable to get folder list.", ioe);
} finally {
releaseConnection(connection);
}
}
@Override
public void checkSettings() throws MessagingException {
try {
ImapConnection connection = new ImapConnection();
connection.open();
connection.close();
}
catch (IOException ioe) {
throw new MessagingException("Unable to connect.", ioe);
}
}
/**
* Gets a connection if one is available for reuse, or creates a new one if not.
* @return
*/
private ImapConnection getConnection() throws MessagingException {
synchronized (mConnections) {
ImapConnection connection = null;
while ((connection = mConnections.poll()) != null) {
try {
connection.executeSimpleCommand("NOOP");
break;
}
catch (IOException ioe) {
connection.close();
}
}
if (connection == null) {
connection = new ImapConnection();
}
return connection;
}
}
private void releaseConnection(ImapConnection connection) {
mConnections.offer(connection);
}
private String encodeFolderName(String name) {
try {
ByteBuffer bb = mModifiedUtf7Charset.encode(name);
byte[] b = new byte[bb.limit()];
bb.get(b);
return new String(b, "US-ASCII");
}
catch (UnsupportedEncodingException uee) {
/*
* The only thing that can throw this is getBytes("US-ASCII") and if US-ASCII doesn't
* exist we're totally screwed.
*/
- throw new RuntimeException("Unabel to encode folder name: " + name, uee);
+ throw new RuntimeException("Unable to encode folder name: " + name, uee);
}
}
private String decodeFolderName(String name) {
/*
* Convert the encoded name to US-ASCII, then pass it through the modified UTF-7
* decoder and return the Unicode String.
*/
try {
byte[] encoded = name.getBytes("US-ASCII");
CharBuffer cb = mModifiedUtf7Charset.decode(ByteBuffer.wrap(encoded));
return cb.toString();
}
catch (UnsupportedEncodingException uee) {
/*
* The only thing that can throw this is getBytes("US-ASCII") and if US-ASCII doesn't
* exist we're totally screwed.
*/
throw new RuntimeException("Unable to decode folder name: " + name, uee);
}
}
class ImapFolder extends Folder {
private String mName;
private int mMessageCount = -1;
private ImapConnection mConnection;
private OpenMode mMode;
private boolean mExists;
public ImapFolder(String name) {
this.mName = name;
}
public String getPrefixedName() {
String prefixedName = "";
if(mPathPrefix.length() > 0 && !mName.equalsIgnoreCase(k9.INBOX)){
prefixedName += mPathPrefix + ".";
}
prefixedName += mName;
return prefixedName;
}
public void open(OpenMode mode) throws MessagingException {
if (isOpen() && mMode == mode) {
// Make sure the connection is valid. If it's not we'll close it down and continue
// on to get a new one.
try {
mConnection.executeSimpleCommand("NOOP");
return;
}
catch (IOException ioe) {
ioExceptionHandler(mConnection, ioe);
}
}
synchronized (this) {
mConnection = getConnection();
}
// * FLAGS (\Answered \Flagged \Deleted \Seen \Draft NonJunk
// $MDNSent)
// * OK [PERMANENTFLAGS (\Answered \Flagged \Deleted \Seen \Draft
// NonJunk $MDNSent \*)] Flags permitted.
// * 23 EXISTS
// * 0 RECENT
// * OK [UIDVALIDITY 1125022061] UIDs valid
// * OK [UIDNEXT 57576] Predicted next UID
// 2 OK [READ-WRITE] Select completed.
try {
List<ImapResponse> responses = mConnection.executeSimpleCommand(
String.format("SELECT \"%s\"",
encodeFolderName(getPrefixedName())));
/*
* If the command succeeds we expect the folder has been opened read-write
* unless we are notified otherwise in the responses.
*/
mMode = OpenMode.READ_WRITE;
for (ImapResponse response : responses) {
if (response.mTag == null && response.get(1).equals("EXISTS")) {
mMessageCount = response.getNumber(0);
}
else if (response.mTag != null && response.size() >= 2) {
if ("[READ-ONLY]".equalsIgnoreCase(response.getString(1))) {
mMode = OpenMode.READ_ONLY;
}
else if ("[READ-WRITE]".equalsIgnoreCase(response.getString(1))) {
mMode = OpenMode.READ_WRITE;
}
}
}
if (mMessageCount == -1) {
throw new MessagingException(
"Did not find message count during select");
}
mExists = true;
} catch (IOException ioe) {
throw ioExceptionHandler(mConnection, ioe);
}
}
public boolean isOpen() {
return mConnection != null;
}
@Override
public OpenMode getMode() throws MessagingException {
return mMode;
}
public void close(boolean expunge) {
if (!isOpen()) {
return;
}
// TODO implement expunge
mMessageCount = -1;
synchronized (this) {
releaseConnection(mConnection);
mConnection = null;
}
}
public String getName() {
return mName;
}
public boolean exists() throws MessagingException {
if (mExists) {
return true;
}
/*
* This method needs to operate in the unselected mode as well as the selected mode
* so we must get the connection ourselves if it's not there. We are specifically
* not calling checkOpen() since we don't care if the folder is open.
*/
ImapConnection connection = null;
synchronized(this) {
if (mConnection == null) {
connection = getConnection();
}
else {
connection = mConnection;
}
}
try {
connection.executeSimpleCommand(String.format("STATUS \"%s\" (UIDVALIDITY)",
encodeFolderName(getPrefixedName())));
mExists = true;
return true;
}
catch (MessagingException me) {
return false;
}
catch (IOException ioe) {
throw ioExceptionHandler(connection, ioe);
}
finally {
if (mConnection == null) {
releaseConnection(connection);
}
}
}
public boolean create(FolderType type) throws MessagingException {
/*
* This method needs to operate in the unselected mode as well as the selected mode
* so we must get the connection ourselves if it's not there. We are specifically
* not calling checkOpen() since we don't care if the folder is open.
*/
ImapConnection connection = null;
synchronized(this) {
if (mConnection == null) {
connection = getConnection();
}
else {
connection = mConnection;
}
}
try {
connection.executeSimpleCommand(String.format("CREATE \"%s\"",
encodeFolderName(getPrefixedName())));
return true;
}
catch (MessagingException me) {
return false;
}
catch (IOException ioe) {
throw ioExceptionHandler(mConnection, ioe);
}
finally {
if (mConnection == null) {
releaseConnection(connection);
}
}
}
@Override
public void copyMessages(Message[] messages, Folder folder) throws MessagingException {
checkOpen();
String[] uids = new String[messages.length];
for (int i = 0, count = messages.length; i < count; i++) {
uids[i] = messages[i].getUid();
}
try {
mConnection.executeSimpleCommand(String.format("UID COPY %s \"%s\"",
Utility.combine(uids, ','),
encodeFolderName(folder.getName())));
}
catch (IOException ioe) {
throw ioExceptionHandler(mConnection, ioe);
}
}
@Override
public int getMessageCount() {
return mMessageCount;
}
@Override
public int getUnreadMessageCount() throws MessagingException {
checkOpen();
try {
int unreadMessageCount = 0;
List<ImapResponse> responses = mConnection.executeSimpleCommand(
String.format("STATUS \"%s\" (UNSEEN)",
encodeFolderName(getPrefixedName())));
for (ImapResponse response : responses) {
if (response.mTag == null && response.get(0).equals("STATUS")) {
ImapList status = response.getList(2);
unreadMessageCount = status.getKeyedNumber("UNSEEN");
}
}
return unreadMessageCount;
}
catch (IOException ioe) {
throw ioExceptionHandler(mConnection, ioe);
}
}
@Override
public void delete(boolean recurse) throws MessagingException {
throw new Error("ImapStore.delete() not yet implemented");
}
@Override
public Message getMessage(String uid) throws MessagingException {
checkOpen();
try {
try {
List<ImapResponse> responses =
mConnection.executeSimpleCommand(String.format("UID SEARCH UID %S", uid));
for (ImapResponse response : responses) {
if (response.mTag == null && response.get(0).equals("SEARCH")) {
for (int i = 1, count = response.size(); i < count; i++) {
if (uid.equals(response.get(i))) {
return new ImapMessage(uid, this);
}
}
}
}
}
catch (MessagingException me) {
return null;
}
}
catch (IOException ioe) {
throw ioExceptionHandler(mConnection, ioe);
}
return null;
}
@Override
public Message[] getMessages(int start, int end, MessageRetrievalListener listener)
throws MessagingException {
if (start < 1 || end < 1 || end < start) {
throw new MessagingException(
String.format("Invalid message set %d %d",
start, end));
}
checkOpen();
ArrayList<Message> messages = new ArrayList<Message>();
try {
ArrayList<String> uids = new ArrayList<String>();
List<ImapResponse> responses = mConnection
.executeSimpleCommand(String.format("UID SEARCH %d:%d NOT DELETED", start, end));
for (ImapResponse response : responses) {
if (response.get(0).equals("SEARCH")) {
for (int i = 1, count = response.size(); i < count; i++) {
uids.add(response.getString(i));
}
}
}
for (int i = 0, count = uids.size(); i < count; i++) {
if (listener != null) {
listener.messageStarted(uids.get(i), i, count);
}
ImapMessage message = new ImapMessage(uids.get(i), this);
messages.add(message);
if (listener != null) {
listener.messageFinished(message, i, count);
}
}
} catch (IOException ioe) {
throw ioExceptionHandler(mConnection, ioe);
}
return messages.toArray(new Message[] {});
}
public Message[] getMessages(MessageRetrievalListener listener) throws MessagingException {
return getMessages(null, listener);
}
public Message[] getMessages(String[] uids, MessageRetrievalListener listener)
throws MessagingException {
checkOpen();
ArrayList<Message> messages = new ArrayList<Message>();
try {
if (uids == null) {
List<ImapResponse> responses = mConnection
.executeSimpleCommand("UID SEARCH 1:* NOT DELETED");
ArrayList<String> tempUids = new ArrayList<String>();
for (ImapResponse response : responses) {
if (response.get(0).equals("SEARCH")) {
for (int i = 1, count = response.size(); i < count; i++) {
tempUids.add(response.getString(i));
}
}
}
uids = tempUids.toArray(new String[] {});
}
for (int i = 0, count = uids.length; i < count; i++) {
if (listener != null) {
listener.messageStarted(uids[i], i, count);
}
ImapMessage message = new ImapMessage(uids[i], this);
messages.add(message);
if (listener != null) {
listener.messageFinished(message, i, count);
}
}
} catch (IOException ioe) {
throw ioExceptionHandler(mConnection, ioe);
}
return messages.toArray(new Message[] {});
}
public void fetch(Message[] messages, FetchProfile fp, MessageRetrievalListener listener)
throws MessagingException {
if (messages == null || messages.length == 0) {
return;
}
checkOpen();
String[] uids = new String[messages.length];
HashMap<String, Message> messageMap = new HashMap<String, Message>();
for (int i = 0, count = messages.length; i < count; i++) {
uids[i] = messages[i].getUid();
messageMap.put(uids[i], messages[i]);
}
/*
* Figure out what command we are going to run:
* Flags - UID FETCH (FLAGS)
* Envelope - UID FETCH ([FLAGS] INTERNALDATE UID RFC822.SIZE FLAGS BODY.PEEK[HEADER.FIELDS (date subject from content-type to cc)])
*
*/
LinkedHashSet<String> fetchFields = new LinkedHashSet<String>();
fetchFields.add("UID");
if (fp.contains(FetchProfile.Item.FLAGS)) {
fetchFields.add("FLAGS");
}
if (fp.contains(FetchProfile.Item.ENVELOPE)) {
fetchFields.add("INTERNALDATE");
fetchFields.add("RFC822.SIZE");
fetchFields.add("BODY.PEEK[HEADER.FIELDS (date subject from content-type to cc)]");
}
if (fp.contains(FetchProfile.Item.STRUCTURE)) {
fetchFields.add("BODYSTRUCTURE");
}
if (fp.contains(FetchProfile.Item.BODY_SANE)) {
fetchFields.add(String.format("BODY.PEEK[]<0.%d>", FETCH_BODY_SANE_SUGGESTED_SIZE));
}
if (fp.contains(FetchProfile.Item.BODY)) {
fetchFields.add("BODY.PEEK[]");
}
for (Object o : fp) {
if (o instanceof Part) {
Part part = (Part) o;
String partId = part.getHeader(MimeHeader.HEADER_ANDROID_ATTACHMENT_STORE_DATA)[0];
fetchFields.add("BODY.PEEK[" + partId + "]");
}
}
try {
String tag = mConnection.sendCommand(String.format("UID FETCH %s (%s)",
Utility.combine(uids, ','),
Utility.combine(fetchFields.toArray(new String[fetchFields.size()]), ' ')
), false);
ImapResponse response;
int messageNumber = 0;
do {
response = mConnection.readResponse();
if (response.mTag == null && response.get(1).equals("FETCH")) {
ImapList fetchList = (ImapList)response.getKeyedValue("FETCH");
String uid = fetchList.getKeyedString("UID");
Message message = messageMap.get(uid);
if (listener != null) {
listener.messageStarted(uid, messageNumber++, messageMap.size());
}
if (fp.contains(FetchProfile.Item.FLAGS)) {
ImapList flags = fetchList.getKeyedList("FLAGS");
ImapMessage imapMessage = (ImapMessage) message;
if (flags != null) {
for (int i = 0, count = flags.size(); i < count; i++) {
String flag = flags.getString(i);
if (flag.equals("\\Deleted")) {
imapMessage.setFlagInternal(Flag.DELETED, true);
}
else if (flag.equals("\\Answered")) {
imapMessage.setFlagInternal(Flag.ANSWERED, true);
}
else if (flag.equals("\\Seen")) {
imapMessage.setFlagInternal(Flag.SEEN, true);
}
else if (flag.equals("\\Flagged")) {
imapMessage.setFlagInternal(Flag.FLAGGED, true);
}
}
}
}
if (fp.contains(FetchProfile.Item.ENVELOPE)) {
Date internalDate = fetchList.getKeyedDate("INTERNALDATE");
int size = fetchList.getKeyedNumber("RFC822.SIZE");
InputStream headerStream = fetchList.getLiteral(fetchList.size() - 1);
ImapMessage imapMessage = (ImapMessage) message;
message.setInternalDate(internalDate);
imapMessage.setSize(size);
imapMessage.parse(headerStream);
}
if (fp.contains(FetchProfile.Item.STRUCTURE)) {
ImapList bs = fetchList.getKeyedList("BODYSTRUCTURE");
if (bs != null) {
try {
parseBodyStructure(bs, message, "TEXT");
}
catch (MessagingException e) {
if (Config.LOGV) {
Log.v(k9.LOG_TAG, "Error handling message", e);
}
message.setBody(null);
}
}
}
if (fp.contains(FetchProfile.Item.BODY)) {
InputStream bodyStream = fetchList.getLiteral(fetchList.size() - 1);
ImapMessage imapMessage = (ImapMessage) message;
imapMessage.parse(bodyStream);
}
if (fp.contains(FetchProfile.Item.BODY_SANE)) {
InputStream bodyStream = fetchList.getLiteral(fetchList.size() - 1);
ImapMessage imapMessage = (ImapMessage) message;
imapMessage.parse(bodyStream);
}
for (Object o : fp) {
if (o instanceof Part) {
Part part = (Part) o;
InputStream bodyStream = fetchList.getLiteral(fetchList.size() - 1);
String contentType = part.getContentType();
String contentTransferEncoding = part.getHeader(
MimeHeader.HEADER_CONTENT_TRANSFER_ENCODING)[0];
part.setBody(MimeUtility.decodeBody(
bodyStream,
contentTransferEncoding));
}
}
if (listener != null) {
listener.messageFinished(message, messageNumber, messageMap.size());
}
}
while (response.more());
} while (response.mTag == null);
}
catch (IOException ioe) {
throw ioExceptionHandler(mConnection, ioe);
}
}
@Override
public Flag[] getPermanentFlags() throws MessagingException {
return PERMANENT_FLAGS;
}
/**
* Handle any untagged responses that the caller doesn't care to handle themselves.
* @param responses
*/
private void handleUntaggedResponses(List<ImapResponse> responses) {
for (ImapResponse response : responses) {
handleUntaggedResponse(response);
}
}
/**
* Handle an untagged response that the caller doesn't care to handle themselves.
* @param response
*/
private void handleUntaggedResponse(ImapResponse response) {
if (response.mTag == null && response.get(1).equals("EXISTS")) {
mMessageCount = response.getNumber(0);
}
}
private void parseBodyStructure(ImapList bs, Part part, String id)
throws MessagingException {
if (bs.get(0) instanceof ImapList) {
/*
* This is a multipart/*
*/
MimeMultipart mp = new MimeMultipart();
for (int i = 0, count = bs.size(); i < count; i++) {
if (bs.get(i) instanceof ImapList) {
/*
* For each part in the message we're going to add a new BodyPart and parse
* into it.
*/
ImapBodyPart bp = new ImapBodyPart();
if (id.equals("TEXT")) {
parseBodyStructure(bs.getList(i), bp, Integer.toString(i + 1));
}
else {
parseBodyStructure(bs.getList(i), bp, id + "." + (i + 1));
}
mp.addBodyPart(bp);
}
else {
/*
* We've got to the end of the children of the part, so now we can find out
* what type it is and bail out.
*/
String subType = bs.getString(i);
mp.setSubType(subType.toLowerCase());
break;
}
}
part.setBody(mp);
}
else{
/*
* This is a body. We need to add as much information as we can find out about
* it to the Part.
*/
/*
body type
body subtype
body parameter parenthesized list
body id
body description
body encoding
body size
*/
String type = bs.getString(0);
String subType = bs.getString(1);
String mimeType = (type + "/" + subType).toLowerCase();
ImapList bodyParams = null;
if (bs.get(2) instanceof ImapList) {
bodyParams = bs.getList(2);
}
String encoding = bs.getString(5);
int size = bs.getNumber(6);
if (MimeUtility.mimeTypeMatches(mimeType, "message/rfc822")) {
// A body type of type MESSAGE and subtype RFC822
// contains, immediately after the basic fields, the
// envelope structure, body structure, and size in
// text lines of the encapsulated message.
// [MESSAGE, RFC822, [NAME, Fwd: [#HTR-517941]: update plans at 1am Friday - Memory allocation - displayware.eml], NIL, NIL, 7BIT, 5974, NIL, [INLINE, [FILENAME*0, Fwd: [#HTR-517941]: update plans at 1am Friday - Memory all, FILENAME*1, ocation - displayware.eml]], NIL]
/*
* This will be caught by fetch and handled appropriately.
*/
throw new MessagingException("BODYSTRUCTURE message/rfc822 not yet supported.");
}
/*
* Set the content type with as much information as we know right now.
*/
String contentType = String.format("%s", mimeType);
if (bodyParams != null) {
/*
* If there are body params we might be able to get some more information out
* of them.
*/
for (int i = 0, count = bodyParams.size(); i < count; i += 2) {
contentType += String.format(";\n %s=\"%s\"",
bodyParams.getString(i),
bodyParams.getString(i + 1));
}
}
part.setHeader(MimeHeader.HEADER_CONTENT_TYPE, contentType);
// Extension items
ImapList bodyDisposition = null;
if (("text".equalsIgnoreCase(type))
&& (bs.size() > 8)
&& (bs.get(9) instanceof ImapList)) {
bodyDisposition = bs.getList(9);
}
else if (!("text".equalsIgnoreCase(type))
&& (bs.size() > 7)
&& (bs.get(8) instanceof ImapList)) {
bodyDisposition = bs.getList(8);
}
String contentDisposition = "";
if (bodyDisposition != null && bodyDisposition.size() > 0) {
if (!"NIL".equalsIgnoreCase(bodyDisposition.getString(0))) {
contentDisposition = bodyDisposition.getString(0).toLowerCase();
}
if ((bodyDisposition.size() > 1)
&& (bodyDisposition.get(1) instanceof ImapList)) {
ImapList bodyDispositionParams = bodyDisposition.getList(1);
/*
* If there is body disposition information we can pull some more information
* about the attachment out.
*/
for (int i = 0, count = bodyDispositionParams.size(); i < count; i += 2) {
contentDisposition += String.format(";\n %s=\"%s\"",
bodyDispositionParams.getString(i).toLowerCase(),
bodyDispositionParams.getString(i + 1));
}
}
}
if (MimeUtility.getHeaderParameter(contentDisposition, "size") == null) {
contentDisposition += String.format(";\n size=%d", size);
}
/*
* Set the content disposition containing at least the size. Attachment
* handling code will use this down the road.
*/
part.setHeader(MimeHeader.HEADER_CONTENT_DISPOSITION, contentDisposition);
/*
* Set the Content-Transfer-Encoding header. Attachment code will use this
* to parse the body.
*/
part.setHeader(MimeHeader.HEADER_CONTENT_TRANSFER_ENCODING, encoding);
if (part instanceof ImapMessage) {
((ImapMessage) part).setSize(size);
}
else if (part instanceof ImapBodyPart) {
((ImapBodyPart) part).setSize(size);
}
else {
throw new MessagingException("Unknown part type " + part.toString());
}
part.setHeader(MimeHeader.HEADER_ANDROID_ATTACHMENT_STORE_DATA, id);
}
}
/**
* Appends the given messages to the selected folder. This implementation also determines
* the new UID of the given message on the IMAP server and sets the Message's UID to the
* new server UID.
*/
public void appendMessages(Message[] messages) throws MessagingException {
checkOpen();
try {
for (Message message : messages) {
CountingOutputStream out = new CountingOutputStream();
EOLConvertingOutputStream eolOut = new EOLConvertingOutputStream(out);
message.writeTo(eolOut);
eolOut.flush();
mConnection.sendCommand(
String.format("APPEND \"%s\" {%d}",
encodeFolderName(getPrefixedName()),
out.getCount()), false);
ImapResponse response;
do {
response = mConnection.readResponse();
if (response.mCommandContinuationRequested) {
eolOut = new EOLConvertingOutputStream(mConnection.mOut);
message.writeTo(eolOut);
eolOut.write('\r');
eolOut.write('\n');
eolOut.flush();
}
else if (response.mTag == null) {
handleUntaggedResponse(response);
}
while (response.more());
} while(response.mTag == null);
/*
* Try to find the UID of the message we just appended using the
* Message-ID header.
*/
String[] messageIdHeader = message.getHeader("Message-ID");
if (messageIdHeader == null || messageIdHeader.length == 0) {
continue;
}
String messageId = messageIdHeader[0];
List<ImapResponse> responses =
mConnection.executeSimpleCommand(
String.format("UID SEARCH (HEADER MESSAGE-ID %s)", messageId));
for (ImapResponse response1 : responses) {
if (response1.mTag == null && response1.get(0).equals("SEARCH")
&& response1.size() > 1) {
message.setUid(response1.getString(1));
}
}
}
}
catch (IOException ioe) {
throw ioExceptionHandler(mConnection, ioe);
}
}
public Message[] expunge() throws MessagingException {
checkOpen();
try {
handleUntaggedResponses(mConnection.executeSimpleCommand("EXPUNGE"));
} catch (IOException ioe) {
throw ioExceptionHandler(mConnection, ioe);
}
return null;
}
public void setFlags(Message[] messages, Flag[] flags, boolean value)
throws MessagingException {
checkOpen();
String[] uids = new String[messages.length];
for (int i = 0, count = messages.length; i < count; i++) {
uids[i] = messages[i].getUid();
}
ArrayList<String> flagNames = new ArrayList<String>();
for (int i = 0, count = flags.length; i < count; i++) {
Flag flag = flags[i];
if (flag == Flag.SEEN) {
flagNames.add("\\Seen");
}
else if (flag == Flag.DELETED) {
flagNames.add("\\Deleted");
}
}
try {
mConnection.executeSimpleCommand(String.format("UID STORE %s %sFLAGS.SILENT (%s)",
Utility.combine(uids, ','),
value ? "+" : "-",
Utility.combine(flagNames.toArray(new String[flagNames.size()]), ' ')));
}
catch (IOException ioe) {
throw ioExceptionHandler(mConnection, ioe);
}
}
private void checkOpen() throws MessagingException {
if (!isOpen()) {
throw new MessagingException("Folder " + getPrefixedName() + " is not open.");
}
}
private MessagingException ioExceptionHandler(ImapConnection connection, IOException ioe)
throws MessagingException {
connection.close();
close(false);
return new MessagingException("IO Error", ioe);
}
@Override
public boolean equals(Object o) {
if (o instanceof ImapFolder) {
return ((ImapFolder)o).getPrefixedName().equals(getPrefixedName());
}
return super.equals(o);
}
}
/**
* A cacheable class that stores the details for a single IMAP connection.
*/
class ImapConnection {
private Socket mSocket;
private PeekableInputStream mIn;
private OutputStream mOut;
private ImapResponseParser mParser;
private int mNextCommandTag;
public void open() throws IOException, MessagingException {
if (isOpen()) {
return;
}
mNextCommandTag = 1;
try {
SocketAddress socketAddress = new InetSocketAddress(mHost, mPort);
if (mConnectionSecurity == CONNECTION_SECURITY_SSL_REQUIRED ||
mConnectionSecurity == CONNECTION_SECURITY_SSL_OPTIONAL) {
SSLContext sslContext = SSLContext.getInstance("TLS");
final boolean secure = mConnectionSecurity == CONNECTION_SECURITY_SSL_REQUIRED;
sslContext.init(null, new TrustManager[] {
TrustManagerFactory.get(mHost, secure)
}, new SecureRandom());
mSocket = sslContext.getSocketFactory().createSocket();
mSocket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT);
} else {
mSocket = new Socket();
mSocket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT);
}
mSocket.setSoTimeout(Store.SOCKET_READ_TIMEOUT);
mIn = new PeekableInputStream(new BufferedInputStream(mSocket.getInputStream(),
1024));
mParser = new ImapResponseParser(mIn);
mOut = mSocket.getOutputStream();
// BANNER
mParser.readResponse();
if (mConnectionSecurity == CONNECTION_SECURITY_TLS_OPTIONAL
|| mConnectionSecurity == CONNECTION_SECURITY_TLS_REQUIRED) {
// CAPABILITY
List<ImapResponse> responses = executeSimpleCommand("CAPABILITY");
if (responses.size() != 2) {
throw new MessagingException("Invalid CAPABILITY response received");
}
if (responses.get(0).contains("STARTTLS")) {
// STARTTLS
executeSimpleCommand("STARTTLS");
SSLContext sslContext = SSLContext.getInstance("TLS");
boolean secure = mConnectionSecurity == CONNECTION_SECURITY_TLS_REQUIRED;
sslContext.init(null, new TrustManager[] {
TrustManagerFactory.get(mHost, secure)
}, new SecureRandom());
mSocket = sslContext.getSocketFactory().createSocket(mSocket, mHost, mPort,
true);
mSocket.setSoTimeout(Store.SOCKET_READ_TIMEOUT);
mIn = new PeekableInputStream(new BufferedInputStream(mSocket
.getInputStream(), 1024));
mParser = new ImapResponseParser(mIn);
mOut = mSocket.getOutputStream();
} else if (mConnectionSecurity == CONNECTION_SECURITY_TLS_REQUIRED) {
throw new MessagingException("TLS not supported but required");
}
}
mOut = new BufferedOutputStream(mOut);
try {
// TODO eventually we need to add additional authentication
// options such as SASL
executeSimpleCommand("LOGIN " + mUsername + " " + mPassword, true);
} catch (ImapException ie) {
throw new AuthenticationFailedException(ie.getAlertText(), ie);
} catch (MessagingException me) {
throw new AuthenticationFailedException(null, me);
}
} catch (SSLException e) {
throw new CertificateValidationException(e.getMessage(), e);
} catch (GeneralSecurityException gse) {
throw new MessagingException(
"Unable to open connection to IMAP server due to security error.", gse);
}
}
public boolean isOpen() {
return (mIn != null && mOut != null && mSocket != null && mSocket.isConnected() && !mSocket
.isClosed());
}
public void close() {
// if (isOpen()) {
// try {
// executeSimpleCommand("LOGOUT");
// } catch (Exception e) {
//
// }
// }
try {
mIn.close();
} catch (Exception e) {
}
try {
mOut.close();
} catch (Exception e) {
}
try {
mSocket.close();
} catch (Exception e) {
}
mIn = null;
mOut = null;
mSocket = null;
}
public ImapResponse readResponse() throws IOException, MessagingException {
return mParser.readResponse();
}
public String sendCommand(String command, boolean sensitive)
throws MessagingException, IOException {
open();
String tag = Integer.toString(mNextCommandTag++);
String commandToSend = tag + " " + command;
mOut.write(commandToSend.getBytes());
mOut.write('\r');
mOut.write('\n');
mOut.flush();
if (Config.LOGD) {
if (k9.DEBUG) {
if (sensitive && !k9.DEBUG_SENSITIVE) {
Log.d(k9.LOG_TAG, ">>> "
+ "[Command Hidden, Enable Sensitive Debug Logging To Show]");
} else {
Log.d(k9.LOG_TAG, ">>> " + commandToSend);
}
}
}
return tag;
}
public List<ImapResponse> executeSimpleCommand(String command) throws IOException,
ImapException, MessagingException {
return executeSimpleCommand(command, false);
}
public List<ImapResponse> executeSimpleCommand(String command, boolean sensitive)
throws IOException, ImapException, MessagingException {
String tag = sendCommand(command, sensitive);
ArrayList<ImapResponse> responses = new ArrayList<ImapResponse>();
ImapResponse response;
do {
response = mParser.readResponse();
responses.add(response);
} while (response.mTag == null);
if (response.size() < 1 || !response.get(0).equals("OK")) {
throw new ImapException(response.toString(), response.getAlertText());
}
return responses;
}
}
class ImapMessage extends MimeMessage {
ImapMessage(String uid, Folder folder) throws MessagingException {
this.mUid = uid;
this.mFolder = folder;
}
public void setSize(int size) {
this.mSize = size;
}
public void parse(InputStream in) throws IOException, MessagingException {
super.parse(in);
}
public void setFlagInternal(Flag flag, boolean set) throws MessagingException {
super.setFlag(flag, set);
}
@Override
public void setFlag(Flag flag, boolean set) throws MessagingException {
super.setFlag(flag, set);
mFolder.setFlags(new Message[] { this }, new Flag[] { flag }, set);
}
}
class ImapBodyPart extends MimeBodyPart {
public ImapBodyPart() throws MessagingException {
super();
}
public void setSize(int size) {
this.mSize = size;
}
}
class ImapException extends MessagingException {
String mAlertText;
public ImapException(String message, String alertText, Throwable throwable) {
super(message, throwable);
this.mAlertText = alertText;
}
public ImapException(String message, String alertText) {
super(message);
this.mAlertText = alertText;
}
public String getAlertText() {
return mAlertText;
}
public void setAlertText(String alertText) {
mAlertText = alertText;
}
}
}
| true | false | null | null |
diff --git a/groovyConsole/src/main/java/org/orbisgis/groovy/GroovyConsolePanel.java b/groovyConsole/src/main/java/org/orbisgis/groovy/GroovyConsolePanel.java
index 80b1f4f..aa8cf20 100644
--- a/groovyConsole/src/main/java/org/orbisgis/groovy/GroovyConsolePanel.java
+++ b/groovyConsole/src/main/java/org/orbisgis/groovy/GroovyConsolePanel.java
@@ -1,488 +1,489 @@
/*
* OrbisGIS is a GIS application dedicated to scientific spatial simulation.
* This cross-platform GIS is developed at French IRSTV institute and is able to
* manipulate and create vector and raster spatial information.
*
* OrbisGIS is distributed under GPL 3 license. It is produced by the "Atelier SIG"
* team of the IRSTV Institute <http://www.irstv.fr/> CNRS FR 2488.
*
* Copyright (C) 2007-2012 IRSTV (FR CNRS 2488)
*
* This file is part of OrbisGIS.
*
* OrbisGIS 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.
*
* OrbisGIS 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
* OrbisGIS. If not, see <http://www.gnu.org/licenses/>.
*
* For more information, please consult: <http://www.orbisgis.org/>
* or contact directly:
* info_at_ orbisgis.org
*/
package org.orbisgis.groovy;
import groovy.lang.GroovyShell;
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.beans.EventHandler;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Arrays;
+import java.util.HashMap;
import java.util.Map;
import javax.sql.DataSource;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.SwingWorker;
import javax.swing.event.CaretListener;
import javax.swing.event.DocumentListener;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.fife.rsta.ac.LanguageSupportFactory;
import org.fife.rsta.ac.groovy.GroovyLanguageSupport;
import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea;
import org.fife.ui.rsyntaxtextarea.SyntaxConstants;
import org.fife.ui.rtextarea.RTextScrollPane;
import org.orbisgis.core.layerModel.MapContext;
import org.orbisgis.mapeditorapi.MapElement;
import org.orbisgis.sif.UIFactory;
import org.orbisgis.sif.components.OpenFilePanel;
import org.orbisgis.sif.components.SaveFilePanel;
import org.orbisgis.view.components.Log4JOutputStream;
import org.orbisgis.view.components.actions.ActionCommands;
import org.orbisgis.view.components.findReplace.FindReplaceDialog;
import org.orbisgis.view.icons.OrbisGISIcon;
import org.orbisgis.view.util.CommentUtil;
import org.orbisgis.viewapi.components.actions.DefaultAction;
import org.orbisgis.viewapi.docking.DockingPanelParameters;
import org.orbisgis.viewapi.edition.EditableElement;
import org.orbisgis.viewapi.edition.EditorDockable;
import org.orbisgis.viewapi.edition.EditorManager;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.component.annotations.ReferenceCardinality;
import org.xnap.commons.i18n.I18n;
import org.xnap.commons.i18n.I18nFactory;
/**
* Create the groovy console panel
*
* @author Erwan Bocher
*/
-@Component
+@Component(service = EditorDockable.class)
public class GroovyConsolePanel extends JPanel implements EditorDockable {
public static final String EDITOR_NAME = "Groovy";
private static final I18n I18N = I18nFactory.getI18n(GroovyConsolePanel.class);
private static final Logger LOGGER = Logger.getLogger("gui." + GroovyConsolePanel.class);
private static final Logger LOGGER_POPUP = Logger.getLogger("gui.popup" + GroovyConsolePanel.class);
private final Log4JOutputStream infoLogger = new Log4JOutputStream(LOGGER, Level.INFO);
private final Log4JOutputStream errorLogger = new Log4JOutputStream(LOGGER, Level.ERROR);
private DockingPanelParameters parameters = new DockingPanelParameters();
private ActionCommands actions = new ActionCommands();
private GroovyLanguageSupport gls;
private RTextScrollPane centerPanel;
private RSyntaxTextArea scriptPanel;
private DefaultAction executeAction;
private DefaultAction clearAction;
private DefaultAction saveAction;
private DefaultAction findAction;
private DefaultAction commentAction;
private DefaultAction blockCommentAction;
private FindReplaceDialog findReplaceDialog;
private int line = 0;
private int character = 0;
private MapElement mapElement;
private static final String MESSAGEBASE = "%d | %d";
private JLabel statusMessage=new JLabel();
- private Map<String, Object> variables;
- private Map<String, Object> properties;
+ private Map<String, Object> variables = new HashMap<String, Object>();
+ private Map<String, Object> properties = new HashMap<String, Object>();
/**
* Create the groovy console panel
*/
public GroovyConsolePanel() {
setLayout(new BorderLayout());
add(getCenterPanel(), BorderLayout.CENTER);
add(statusMessage, BorderLayout.SOUTH);
init();
}
public void setDataSource(DataSource ds) {
try {
variables.put("grv.ds", ds);
} catch (Error ex) {
LOGGER.error(ex.getLocalizedMessage(), ex);
}
}
@Reference(cardinality = ReferenceCardinality.OPTIONAL)
public void setEditorManager(EditorManager editorManager) {
// If a map is already loaded fetch it in the EditorManager
if(editorManager != null) {
try {
mapElement = MapElement.fetchFirstMapElement(editorManager);
} catch (Exception ex) {
LOGGER.error(ex.getLocalizedMessage(), ex);
}
}
if (mapElement != null) {
setMapContext(mapElement.getMapContext());
}
}
public void unsetEditorManager(EditorManager editorManager) {
}
/**
* Init the groovy panel with all docking parameters and set the necessary
* properties to the console shell
*/
private void init() {
properties.put("out", new PrintStream(infoLogger));
properties.put("err", new PrintStream(errorLogger));
parameters.setName(EDITOR_NAME);
parameters.setTitle(I18N.tr("Groovy"));
parameters.setTitleIcon(OrbisGISIcon.getIcon("page_white_cup"));
parameters.setDockActions(getActions().getActions());
}
/**
* Get the action manager.
*
* @return ActionCommands instance.
*/
public ActionCommands getActions() {
return actions;
}
/**
* The main panel to write and execute a groovy script.
*
* @return
*/
private RTextScrollPane getCenterPanel() {
if (centerPanel == null) {
initActions();
LanguageSupportFactory lsf = LanguageSupportFactory.get();
gls = (GroovyLanguageSupport) lsf.getSupportFor(SyntaxConstants.SYNTAX_STYLE_GROOVY);
scriptPanel = new RSyntaxTextArea();
scriptPanel.setLineWrap(true);
lsf.register(scriptPanel);
scriptPanel.setSyntaxEditingStyle(RSyntaxTextArea.SYNTAX_STYLE_JAVA);
scriptPanel.addCaretListener(EventHandler.create(CaretListener.class, this, "onScriptPanelCaretUpdate"));
scriptPanel.getDocument().addDocumentListener(EventHandler.create(DocumentListener.class, this, "onUserSelectionChange"));
scriptPanel.clearParsers();
actions.setAccelerators(scriptPanel);
// Actions will be set on the scriptPanel PopupMenu
scriptPanel.getPopupMenu().addSeparator();
actions.registerContainer(scriptPanel.getPopupMenu());
centerPanel = new RTextScrollPane(scriptPanel);
onUserSelectionChange();
}
return centerPanel;
}
/**
* Create actions instances
*
* Each action is put in the Popup menu and the tool bar Their shortcuts are
* registered also in the editor
*/
private void initActions() {
//Execute action
executeAction = new DefaultAction(GroovyConsoleActions.A_EXECUTE, I18N.tr("Execute"),
I18N.tr("Execute the groovy script"),
OrbisGISIcon.getIcon("execute"),
EventHandler.create(ActionListener.class, this, "onExecute"),
KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, InputEvent.CTRL_DOWN_MASK));
actions.addAction(executeAction);
//Clear action
clearAction = new DefaultAction(GroovyConsoleActions.A_CLEAR,
I18N.tr("Clear"),
I18N.tr("Erase the content of the editor"),
OrbisGISIcon.getIcon("erase"),
EventHandler.create(ActionListener.class, this, "onClear"),
null);
actions.addAction(clearAction);
//Open action
actions.addAction(new DefaultAction(GroovyConsoleActions.A_OPEN,
I18N.tr("Open"),
I18N.tr("Load a file in this editor"),
OrbisGISIcon.getIcon("open"),
EventHandler.create(ActionListener.class, this, "onOpenFile"),
KeyStroke.getKeyStroke(KeyEvent.VK_O, InputEvent.CTRL_DOWN_MASK)));
//Save
saveAction = new DefaultAction(GroovyConsoleActions.A_SAVE,
I18N.tr("Save"),
I18N.tr("Save the editor content into a file"),
OrbisGISIcon.getIcon("save"),
EventHandler.create(ActionListener.class, this, "onSaveFile"),
KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.CTRL_DOWN_MASK));
actions.addAction(saveAction);
//Find action
findAction = new DefaultAction(GroovyConsoleActions.A_SEARCH,
I18N.tr("Search.."),
I18N.tr("Search text in the document"),
OrbisGISIcon.getIcon("find"),
EventHandler.create(ActionListener.class, this, "openFindReplaceDialog"),
KeyStroke.getKeyStroke(KeyEvent.VK_F, InputEvent.CTRL_DOWN_MASK)).addStroke(KeyStroke.getKeyStroke(KeyEvent.VK_H, InputEvent.CTRL_DOWN_MASK));
actions.addAction(findAction);
// Comment/Uncomment
commentAction = new DefaultAction(GroovyConsoleActions.A_COMMENT,
I18N.tr("(Un)comment"),
I18N.tr("(Un)comment the selected text"),
null,
EventHandler.create(ActionListener.class, this, "onComment"),
KeyStroke.getKeyStroke("alt C")).setLogicalGroup("format");
actions.addAction(commentAction);
// Block Comment/Uncomment
blockCommentAction = new DefaultAction(GroovyConsoleActions.A_BLOCKCOMMENT,
I18N.tr("Block (un)comment"),
I18N.tr("Block (un)comment the selected text."),
null,
EventHandler.create(ActionListener.class, this, "onBlockComment"),
KeyStroke.getKeyStroke("alt shift C")).setLogicalGroup("format");
actions.addAction(blockCommentAction);
}
/**
* Clear the content of the console
*/
public void onClear() {
if (scriptPanel.getDocument().getLength() != 0) {
int answer = JOptionPane.showConfirmDialog(this,
I18N.tr("Do you want to clear the contents of the console?"),
I18N.tr("Clear script"), JOptionPane.YES_NO_OPTION);
if (answer == JOptionPane.YES_OPTION) {
scriptPanel.setText("");
}
}
}
/**
* Open a dialog that let the user select a file and save the content of the
* sql editor into this file.
*/
public void onSaveFile() {
final SaveFilePanel outfilePanel = new SaveFilePanel(
"groovyConsoleOutFile", I18N.tr("Save script"));
outfilePanel.addFilter("groovy", I18N.tr("Groovy script (*.groovy)"));
outfilePanel.loadState();
if (UIFactory.showDialog(outfilePanel)) {
try {
FileUtils.writeLines(outfilePanel.getSelectedFile(), Arrays.asList(scriptPanel.getText()));
} catch (IOException e1) {
LOGGER.error(I18N.tr("Cannot write the script."), e1);
}
LOGGER_POPUP.info(I18N.tr("The file has been saved."));
}
}
/**
* Open a dialog that let the user select a file and add or replace the
* content of the sql editor.
*/
public void onOpenFile() {
final OpenFilePanel inFilePanel = new OpenFilePanel("groovyConsoleInFile",
I18N.tr("Open script"));
inFilePanel.addFilter("groovy", I18N.tr("Groovy Script (*.groovy)"));
inFilePanel.loadState();
if (UIFactory.showDialog(inFilePanel)) {
int answer = JOptionPane.NO_OPTION;
if (scriptPanel.getDocument().getLength() > 0) {
answer = JOptionPane.showConfirmDialog(
this,
I18N.tr("Do you want to clear all before loading the file ?"),
I18N.tr("Open file"),
JOptionPane.YES_NO_CANCEL_OPTION);
}
String text;
try {
text = FileUtils.readFileToString(inFilePanel.getSelectedFile());
} catch (IOException e1) {
LOGGER.error(I18N.tr("Cannot write the script."), e1);
return;
}
if (answer == JOptionPane.YES_OPTION) {
scriptPanel.setText(text);
} else if (answer == JOptionPane.NO_OPTION) {
scriptPanel.append(text);
}
}
}
/**
* Update the row:column label
*/
public void onScriptPanelCaretUpdate() {
line = scriptPanel.getCaretLineNumber() + 1;
character = scriptPanel.getCaretOffsetFromLineStart();
statusMessage.setText(String.format(MESSAGEBASE, line, character));
}
/**
* Change the status of the button when the console is empty or not.
*/
public void onUserSelectionChange() {
String text = scriptPanel.getText().trim();
if (text.isEmpty()) {
executeAction.setEnabled(false);
clearAction.setEnabled(false);
saveAction.setEnabled(false);
findAction.setEnabled(false);
commentAction.setEnabled(false);
blockCommentAction.setEnabled(false);
} else {
executeAction.setEnabled(true);
clearAction.setEnabled(true);
saveAction.setEnabled(true);
findAction.setEnabled(true);
commentAction.setEnabled(true);
blockCommentAction.setEnabled(true);
}
}
/**
* User click on execute script button
*/
public void onExecute() {
String text = scriptPanel.getText().trim();
new GroovyExecutor(text, properties, variables, new Log4JOutputStream[] {infoLogger, errorLogger}).execute();
}
/**
* Expose the map context in the groovy interpreter
*
* @param mc MapContext instance
*/
private void setMapContext(MapContext mc) {
try {
variables.put("mc", mc);
} catch (Error ex) {
LOGGER.error(ex.getLocalizedMessage(), ex);
}
}
@Override
public boolean match(EditableElement editableElement) {
return editableElement instanceof MapElement;
}
@Override
public EditableElement getEditableElement() {
return null;
}
@Override
public void setEditableElement(EditableElement editableElement) {
if(editableElement instanceof MapElement) {
setMapContext(((MapElement) editableElement).getMapContext());
}
}
/**
* Dispose
*/
public void freeResources() {
if (gls != null) {
gls.uninstall(scriptPanel);
}
}
@Override
public DockingPanelParameters getDockingParameters() {
return parameters;
}
@Override
public JComponent getComponent() {
return this;
}
/**
* (Un)comment the selected text.
*/
public void onComment() {
CommentUtil.commentOrUncommentJava(scriptPanel);
}
/**
* Block (un)comment the selected text.
*/
public void onBlockComment() {
CommentUtil.blockCommentOrUncomment(scriptPanel);
}
/**
* Open one instanceof the find replace dialog
*/
public void openFindReplaceDialog() {
if (findReplaceDialog == null) {
findReplaceDialog = new FindReplaceDialog(scriptPanel, UIFactory.getMainFrame());
}
findReplaceDialog.setAlwaysOnTop(true);
findReplaceDialog.setVisible(true);
}
private static class GroovyExecutor extends SwingWorker<Object, Object> {
private String script;
Log4JOutputStream[] loggers;
private Map<String, Object> variables;
private Map<String, Object> properties;
public GroovyExecutor(String script,Map<String, Object> properties, Map<String, Object> variables, Log4JOutputStream[] loggers) {
this.script = script;
this.loggers = loggers;
this.variables = variables;
this.properties = properties;
}
@Override
protected Object doInBackground() {
try {
GroovyShell groovyShell = new GroovyShell();
for(Map.Entry<String,Object> variable : variables.entrySet()) {
groovyShell.setVariable(variable.getKey(), variable.getValue());
}
for(Map.Entry<String,Object> property : properties.entrySet()) {
groovyShell.setProperty(property.getKey(), property.getValue());
}
groovyShell.evaluate(script);
} catch (Exception e) {
LOGGER.error(I18N.tr("Cannot execute the script"), e);
}
return null;
}
@Override
protected void done() {
try {
for(Log4JOutputStream logger : loggers) {
logger.flush();
}
} catch (IOException e) {
LOGGER.error(I18N.tr("Cannot display the output of the console"), e);
}
}
}
}
| false | false | null | null |
diff --git a/api/src/main/java/org/openmrs/module/kenyaemr/calculation/library/mchcs/NotOnArtCalculation.java b/api/src/main/java/org/openmrs/module/kenyaemr/calculation/library/mchcs/NotOnArtCalculation.java
index d9dbe3c2..9aae3214 100644
--- a/api/src/main/java/org/openmrs/module/kenyaemr/calculation/library/mchcs/NotOnArtCalculation.java
+++ b/api/src/main/java/org/openmrs/module/kenyaemr/calculation/library/mchcs/NotOnArtCalculation.java
@@ -1,83 +1,108 @@
/**
* 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.kenyaemr.calculation.library.mchcs;
+import org.joda.time.DateTime;
+import org.joda.time.Weeks;
import org.openmrs.Concept;
+import org.openmrs.Encounter;
+import org.openmrs.EncounterType;
+import org.openmrs.Obs;
+import org.openmrs.Patient;
import org.openmrs.Program;
+import org.openmrs.api.EncounterService;
+import org.openmrs.api.context.Context;
import org.openmrs.calculation.patient.PatientCalculationContext;
import org.openmrs.calculation.result.CalculationResultMap;
import org.openmrs.module.kenyacore.calculation.CalculationUtils;
import org.openmrs.module.kenyacore.calculation.Calculations;
import org.openmrs.module.kenyacore.calculation.PatientFlagCalculation;
import org.openmrs.module.kenyacore.metadata.MetadataUtils;
import org.openmrs.module.kenyaemr.Dictionary;
import org.openmrs.module.kenyaemr.Metadata;
import org.openmrs.module.kenyacore.calculation.BooleanResult;
import org.openmrs.module.kenyaemr.calculation.BaseEmrCalculation;
import org.openmrs.module.kenyaemr.calculation.EmrCalculationUtils;
+import org.openmrs.module.kenyaemr.util.EmrUtils;
import java.util.Collection;
+import java.util.Date;
import java.util.Map;
import java.util.Set;
/**
* Calculates whether a mother is HIV+ but is not on ART. Calculation returns true if mother
- * is alive, enrolled in the MCH program, is HIV+ and was not indicated as being on ART in the
- * last encounter.
+ * is alive, enrolled in the MCH program, gestation is greater than 14 weeks, is HIV+ and was
+ * not indicated as being on ART in the last encounter.
*/
public class NotOnArtCalculation extends BaseEmrCalculation implements PatientFlagCalculation {
/**
* @see org.openmrs.module.kenyacore.calculation.PatientFlagCalculation#getFlagMessage()
*/
@Override
public String getFlagMessage() {
return "Mother not on ART";
}
@Override
public CalculationResultMap evaluate(Collection<Integer> cohort, Map<String, Object> parameterValues, PatientCalculationContext context) {
Program mchmsProgram = MetadataUtils.getProgram(Metadata.Program.MCHMS);
Set<Integer> alive = alivePatients(cohort, context);
Set<Integer> inMchmsProgram = CalculationUtils.patientsThatPass(Calculations.activeEnrollment(mchmsProgram, alive, context));
CalculationResultMap lastHivStatusObss = Calculations.lastObs(getConcept(Dictionary.HIV_STATUS), inMchmsProgram, context);
CalculationResultMap artStatusObss = Calculations.lastObs(getConcept(Dictionary.ANTIRETROVIRAL_USE_IN_PREGNANCY), inMchmsProgram, context);
CalculationResultMap ret = new CalculationResultMap();
for (Integer ptId : cohort) {
boolean notOnArt = false;
// Is patient alive and in MCH program?
if (inMchmsProgram.contains(ptId)) {
Concept lastHivStatus = EmrCalculationUtils.codedObsResultForPatient(lastHivStatusObss, ptId);
Concept lastArtStatus = EmrCalculationUtils.codedObsResultForPatient(artStatusObss, ptId);
boolean hivPositive = false;
boolean onArt = false;
if (lastHivStatus != null) {
hivPositive = lastHivStatus.getUuid().equals(Dictionary.POSITIVE);
if (lastArtStatus != null) {
onArt = !lastArtStatus.getUuid().equals(Dictionary.NOT_APPLICABLE);
}
}
- notOnArt = hivPositive && !onArt;
+ notOnArt = hivPositive && gestationIsGreaterThan14Weeks(ptId) && !onArt;
}
ret.put(ptId, new BooleanResult(notOnArt, this, context));
}
return ret;
}
+
+ private boolean gestationIsGreaterThan14Weeks(Integer patientId) {
+ Patient patient = Context.getPatientService().getPatient(patientId);
+ EncounterService encounterService = Context.getEncounterService();
+ EncounterType encounterType = encounterService.getEncounterTypeByUuid(Metadata.EncounterType.MCHMS_ENROLLMENT);
+ Encounter lastMchEnrollment = EmrUtils.lastEncounter(patient, encounterType);
+ Obs lmpObs = EmrUtils.firstObsInEncounter(lastMchEnrollment, Dictionary.getConcept(Dictionary.LAST_MONTHLY_PERIOD));
+ if (lmpObs != null) {
+ Weeks weeks = Weeks.weeksBetween(new DateTime(lmpObs.getValueDate()), new DateTime(new Date()));
+ if (weeks.getWeeks() > 14) {
+ return true;
+ }
+ }
+ return false;
+ }
}
| false | false | null | null |
diff --git a/grails/src/java/org/codehaus/groovy/grails/web/binding/GrailsDataBinder.java b/grails/src/java/org/codehaus/groovy/grails/web/binding/GrailsDataBinder.java
index 7dbabe192..ac84465f6 100644
--- a/grails/src/java/org/codehaus/groovy/grails/web/binding/GrailsDataBinder.java
+++ b/grails/src/java/org/codehaus/groovy/grails/web/binding/GrailsDataBinder.java
@@ -1,775 +1,775 @@
/* Copyright 2004-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.codehaus.groovy.grails.web.binding;
import grails.util.GrailsNameUtils;
import groovy.lang.*;
import org.apache.commons.collections.Factory;
import org.apache.commons.collections.list.LazyList;
import org.apache.commons.collections.set.ListOrderedSet;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.lang.StringUtils;
import org.codehaus.groovy.grails.commons.*;
import org.codehaus.groovy.grails.commons.metaclass.CreateDynamicMethod;
import org.codehaus.groovy.grails.validation.ConstrainedProperty;
import org.codehaus.groovy.grails.web.context.ServletContextHolder;
import org.codehaus.groovy.grails.web.servlet.mvc.GrailsParameterMap;
import org.codehaus.groovy.runtime.InvokerHelper;
import org.springframework.beans.*;
import org.springframework.beans.PropertyValue;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.beans.propertyeditors.CustomNumberEditor;
import org.springframework.beans.propertyeditors.LocaleEditor;
import org.springframework.validation.BeanPropertyBindingResult;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.ServletRequestParameterPropertyValues;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.support.ByteArrayMultipartFileEditor;
import org.springframework.web.multipart.support.StringMultipartFileEditor;
import org.springframework.web.servlet.support.RequestContextUtils;
import javax.servlet.ServletContext;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.beans.PropertyEditor;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.URI;
import java.text.DateFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* A data binder that handles binding dates that are specified with a "struct"-like syntax in request parameters.
* For example for a set of fields defined as:
*
* <code>
* <input type="hidden" name="myDate_year" value="2005" />
* <input type="hidden" name="myDate_month" value="6" />
* <input type="hidden" name="myDate_day" value="12" />
* <input type="hidden" name="myDate_hour" value="13" />
* <input type="hidden" name="myDate_minute" value="45" />
* </code>
*
* This would set the property "myDate" of type java.util.Date with the specified values.
*
* @author Graeme Rocher
* @since 05-Jan-2006
*/
public class GrailsDataBinder extends ServletRequestDataBinder {
private static final Log LOG = LogFactory.getLog(GrailsDataBinder.class);
protected BeanWrapper bean;
public static final String[] GROOVY_DISALLOWED = new String[] { "metaClass", "properties" };
public static final String[] DOMAINCLASS_DISALLOWED = new String[] { "id", "version" };
public static final String[] GROOVY_DOMAINCLASS_DISALLOWED = new String[] { "metaClass", "properties", "id", "version" };
public static final String NULL_ASSOCIATION = "null";
private static final String PREFIX_SEPERATOR = ".";
private static final String[] ALL_OTHER_FIELDS_ALLOWED_BY_DEFAULT = new String[0];
private static final String CONSTRAINTS_PROPERTY = "constraints";
private static final String BLANK = "";
private static final String STRUCTURED_PROPERTY_SEPERATOR = "_";
private static final char PATH_SEPARATOR = '.';
private static final String IDENTIFIER_SUFFIX = ".id";
private List transients = Collections.EMPTY_LIST;
private static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss.S";
/**
* Create a new GrailsDataBinder instance.
*
* @param target target object to bind onto
* @param objectName objectName of the target object
*/
public GrailsDataBinder(Object target, String objectName) {
super(target, objectName);
bean = (BeanWrapper)((BeanPropertyBindingResult)super.getBindingResult()).getPropertyAccessor();
Object tmpTransients = GrailsClassUtils.getStaticPropertyValue(bean.getWrappedClass(), GrailsDomainClassProperty.TRANSIENT);
if(tmpTransients instanceof List) {
this.transients = (List) tmpTransients;
}
String[] disallowed = new String[0];
GrailsApplication grailsApplication = ApplicationHolder.getApplication();
if (grailsApplication!=null && grailsApplication.isArtefactOfType(DomainClassArtefactHandler.TYPE, target.getClass())) {
if (target instanceof GroovyObject) {
disallowed = GROOVY_DOMAINCLASS_DISALLOWED;
} else {
disallowed = DOMAINCLASS_DISALLOWED;
}
} else if (target instanceof GroovyObject) {
disallowed = GROOVY_DISALLOWED;
}
setDisallowedFields(disallowed);
setAllowedFields(ALL_OTHER_FIELDS_ALLOWED_BY_DEFAULT);
setIgnoreInvalidFields(true);
}
/**
* Collects all PropertyEditorRegistrars in the application context and
* calls them to register their custom editors
* @param registry The PropertyEditorRegistry instance
*/
private static void registerCustomEditors(PropertyEditorRegistry registry) {
final ServletContext servletContext = ServletContextHolder.getServletContext();
if(servletContext != null) {
WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(servletContext);
if(context != null) {
Map editors = context.getBeansOfType(PropertyEditorRegistrar.class);
for (Object o : editors.entrySet()) {
PropertyEditorRegistrar editorRegistrar = (PropertyEditorRegistrar) ((Map.Entry) o).getValue();
editorRegistrar.registerCustomEditors(registry);
}
}
}
}
/**
* Utility method for creating a GrailsDataBinder instance
*
* @param target The target object to bind to
* @param objectName The name of the object
* @param request A request instance
* @return A GrailsDataBinder instance
*/
public static GrailsDataBinder createBinder(Object target, String objectName, HttpServletRequest request) {
GrailsDataBinder binder = createBinder(target,objectName);
Locale locale = RequestContextUtils.getLocale(request);
registerCustomEditors(binder, locale);
return binder;
}
/**
* Registers all known
* @param registry
* @param locale
*/
public static void registerCustomEditors(PropertyEditorRegistry registry, Locale locale) {
// Formatters for the different number types.
NumberFormat floatFormat = NumberFormat.getInstance(locale);
NumberFormat integerFormat = NumberFormat.getIntegerInstance(locale);
DateFormat dateFormat = new SimpleDateFormat(DEFAULT_DATE_FORMAT, locale);
registry.registerCustomEditor( Date.class, new CustomDateEditor(dateFormat,true) );
registry.registerCustomEditor( BigDecimal.class, new CustomNumberEditor(BigDecimal.class, floatFormat, true));
registry.registerCustomEditor( BigInteger.class, new CustomNumberEditor(BigInteger.class, floatFormat, true));
registry.registerCustomEditor( Double.class, new CustomNumberEditor(Double.class, floatFormat, true));
registry.registerCustomEditor( double.class, new CustomNumberEditor(Double.class, floatFormat, true));
registry.registerCustomEditor( Float.class, new CustomNumberEditor(Float.class, floatFormat, true));
registry.registerCustomEditor( float.class, new CustomNumberEditor(Float.class, floatFormat, true));
registry.registerCustomEditor( Long.class, new CustomNumberEditor(Long.class, integerFormat, true));
registry.registerCustomEditor( long.class, new CustomNumberEditor(Long.class, integerFormat, true));
registry.registerCustomEditor( Integer.class, new CustomNumberEditor(Integer.class, integerFormat, true));
registry.registerCustomEditor( int.class, new CustomNumberEditor(Integer.class, integerFormat, true));
registry.registerCustomEditor( Short.class, new CustomNumberEditor(Short.class, integerFormat, true));
registry.registerCustomEditor( short.class, new CustomNumberEditor(Short.class, integerFormat, true));
registry.registerCustomEditor( Date.class, new StructuredDateEditor(dateFormat,true));
registry.registerCustomEditor( Calendar.class, new StructuredDateEditor(dateFormat,true));
registerCustomEditors(registry);
}
/**
* Utility method for creating a GrailsDataBinder instance
*
* @param target The target object to bind to
* @param objectName The name of the object
* @return A GrailsDataBinder instance
*/
public static GrailsDataBinder createBinder(Object target, String objectName) {
GrailsDataBinder binder = new GrailsDataBinder(target,objectName);
binder.registerCustomEditor( byte[].class, new ByteArrayMultipartFileEditor());
binder.registerCustomEditor( String.class, new StringMultipartFileEditor());
binder.registerCustomEditor( Currency.class, new CurrencyEditor());
binder.registerCustomEditor( Locale.class, new LocaleEditor());
binder.registerCustomEditor( TimeZone.class, new TimeZoneEditor());
binder.registerCustomEditor( URI.class, new UriEditor());
registerCustomEditors(binder);
return binder;
}
public void bind(PropertyValues propertyValues) {
bind(propertyValues, null);
}
/**
* Binds from a GrailsParameterMap object
*
* @param params The GrailsParameterMap object
*/
public void bind(GrailsParameterMap params) {
bind(params,null);
}
public void bind(GrailsParameterMap params, String prefix) {
Map paramsMap = params;
if(prefix != null) {
Object o = params.get(prefix);
if(o instanceof Map) paramsMap = (Map) o;
}
bindWithRequestAndPropertyValues(params.getRequest(), new MutablePropertyValues(paramsMap));
}
public void bind(PropertyValues propertyValues, String prefix) {
PropertyValues values = filterPropertyValues(propertyValues, prefix);
if(propertyValues instanceof MutablePropertyValues) {
MutablePropertyValues mutablePropertyValues = (MutablePropertyValues) propertyValues;
preProcessMutablePropertyValues(mutablePropertyValues);
}
super.bind(values);
}
public void bind(ServletRequest request) {
bind(request, null);
}
public void bind(ServletRequest request, String prefix) {
MutablePropertyValues mpvs;
if (prefix != null) {
mpvs = new ServletRequestParameterPropertyValues(request, prefix, PREFIX_SEPERATOR);
} else {
mpvs = new ServletRequestParameterPropertyValues(request);
}
bindWithRequestAndPropertyValues(request, mpvs);
}
private void bindWithRequestAndPropertyValues(ServletRequest request, MutablePropertyValues mpvs) {
preProcessMutablePropertyValues(mpvs);
if (request instanceof MultipartHttpServletRequest) {
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
bindMultipartFiles(multipartRequest.getFileMap(), mpvs);
}
doBind(mpvs);
}
private void preProcessMutablePropertyValues(MutablePropertyValues mpvs) {
checkStructuredProperties(mpvs);
autoCreateIfPossible(mpvs);
bindAssociations(mpvs);
}
protected void doBind(MutablePropertyValues mpvs) {
filterNestedParameterMaps(mpvs);
filterBlankValuesWhenTargetIsNullable(mpvs);
super.doBind(mpvs);
}
private void filterBlankValuesWhenTargetIsNullable(MutablePropertyValues mpvs) {
Object target = getTarget();
MetaClass mc = GroovySystem.getMetaClassRegistry().getMetaClass(target.getClass());
if(mc.hasProperty(target, CONSTRAINTS_PROPERTY) != null) {
Map constrainedProperties = (Map)mc.getProperty(target, CONSTRAINTS_PROPERTY);
PropertyValue[] valueArray = mpvs.getPropertyValues();
for (PropertyValue propertyValue : valueArray) {
ConstrainedProperty cp = getConstrainedPropertyForPropertyValue(constrainedProperties, propertyValue);
if (shouldNullifyBlankString(propertyValue, cp)) {
propertyValue.setConvertedValue(null);
}
}
}
}
private ConstrainedProperty getConstrainedPropertyForPropertyValue(Map constrainedProperties, PropertyValue propertyValue) {
final String propertyName = propertyValue.getName();
if(propertyName.indexOf(PATH_SEPARATOR) > -1) {
String[] propertyNames = propertyName.split("\\.");
Object target = getTarget();
Object value = getPropertyValueForPath(target, propertyNames);
if(value != null) {
MetaClass mc = GroovySystem.getMetaClassRegistry().getMetaClass(value.getClass());
if(mc.hasProperty(value, CONSTRAINTS_PROPERTY) != null) {
Map nestedConstrainedProperties = (Map)mc.getProperty(value, CONSTRAINTS_PROPERTY);
return (ConstrainedProperty)nestedConstrainedProperties.get(propertyNames[propertyNames.length-1]);
}
}
}
else {
return (ConstrainedProperty)constrainedProperties.get(propertyName);
}
return null;
}
private Object getPropertyValueForPath(Object target, String[] propertyNames) {
BeanWrapper bean = new BeanWrapperImpl(target);
Object obj = target;
for (int i = 0; i < propertyNames.length-1; i++) {
String propertyName = propertyNames[i];
if(bean.isReadableProperty(propertyName)) {
obj = bean.getPropertyValue(propertyName);
if(obj == null) break;
bean = new BeanWrapperImpl(obj);
}
}
return obj;
}
private boolean shouldNullifyBlankString(PropertyValue propertyValue, ConstrainedProperty cp) {
return cp!= null && cp.isNullable() && BLANK.equals(propertyValue.getValue());
}
private void filterNestedParameterMaps(MutablePropertyValues mpvs) {
PropertyValue[] values = mpvs.getPropertyValues();
for (PropertyValue pv : values) {
if (pv.getValue() instanceof GrailsParameterMap) {
mpvs.removePropertyValue(pv);
}
}
}
private PropertyValues filterPropertyValues(PropertyValues propertyValues, String prefix) {
if(prefix == null || prefix.length() == 0) return propertyValues;
PropertyValue[] valueArray = propertyValues.getPropertyValues();
MutablePropertyValues newValues = new MutablePropertyValues();
for (PropertyValue propertyValue : valueArray) {
if (propertyValue.getName().startsWith(prefix + PREFIX_SEPERATOR)) {
newValues.addPropertyValue(propertyValue.getName().replaceFirst(prefix + PREFIX_SEPERATOR, ""), propertyValue.getValue());
}
}
return newValues;
}
/**
* Method that auto-creates the a type if it is null and is possible to auto-create
*
* @param mpvs A MutablePropertyValues instance
*/
protected void autoCreateIfPossible(MutablePropertyValues mpvs) {
PropertyValue[] pvs = mpvs.getPropertyValues();
for (PropertyValue pv : pvs) {
String propertyName = pv.getName();
//super.
if (propertyName.indexOf(PATH_SEPARATOR) > -1) {
String[] propertyNames = propertyName.split("\\.");
BeanWrapper currentBean = bean;
for (String name : propertyNames) {
Object created = autoCreatePropertyIfPossible(currentBean, name, pv.getValue());
if (created != null)
currentBean = new BeanWrapperImpl(created);
else
break;
}
}
else {
autoCreatePropertyIfPossible(bean, propertyName, pv.getValue());
}
}
}
private Object autoCreatePropertyIfPossible(BeanWrapper bean, String propertyName, Object propertyValue) {
propertyName = PropertyAccessorUtils.canonicalPropertyName(propertyName);
int currentKeyStart = propertyName.indexOf(PropertyAccessor.PROPERTY_KEY_PREFIX_CHAR);
int currentKeyEnd = propertyName.indexOf(PropertyAccessor.PROPERTY_KEY_SUFFIX_CHAR);
String propertyNameWithIndex = propertyName;
if(currentKeyStart>-1) {
propertyName = propertyName.substring(0, currentKeyStart);
}
Class type = bean.getPropertyType(propertyName);
Object val = bean.isReadableProperty(propertyName) ? bean.getPropertyValue(propertyName) : null;
LOG.debug("Checking if auto-create is possible for property ["+propertyName+"] and type ["+type+"]");
- if(type != null && val == null && GroovyObject.class.isAssignableFrom(type)) {
+ if(type != null && val == null && DomainClassArtefactHandler.isDomainClass(type)) {
if(!shouldPropertyValueSkipAutoCreate(propertyValue) && isNullAndWritableProperty(bean, propertyName)) {
Object created = autoInstantiateDomainInstance(type);
if(created!=null) {
val = created;
bean.setPropertyValue(propertyName,created);
}
}
}
else {
final Object beanInstance = bean.getWrappedInstance();
if(type!= null && Collection.class.isAssignableFrom(type)) {
Collection c;
final Class referencedType = getReferencedTypeForCollection(propertyName, beanInstance);
if(isNullAndWritableProperty(bean, propertyName)) {
c = decorateCollectionForDomainAssociation(GrailsClassUtils.createConcreteCollection(type), referencedType);
}
else {
c = decorateCollectionForDomainAssociation((Collection) bean.getPropertyValue(propertyName), referencedType);
}
bean.setPropertyValue(propertyName, c);
val = c;
if(c!= null && currentKeyStart > -1 && currentKeyEnd > -1) {
String indexString = propertyNameWithIndex.substring(currentKeyStart+1, currentKeyEnd);
int index = Integer.parseInt(indexString);
if(DomainClassArtefactHandler.isDomainClass(referencedType)) {
Object instance = findIndexedValue(c, index);
if(instance != null) {
val = instance;
}
else {
instance = autoInstantiateDomainInstance(referencedType);
if(instance !=null) {
val = instance;
if(index == c.size()) {
addAssociationToTarget(propertyName, beanInstance, instance);
}
else if(index > c.size()) {
while(index > c.size()) {
addAssociationToTarget(propertyName, beanInstance, autoInstantiateDomainInstance(referencedType));
}
addAssociationToTarget(propertyName, beanInstance, instance);
}
}
}
}
}
}
else if(type!=null && Map.class.isAssignableFrom(type)) {
Map map;
if(isNullAndWritableProperty(bean, propertyName)) {
map = new HashMap();
bean.setPropertyValue(propertyName,map);
}
else {
map = (Map) bean.getPropertyValue(propertyName);
}
val = map;
bean.setPropertyValue(propertyName, val);
if(currentKeyStart > -1 && currentKeyEnd > -1) {
String indexString = propertyNameWithIndex.substring(currentKeyStart+1, currentKeyEnd);
Class referencedType = getReferencedTypeForCollection(propertyName, beanInstance);
if(DomainClassArtefactHandler.isDomainClass(referencedType)) {
final Object domainInstance = autoInstantiateDomainInstance(referencedType);
val = domainInstance;
map.put(indexString, domainInstance);
}
}
}
}
return val;
}
private boolean shouldPropertyValueSkipAutoCreate(Object propertyValue) {
return (propertyValue instanceof Map) || ((propertyValue instanceof String) && StringUtils.isBlank((String) propertyValue));
}
private Collection decorateCollectionForDomainAssociation(Collection c, final Class referencedType) {
if(canDecorateWithLazyList(c, referencedType)) {
c = LazyList.decorate((List)c, new Factory() {
public Object create() {
return autoInstantiateDomainInstance(referencedType);
}
});
}
else if(canDecorateWithListOrderedSet(c, referencedType)) {
c = ListOrderedSet.decorate((Set) c);
}
return c;
}
private boolean canDecorateWithListOrderedSet(Collection c, Class referencedType) {
return (c instanceof Set) && !(c instanceof ListOrderedSet) && !(c instanceof SortedSet) && DomainClassArtefactHandler.isDomainClass(referencedType);
}
private boolean canDecorateWithLazyList(Collection c, Class referencedType) {
return (c instanceof List) && !(c instanceof LazyList) && DomainClassArtefactHandler.isDomainClass(referencedType);
}
private Object findIndexedValue(Collection c, int index) {
if(index < c.size()) {
if(c instanceof List) {
return ((List)c).get(index);
}
else {
int j =0;
for (Iterator i = c.iterator(); i.hasNext();j++) {
Object o = i.next();
if(j == index) return o;
}
}
}
return null;
}
private Object autoInstantiateDomainInstance(Class type) {
Object created = null;
try {
MetaClass mc = GroovySystem.getMetaClassRegistry()
.getMetaClass(type);
if(mc!=null) {
created = mc.invokeStaticMethod(type, CreateDynamicMethod.METHOD_NAME, new Object[0]);
}
}
catch(MissingMethodException mme) {
LOG.warn("Unable to auto-create type, 'create' method not found");
}
catch(GroovyRuntimeException gre) {
LOG.warn("Unable to auto-create type, Groovy Runtime error: " + gre.getMessage(),gre) ;
}
return created;
}
private boolean isNullAndWritableProperty(ConfigurablePropertyAccessor bean, String propertyName) {
return bean.getPropertyValue(propertyName) == null && bean.isWritableProperty(propertyName);
}
/**
* Interrogates the specified properties looking for properites that represent associations to other
* classes (e.g., 'author.id'). If such a property is found, this method attempts to load the specified
* instance of the association (by ID) and set it on the target object.
*
* @param mpvs the <code>MutablePropertyValues</code> object holding the parameters from the request
*/
protected void bindAssociations(MutablePropertyValues mpvs) {
PropertyValue[] pvs = mpvs.getPropertyValues();
for (PropertyValue pv : pvs) {
String propertyName = pv.getName();
if (propertyName.endsWith(IDENTIFIER_SUFFIX)) {
propertyName = propertyName.substring(0, propertyName.length() - 3);
if (isReadableAndPersistent(propertyName) && bean.isWritableProperty(propertyName)) {
if (NULL_ASSOCIATION.equals(pv.getValue())) {
bean.setPropertyValue(propertyName, null);
mpvs.removePropertyValue(pv);
}
else {
Class type = bean.getPropertyType(propertyName);
Object persisted = getPersistentInstance(type, pv.getValue());
if (persisted != null) {
bean.setPropertyValue(propertyName, persisted);
}
}
}
}
else {
if (isReadableAndPersistent(propertyName)) {
Class type = bean.getPropertyType(propertyName);
if (Collection.class.isAssignableFrom(type)) {
bindCollectionAssociation(mpvs, pv);
}
}
}
}
}
private boolean isReadableAndPersistent(String propertyName) {
return bean.isReadableProperty(propertyName) && !transients.contains(propertyName);
}
private Object getPersistentInstance(Class type, Object id) {
Object persisted;// In order to load the association instance using InvokerHelper below, we need to
// temporarily change this thread's ClassLoader to use the Grails ClassLoader.
// (Otherwise, we'll get a ClassNotFoundException.)
ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader();
ClassLoader grailsClassLoader = getTarget().getClass().getClassLoader();
try {
try {
Thread.currentThread().setContextClassLoader(grailsClassLoader);
}
catch (java.security.AccessControlException e) {
// container doesn't allow, probably related to WAR deployment on AppEngine. proceed.
}
try {
persisted = InvokerHelper.invokeStaticMethod(type, "get", id);
}
catch (MissingMethodException e) {
return null; // GORM not installed, continue to operate as normal
}
} finally {
try {
Thread.currentThread().setContextClassLoader(currentClassLoader);
}
catch (java.security.AccessControlException e) {
// container doesn't allow, probably related to WAR deployment on AppEngine. proceed.
}
}
return persisted;
}
private void bindCollectionAssociation(MutablePropertyValues mpvs, PropertyValue pv) {
Object v = pv.getValue();
Collection collection = (Collection) bean.getPropertyValue(pv.getName());
collection.clear();
if(v != null && v.getClass().isArray()) {
Object[] identifiers = (Object[])v;
for (Object id : identifiers) {
if (id != null) {
associateObjectForId(pv, id);
}
}
mpvs.removePropertyValue(pv);
}
else if(v!=null && (v instanceof String)) {
associateObjectForId(pv,v);
mpvs.removePropertyValue(pv);
}
}
private void associateObjectForId(PropertyValue pv, Object id) {
final Object target = getTarget();
final Class associatedType = getReferencedTypeForCollection(pv.getName(), target);
if(isDomainAssociation(associatedType)) {
final Object obj = getPersistentInstance(associatedType, id);
addAssociationToTarget(pv.getName(), target, obj);
}
}
private boolean isDomainAssociation(Class associatedType) {
return associatedType != null && DomainClassArtefactHandler.isDomainClass(associatedType);
}
private void addAssociationToTarget(String name, Object target, Object obj) {
if(obj!=null) {
MetaClassRegistry reg = GroovySystem.getMetaClassRegistry();
MetaClass mc = reg.getMetaClass(target.getClass());
final String addMethodName = "addTo" + GrailsNameUtils.getClassNameRepresentation(name);
mc.invokeMethod(target, addMethodName,obj);
}
}
private Class getReferencedTypeForCollection(String name, Object target) {
final GrailsApplication grailsApplication = ApplicationHolder.getApplication();
if(grailsApplication!=null) {
GrailsDomainClass domainClass = (GrailsDomainClass) grailsApplication.getArtefact(DomainClassArtefactHandler.TYPE, target.getClass().getName());
if(domainClass!=null) {
GrailsDomainClassProperty domainProperty = domainClass.getPropertyByName(name);
if(domainProperty!=null && (domainProperty.isOneToMany()|| domainProperty.isManyToMany())) {
return domainProperty.getReferencedPropertyType();
}
}
}
return null;
}
private String getNameOf(PropertyValue propertyValue) {
String name = propertyValue.getName();
if (name.indexOf(STRUCTURED_PROPERTY_SEPERATOR) == -1) {
return name;
}
return name.substring(0, name.indexOf(STRUCTURED_PROPERTY_SEPERATOR));
}
private boolean isStructured(PropertyValue propertyValue) {
String name = propertyValue.getName();
return name.indexOf(STRUCTURED_PROPERTY_SEPERATOR) != -1;
}
/**
* Checks for structured properties. Structured properties are properties with a name
* containg a "_"
* @param propertyValues
*/
private void checkStructuredProperties(MutablePropertyValues propertyValues) {
PropertyValue[] pvs = propertyValues.getPropertyValues();
for (PropertyValue propertyValue : pvs) {
if (!isStructured(propertyValue)) {
continue;
}
String propertyName = getNameOf(propertyValue);
Class type = bean.getPropertyType(propertyName);
if (type != null) {
PropertyEditor editor = findCustomEditor(type, propertyName);
if (null != editor && StructuredPropertyEditor.class.isAssignableFrom(editor.getClass())) {
StructuredPropertyEditor structuredEditor = (StructuredPropertyEditor) editor;
List fields = new ArrayList();
fields.addAll(structuredEditor.getRequiredFields());
fields.addAll(structuredEditor.getOptionalFields());
Map<String, String> fieldValues = new HashMap<String, String>();
try {
for (Object field1 : fields) {
String field = (String) field1;
PropertyValue requiredProperty = propertyValues.getPropertyValue(propertyName + STRUCTURED_PROPERTY_SEPERATOR + field);
if (requiredProperty == null && structuredEditor.getRequiredFields().contains(field)) {
break;
}
else if (requiredProperty == null)
continue;
fieldValues.put(field, getStringValue(requiredProperty));
}
try {
Object value = structuredEditor.assemble(type, fieldValues);
if (null != value) {
for (Object field : fields) {
String requiredField = (String) field;
PropertyValue requiredProperty = propertyValues.getPropertyValue(propertyName + STRUCTURED_PROPERTY_SEPERATOR + requiredField);
if (null != requiredProperty) {
requiredProperty.setConvertedValue(getStringValue(requiredProperty));
}
}
propertyValues.addPropertyValue(new PropertyValue(propertyName, value));
}
}
catch (IllegalArgumentException iae) {
LOG.warn("Unable to parse structured date from request for date [" + propertyName + "]", iae);
}
}
catch (InvalidPropertyException ipe) {
// ignore
}
}
}
}
}
private String getStringValue(PropertyValue yearProperty) {
Object value = yearProperty.getValue();
if(value == null) return null;
else if(value.getClass().isArray()) {
return ((String[])value)[0];
}
return (String)value ;
}
}
| true | true | private Object autoCreatePropertyIfPossible(BeanWrapper bean, String propertyName, Object propertyValue) {
propertyName = PropertyAccessorUtils.canonicalPropertyName(propertyName);
int currentKeyStart = propertyName.indexOf(PropertyAccessor.PROPERTY_KEY_PREFIX_CHAR);
int currentKeyEnd = propertyName.indexOf(PropertyAccessor.PROPERTY_KEY_SUFFIX_CHAR);
String propertyNameWithIndex = propertyName;
if(currentKeyStart>-1) {
propertyName = propertyName.substring(0, currentKeyStart);
}
Class type = bean.getPropertyType(propertyName);
Object val = bean.isReadableProperty(propertyName) ? bean.getPropertyValue(propertyName) : null;
LOG.debug("Checking if auto-create is possible for property ["+propertyName+"] and type ["+type+"]");
if(type != null && val == null && GroovyObject.class.isAssignableFrom(type)) {
if(!shouldPropertyValueSkipAutoCreate(propertyValue) && isNullAndWritableProperty(bean, propertyName)) {
Object created = autoInstantiateDomainInstance(type);
if(created!=null) {
val = created;
bean.setPropertyValue(propertyName,created);
}
}
}
else {
final Object beanInstance = bean.getWrappedInstance();
if(type!= null && Collection.class.isAssignableFrom(type)) {
Collection c;
final Class referencedType = getReferencedTypeForCollection(propertyName, beanInstance);
if(isNullAndWritableProperty(bean, propertyName)) {
c = decorateCollectionForDomainAssociation(GrailsClassUtils.createConcreteCollection(type), referencedType);
}
else {
c = decorateCollectionForDomainAssociation((Collection) bean.getPropertyValue(propertyName), referencedType);
}
bean.setPropertyValue(propertyName, c);
val = c;
if(c!= null && currentKeyStart > -1 && currentKeyEnd > -1) {
String indexString = propertyNameWithIndex.substring(currentKeyStart+1, currentKeyEnd);
int index = Integer.parseInt(indexString);
if(DomainClassArtefactHandler.isDomainClass(referencedType)) {
Object instance = findIndexedValue(c, index);
if(instance != null) {
val = instance;
}
else {
instance = autoInstantiateDomainInstance(referencedType);
if(instance !=null) {
val = instance;
if(index == c.size()) {
addAssociationToTarget(propertyName, beanInstance, instance);
}
else if(index > c.size()) {
while(index > c.size()) {
addAssociationToTarget(propertyName, beanInstance, autoInstantiateDomainInstance(referencedType));
}
addAssociationToTarget(propertyName, beanInstance, instance);
}
}
}
}
}
}
else if(type!=null && Map.class.isAssignableFrom(type)) {
Map map;
if(isNullAndWritableProperty(bean, propertyName)) {
map = new HashMap();
bean.setPropertyValue(propertyName,map);
}
else {
map = (Map) bean.getPropertyValue(propertyName);
}
val = map;
bean.setPropertyValue(propertyName, val);
if(currentKeyStart > -1 && currentKeyEnd > -1) {
String indexString = propertyNameWithIndex.substring(currentKeyStart+1, currentKeyEnd);
Class referencedType = getReferencedTypeForCollection(propertyName, beanInstance);
if(DomainClassArtefactHandler.isDomainClass(referencedType)) {
final Object domainInstance = autoInstantiateDomainInstance(referencedType);
val = domainInstance;
map.put(indexString, domainInstance);
}
}
}
}
return val;
}
| private Object autoCreatePropertyIfPossible(BeanWrapper bean, String propertyName, Object propertyValue) {
propertyName = PropertyAccessorUtils.canonicalPropertyName(propertyName);
int currentKeyStart = propertyName.indexOf(PropertyAccessor.PROPERTY_KEY_PREFIX_CHAR);
int currentKeyEnd = propertyName.indexOf(PropertyAccessor.PROPERTY_KEY_SUFFIX_CHAR);
String propertyNameWithIndex = propertyName;
if(currentKeyStart>-1) {
propertyName = propertyName.substring(0, currentKeyStart);
}
Class type = bean.getPropertyType(propertyName);
Object val = bean.isReadableProperty(propertyName) ? bean.getPropertyValue(propertyName) : null;
LOG.debug("Checking if auto-create is possible for property ["+propertyName+"] and type ["+type+"]");
if(type != null && val == null && DomainClassArtefactHandler.isDomainClass(type)) {
if(!shouldPropertyValueSkipAutoCreate(propertyValue) && isNullAndWritableProperty(bean, propertyName)) {
Object created = autoInstantiateDomainInstance(type);
if(created!=null) {
val = created;
bean.setPropertyValue(propertyName,created);
}
}
}
else {
final Object beanInstance = bean.getWrappedInstance();
if(type!= null && Collection.class.isAssignableFrom(type)) {
Collection c;
final Class referencedType = getReferencedTypeForCollection(propertyName, beanInstance);
if(isNullAndWritableProperty(bean, propertyName)) {
c = decorateCollectionForDomainAssociation(GrailsClassUtils.createConcreteCollection(type), referencedType);
}
else {
c = decorateCollectionForDomainAssociation((Collection) bean.getPropertyValue(propertyName), referencedType);
}
bean.setPropertyValue(propertyName, c);
val = c;
if(c!= null && currentKeyStart > -1 && currentKeyEnd > -1) {
String indexString = propertyNameWithIndex.substring(currentKeyStart+1, currentKeyEnd);
int index = Integer.parseInt(indexString);
if(DomainClassArtefactHandler.isDomainClass(referencedType)) {
Object instance = findIndexedValue(c, index);
if(instance != null) {
val = instance;
}
else {
instance = autoInstantiateDomainInstance(referencedType);
if(instance !=null) {
val = instance;
if(index == c.size()) {
addAssociationToTarget(propertyName, beanInstance, instance);
}
else if(index > c.size()) {
while(index > c.size()) {
addAssociationToTarget(propertyName, beanInstance, autoInstantiateDomainInstance(referencedType));
}
addAssociationToTarget(propertyName, beanInstance, instance);
}
}
}
}
}
}
else if(type!=null && Map.class.isAssignableFrom(type)) {
Map map;
if(isNullAndWritableProperty(bean, propertyName)) {
map = new HashMap();
bean.setPropertyValue(propertyName,map);
}
else {
map = (Map) bean.getPropertyValue(propertyName);
}
val = map;
bean.setPropertyValue(propertyName, val);
if(currentKeyStart > -1 && currentKeyEnd > -1) {
String indexString = propertyNameWithIndex.substring(currentKeyStart+1, currentKeyEnd);
Class referencedType = getReferencedTypeForCollection(propertyName, beanInstance);
if(DomainClassArtefactHandler.isDomainClass(referencedType)) {
final Object domainInstance = autoInstantiateDomainInstance(referencedType);
val = domainInstance;
map.put(indexString, domainInstance);
}
}
}
}
return val;
}
|
diff --git a/modules/cpr/src/main/java/org/atmosphere/cpr/AtmosphereFramework.java b/modules/cpr/src/main/java/org/atmosphere/cpr/AtmosphereFramework.java
index 2812a5fe9..35b97227e 100644
--- a/modules/cpr/src/main/java/org/atmosphere/cpr/AtmosphereFramework.java
+++ b/modules/cpr/src/main/java/org/atmosphere/cpr/AtmosphereFramework.java
@@ -1,1861 +1,1837 @@
/*
* Copyright 2012 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.
*/
package org.atmosphere.cpr;
import org.atmosphere.cache.BroadcasterCacheInspector;
import org.atmosphere.cache.EventCacheBroadcasterCache;
import org.atmosphere.client.TrackMessageSizeFilter;
import org.atmosphere.client.TrackMessageSizeInterceptor;
import org.atmosphere.config.ApplicationConfiguration;
import org.atmosphere.config.AtmosphereHandlerConfig;
import org.atmosphere.config.AtmosphereHandlerProperty;
import org.atmosphere.config.FrameworkConfiguration;
import org.atmosphere.container.BlockingIOCometSupport;
import org.atmosphere.container.Tomcat7BIOSupportWithWebSocket;
import org.atmosphere.di.InjectorProvider;
import org.atmosphere.di.ServletContextHolder;
import org.atmosphere.di.ServletContextProvider;
import org.atmosphere.handler.AbstractReflectorAtmosphereHandler;
import org.atmosphere.handler.ReflectorServletProcessor;
import org.atmosphere.interceptor.AndroidAtmosphereInterceptor;
import org.atmosphere.interceptor.DefaultHeadersInterceptor;
import org.atmosphere.interceptor.JSONPAtmosphereInterceptor;
import org.atmosphere.interceptor.JavaScriptProtocol;
import org.atmosphere.interceptor.OnDisconnectInterceptor;
import org.atmosphere.interceptor.SSEAtmosphereInterceptor;
import org.atmosphere.interceptor.StreamingAtmosphereInterceptor;
import org.atmosphere.util.AtmosphereConfigReader;
import org.atmosphere.util.DefaultEndpointMapper;
import org.atmosphere.util.EndpointMapper;
import org.atmosphere.util.IntrospectionUtils;
import org.atmosphere.util.Version;
import org.atmosphere.websocket.DefaultWebSocketProcessor;
import org.atmosphere.websocket.WebSocket;
import org.atmosphere.websocket.WebSocketProtocol;
import org.atmosphere.websocket.protocol.SimpleHttpProtocol;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLClassLoader;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicBoolean;
import static org.atmosphere.cpr.ApplicationConfig.ALLOW_QUERYSTRING_AS_REQUEST;
import static org.atmosphere.cpr.ApplicationConfig.ATMOSPHERE_HANDLER;
import static org.atmosphere.cpr.ApplicationConfig.ATMOSPHERE_HANDLER_MAPPING;
import static org.atmosphere.cpr.ApplicationConfig.ATMOSPHERE_HANDLER_PATH;
import static org.atmosphere.cpr.ApplicationConfig.BROADCASTER_CACHE;
import static org.atmosphere.cpr.ApplicationConfig.BROADCASTER_CLASS;
import static org.atmosphere.cpr.ApplicationConfig.BROADCASTER_FACTORY;
import static org.atmosphere.cpr.ApplicationConfig.BROADCASTER_LIFECYCLE_POLICY;
import static org.atmosphere.cpr.ApplicationConfig.BROADCAST_FILTER_CLASSES;
import static org.atmosphere.cpr.ApplicationConfig.DISABLE_ONSTATE_EVENT;
import static org.atmosphere.cpr.ApplicationConfig.PROPERTY_ATMOSPHERE_XML;
import static org.atmosphere.cpr.ApplicationConfig.PROPERTY_BLOCKING_COMETSUPPORT;
import static org.atmosphere.cpr.ApplicationConfig.PROPERTY_COMET_SUPPORT;
import static org.atmosphere.cpr.ApplicationConfig.PROPERTY_NATIVE_COMETSUPPORT;
import static org.atmosphere.cpr.ApplicationConfig.PROPERTY_SERVLET_MAPPING;
import static org.atmosphere.cpr.ApplicationConfig.PROPERTY_SESSION_SUPPORT;
import static org.atmosphere.cpr.ApplicationConfig.PROPERTY_USE_STREAM;
import static org.atmosphere.cpr.ApplicationConfig.RESUME_AND_KEEPALIVE;
import static org.atmosphere.cpr.ApplicationConfig.SUSPENDED_ATMOSPHERE_RESOURCE_UUID;
import static org.atmosphere.cpr.ApplicationConfig.WEBSOCKET_PROCESSOR;
import static org.atmosphere.cpr.ApplicationConfig.WEBSOCKET_PROTOCOL;
import static org.atmosphere.cpr.ApplicationConfig.WEBSOCKET_SUPPORT;
import static org.atmosphere.cpr.FrameworkConfig.ATMOSPHERE_CONFIG;
import static org.atmosphere.cpr.FrameworkConfig.HAZELCAST_BROADCASTER;
import static org.atmosphere.cpr.FrameworkConfig.JERSEY_BROADCASTER;
import static org.atmosphere.cpr.FrameworkConfig.JERSEY_CONTAINER;
import static org.atmosphere.cpr.FrameworkConfig.JGROUPS_BROADCASTER;
import static org.atmosphere.cpr.FrameworkConfig.JMS_BROADCASTER;
import static org.atmosphere.cpr.FrameworkConfig.REDIS_BROADCASTER;
import static org.atmosphere.cpr.FrameworkConfig.WRITE_HEADERS;
import static org.atmosphere.cpr.FrameworkConfig.XMPP_BROADCASTER;
import static org.atmosphere.cpr.HeaderConfig.ATMOSPHERE_POST_BODY;
import static org.atmosphere.cpr.HeaderConfig.X_ATMOSPHERE_TRACKING_ID;
import static org.atmosphere.websocket.WebSocket.WEBSOCKET_SUSPEND;
/**
* The {@link AtmosphereFramework} is the entry point for the framework. This class can be used to from Servlet/filter
* to dispatch {@link AtmosphereRequest} and {@link AtmosphereResponse}. The framework can also be configured using
* the setXXX method. The life cycle of this class is
* <blockquote><pre>
* AtmosphereFramework f = new AtmosphereFramework();
* f.init();
* f.doCometSupport(AtmosphereRequest, AtmosphereResource);
* f.destroy();
* </pre></blockquote>
*
* @author Jeanfrancois Arcand
*/
public class AtmosphereFramework implements ServletContextProvider {
public static final String DEFAULT_ATMOSPHERE_CONFIG_PATH = "/META-INF/atmosphere.xml";
public static final String DEFAULT_LIB_PATH = "/WEB-INF/lib/";
public static final String MAPPING_REGEX = "[a-zA-Z0-9-&.*=@;\\?]+";
protected static final Logger logger = LoggerFactory.getLogger(AtmosphereFramework.class);
protected final List<String> broadcasterFilters = new ArrayList<String>();
protected final List<AsyncSupportListener> asyncSupportListeners = new ArrayList<AsyncSupportListener>();
protected final ArrayList<String> possibleComponentsCandidate = new ArrayList<String>();
protected final HashMap<String, String> initParams = new HashMap<String, String>();
protected final AtmosphereConfig config;
protected final AtomicBoolean isCometSupportConfigured = new AtomicBoolean(false);
protected final boolean isFilter;
protected final Map<String, AtmosphereHandlerWrapper> atmosphereHandlers = new ConcurrentHashMap<String, AtmosphereHandlerWrapper>();
protected final ConcurrentLinkedQueue<String> broadcasterTypes = new ConcurrentLinkedQueue<String>();
protected final ConcurrentLinkedQueue<BroadcasterCacheInspector> inspectors = new ConcurrentLinkedQueue<BroadcasterCacheInspector>();
protected String mappingRegex = MAPPING_REGEX;
protected boolean useNativeImplementation = false;
protected boolean useBlockingImplementation = false;
protected boolean useStreamForFlushingComments = false;
protected AsyncSupport asyncSupport;
protected String broadcasterClassName = DefaultBroadcaster.class.getName();
protected boolean isCometSupportSpecified = false;
protected boolean isBroadcasterSpecified = false;
protected boolean isSessionSupportSpecified = false;
protected BroadcasterFactory broadcasterFactory;
protected String broadcasterFactoryClassName;
protected String broadcasterCacheClassName;
protected boolean webSocketEnabled = true;
protected String broadcasterLifeCyclePolicy = "NEVER";
protected String webSocketProtocolClassName = SimpleHttpProtocol.class.getName();
protected WebSocketProtocol webSocketProtocol;
protected String handlersPath = "/WEB-INF/classes/";
protected ServletConfig servletConfig;
protected boolean autoDetectHandlers = true;
private boolean hasNewWebSocketProtocol = false;
protected String atmosphereDotXmlPath = DEFAULT_ATMOSPHERE_CONFIG_PATH;
protected final LinkedList<AtmosphereInterceptor> interceptors = new LinkedList<AtmosphereInterceptor>();
protected boolean scanDone = false;
protected String annotationProcessorClassName = "org.atmosphere.cpr.DefaultAnnotationProcessor";
protected final List<BroadcasterListener> broadcasterListeners = new ArrayList<BroadcasterListener>();
protected String webSocketProcessorClassName = DefaultWebSocketProcessor.class.getName();
protected boolean webSocketProtocolInitialized = false;
protected EndpointMapper<AtmosphereHandlerWrapper> endpointMapper = new DefaultEndpointMapper<AtmosphereHandlerWrapper>();
protected String libPath = DEFAULT_LIB_PATH;
@Override
public ServletContext getServletContext() {
return servletConfig.getServletContext();
}
public ServletConfig getServletConfig() {
return servletConfig;
}
public List<String> broadcasterFilters() {
return broadcasterFilters;
}
public static final class AtmosphereHandlerWrapper {
public final AtmosphereHandler atmosphereHandler;
public Broadcaster broadcaster;
public String mapping;
public List<AtmosphereInterceptor> interceptors = Collections.<AtmosphereInterceptor>emptyList();
public AtmosphereHandlerWrapper(BroadcasterFactory broadcasterFactory, AtmosphereHandler atmosphereHandler, String mapping) {
this.atmosphereHandler = atmosphereHandler;
try {
if (broadcasterFactory != null) {
this.broadcaster = broadcasterFactory.lookup(mapping, true);
} else {
this.mapping = mapping;
}
} catch (Exception t) {
throw new RuntimeException(t);
}
}
public AtmosphereHandlerWrapper(AtmosphereHandler atmosphereHandler, Broadcaster broadcaster) {
this.atmosphereHandler = atmosphereHandler;
this.broadcaster = broadcaster;
}
@Override
public String toString() {
return "AtmosphereHandlerWrapper{ atmosphereHandler=" + atmosphereHandler + ", broadcaster=" +
broadcaster + " }";
}
}
/**
* Return a configured instance of {@link AtmosphereConfig}
*
* @return a configured instance of {@link AtmosphereConfig}
*/
public AtmosphereConfig getAtmosphereConfig() {
return config;
}
/**
* Create an AtmosphereFramework.
*/
public AtmosphereFramework() {
this(false, true);
}
/**
* Create an AtmosphereFramework and initialize it via {@link AtmosphereFramework#init(javax.servlet.ServletConfig)}
*/
public AtmosphereFramework(ServletConfig sc) throws ServletException {
this(false, true);
init(sc);
}
/**
* Create an AtmosphereFramework.
*
* @param isFilter true if this instance is used as an {@link AtmosphereFilter}
*/
public AtmosphereFramework(boolean isFilter, boolean autoDetectHandlers) {
this.isFilter = isFilter;
this.autoDetectHandlers = autoDetectHandlers;
readSystemProperties();
populateBroadcasterType();
config = new AtmosphereConfig(this);
}
/**
* The order of addition is quite important here.
*/
private void populateBroadcasterType() {
broadcasterTypes.add(HAZELCAST_BROADCASTER);
broadcasterTypes.add(XMPP_BROADCASTER);
broadcasterTypes.add(REDIS_BROADCASTER);
broadcasterTypes.add(JGROUPS_BROADCASTER);
broadcasterTypes.add(JMS_BROADCASTER);
}
/**
* Add an {@link AtmosphereHandler} serviced by the {@link Servlet}
* This API is exposed to allow embedding an Atmosphere application.
*
* @param mapping The servlet mapping (servlet path)
* @param h implementation of an {@link AtmosphereHandler}
* @param l An attay of {@link AtmosphereInterceptor}
*/
public AtmosphereFramework addAtmosphereHandler(String mapping, AtmosphereHandler h, List<AtmosphereInterceptor> l) {
if (!mapping.startsWith("/")) {
mapping = "/" + mapping;
}
AtmosphereHandlerWrapper w = new AtmosphereHandlerWrapper(broadcasterFactory, h, mapping);
w.interceptors = l;
addMapping(mapping, w);
logger.info("Installed AtmosphereHandler {} mapped to context-path: {}", h.getClass().getName(), mapping);
if (l.size() > 0) {
logger.info("Installed AtmosphereInterceptor {} mapped to AtmosphereHandler {}", l, h.getClass().getName());
}
return this;
}
/**
* Add an {@link AtmosphereHandler} serviced by the {@link Servlet}
* This API is exposed to allow embedding an Atmosphere application.
*
* @param mapping The servlet mapping (servlet path)
* @param h implementation of an {@link AtmosphereHandler}
*/
public AtmosphereFramework addAtmosphereHandler(String mapping, AtmosphereHandler h) {
addAtmosphereHandler(mapping, h, Collections.<AtmosphereInterceptor>emptyList());
return this;
}
private AtmosphereFramework addMapping(String path, AtmosphereHandlerWrapper w) {
// We are using JAXRS mapping algorithm.
if (path.contains("*")) {
path = path.replace("*", mappingRegex);
}
if (path.endsWith("/")) {
path = path + mappingRegex;
}
InjectorProvider.getInjector().inject(w.atmosphereHandler);
atmosphereHandlers.put(path, w);
return this;
}
/**
* Add an {@link AtmosphereHandler} serviced by the {@link Servlet}
* This API is exposed to allow embedding an Atmosphere application.
*
* @param mapping The servlet mapping (servlet path)
* @param h implementation of an {@link AtmosphereHandler}
* @param broadcasterId The {@link Broadcaster#getID} value.
* @param l An attay of {@link AtmosphereInterceptor}
*/
public AtmosphereFramework addAtmosphereHandler(String mapping, AtmosphereHandler h, String broadcasterId, List<AtmosphereInterceptor> l) {
if (!mapping.startsWith("/")) {
mapping = "/" + mapping;
}
AtmosphereHandlerWrapper w = new AtmosphereHandlerWrapper(broadcasterFactory, h, mapping);
w.broadcaster.setID(broadcasterId);
w.interceptors = l;
addMapping(mapping, w);
logger.info("Installed AtmosphereHandler {} mapped to context-path: {}", h.getClass().getName(), mapping);
if (l.size() > 0) {
logger.info("Installed AtmosphereInterceptor {} mapped to AtmosphereHandler {}", l, h.getClass().getName());
}
return this;
}
/**
* Add an {@link AtmosphereHandler} serviced by the {@link Servlet}
* This API is exposed to allow embedding an Atmosphere application.
*
* @param mapping The servlet mapping (servlet path)
* @param h implementation of an {@link AtmosphereHandler}
* @param broadcasterId The {@link Broadcaster#getID} value.
*/
public AtmosphereFramework addAtmosphereHandler(String mapping, AtmosphereHandler h, String broadcasterId) {
addAtmosphereHandler(mapping, h, broadcasterId, Collections.<AtmosphereInterceptor>emptyList());
return this;
}
/**
* Add an {@link AtmosphereHandler} serviced by the {@link Servlet}
* This API is exposed to allow embedding an Atmosphere application.
*
* @param mapping The servlet mapping (servlet path)
* @param h implementation of an {@link AtmosphereHandler}
* @param broadcaster The {@link Broadcaster} associated with AtmosphereHandler.
* @param l An attay of {@link AtmosphereInterceptor}
*/
public AtmosphereFramework addAtmosphereHandler(String mapping, AtmosphereHandler h, Broadcaster broadcaster, List<AtmosphereInterceptor> l) {
if (!mapping.startsWith("/")) {
mapping = "/" + mapping;
}
AtmosphereHandlerWrapper w = new AtmosphereHandlerWrapper(h, broadcaster);
w.interceptors = l;
addMapping(mapping, w);
logger.info("Installed AtmosphereHandler {} mapped to context-path: {}", h.getClass().getName(), mapping);
if (l.size() > 0) {
logger.info("Installed AtmosphereInterceptor {} mapped to AtmosphereHandler {}", l, h.getClass().getName());
}
return this;
}
/**
* Add an {@link AtmosphereHandler} serviced by the {@link Servlet}
* This API is exposed to allow embedding an Atmosphere application.
*
* @param mapping The servlet mapping (servlet path)
* @param h implementation of an {@link AtmosphereHandler}
* @param broadcaster The {@link Broadcaster} associated with AtmosphereHandler.
*/
public AtmosphereFramework addAtmosphereHandler(String mapping, AtmosphereHandler h, Broadcaster broadcaster) {
addAtmosphereHandler(mapping, h, broadcaster, Collections.<AtmosphereInterceptor>emptyList());
return this;
}
/**
* Remove an {@link AtmosphereHandler}
*
* @param mapping the mapping used when invoking {@link #addAtmosphereHandler(String, AtmosphereHandler)};
* @return true if removed
*/
public AtmosphereFramework removeAtmosphereHandler(String mapping) {
if (mapping.endsWith("/")) {
mapping += mappingRegex;
}
atmosphereHandlers.remove(mapping);
return this;
}
/**
* Remove all {@link AtmosphereHandler}
*/
public AtmosphereFramework removeAllAtmosphereHandler() {
atmosphereHandlers.clear();
return this;
}
/**
* Remove all init parameters.
*/
public AtmosphereFramework removeAllInitParams() {
initParams.clear();
return this;
}
/**
* Add init-param like if they were defined in web.xml
*
* @param name The name
* @param value The value
*/
public AtmosphereFramework addInitParameter(String name, String value) {
initParams.put(name, value);
return this;
}
protected void readSystemProperties() {
if (System.getProperty(PROPERTY_NATIVE_COMETSUPPORT) != null) {
useNativeImplementation = Boolean
.parseBoolean(System.getProperty(PROPERTY_NATIVE_COMETSUPPORT));
isCometSupportSpecified = true;
}
if (System.getProperty(PROPERTY_BLOCKING_COMETSUPPORT) != null) {
useBlockingImplementation = Boolean
.parseBoolean(System.getProperty(PROPERTY_BLOCKING_COMETSUPPORT));
isCometSupportSpecified = true;
}
atmosphereDotXmlPath = System.getProperty(PROPERTY_ATMOSPHERE_XML, atmosphereDotXmlPath);
if (System.getProperty(DISABLE_ONSTATE_EVENT) != null) {
initParams.put(DISABLE_ONSTATE_EVENT, System.getProperty(DISABLE_ONSTATE_EVENT));
}
}
/**
* Path specific container using their own property.
*/
public void patchContainer() {
System.setProperty("org.apache.catalina.STRICT_SERVLET_COMPLIANCE", "false");
}
/**
* Initialize the AtmosphereFramework. Invoke that method after having properly configured this class using the setter.
*/
public AtmosphereFramework init() {
try {
init(new ServletConfig(){
@Override
public String getServletName() {
return "AtmosphereFramework";
}
@Override
public ServletContext getServletContext() {
return (ServletContext) Proxy.newProxyInstance(getClass().getClassLoader(), new Class[]{ServletContext.class},
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
logger.trace("Method {} not supported", method.getName());
return null;
}
});
}
@Override
public String getInitParameter(String name) {
return initParams.get(name);
}
@Override
public Enumeration<String> getInitParameterNames() {
return Collections.enumeration(initParams.values());
}
});
} catch (ServletException e) {
logger.error("",e);
}
return this;
}
/**
* Initialize the AtmosphereFramework using the {@link ServletContext}
*
* @param sc the {@link ServletContext}
*/
public AtmosphereFramework init(final ServletConfig sc) throws ServletException {
try {
ServletContextHolder.register(this);
ServletConfig scFacade = new ServletConfig() {
public String getServletName() {
return sc.getServletName();
}
public ServletContext getServletContext() {
return sc.getServletContext();
}
public String getInitParameter(String name) {
String param = initParams.get(name);
if (param == null) {
return sc.getInitParameter(name);
}
return param;
}
public Enumeration<String> getInitParameterNames() {
Enumeration en = sc.getInitParameterNames();
while (en.hasMoreElements()) {
String name = (String) en.nextElement();
if (!initParams.containsKey(name)) {
initParams.put(name, sc.getInitParameter(name));
}
}
return Collections.enumeration(initParams.keySet());
}
};
this.servletConfig = scFacade;
asyncSupportListener(new AsyncSupportListenerAdapter());
installAnnotationProcessor(scFacade);
autoConfigureService(scFacade.getServletContext());
patchContainer();
doInitParams(scFacade);
doInitParamsForWebSocket(scFacade);
configureBroadcaster();
loadConfiguration(scFacade);
initWebSocket();
initEndpointMapper();
autoDetectContainer();
configureWebDotXmlAtmosphereHandler(sc);
asyncSupport.init(scFacade);
initAtmosphereHandler(scFacade);
configureAtmosphereInterceptor(sc);
if (broadcasterCacheClassName == null) {
logger.warn("No BroadcasterCache configured. Broadcasted message between client reconnection will be LOST. " +
"It is recommended to configure the {}", EventCacheBroadcasterCache.class.getName());
} else {
logger.info("Using BroadcasterCache: {}", broadcasterCacheClassName);
}
// http://java.net/jira/browse/ATMOSPHERE-157
if (sc.getServletContext() != null) {
sc.getServletContext().setAttribute(BroadcasterFactory.class.getName(), broadcasterFactory);
}
- boolean found = false;
- for (AtmosphereInterceptor i: interceptors) {
- if (i.getClass().isAssignableFrom(TrackMessageSizeInterceptor.class)) {
- found = true;
- break;
- }
- }
-
- for (Entry<String, AtmosphereHandlerWrapper> e : atmosphereHandlers.entrySet()) {
- for (AtmosphereInterceptor i : e.getValue().interceptors) {
- if (i.getClass().isAssignableFrom(TrackMessageSizeInterceptor.class)) {
- found = true;
- break;
- }
- }
- }
for (String i: broadcasterFilters) {
- if (i.equals(TrackMessageSizeFilter.class.getName())) {
- found = true;
- break;
- }
- }
-
- if (!found) {
- logger.warn("Neither TrackMessageSizeInterceptor or TrackMessageSizeFilter are installed." +
- " atmosphere.js may receive glued and incomplete message.");
+ logger.info("Using BroadcastFilter: {}", i);
}
logger.info("HttpSession supported: {}", config.isSupportSession());
logger.info("Using BroadcasterFactory: {}", broadcasterFactory.getClass().getName());
logger.info("Using WebSocketProcessor: {}", webSocketProcessorClassName);
logger.info("Using Broadcaster: {}", broadcasterClassName);
logger.info("Atmosphere Framework {} started.", Version.getRawVersion());
} catch (Throwable t) {
logger.error("Failed to initialize Atmosphere Framework", t);
if (t instanceof ServletException) {
throw (ServletException) t;
}
throw new ServletException(t);
}
return this;
}
/**
* Configure the list of {@link AtmosphereInterceptor}.
*
* @param sc a ServletConfig
*/
protected void configureAtmosphereInterceptor(ServletConfig sc) {
String s = sc.getInitParameter(ApplicationConfig.ATMOSPHERE_INTERCEPTORS);
if (s != null) {
String[] list = s.split(",");
for (String a : list) {
try {
AtmosphereInterceptor ai = (AtmosphereInterceptor) Thread.currentThread().getContextClassLoader()
.loadClass(a.trim()).newInstance();
ai.configure(config);
interceptor(ai);
} catch (InstantiationException e) {
logger.warn("", e);
} catch (IllegalAccessException e) {
logger.warn("", e);
} catch (ClassNotFoundException e) {
logger.warn("", e);
}
}
}
logger.info("Installing Default AtmosphereInterceptor");
s = sc.getInitParameter(ApplicationConfig.DISABLE_ATMOSPHEREINTERCEPTOR);
if (s == null) {
// OnDisconnect
interceptors.addFirst(newAInterceptor(OnDisconnectInterceptor.class));
// ADD Tracking ID Handshake
interceptors.addFirst(newAInterceptor(JavaScriptProtocol.class));
// ADD JSONP support
interceptors.addFirst(newAInterceptor(JSONPAtmosphereInterceptor.class));
// Add SSE support
interceptors.addFirst(newAInterceptor(SSEAtmosphereInterceptor.class));
// Android 2.3.x streaming support
interceptors.addFirst(newAInterceptor(AndroidAtmosphereInterceptor.class));
// WebKit & IE Padding
interceptors.addFirst(newAInterceptor(StreamingAtmosphereInterceptor.class));
// Default Interceptor
interceptors.addFirst(newAInterceptor(DefaultHeadersInterceptor.class));
logger.info("Installed Default AtmosphereInterceptor {}. " +
"Set org.atmosphere.cpr.AtmosphereInterceptor.disableDefaults in your xml to disable them.", interceptors);
}
}
protected AtmosphereInterceptor newAInterceptor(Class<? extends AtmosphereInterceptor> a) {
AtmosphereInterceptor ai = null;
try {
ai = (AtmosphereInterceptor) getClass().getClassLoader().loadClass(a.getName()).newInstance();
ai.configure(config);
logger.info("\t{} : {}", a.getName(), ai);
} catch (Exception ex) {
logger.warn("", ex);
}
return ai;
}
protected void configureWebDotXmlAtmosphereHandler(ServletConfig sc) {
String s = sc.getInitParameter(ATMOSPHERE_HANDLER);
if (s != null) {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
try {
String mapping = sc.getInitParameter(ATMOSPHERE_HANDLER_MAPPING);
if (mapping == null) {
mapping = "/*";
}
addAtmosphereHandler(mapping, (AtmosphereHandler) cl.loadClass(s).newInstance());
} catch (Exception ex) {
logger.warn("Unable to load WebSocketHandle instance", ex);
}
}
}
protected void configureBroadcaster() {
try {
// Check auto supported one
if (isBroadcasterSpecified == false) {
broadcasterClassName = lookupDefaultBroadcasterType(broadcasterClassName);
}
if (broadcasterFactoryClassName != null) {
broadcasterFactory = (BroadcasterFactory) Thread.currentThread().getContextClassLoader()
.loadClass(broadcasterFactoryClassName).newInstance();
}
if (broadcasterFactory == null) {
Class<? extends Broadcaster> bc =
(Class<? extends Broadcaster>) Thread.currentThread().getContextClassLoader()
.loadClass(broadcasterClassName);
broadcasterFactory = new DefaultBroadcasterFactory(bc, broadcasterLifeCyclePolicy, config);
}
for (BroadcasterListener b: broadcasterListeners) {
broadcasterFactory.addBroadcasterListener(b);
}
BroadcasterFactory.setBroadcasterFactory(broadcasterFactory, config);
InjectorProvider.getInjector().inject(broadcasterFactory);
Iterator<Entry<String, AtmosphereHandlerWrapper>> i = atmosphereHandlers.entrySet().iterator();
AtmosphereHandlerWrapper w;
Entry<String, AtmosphereHandlerWrapper> e;
while (i.hasNext()) {
e = i.next();
w = e.getValue();
BroadcasterConfig broadcasterConfig = new BroadcasterConfig(broadcasterFilters, config, w.mapping);
if (w.broadcaster == null) {
w.broadcaster = broadcasterFactory.get(w.mapping);
} else {
w.broadcaster.setBroadcasterConfig(broadcasterConfig);
if (broadcasterCacheClassName != null) {
BroadcasterCache cache = (BroadcasterCache) Thread.currentThread().getContextClassLoader()
.loadClass(broadcasterCacheClassName).newInstance();
InjectorProvider.getInjector().inject(cache);
broadcasterConfig.setBroadcasterCache(cache);
}
}
}
} catch (Exception ex) {
logger.error("Unable to configure Broadcaster/Factory/Cache", ex);
}
}
protected void installAnnotationProcessor(ServletConfig sc) {
String s = sc.getInitParameter(ApplicationConfig.ANNOTATION_PROCESSOR);
if (s != null) {
annotationProcessorClassName = s;
}
}
protected void doInitParamsForWebSocket(ServletConfig sc) {
String s = sc.getInitParameter(WEBSOCKET_SUPPORT);
if (s != null) {
webSocketEnabled = Boolean.parseBoolean(s);
sessionSupport(false);
}
s = sc.getInitParameter(WEBSOCKET_PROTOCOL);
if (s != null) {
webSocketProtocolClassName = s;
}
s = sc.getInitParameter(WEBSOCKET_PROCESSOR);
if (s != null) {
webSocketProcessorClassName = s;
}
}
/**
* Read init param from web.xml and apply them.
*
* @param sc {@link ServletConfig}
*/
protected void doInitParams(ServletConfig sc) {
String s = sc.getInitParameter(PROPERTY_NATIVE_COMETSUPPORT);
if (s != null) {
useNativeImplementation = Boolean.parseBoolean(s);
if (useNativeImplementation) isCometSupportSpecified = true;
}
s = sc.getInitParameter(PROPERTY_BLOCKING_COMETSUPPORT);
if (s != null) {
useBlockingImplementation = Boolean.parseBoolean(s);
if (useBlockingImplementation) isCometSupportSpecified = true;
}
s = sc.getInitParameter(PROPERTY_USE_STREAM);
if (s != null) {
useStreamForFlushingComments = Boolean.parseBoolean(s);
}
s = sc.getInitParameter(PROPERTY_COMET_SUPPORT);
if (s != null) {
asyncSupport = new DefaultAsyncSupportResolver(config).newCometSupport(s);
isCometSupportSpecified = true;
}
s = sc.getInitParameter(BROADCASTER_CLASS);
if (s != null) {
broadcasterClassName = s;
isBroadcasterSpecified = true;
}
s = sc.getInitParameter(BROADCASTER_CACHE);
if (s != null) {
broadcasterCacheClassName = s;
}
s = sc.getInitParameter(PROPERTY_SESSION_SUPPORT);
if (s != null) {
config.setSupportSession(Boolean.valueOf(s));
isSessionSupportSpecified = true;
}
s = sc.getInitParameter(DISABLE_ONSTATE_EVENT);
if (s != null) {
initParams.put(DISABLE_ONSTATE_EVENT, s);
} else {
initParams.put(DISABLE_ONSTATE_EVENT, "false");
}
s = sc.getInitParameter(RESUME_AND_KEEPALIVE);
if (s != null) {
initParams.put(RESUME_AND_KEEPALIVE, s);
}
s = sc.getInitParameter(BROADCAST_FILTER_CLASSES);
if (s != null) {
broadcasterFilters.addAll(Arrays.asList(s.split(",")));
logger.info("Installing BroadcastFilter class(es) {}", s);
}
s = sc.getInitParameter(BROADCASTER_LIFECYCLE_POLICY);
if (s != null) {
broadcasterLifeCyclePolicy = s;
}
s = sc.getInitParameter(BROADCASTER_FACTORY);
if (s != null) {
broadcasterFactoryClassName = s;
}
s = sc.getInitParameter(ATMOSPHERE_HANDLER_PATH);
if (s != null) {
handlersPath = s;
}
s = sc.getInitParameter(PROPERTY_ATMOSPHERE_XML);
if (s != null) {
atmosphereDotXmlPath = s;
}
s = sc.getInitParameter(ApplicationConfig.HANDLER_MAPPING_REGEX);
if (s != null) {
mappingRegex = s;
}
}
public void loadConfiguration(ServletConfig sc) throws ServletException {
if (!autoDetectHandlers) return;
try {
URL url = sc.getServletContext().getResource(handlersPath);
URLClassLoader urlC = new URLClassLoader(new URL[]{url},
Thread.currentThread().getContextClassLoader());
loadAtmosphereDotXml(sc.getServletContext().
getResourceAsStream(atmosphereDotXmlPath), urlC);
if (atmosphereHandlers.size() == 0) {
autoDetectAtmosphereHandlers(sc.getServletContext(), urlC);
if (atmosphereHandlers.size() == 0) {
detectSupportedFramework(sc);
}
}
autoDetectWebSocketHandler(sc.getServletContext(), urlC);
} catch (Throwable t) {
throw new ServletException(t);
}
}
/**
* Auto-detect Jersey when no atmosphere.xml file are specified.
*
* @param sc {@link ServletConfig}
* @return true if Jersey classes are detected
* @throws ClassNotFoundException
*/
protected boolean detectSupportedFramework(ServletConfig sc) throws ClassNotFoundException, IllegalAccessException,
InstantiationException, NoSuchMethodException, InvocationTargetException {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
String broadcasterClassNameTmp = null;
try {
cl.loadClass(JERSEY_CONTAINER);
if (!isBroadcasterSpecified) {
broadcasterClassNameTmp = lookupDefaultBroadcasterType(JERSEY_BROADCASTER);
cl.loadClass(broadcasterClassNameTmp);
}
useStreamForFlushingComments = true;
} catch (Throwable t) {
logger.trace("", t);
return false;
}
logger.warn("Missing META-INF/atmosphere.xml but found the Jersey runtime. Starting Jersey");
// Jersey will handle itself the headers.
initParams.put(WRITE_HEADERS, "false");
ReflectorServletProcessor rsp = new ReflectorServletProcessor();
if (broadcasterClassNameTmp != null) broadcasterClassName = broadcasterClassNameTmp;
rsp.setServletClassName(JERSEY_CONTAINER);
sessionSupport(false);
initParams.put(DISABLE_ONSTATE_EVENT, "true");
String mapping = sc.getInitParameter(PROPERTY_SERVLET_MAPPING);
if (mapping == null) {
mapping = "/*";
}
Class<? extends Broadcaster> bc = (Class<? extends Broadcaster>) cl.loadClass(broadcasterClassName);
broadcasterFactory.destroy();
broadcasterFactory = new DefaultBroadcasterFactory(bc, broadcasterLifeCyclePolicy, config);
BroadcasterFactory.setBroadcasterFactory(broadcasterFactory, config);
for (BroadcasterListener b: broadcasterListeners) {
broadcasterFactory.addBroadcasterListener(b);
}
Broadcaster b;
try {
b = broadcasterFactory.get(bc, mapping);
} catch (IllegalStateException ex) {
logger.warn("Two Broadcaster's named {}. Renaming the second one to {}", mapping, sc.getServletName() + mapping);
b = broadcasterFactory.get(bc, sc.getServletName() + mapping);
}
addAtmosphereHandler(mapping, rsp, b);
return true;
}
protected String lookupDefaultBroadcasterType(String defaultB) {
for (String b : broadcasterTypes) {
try {
Class.forName(b);
return b;
} catch (ClassNotFoundException e) {
}
}
return defaultB;
}
protected void sessionSupport(boolean sessionSupport) {
if (!isSessionSupportSpecified) {
config.setSupportSession(sessionSupport);
} else if (!config.isSupportSession()) {
// Don't turn off session support. Once it's on, leave it on.
config.setSupportSession(sessionSupport);
}
}
/**
* Initialize {@link AtmosphereServletProcessor}
*
* @param sc the {@link ServletConfig}
* @throws javax.servlet.ServletException
*/
public void initAtmosphereHandler(ServletConfig sc) throws ServletException {
AtmosphereHandler a;
AtmosphereHandlerWrapper w;
for (Entry<String, AtmosphereHandlerWrapper> h : atmosphereHandlers.entrySet()) {
w = h.getValue();
a = w.atmosphereHandler;
if (a instanceof AtmosphereServletProcessor) {
((AtmosphereServletProcessor) a).init(sc);
}
}
if (atmosphereHandlers.size() == 0 && !SimpleHttpProtocol.class.isAssignableFrom(webSocketProtocol.getClass())) {
logger.debug("Adding a void AtmosphereHandler mapped to /* to allow WebSocket application only");
addAtmosphereHandler("/*", new AbstractReflectorAtmosphereHandler() {
@Override
public void onRequest(AtmosphereResource r) throws IOException {
logger.debug("No AtmosphereHandler defined.");
}
@Override
public void destroy() {
}
});
}
}
public void initWebSocket() {
if(webSocketProtocolInitialized) return;
if (webSocketProtocol == null) {
try {
webSocketProtocol = (WebSocketProtocol) Thread.currentThread().getContextClassLoader()
.loadClass(webSocketProtocolClassName).newInstance();
logger.info("Installed WebSocketProtocol {} ", webSocketProtocolClassName);
} catch (Exception ex) {
try {
webSocketProtocol = (WebSocketProtocol) AtmosphereFramework.class.getClassLoader()
.loadClass(webSocketProtocolClassName).newInstance();
logger.info("Installed WebSocketProtocol {} ", webSocketProtocolClassName);
} catch (Exception ex2) {
logger.error("Cannot load the WebSocketProtocol {}", getWebSocketProtocolClassName(), ex);
webSocketProtocol = new SimpleHttpProtocol();
}
}
}
webSocketProtocolInitialized = true;
webSocketProtocol.configure(config);
}
public void initEndpointMapper() {
String s = servletConfig.getInitParameter(ApplicationConfig.ENDPOINT_MAPPER);
if (s != null) {
try {
endpointMapper = (EndpointMapper) AtmosphereFramework.class.getClassLoader()
.loadClass(s).newInstance();
logger.info("Installed EndpointMapper {} ", s);
} catch (Exception ex) {
logger.error("Cannot load the EndpointMapper {}", s, ex);
}
}
}
public AtmosphereFramework destroy() {
if (asyncSupport != null && AsynchronousProcessor.class.isAssignableFrom(asyncSupport.getClass())) {
((AsynchronousProcessor) asyncSupport).shutdown();
}
// We just need one bc to shutdown the shared thread pool
for (Entry<String, AtmosphereHandlerWrapper> entry : atmosphereHandlers.entrySet()) {
AtmosphereHandlerWrapper handlerWrapper = entry.getValue();
handlerWrapper.atmosphereHandler.destroy();
}
BroadcasterFactory factory = broadcasterFactory;
if (factory != null) {
factory.destroy();
BroadcasterFactory.factory = null;
}
WebSocketProcessorFactory.getDefault().destroy();
return this;
}
/**
* Load AtmosphereHandler defined under META-INF/atmosphere.xml
*
* @param stream The input stream we read from.
* @param c The classloader
*/
protected void loadAtmosphereDotXml(InputStream stream, URLClassLoader c)
throws IOException, ServletException {
if (stream == null) {
return;
}
AtmosphereConfigReader.getInstance().parse(config, stream);
for (AtmosphereHandlerConfig atmoHandler : config.getAtmosphereHandlerConfig()) {
try {
AtmosphereHandler handler;
if (!ReflectorServletProcessor.class.getName().equals(atmoHandler.getClassName())) {
handler = (AtmosphereHandler) c.loadClass(atmoHandler.getClassName()).newInstance();
} else {
handler = new ReflectorServletProcessor();
}
logger.info("Installed AtmosphereHandler {} mapped to context-path: {}", handler, atmoHandler.getContextRoot());
for (ApplicationConfiguration a : atmoHandler.getApplicationConfig()) {
initParams.put(a.getParamName(), a.getParamValue());
}
for (FrameworkConfiguration a : atmoHandler.getFrameworkConfig()) {
initParams.put(a.getParamName(), a.getParamValue());
}
for (AtmosphereHandlerProperty handlerProperty : atmoHandler.getProperties()) {
if (handlerProperty.getValue() != null && handlerProperty.getValue().indexOf("jersey") != -1) {
initParams.put(DISABLE_ONSTATE_EVENT, "true");
useStreamForFlushingComments = true;
broadcasterClassName = lookupDefaultBroadcasterType(JERSEY_BROADCASTER);
broadcasterFactory = null;
configureBroadcaster();
}
IntrospectionUtils.setProperty(handler, handlerProperty.getName(), handlerProperty.getValue());
IntrospectionUtils.addProperty(handler, handlerProperty.getName(), handlerProperty.getValue());
}
sessionSupport(Boolean.valueOf(atmoHandler.getSupportSession()));
String broadcasterClass = atmoHandler.getBroadcaster();
Broadcaster b;
/**
* If there is more than one AtmosphereHandler defined, their Broadcaster
* may clash each other with the BroadcasterFactory. In that case we will use the
* last one defined.
*/
if (broadcasterClass != null) {
broadcasterClassName = broadcasterClass;
ClassLoader cl = Thread.currentThread().getContextClassLoader();
Class<? extends Broadcaster> bc = (Class<? extends Broadcaster>) cl.loadClass(broadcasterClassName);
broadcasterFactory = new DefaultBroadcasterFactory(bc, broadcasterLifeCyclePolicy, config);
BroadcasterFactory.setBroadcasterFactory(broadcasterFactory, config);
}
b = broadcasterFactory.lookup(atmoHandler.getContextRoot(), true);
AtmosphereHandlerWrapper wrapper = new AtmosphereHandlerWrapper(handler, b);
addMapping(atmoHandler.getContextRoot(), wrapper);
String bc = atmoHandler.getBroadcasterCache();
if (bc != null) {
broadcasterCacheClassName = bc;
}
if (atmoHandler.getCometSupport() != null) {
asyncSupport = (AsyncSupport) c.loadClass(atmoHandler.getCometSupport())
.getDeclaredConstructor(new Class[]{AtmosphereConfig.class})
.newInstance(new Object[]{config});
}
if (atmoHandler.getBroadcastFilterClasses() != null) {
broadcasterFilters.addAll(atmoHandler.getBroadcastFilterClasses());
}
List<AtmosphereInterceptor> l = new ArrayList<AtmosphereInterceptor>();
if (atmoHandler.getAtmosphereInterceptorClasses() != null) {
for (String a : atmoHandler.getAtmosphereInterceptorClasses()) {
try {
AtmosphereInterceptor ai = (AtmosphereInterceptor) c.loadClass(a).newInstance();
ai.configure(config);
l.add(ai);
} catch (Throwable e) {
logger.warn("", e);
}
}
}
wrapper.interceptors = l;
if (l.size() > 0) {
logger.info("Installed AtmosphereInterceptor {} mapped to AtmosphereHandler {}", l, atmoHandler.getClassName());
}
} catch (Throwable t) {
logger.warn("Unable to load AtmosphereHandler class: " + atmoHandler.getClassName(), t);
throw new ServletException(t);
}
}
}
/**
* Set the {@link AsyncSupport} implementation. Make sure you don't set
* an implementation that only works on some Container. See {@link BlockingIOCometSupport}
* for an example.
*
* @param asyncSupport
*/
public AtmosphereFramework setAsyncSupport(AsyncSupport asyncSupport) {
this.asyncSupport = asyncSupport;
return this;
}
/**
* @param asyncSupport
* @return
* @Deprecated - Use {@link #setAsyncSupport(AsyncSupport)}
*/
public AtmosphereFramework setCometSupport(AsyncSupport asyncSupport) {
return setAsyncSupport(asyncSupport);
}
/**
* Return the current {@link AsyncSupport}
*
* @return the current {@link AsyncSupport}
*/
public AsyncSupport getAsyncSupport() {
return asyncSupport;
}
/**
* Return the current {@link AsyncSupport}
*
* @return the current {@link AsyncSupport}
* @deprecated Use getAsyncSupport
*/
public AsyncSupport getCometSupport() {
return asyncSupport;
}
/**
* Returns an instance of AsyncSupportResolver {@link AsyncSupportResolver}
*
* @return CometSupportResolver
*/
protected AsyncSupportResolver createAsyncSupportResolver() {
return new DefaultAsyncSupportResolver(config);
}
/**
* Auto detect the underlying Servlet Container we are running on.
*/
protected void autoDetectContainer() {
// Was defined in atmosphere.xml
if (getAsyncSupport() == null) {
setAsyncSupport(createAsyncSupportResolver()
.resolve(useNativeImplementation, useBlockingImplementation, webSocketEnabled));
}
logger.info("Atmosphere is using async support: {} running under container: {}",
getAsyncSupport().getClass().getName(), asyncSupport.getContainerName());
}
/**
* Auto detect instance of {@link AtmosphereHandler} in case META-INF/atmosphere.xml
* is missing.
*
* @param servletContext {@link ServletContext}
* @param classloader {@link URLClassLoader} to load the class.
* @throws java.net.MalformedURLException
* @throws java.net.URISyntaxException
*/
public void autoDetectAtmosphereHandlers(ServletContext servletContext, URLClassLoader classloader)
throws MalformedURLException, URISyntaxException {
// If Handler has been added
if (atmosphereHandlers.size() > 0) return;
logger.info("Auto detecting atmosphere handlers {}", handlersPath);
String realPath = servletContext.getRealPath(handlersPath);
// Weblogic bug
if (realPath == null) {
URL u = servletContext.getResource(handlersPath);
if (u == null) return;
realPath = u.getPath();
}
loadAtmosphereHandlersFromPath(classloader, realPath);
}
public void loadAtmosphereHandlersFromPath(URLClassLoader classloader, String realPath) {
File file = new File(realPath);
if (file.isDirectory()) {
getFiles(file);
scanDone = true;
for (String className : possibleComponentsCandidate) {
try {
className = className.replace('\\', '/');
className = className.replaceFirst("^.*/(WEB-INF|target)(?:/scala-[^/]+)?/(test-)?classes/(.*)\\.class", "$3").replace("/", ".");
Class<?> clazz = classloader.loadClass(className);
if (AtmosphereHandler.class.isAssignableFrom(clazz)) {
AtmosphereHandler handler = (AtmosphereHandler) clazz.newInstance();
InjectorProvider.getInjector().inject(handler);
addMapping("/" + handler.getClass().getSimpleName(),
new AtmosphereHandlerWrapper(broadcasterFactory, handler, "/" + handler.getClass().getSimpleName()));
logger.info("Installed AtmosphereHandler {} mapped to context-path: {}", handler, handler.getClass().getName());
}
} catch (Throwable t) {
logger.trace("failed to load class as an AtmosphereHandler: " + className, t);
}
}
}
}
/**
* Auto detect instance of {@link org.atmosphere.websocket.WebSocketHandler} in case META-INF/atmosphere.xml
* is missing.
*
* @param servletContext {@link ServletContext}
* @param classloader {@link URLClassLoader} to load the class.
* @throws java.net.MalformedURLException
* @throws java.net.URISyntaxException
*/
protected void autoDetectWebSocketHandler(ServletContext servletContext, URLClassLoader classloader)
throws MalformedURLException, URISyntaxException {
if (hasNewWebSocketProtocol) return;
logger.info("Auto detecting WebSocketHandler in {}", handlersPath);
String realPath = servletContext.getRealPath(handlersPath);
// Weblogic bug
if (realPath == null) {
URL u = servletContext.getResource(handlersPath);
if (u == null) return;
realPath = u.getPath();
}
loadWebSocketFromPath(classloader, realPath);
}
protected void loadWebSocketFromPath(URLClassLoader classloader, String realPath) {
File file = new File(realPath);
if (file.isDirectory()) {
getFiles(file);
scanDone = true;
for (String className : possibleComponentsCandidate) {
try {
className = className.replace('\\', '/');
className = className.replaceFirst("^.*/(WEB-INF|target)(?:/scala-[^/]+)?/(test-)?classes/(.*)\\.class", "$3").replace("/", ".");
Class<?> clazz = classloader.loadClass(className);
if (WebSocketProtocol.class.isAssignableFrom(clazz)) {
webSocketProtocol = (WebSocketProtocol) clazz.newInstance();
InjectorProvider.getInjector().inject(webSocketProtocol);
logger.info("Installed WebSocketProtocol {}", webSocketProtocol);
}
} catch (Throwable t) {
logger.trace("failed to load class as an WebSocketProtocol: " + className, t);
}
}
}
}
/**
* Get the list of possible candidate to load as {@link AtmosphereHandler}
*
* @param f the real path {@link File}
*/
private void getFiles(File f) {
if (scanDone) return;
File[] files = f.listFiles();
for (File test : files) {
if (test.isDirectory()) {
getFiles(test);
} else {
String clazz = test.getAbsolutePath();
if (clazz.endsWith(".class")) {
possibleComponentsCandidate.add(clazz);
}
}
}
}
/**
* Configure some Attribute on the {@link AtmosphereRequest}
* @param req {@link AtmosphereRequest}
*/
public AtmosphereFramework configureRequestResponse(AtmosphereRequest req, AtmosphereResponse res) throws UnsupportedEncodingException {
req.setAttribute(BROADCASTER_FACTORY, BroadcasterFactory.getDefault());
req.setAttribute(PROPERTY_USE_STREAM, useStreamForFlushingComments);
req.setAttribute(BROADCASTER_CLASS, broadcasterClassName);
req.setAttribute(ATMOSPHERE_CONFIG, config);
boolean skip = true;
String s = config.getInitParameter(ALLOW_QUERYSTRING_AS_REQUEST);
if (s != null) {
skip = Boolean.valueOf(s);
}
if (!skip || req.getAttribute(WEBSOCKET_SUSPEND) == null) {
Map<String, String> headers = configureQueryStringAsRequest(req);
String body = headers.remove(ATMOSPHERE_POST_BODY);
if (body != null && body.isEmpty()) {
body = null;
}
// We need to strip Atmosphere's own query string from the request in case an
// interceptor re-inject the request because the wrong body will be passed.
StringBuilder queryStrings = new StringBuilder("");
Enumeration<String> e = req.getParameterNames();
String name, key;
while (e.hasMoreElements()) {
key = e.nextElement();
name = key.toLowerCase().trim();
if (!name.startsWith("x-atmosphere") && !name.equalsIgnoreCase("x-cache-date")) {
queryStrings.append(key).append("=").append(req.getParameter(key));
}
if (e.hasMoreElements() && queryStrings.length() > 0) {
queryStrings.append("&");
}
}
// Reconfigure the request. Clear the Atmosphere queryString
req.headers(headers)
.queryString(queryStrings.toString())
.method(body != null && req.getMethod().equalsIgnoreCase("GET") ? "POST" : req.getMethod());
if (body != null) {
req.body(URLDecoder.decode(body, req.getCharacterEncoding() == null ? "UTF-8" : req.getCharacterEncoding()));
}
}
s = req.getHeader(X_ATMOSPHERE_TRACKING_ID);
// Lookup for websocket
if (s == null || s.equals("0")) {
String unique = config.getInitParameter(ApplicationConfig.UNIQUE_UUID_WEBSOCKET);
if (unique != null && Boolean.valueOf(unique)) {
s = (String) req.getAttribute(SUSPENDED_ATMOSPHERE_RESOURCE_UUID);
}
}
if (s == null || s.equals("0")) {
s = UUID.randomUUID().toString();
res.setHeader(X_ATMOSPHERE_TRACKING_ID, s);
} else {
// This may breaks 1.0.0 application because the WebSocket's associated AtmosphereResource will
// all have the same UUID, and retrieving the original one for WebSocket, so we don't set it at all.
// Null means it is not an HTTP request.
if (req.resource() == null) {
res.setHeader(X_ATMOSPHERE_TRACKING_ID, s);
} else if (req.getAttribute(WebSocket.WEBSOCKET_INITIATED) == null) {
// WebSocket reconnect, in case an application manually set the header
// (impossible to retrieve the headers normally with WebSocket or SSE)
res.setHeader(X_ATMOSPHERE_TRACKING_ID, s);
}
}
if (req.getAttribute(SUSPENDED_ATMOSPHERE_RESOURCE_UUID) == null) {
req.setAttribute(SUSPENDED_ATMOSPHERE_RESOURCE_UUID, s);
}
return this;
}
/**
* Invoke the proprietary {@link AsyncSupport}
*
* @param req
* @param res
* @return an {@link Action}
* @throws IOException
* @throws ServletException
*/
public Action doCometSupport(AtmosphereRequest req, AtmosphereResponse res) throws IOException, ServletException {
Action a = null;
try {
configureRequestResponse(req, res);
a = asyncSupport.service(req, res);
} catch (IllegalStateException ex) {
if (ex.getMessage() != null && (ex.getMessage().startsWith("Tomcat failed") || ex.getMessage().startsWith("JBoss failed"))) {
if (!isFilter) {
logger.warn("Failed using comet support: {}, error: {} Is the Nio or Apr Connector enabled?", asyncSupport.getClass().getName(),
ex.getMessage());
}
logger.error("If you have more than one Connector enabled, make sure they both use the same protocol, " +
"e.g NIO/APR or HTTP for all. If not, {} will be used and cannot be changed.", BlockingIOCometSupport.class.getName());
logger.trace(ex.getMessage(), ex);
AsyncSupport current = asyncSupport;
asyncSupport = asyncSupport.supportWebSocket() ? new Tomcat7BIOSupportWithWebSocket(config) : new BlockingIOCometSupport(config);
if(current instanceof AsynchronousProcessor) {
((AsynchronousProcessor)current).shutdown();
}
asyncSupport.init(config.getServletConfig());
logger.warn("Using " + asyncSupport.getClass().getName());
a = asyncSupport.service(req, res);
} else {
logger.error("AtmosphereFramework exception", ex);
throw ex;
}
} finally {
if (a != null) {
notify(a.type(), req, res);
}
if (req != null && a != null && a.type() != Action.TYPE.SUSPEND) {
req.destroy();
res.destroy();
notify(Action.TYPE.DESTROYED, req, res);
}
}
return a;
}
/**
* Return the default {@link Broadcaster} class name.
*
* @return the broadcasterClassName
*/
public String getDefaultBroadcasterClassName() {
return broadcasterClassName;
}
/**
* Set the default {@link Broadcaster} class name
*
* @param bccn the broadcasterClassName to set
*/
public AtmosphereFramework setDefaultBroadcasterClassName(String bccn) {
broadcasterClassName = bccn;
return this;
}
/**
* <tt>true</tt> if Atmosphere uses {@link AtmosphereResponse#getOutputStream()}
* by default for write operation.
*
* @return the useStreamForFlushingComments
*/
public boolean isUseStreamForFlushingComments() {
return useStreamForFlushingComments;
}
/**
* Set to <tt>true</tt> so Atmosphere uses {@link AtmosphereResponse#getOutputStream()}
* by default for write operation. Default is false.
*
* @param useStreamForFlushingComments the useStreamForFlushingComments to set
*/
public AtmosphereFramework setUseStreamForFlushingComments(boolean useStreamForFlushingComments) {
this.useStreamForFlushingComments = useStreamForFlushingComments;
return this;
}
/**
* Get the {@link BroadcasterFactory} which is used by Atmosphere to construct
* {@link Broadcaster}
*
* @return {@link BroadcasterFactory}
*/
public BroadcasterFactory getBroadcasterFactory() {
return broadcasterFactory;
}
/**
* Set the {@link BroadcasterFactory} which is used by Atmosphere to construct
* {@link Broadcaster}
*
* @return {@link BroadcasterFactory}
*/
public AtmosphereFramework setBroadcasterFactory(final BroadcasterFactory broadcasterFactory) {
this.broadcasterFactory = broadcasterFactory;
configureBroadcaster();
return this;
}
/**
* Return the {@link org.atmosphere.cpr.BroadcasterCache} class name.
*
* @return the {@link org.atmosphere.cpr.BroadcasterCache} class name.
*/
public String getBroadcasterCacheClassName() {
return broadcasterCacheClassName;
}
/**
* Set the {@link org.atmosphere.cpr.BroadcasterCache} class name.
*
* @param broadcasterCacheClassName
*/
public void setBroadcasterCacheClassName(String broadcasterCacheClassName) {
this.broadcasterCacheClassName = broadcasterCacheClassName;
}
/**
* Add a new Broadcaster class name AtmosphereServlet can use when initializing requests, and when
* atmosphere.xml broadcaster element is unspecified.
*
* @param broadcasterTypeString
*/
public AtmosphereFramework addBroadcasterType(String broadcasterTypeString) {
broadcasterTypes.add(broadcasterTypeString);
return this;
}
public String getWebSocketProtocolClassName() {
return webSocketProtocolClassName;
}
public AtmosphereFramework setWebSocketProtocolClassName(String webSocketProtocolClassName) {
hasNewWebSocketProtocol = true;
this.webSocketProtocolClassName = webSocketProtocolClassName;
return this;
}
public Map<String, AtmosphereHandlerWrapper> getAtmosphereHandlers() {
return atmosphereHandlers;
}
protected Map<String, String> configureQueryStringAsRequest(AtmosphereRequest request) {
Map<String, String> headers = new HashMap<String, String>();
Enumeration<String> e = request.getParameterNames();
String s;
while (e.hasMoreElements()) {
s = e.nextElement();
if (s.equalsIgnoreCase("Content-Type")) {
// Use the one set by the user first.
if (request.getContentType() == null ||
!request.getContentType().equalsIgnoreCase(request.getParameter(s))) {
request.contentType(request.getParameter(s));
}
}
headers.put(s, request.getParameter(s));
}
logger.trace("Query String translated to headers {}", headers);
return headers;
}
protected boolean isIECandidate(AtmosphereRequest request) {
String userAgent = request.getHeader("User-Agent");
if (userAgent == null) return false;
if (userAgent.contains("MSIE") || userAgent.contains(".NET")) {
// Now check the header
String transport = request.getHeader(HeaderConfig.X_ATMOSPHERE_TRANSPORT);
if (transport != null) {
return false;
} else {
return true;
}
}
return false;
}
public WebSocketProtocol getWebSocketProtocol() {
// TODO: Spagetthi code, needs to rework.
// Make sure we initialized the WebSocketProtocol
initWebSocket();
return webSocketProtocol;
}
public boolean isUseNativeImplementation() {
return useNativeImplementation;
}
public AtmosphereFramework setUseNativeImplementation(boolean useNativeImplementation) {
this.useNativeImplementation = useNativeImplementation;
return this;
}
public boolean isUseBlockingImplementation() {
return useBlockingImplementation;
}
public AtmosphereFramework setUseBlockingImplementation(boolean useBlockingImplementation) {
this.useBlockingImplementation = useBlockingImplementation;
return this;
}
public String getAtmosphereDotXmlPath() {
return atmosphereDotXmlPath;
}
public AtmosphereFramework setAtmosphereDotXmlPath(String atmosphereDotXmlPath) {
this.atmosphereDotXmlPath = atmosphereDotXmlPath;
return this;
}
public String getHandlersPath() {
return handlersPath;
}
public AtmosphereFramework setHandlersPath(String handlersPath) {
this.handlersPath = handlersPath;
return this;
}
/**
* Return the location of the jars containing the application classes. Default is WEB-INF/lib
* @return the location of the jars containing the application classes. Default is WEB-INF/lib
*/
public String getLibPath() {
return libPath;
}
/**
* Set the location of the jars containing the application.
* @param libPath the location of the jars containing the application.
* @return this
*/
public AtmosphereFramework setLibPath(String libPath) {
this.libPath = libPath;
return this;
}
public String getWebSocketProcessorClassName() {
return webSocketProcessorClassName;
}
public AtmosphereFramework setWebsocketProcessorClassName(String webSocketProcessorClassName){
this.webSocketProcessorClassName = webSocketProcessorClassName;
return this;
}
/**
* Add an {@link AtmosphereInterceptor} implementation. The adding order or {@link AtmosphereInterceptor} will be used, e.g
* the first added {@link AtmosphereInterceptor} will always be called first.
*
* @param c {@link AtmosphereInterceptor}
* @return this
*/
public AtmosphereFramework interceptor(AtmosphereInterceptor c) {
boolean found = false;
for (AtmosphereInterceptor interceptor : interceptors) {
if (interceptor.getClass().equals(c.getClass())) {
found = true;
break;
}
}
if (!found) {
interceptors.addLast(c);
logger.info("Installed AtmosphereInterceptor {}. ", c);
}
return this;
}
/**
* Return the list of {@link AtmosphereInterceptor}
*
* @return the list of {@link AtmosphereInterceptor}
*/
public LinkedList<AtmosphereInterceptor> interceptors() {
return interceptors;
}
/**
* Set the {@link AnnotationProcessor} class name.
*
* @param annotationProcessorClassName the {@link AnnotationProcessor} class name.
* @return this
*/
public AtmosphereFramework annotationProcessorClassName(String annotationProcessorClassName) {
this.annotationProcessorClassName = annotationProcessorClassName;
return this;
}
/**
* Add an {@link AsyncSupportListener}
*
* @param asyncSupportListener an {@link AsyncSupportListener}
* @return this;
*/
public AtmosphereFramework asyncSupportListener(AsyncSupportListener asyncSupportListener) {
asyncSupportListeners.add(asyncSupportListener);
return this;
}
/**
* Return the list of an {@link AsyncSupportListener}
*
* @return
*/
public List<AsyncSupportListener> asyncSupportListeners() {
return asyncSupportListeners;
}
/**
* Add {@link BroadcasterListener} to all created {@link Broadcaster}
*/
public AtmosphereFramework addBroadcastListener(BroadcasterListener b) {
broadcasterListeners.add(b);
return this;
}
/**
* Add a {@link BroadcasterCacheInspector} which will be associated with the defined {@link BroadcasterCache}
* @param b {@link BroadcasterCacheInspector}
* @return this;
*/
public AtmosphereFramework addBroadcasterCacheInjector(BroadcasterCacheInspector b) {
inspectors.add(b);
return this;
}
/**
* Return the list of {@link BroadcasterCacheInspector}
*
* @return the list of {@link BroadcasterCacheInspector}
*/
protected ConcurrentLinkedQueue<BroadcasterCacheInspector> inspectors() {
return inspectors;
}
protected void autoConfigureService(ServletContext sc) throws IOException {
final ClassLoader cl = Thread.currentThread().getContextClassLoader();
String path = libPath != DEFAULT_LIB_PATH ? libPath : sc.getRealPath(handlersPath);
try {
AnnotationProcessor p = (AnnotationProcessor) cl.loadClass(annotationProcessorClassName).newInstance();
logger.info("Atmosphere is using {} for processing annotation", annotationProcessorClassName);
p.configure(this);
if (path != null) {
p.scan(new File(path));
}
String pathLibs = sc.getRealPath(DEFAULT_LIB_PATH);
if (pathLibs != null) {
File libFolder = new File(pathLibs);
File jars[] = libFolder.listFiles(new FilenameFilter() {
@Override
public boolean accept(File arg0, String arg1) {
return arg1.endsWith(".jar");
}
});
if (jars != null) {
for (File file : jars) {
p.scan(file);
}
}
}
} catch (Throwable e) {
logger.debug("Atmosphere's Service Annotation Not Supported. Please add https://github.com/rmuller/infomas-asl as dependencies or your own AnnotationProcessor to support @Service");
logger.trace("", e);
return;
}
}
public EndpointMapper<AtmosphereHandlerWrapper> endPointMapper() {
return endpointMapper;
}
public AtmosphereFramework endPointMapper(EndpointMapper endpointMapper) {
this.endpointMapper = endpointMapper;
return this;
}
protected void notify(Action.TYPE type, AtmosphereRequest request, AtmosphereResponse response) {
for (AsyncSupportListener l : asyncSupportListeners()) {
try {
switch (type) {
case TIMEOUT:
l.onTimeout(request, response);
break;
case CANCELLED:
l.onClose(request, response);
break;
case SUSPEND:
l.onSuspend(request, response);
break;
case RESUME:
l.onSuspend(request, response);
break;
case DESTROYED:
l.onDestroyed(request, response);
break;
}
} catch (Throwable t) {
logger.warn("", t);
}
}
}
}
| false | false | null | null |
diff --git a/runwaysdk-test/src/main/java/com/runwaysdk/dataaccess/MdDimensionTest.java b/runwaysdk-test/src/main/java/com/runwaysdk/dataaccess/MdDimensionTest.java
index 18f05da90..2d44237c7 100644
--- a/runwaysdk-test/src/main/java/com/runwaysdk/dataaccess/MdDimensionTest.java
+++ b/runwaysdk-test/src/main/java/com/runwaysdk/dataaccess/MdDimensionTest.java
@@ -1,1020 +1,1020 @@
/*******************************************************************************
* Copyright (c) 2013 TerraFrame, Inc. All rights reserved.
*
* This file is part of Runway SDK(tm).
*
* Runway SDK(tm) 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.
*
* Runway SDK(tm) 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 Runway SDK(tm). If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
package com.runwaysdk.dataaccess;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import junit.extensions.TestSetup;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestResult;
import junit.framework.TestSuite;
import com.runwaysdk.ProblemException;
import com.runwaysdk.ProblemIF;
import com.runwaysdk.business.generation.StateGenerator;
import com.runwaysdk.constants.MdAttributeBooleanInfo;
import com.runwaysdk.constants.MdAttributeCharacterInfo;
import com.runwaysdk.constants.MdAttributeDimensionInfo;
import com.runwaysdk.constants.MdAttributeEnumerationInfo;
import com.runwaysdk.constants.MdAttributeFloatInfo;
import com.runwaysdk.constants.MdAttributeLocalInfo;
import com.runwaysdk.constants.ServerConstants;
import com.runwaysdk.dataaccess.attributes.AttributeLengthCharacterException;
import com.runwaysdk.dataaccess.attributes.AttributeValueCannotBeNegativeProblem;
import com.runwaysdk.dataaccess.attributes.AttributeValueCannotBePositiveProblem;
import com.runwaysdk.dataaccess.attributes.AttributeValueException;
import com.runwaysdk.dataaccess.attributes.EmptyValueProblem;
import com.runwaysdk.dataaccess.attributes.InvalidReferenceException;
import com.runwaysdk.dataaccess.cache.DataNotFoundException;
import com.runwaysdk.dataaccess.io.TestFixtureFactory;
import com.runwaysdk.dataaccess.metadata.ForbiddenMethodException;
import com.runwaysdk.dataaccess.metadata.MdAttributeBlobDAO;
import com.runwaysdk.dataaccess.metadata.MdAttributeBooleanDAO;
import com.runwaysdk.dataaccess.metadata.MdAttributeCharacterDAO;
import com.runwaysdk.dataaccess.metadata.MdAttributeDAO;
import com.runwaysdk.dataaccess.metadata.MdAttributeDateDAO;
import com.runwaysdk.dataaccess.metadata.MdAttributeDimensionDAO;
import com.runwaysdk.dataaccess.metadata.MdAttributeEnumerationDAO;
import com.runwaysdk.dataaccess.metadata.MdAttributeFloatDAO;
import com.runwaysdk.dataaccess.metadata.MdAttributeIntegerDAO;
import com.runwaysdk.dataaccess.metadata.MdAttributeReferenceDAO;
import com.runwaysdk.dataaccess.metadata.MdAttributeTextDAO;
import com.runwaysdk.dataaccess.metadata.MdBusinessDAO;
import com.runwaysdk.dataaccess.metadata.MdDimensionDAO;
import com.runwaysdk.dataaccess.metadata.MdEnumerationDAO;
import com.runwaysdk.facade.Facade;
import com.runwaysdk.query.BusinessDAOQuery;
import com.runwaysdk.query.OIterator;
import com.runwaysdk.query.QueryFactory;
import com.runwaysdk.session.Request;
import com.runwaysdk.session.RequestType;
import com.runwaysdk.session.Session;
public class MdDimensionTest extends TestCase
{
@Override
public TestResult run()
{
return super.run();
}
@Override
public void run(TestResult testResult)
{
super.run(testResult);
}
private static MdBusinessDAO testMdBusiness;
private static MdAttributeCharacterDAO mdAttribute;
private static MdAttributeCharacterDAO dimensionMdAttributeRequired;
private static MdAttributeDAO mdAttribute2;
private static MdDimensionDAO mdDimension;
private static MdDimensionDAO mdDimension2;
public static Test suite()
{
TestSuite suite = new TestSuite();
suite.addTestSuite(MdDimensionTest.class);
TestSetup wrapper = new TestSetup(suite)
{
protected void setUp()
{
classSetUp();
}
protected void tearDown()
{
classTearDown();
}
};
return wrapper;
}
public static void classSetUp()
{
testMdBusiness = TestFixtureFactory.createMdBusiness1();
testMdBusiness.apply();
mdAttribute = TestFixtureFactory.addCharacterAttribute(testMdBusiness, "characterAttribute");
mdAttribute.apply();
dimensionMdAttributeRequired = TestFixtureFactory.addCharacterAttribute(testMdBusiness, "testCharDimensionRequired");
dimensionMdAttributeRequired.setValue(MdAttributeCharacterInfo.REQUIRED, MdAttributeBooleanInfo.FALSE);
dimensionMdAttributeRequired.apply();
mdAttribute2 = TestFixtureFactory.addIntegerAttribute(testMdBusiness, "integerCharacter");
mdAttribute2.apply();
mdDimension = TestFixtureFactory.createMdDimension();
mdDimension.apply();
mdDimension2 = TestFixtureFactory.createMdDimension("D2");
mdDimension2.apply();
}
public static void classTearDown()
{
TestFixtureFactory.delete(mdAttribute);
TestFixtureFactory.delete(dimensionMdAttributeRequired);
TestFixtureFactory.delete(mdAttribute2);
TestFixtureFactory.delete(mdDimension);
TestFixtureFactory.delete(mdDimension2);
TestFixtureFactory.delete(testMdBusiness);
}
/**
* Tests for a valid default value set on attribute dimensions.
*
*/
public void testInvalidDefaultBooleanAttribute()
{
MdAttributeBooleanDAO mdAttrBoolean = TestFixtureFactory.addBooleanAttribute(testMdBusiness);
mdAttrBoolean.apply();
try
{
MdAttributeDimensionDAO mdAttributeDimensionDAO = mdAttrBoolean.getMdAttributeDimension(mdDimension).getBusinessDAO();
mdAttributeDimensionDAO.setValue(MdAttributeDimensionInfo.DEFAULT_VALUE, "Hello!");
try
{
mdAttributeDimensionDAO.apply();
fail("A boolean default value on an attribute dimension was set with an invalid value.");
}
catch (AttributeValueException e)
{
// This is expected
}
}
finally
{
mdAttrBoolean.delete();
}
}
/**
* Tests for a valid default value set on attribute dimensions.
*
*/
public void testValidDefaultBooleanAttribute()
{
MdAttributeBooleanDAO mdAttrBoolean = TestFixtureFactory.addBooleanAttribute(testMdBusiness);
mdAttrBoolean.apply();
String dimensionDefaultValue = MdAttributeBooleanInfo.TRUE;
MdAttributeDimensionDAO mdAttributeDimensionDAO = (MdAttributeDimensionDAO) mdAttrBoolean.getMdAttributeDimension(mdDimension).getBusinessDAO();
mdAttributeDimensionDAO.setValue(MdAttributeDimensionInfo.DEFAULT_VALUE, dimensionDefaultValue);
try
{
try
{
mdAttributeDimensionDAO.apply();
}
catch (Throwable e)
{
fail("Unable to set a valid boolean default value on an attribute dimension.");
}
String sessionId = null;
try
{
sessionId = Facade.login(ServerConstants.SYSTEM_USER_NAME, ServerConstants.SYSTEM_DEFAULT_PASSWORD, new Locale[] { Session.getCurrentLocale() });
validDefaultBooleanAttribute(sessionId, dimensionDefaultValue);
}
finally
{
if (sessionId != null)
{
Facade.logout(sessionId);
}
}
}
finally
{
mdAttrBoolean.delete();
}
}
@Request(RequestType.SESSION)
private void validDefaultBooleanAttribute(String sessionId, String dimensionDefaultValue)
{
Session session = (Session) Session.getCurrentSession();
session.setDimension(mdDimension);
BusinessDAO businessDAO = BusinessDAO.newInstance(testMdBusiness.definesType());
assertEquals("Dimension default value was not set on a new business object.", dimensionDefaultValue, businessDAO.getValue("testBoolean"));
}
/**
* Tests for a valid default value set on attribute dimensions.
*
*/
public void testInvalidDefaultCharacterAttribute()
{
MdAttributeCharacterDAO mdAttrCharacter = TestFixtureFactory.addCharacterAttribute(testMdBusiness);
mdAttrCharacter.setValue(MdAttributeCharacterInfo.SIZE, "4");
mdAttrCharacter.apply();
try
{
MdAttributeDimensionDAO mdAttributeDimensionDAO = mdAttrCharacter.getMdAttributeDimension(mdDimension).getBusinessDAO();
mdAttributeDimensionDAO.setValue(MdAttributeDimensionInfo.DEFAULT_VALUE, "This is longer than 4 characters");
mdAttributeDimensionDAO.apply();
fail("A character default value on an attribute dimension was set with an invalid value.");
}
catch (AttributeLengthCharacterException e)
{
// This is expected
}
finally
{
mdAttrCharacter.delete();
}
}
/**
* Tests for a valid default value set on attribute dimensions.
*
*/
public void testValidDefaultCharacterAttribute()
{
MdAttributeCharacterDAO mdAttrCharacter = TestFixtureFactory.addCharacterAttribute(testMdBusiness);
mdAttrCharacter.setValue(MdAttributeCharacterInfo.SIZE, "4");
mdAttrCharacter.apply();
String dimensionDefaultValue = "1234";
MdAttributeDimensionDAO mdAttributeDimensionDAO = (MdAttributeDimensionDAO) mdAttrCharacter.getMdAttributeDimension(mdDimension).getBusinessDAO();
mdAttributeDimensionDAO.setValue(MdAttributeDimensionInfo.DEFAULT_VALUE, dimensionDefaultValue);
try
{
try
{
mdAttributeDimensionDAO.apply();
}
catch (Throwable e)
{
fail("Unable to set a valid character default value on an attribute dimension.");
}
String sessionId = null;
try
{
sessionId = Facade.login(ServerConstants.SYSTEM_USER_NAME, ServerConstants.SYSTEM_DEFAULT_PASSWORD, new Locale[] { Session.getCurrentLocale() });
validDefaultCharacterAttribute(sessionId, dimensionDefaultValue);
}
finally
{
if (sessionId != null)
{
Facade.logout(sessionId);
}
}
}
finally
{
mdAttrCharacter.delete();
}
}
@Request(RequestType.SESSION)
private void validDefaultCharacterAttribute(String sessionId, String dimensionDefaultValue)
{
Session session = (Session) Session.getCurrentSession();
session.setDimension(mdDimension);
BusinessDAO businessDAO = BusinessDAO.newInstance(testMdBusiness.definesType());
assertEquals("Dimension default value was not set on a new business object.", dimensionDefaultValue, businessDAO.getValue("testCharacter"));
}
/**
* Tests for a valid default value set on attribute dimensions.
* @throws Exception
*
*/
public void testInvalidDefaultFloatAttribute() throws Exception
{
MdAttributeFloatDAO mdAttrFloat = TestFixtureFactory.addFloatAttribute(testMdBusiness);
mdAttrFloat.setValue(MdAttributeFloatInfo.REJECT_NEGATIVE, MdAttributeBooleanInfo.TRUE);
mdAttrFloat.apply();
try
{
MdAttributeDimensionDAO mdAttributeDimensionDAO = mdAttrFloat.getMdAttributeDimension(mdDimension).getBusinessDAO();
mdAttributeDimensionDAO.setValue(MdAttributeDimensionInfo.DEFAULT_VALUE, "-1.0");
mdAttributeDimensionDAO.apply();
fail("A float default value on an attribute dimension was set with an invalid value.");
}
catch (AttributeValueException e)
{
// This is expected
}
catch (ProblemException e)
{
// This is expected
List<ProblemIF> problems = e.getProblems();
boolean problemFound = false;
for (ProblemIF p : problems)
{
if (p instanceof AttributeValueCannotBeNegativeProblem)
problemFound = true;
}
if (!problemFound)
throw new Exception("AttributeValueCannotBeNegativeProblem was not thrown");
}
finally
{
mdAttrFloat.delete();
}
}
/**
* Tests for a valid default value set on attribute dimensions.
*
*/
public void testValidDefaultFloatAttribute()
{
MdAttributeFloatDAO mdAttrFloat = TestFixtureFactory.addFloatAttribute(testMdBusiness);
mdAttrFloat.setValue(MdAttributeFloatInfo.REJECT_NEGATIVE, MdAttributeBooleanInfo.TRUE);
mdAttrFloat.setValue(MdAttributeFloatInfo.REJECT_POSITIVE, MdAttributeBooleanInfo.FALSE);
mdAttrFloat.apply();
String dimensionDefaultValue = "1.1";
MdAttributeDimensionDAO mdAttributeDimensionDAO = (MdAttributeDimensionDAO) mdAttrFloat.getMdAttributeDimension(mdDimension).getBusinessDAO();
mdAttributeDimensionDAO.setValue(MdAttributeDimensionInfo.DEFAULT_VALUE, dimensionDefaultValue);
try
{
try
{
mdAttributeDimensionDAO.apply();
}
catch (Throwable e)
{
fail("Unable to set a valid float default value on an attribute dimension.");
}
String sessionId = null;
try
{
sessionId = Facade.login(ServerConstants.SYSTEM_USER_NAME, ServerConstants.SYSTEM_DEFAULT_PASSWORD, new Locale[] { Session.getCurrentLocale() });
validDefaultFloatAttribute(sessionId, dimensionDefaultValue);
}
finally
{
if (sessionId != null)
{
Facade.logout(sessionId);
}
}
}
finally
{
mdAttrFloat.delete();
}
}
@Request(RequestType.SESSION)
private void validDefaultFloatAttribute(String sessionId, String dimensionDefaultValue)
{
Session session = (Session) Session.getCurrentSession();
session.setDimension(mdDimension);
BusinessDAO businessDAO = BusinessDAO.newInstance(testMdBusiness.definesType());
assertEquals("Dimension default value was not set on a new business object.", dimensionDefaultValue, businessDAO.getValue("testFloat"));
}
/**
* Tests that an attribute that should be unique should also be required.
*
*/
public void testInvalidDefaultEnumerationAttribute()
{
MdEnumerationDAOIF mdEnumerationIF = MdEnumerationDAO.getMdEnumerationDAO(StateGenerator.ENTRY_ENUM);
MdAttributeEnumerationDAO mdAttrEnum = MdAttributeEnumerationDAO.newInstance();
- mdAttrEnum.setValue(MdAttributeEnumerationInfo.NAME, "attrEnumeration");
+ mdAttrEnum.setValue(MdAttributeEnumerationInfo.NAME, "secondEnumeration");
mdAttrEnum.setStructValue(MdAttributeEnumerationInfo.DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "Attribute Enumeration");
mdAttrEnum.setValue(MdAttributeEnumerationInfo.REQUIRED, MdAttributeBooleanInfo.FALSE);
mdAttrEnum.setValue(MdAttributeEnumerationInfo.REMOVE, MdAttributeBooleanInfo.TRUE);
mdAttrEnum.setValue(MdAttributeEnumerationInfo.SELECT_MULTIPLE, MdAttributeBooleanInfo.FALSE);
mdAttrEnum.setValue(MdAttributeEnumerationInfo.MD_ENUMERATION, mdEnumerationIF.getId());
mdAttrEnum.setValue(MdAttributeEnumerationInfo.DEFINING_MD_CLASS, testMdBusiness.getId());
mdAttrEnum.apply();
MdAttributeDimensionDAO mdAttributeDimensionDAO = (MdAttributeDimensionDAO) mdAttrEnum.getMdAttributeDimension(mdDimension).getBusinessDAO();
mdAttributeDimensionDAO.setValue(MdAttributeDimensionInfo.DEFAULT_VALUE, "An invalid enumeration item");
try
{
mdAttributeDimensionDAO.apply();
fail("A reference attribute was defined with an invalid value.");
}
catch (AttributeValueException e)
{
// This is expected
}
finally
{
mdAttrEnum.delete();
}
}
/**
* Tests that an attribute that should be unique should also be required.
*
*/
public void testValidDefaultEnumerationAttribute()
{
MdEnumerationDAOIF mdEnumerationIF = MdEnumerationDAO.getMdEnumerationDAO(StateGenerator.ENTRY_ENUM);
MdAttributeEnumerationDAO mdAttrEnum = MdAttributeEnumerationDAO.newInstance();
mdAttrEnum.setValue(MdAttributeEnumerationInfo.NAME, "attrEnumeration");
mdAttrEnum.setStructValue(MdAttributeEnumerationInfo.DISPLAY_LABEL, MdAttributeLocalInfo.DEFAULT_LOCALE, "Attribute Enumeration");
mdAttrEnum.setValue(MdAttributeEnumerationInfo.REQUIRED, MdAttributeBooleanInfo.FALSE);
mdAttrEnum.setValue(MdAttributeEnumerationInfo.REMOVE, MdAttributeBooleanInfo.TRUE);
mdAttrEnum.setValue(MdAttributeEnumerationInfo.SELECT_MULTIPLE, MdAttributeBooleanInfo.FALSE);
mdAttrEnum.setValue(MdAttributeEnumerationInfo.MD_ENUMERATION, mdEnumerationIF.getId());
mdAttrEnum.setValue(MdAttributeEnumerationInfo.DEFINING_MD_CLASS, testMdBusiness.getId());
mdAttrEnum.apply();
String masterDefiningType = mdEnumerationIF.getMasterListMdBusinessDAO().definesType();
QueryFactory qf = new QueryFactory();
BusinessDAOQuery q = qf.businessDAOQuery(masterDefiningType);
OIterator<BusinessDAOIF> i = q.getIterator();
BusinessDAOIF businessDAOIF = null;
try
{
businessDAOIF = i.next();
}
finally
{
i.close();
}
String dimensionDefaultValue = businessDAOIF.getId();
MdAttributeDimensionDAO mdAttributeDimensionDAO = (MdAttributeDimensionDAO) mdAttrEnum.getMdAttributeDimension(mdDimension).getBusinessDAO();
mdAttributeDimensionDAO.setValue(MdAttributeDimensionInfo.DEFAULT_VALUE, dimensionDefaultValue);
try
{
try
{
mdAttributeDimensionDAO.apply();
}
catch (AttributeValueException e)
{
fail("Unable to set a valid enumeration attribute as an attribute dimension default value.");
}
String sessionId = null;
try
{
sessionId = Facade.login(ServerConstants.SYSTEM_USER_NAME, ServerConstants.SYSTEM_DEFAULT_PASSWORD, new Locale[] { Session.getCurrentLocale() });
validDefaultEnumerationAttribute(sessionId, dimensionDefaultValue);
}
finally
{
if (sessionId != null)
{
Facade.logout(sessionId);
}
}
}
finally
{
mdAttributeDimensionDAO.delete();
}
}
@Request(RequestType.SESSION)
private void validDefaultEnumerationAttribute(String sessionId, String dimensionDefaultValue)
{
Session session = (Session) Session.getCurrentSession();
session.setDimension(mdDimension);
BusinessDAO businessDAO = BusinessDAO.newInstance(testMdBusiness.definesType());
Set<String> idSet = ( (AttributeEnumerationIF) businessDAO.getAttributeIF("attrEnumeration") ).getCachedEnumItemIdSet();
assertTrue("Dimension default value was not set on a new business object.", idSet.contains(dimensionDefaultValue));
}
public void testInvalidClobValue()
{
MdAttributeBlobDAO mdBlobAttribute = TestFixtureFactory.addBlobAttribute(testMdBusiness);
mdBlobAttribute.apply();
try
{
MdAttributeDimensionDAO mdAttributeDimensionDAO = mdBlobAttribute.getMdAttributeDimension(mdDimension).getBusinessDAO();
mdAttributeDimensionDAO.setValue(MdAttributeDimensionInfo.DEFAULT_VALUE, "Invalid value");
mdAttributeDimensionDAO.apply();
fail("A float default value on an attribute dimension was set with an invalid value.");
}
catch (ForbiddenMethodException e)
{
// This is expected
}
finally
{
mdBlobAttribute.delete();
}
}
public void testInvalidReferenceValue()
{
MdBusinessDAO mdBusiness2 = TestFixtureFactory.createMdBusiness2();
mdBusiness2.apply();
try
{
MdAttributeReferenceDAO mdAttributeReference = TestFixtureFactory.addReferenceAttribute(testMdBusiness, mdBusiness2);
mdAttributeReference.apply();
try
{
MdAttributeDimensionDAO mdAttributeDimensionDAO = mdAttributeReference.getMdAttributeDimension(mdDimension).getBusinessDAO();
mdAttributeDimensionDAO.setValue(MdAttributeDimensionInfo.DEFAULT_VALUE, "INVALID_REFERENCE");
mdAttributeDimensionDAO.apply();
fail("A reference attribute was defined with an invalid value.");
}
catch (InvalidReferenceException e)
{
// This is expected
}
finally
{
TestFixtureFactory.delete(mdAttributeReference);
}
}
finally
{
TestFixtureFactory.delete(mdBusiness2);
}
}
public void testValidReferenceValue()
{
MdBusinessDAO mdBusiness2 = TestFixtureFactory.createMdBusiness2();
mdBusiness2.apply();
try
{
BusinessDAO businessDAO = BusinessDAO.newInstance(mdBusiness2.definesType());
businessDAO.apply();
MdAttributeReferenceDAO mdAttributeReference = TestFixtureFactory.addReferenceAttribute(testMdBusiness, mdBusiness2);
mdAttributeReference.apply();
try
{
MdAttributeDimensionDAO mdAttributeDimensionDAO = mdAttributeReference.getMdAttributeDimension(mdDimension).getBusinessDAO();
mdAttributeDimensionDAO.setValue(MdAttributeDimensionInfo.DEFAULT_VALUE, businessDAO.getId());
mdAttributeDimensionDAO.apply();
}
catch (AttributeValueException e)
{
fail("Unable to define reference attribute was with a valid default value.");
}
finally
{
TestFixtureFactory.delete(mdAttributeReference);
}
}
finally
{
TestFixtureFactory.delete(mdBusiness2);
}
}
public void testInvalidDateValue()
{
MdAttributeDateDAO mdDateAttribute = TestFixtureFactory.addDateAttribute(testMdBusiness);
mdDateAttribute.apply();
try
{
MdAttributeDimensionDAO mdAttributeDimensionDAO = mdDateAttribute.getMdAttributeDimension(mdDimension).getBusinessDAO();
mdAttributeDimensionDAO.setValue(MdAttributeDimensionInfo.DEFAULT_VALUE, "INVALID DATE");
mdAttributeDimensionDAO.apply();
fail("Able to set an invalid date default value");
}
catch (Throwable e)
{
// This is expected
}
finally
{
mdDateAttribute.delete();
}
}
public void testValidDateValue()
{
MdAttributeDateDAO mdDateAttribute = TestFixtureFactory.addDateAttribute(testMdBusiness);
mdDateAttribute.apply();
try
{
MdAttributeDimensionDAO mdAttributeDimensionDAO = mdDateAttribute.getMdAttributeDimension(mdDimension).getBusinessDAO();
mdAttributeDimensionDAO.setValue(MdAttributeDimensionInfo.DEFAULT_VALUE, "2008-12-12");
mdAttributeDimensionDAO.apply();
}
catch (Throwable e)
{
fail(e.getLocalizedMessage());
}
finally
{
mdDateAttribute.delete();
}
}
public void testValidTextValue()
{
MdAttributeTextDAO mdAttributeText = TestFixtureFactory.addTextAttribute(testMdBusiness);
mdAttributeText.apply();
try
{
MdAttributeDimensionDAO mdAttributeDimensionDAO = mdAttributeText.getMdAttributeDimension(mdDimension).getBusinessDAO();
mdAttributeDimensionDAO.setValue(MdAttributeDimensionInfo.DEFAULT_VALUE, "Blah!!!");
mdAttributeDimensionDAO.apply();
}
catch (Throwable e)
{
fail(e.getLocalizedMessage());
}
finally
{
mdAttributeText.delete();
}
}
/**
* Tests for a valid default value set on attribute dimensions.
* @throws Exception
*
*/
public void testInvalidDefaultIntegerAttribute() throws Exception
{
MdAttributeIntegerDAO mdAttributeInteger = TestFixtureFactory.addIntegerAttribute(testMdBusiness);
mdAttributeInteger.apply();
try
{
MdAttributeDimensionDAO mdAttributeDimensionDAO = mdAttributeInteger.getMdAttributeDimension(mdDimension).getBusinessDAO();
mdAttributeDimensionDAO.setValue(MdAttributeDimensionInfo.DEFAULT_VALUE, "1");
mdAttributeDimensionDAO.apply();
fail("A integer default value on an attribute dimension was set with an invalid value.");
}
catch (ProblemException e)
{
// This is expected
List<ProblemIF> problems = e.getProblems();
boolean problemFound = false;
for (ProblemIF p : problems)
{
if (p instanceof AttributeValueCannotBePositiveProblem)
problemFound = true;
}
if (!problemFound)
throw new Exception("AttributeValueCannotBePositiveProblem was not thrown");
}
finally
{
mdAttributeInteger.delete();
}
}
/**
* Tests for a valid default value set on attribute dimensions.
*
*/
public void testValidDefaultIntegerAttribute()
{
MdAttributeIntegerDAO mdAttributeInteger = TestFixtureFactory.addIntegerAttribute(testMdBusiness);
mdAttributeInteger.apply();
try
{
MdAttributeDimensionDAO mdAttributeDimensionDAO = mdAttributeInteger.getMdAttributeDimension(mdDimension).getBusinessDAO();
mdAttributeDimensionDAO.setValue(MdAttributeDimensionInfo.DEFAULT_VALUE, "-1");
mdAttributeDimensionDAO.apply();
}
catch (Throwable e)
{
fail(e.getLocalizedMessage());
}
finally
{
mdAttributeInteger.delete();
}
}
public void testDimensionalNotRequiredAttribute()
{
MdAttributeDimensionDAO mdAttributeDimensionDAO = dimensionMdAttributeRequired.getMdAttributeDimension(mdDimension).getBusinessDAO();
mdAttributeDimensionDAO.setValue(MdAttributeDimensionInfo.REQUIRED, MdAttributeBooleanInfo.FALSE);
mdAttributeDimensionDAO.apply();
String sessionId = null;
try
{
sessionId = Facade.login(ServerConstants.SYSTEM_USER_NAME, ServerConstants.SYSTEM_DEFAULT_PASSWORD, new Locale[] { Session.getCurrentLocale() });
dimensionalNotRequiredAttribute(sessionId);
}
finally
{
if (sessionId != null)
{
Facade.logout(sessionId);
}
}
}
@Request(RequestType.SESSION)
private void dimensionalNotRequiredAttribute(String sessionId)
{
Session session = (Session) Session.getCurrentSession();
session.setDimension(mdDimension);
assertFalse("Attribute Dimension required permission is incorrect.", dimensionMdAttributeRequired.isRequiredForDTO());
BusinessDAO businessDAO = null;
try
{
businessDAO = BusinessDAO.newInstance(testMdBusiness.definesType());
businessDAO.apply();
}
catch (ProblemException e)
{
fail("Unable to add a non-required attribute for a dimension.");
}
finally
{
if (businessDAO != null && !businessDAO.isNew())
{
businessDAO.delete();
}
session.setDimension((MdDimensionDAOIF) null);
}
}
public void testDimensionalRequiredAttribute()
{
MdAttributeDimensionDAO mdAttributeDimensionDAO = dimensionMdAttributeRequired.getMdAttributeDimension(mdDimension).getBusinessDAO();
mdAttributeDimensionDAO.setValue(MdAttributeDimensionInfo.REQUIRED, MdAttributeBooleanInfo.TRUE);
mdAttributeDimensionDAO.apply();
String sessionId = null;
try
{
sessionId = Facade.login(ServerConstants.SYSTEM_USER_NAME, ServerConstants.SYSTEM_DEFAULT_PASSWORD, new Locale[] { Session.getCurrentLocale() });
dimensionalRequiredAttribute(sessionId);
}
finally
{
if (sessionId != null)
{
Facade.logout(sessionId);
}
mdAttributeDimensionDAO.setValue(MdAttributeDimensionInfo.REQUIRED, MdAttributeBooleanInfo.FALSE);
mdAttributeDimensionDAO.apply();
}
}
@Request(RequestType.SESSION)
private void dimensionalRequiredAttribute(String sessionId)
{
Session session = (Session) Session.getCurrentSession();
session.setDimension(mdDimension);
assertTrue("Attribute Dimension required permission is incorrect.", dimensionMdAttributeRequired.isRequiredForDTO());
BusinessDAO businessDAO = null;
try
{
businessDAO = BusinessDAO.newInstance(testMdBusiness.definesType());
businessDAO.apply();
fail("Attribute.validateRequired() accepted a blank value on a required field for a dimension.");
}
catch (ProblemException e)
{
ProblemException problemException = (ProblemException) e;
if (problemException.getProblems().size() == 1 && problemException.getProblems().get(0) instanceof EmptyValueProblem)
{
// Expected to land here
}
else
{
fail(EmptyValueProblem.class.getName() + " was not thrown.");
}
}
finally
{
if (businessDAO != null && !businessDAO.isNew())
{
businessDAO.delete();
}
session.setDimension((MdDimensionDAOIF) null);
}
}
public void testCreateMdAttributeDimension()
{
MdAttributeDimensionDAOIF mdAttributeDimension = mdAttribute.getMdAttributeDimension(mdDimension);
MdAttributeDimensionDAOIF test = MdAttributeDimensionDAO.get(mdAttributeDimension.getId());
assertEquals(mdAttribute.getId(), test.definingMdAttribute().getId());
assertEquals(mdDimension.getId(), test.definingMdDimension().getId());
}
public void testDoubleApply()
{
MdAttributeDimensionDAO mdAttributeDimension = mdAttribute.getMdAttributeDimension(mdDimension).getBusinessDAO();
mdAttributeDimension.apply();
try
{
mdAttributeDimension.apply();
MdAttributeDimensionDAOIF test = MdAttributeDimensionDAO.get(mdAttributeDimension.getId());
assertEquals(mdAttribute.getId(), test.definingMdAttribute().getId());
assertEquals(mdDimension.getId(), test.definingMdDimension().getId());
}
finally
{
}
}
public void testDeleteMdBusinessWithAttributeDimesnions()
{
MdBusinessDAO _mdBusiness = TestFixtureFactory.createMdBusiness2();
_mdBusiness.apply();
MdAttributeCharacterDAO _mdAttribute = TestFixtureFactory.addCharacterAttribute(_mdBusiness);
_mdAttribute.apply();
MdAttributeDimensionDAOIF mdAttributeDimension = _mdAttribute.getMdAttributeDimension(mdDimension);
try
{
TestFixtureFactory.delete(_mdBusiness);
try
{
MdAttributeDimensionDAO.get(mdAttributeDimension.getId());
fail("MdAttributeDimension was not deleted when the defining MdBusiness of the MdAttribute was deleted.");
}
catch (DataNotFoundException e)
{
// This is expected
}
}
catch (Exception e)
{
TestFixtureFactory.delete(_mdAttribute);
TestFixtureFactory.delete(_mdBusiness);
e.printStackTrace();
fail(e.getMessage());
}
}
public void testDeleteMdDimensionWithAttributeDimesnions()
{
MdDimensionDAO _mdDimension = TestFixtureFactory.createMdDimension("TempD");
_mdDimension.apply();
MdAttributeDimensionDAOIF mdAttributeDimension = mdAttribute.getMdAttributeDimension(_mdDimension);
try
{
TestFixtureFactory.delete(_mdDimension);
try
{
MdAttributeDimensionDAO.get(mdAttributeDimension.getId());
fail("MdAttributeDimension was not deleted when the defining MdBusiness of the MdAttribute was deleted.");
}
catch (DataNotFoundException e)
{
// This is expected
}
}
catch (Exception e)
{
TestFixtureFactory.delete(_mdDimension);
e.printStackTrace();
fail(e.getMessage());
}
}
public void testGetMdAttributeDimension()
{
MdAttributeDimensionDAOIF test = mdAttribute.getMdAttributeDimension(mdDimension);
assertNotNull(test);
assertEquals(mdAttribute.getId(), test.definingMdAttribute().getId());
assertEquals(mdDimension.getId(), test.definingMdDimension().getId());
}
public void testGetAllMdAttributeDimension()
{
List<MdAttributeDimensionDAOIF> list = mdAttribute.getMdAttributeDimensions();
assertEquals(2, list.size());
}
public void testGetMdAttributeDimensionFromMdDimension()
{
MdAttributeDimensionDAOIF test = mdDimension.getMdAttributeDimension(mdAttribute);
assertNotNull(test);
assertEquals(mdAttribute.getId(), test.definingMdAttribute().getId());
assertEquals(mdDimension.getId(), test.definingMdDimension().getId());
}
public void testGetAllMdAttributeDimensionFromDimension()
{
List<MdAttributeDimensionDAOIF> list = mdDimension.getMdAttributeDimensions();
assertTrue(0 != list.size());
}
public void testGetMdClassDimension()
{
MdClassDimensionDAOIF test = testMdBusiness.getMdClassDimension(mdDimension);
assertNotNull(test);
assertEquals(testMdBusiness.getId(), test.definingMdClass().getId());
assertEquals(mdDimension.getId(), test.definingMdDimension().getId());
}
public void testGetAllMdClassDimension()
{
List<MdClassDimensionDAOIF> list = testMdBusiness.getMdClassDimensions();
assertEquals(2, list.size());
}
public void testGetMdClassDimensionFromMdDimension()
{
MdClassDimensionDAOIF test = mdDimension.getMdClassDimension(testMdBusiness);
assertNotNull(test);
assertEquals(testMdBusiness.getId(), test.definingMdClass().getId());
assertEquals(mdDimension.getId(), test.definingMdDimension().getId());
}
public void testGetAllMdClassDimensionFromDimension()
{
List<MdClassDimensionDAOIF> list = mdDimension.getMdClassDimensions();
assertTrue(0 != list.size());
}
}
| true | false | null | null |
diff --git a/src/com/jidesoft/swing/JideSplitPane.java b/src/com/jidesoft/swing/JideSplitPane.java
index 6189504e..2d8aa51c 100644
--- a/src/com/jidesoft/swing/JideSplitPane.java
+++ b/src/com/jidesoft/swing/JideSplitPane.java
@@ -1,1451 +1,1463 @@
/*
* @(#)JideSplitPane.java
*
* Copyright 2002 JIDE Software Inc. All rights reserved.
*/
package com.jidesoft.swing;
import com.jidesoft.plaf.LookAndFeelFactory;
import com.jidesoft.plaf.UIDefaultsLookup;
import javax.accessibility.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Arrays;
+import java.util.Map;
/**
* <code>JideSplitPane</code> is used to divide multiple <code>Component</code>s.
* <p/>
* These <code>Component</code>s in a split pane can be aligned left to right using
* <code>JideSplitPane.HORIZONTAL_SPLIT</code>, or top to bottom using <code>JideSplitPane.VERTICAL_SPLIT</code>.
*/
public class JideSplitPane extends JPanel implements ContainerListener, ComponentListener, Accessible {
/**
* The divider used for non-continuous layout is added to the split pane with this object.
*/
protected static final String NON_CONTINUOUS_DIVIDER =
"nonContinuousDivider";
/**
* Vertical split indicates the <code>Component</code>s are split along the y axis. For example the two or more
* <code>Component</code>s will be split one on top of the other.
*/
public static final int VERTICAL_SPLIT = 0;
/**
* Horizontal split indicates the <code>Component</code>s are split along the x axis. For example the two or more
* <code>Component</code>s will be split one to the left of the other.
*/
public static final int HORIZONTAL_SPLIT = 1;
/**
* Bound property name for orientation (horizontal or vertical).
*/
public static final String ORIENTATION_PROPERTY = "orientation";
/**
* Bound property name for border size.
*/
public static final String DIVIDER_SIZE_PROPERTY = "dividerSize";
/**
* Bound property name for border size.
*/
public static final String PROPERTY_DIVIDER_LOCATION = "dividerLocation";
/**
* Bound property name for continuousLayout.
*/
public static final String CONTINUOUS_LAYOUT_PROPERTY = "continuousLayout";
/**
* Bound property name for gripper.
*/
public static final String GRIPPER_PROPERTY = "gripper";
/**
* Bound property name for proportional layout.
*/
public static final String PROPORTIONAL_LAYOUT_PROPERTY = "proportionalLayout";
/**
* Bound property name for the proportions used in the layout.
*/
public static final String PROPORTIONS_PROPERTY = "proportions";
public static final String PROPERTY_HEAVYWEIGHT_COMPONENT_ENABLED = "heavyweightComponentEnabled";
/**
* How the views are split. The value of it can be either <code>HORIZONTAL_SPLIT</code> or
* <code>VERTICAL_SPLIT</code>.
*/
private int _orientation;
/**
* Size of the divider. All dividers have the same size. If <code>orientation</code> is
* <code>HORIZONTAL_SPLIT</code>, the size will equal to the width of the divider If <code>orientation</code> is
* <code>VERTICAL_SPLIT</code>, the size will equal to the height of the divider.
*/
private int _dividerSize = UIDefaultsLookup.getInt("JideSplitPane.dividerSize");
// /**
// * Instance for the shadow of the divider when non continuous layout
// * is being used.
// */
// private Contour _nonContinuousLayoutDivider;
private HeavyweightWrapper _nonContinuousLayoutDividerWrapper;
/**
* Continuous layout or not.
*/
private boolean _continuousLayout = false;
/**
* Layered pane where _nonContinuousLayoutDivider is added to.
*/
private Container _layeredPane;
/**
* If the gripper should be shown. Gripper is something on divider to indicate it can be dragged.
*/
private boolean _showGripper = false;
/**
* Whether the contained panes should be laid out proportionally.
*/
private boolean _proportionalLayout = false;
/**
* An array of the proportions to assign to the widths or heights of the contained panes. Has one fewer elements
* than there are contained panes; the last pane receives the remaining room.
*/
private double[] _proportions;
/**
* For proportional layouts only, when this flag is true the initial layout uses even proportions for the contained
* panes, unless the proportions are explicitly set.
*/
private boolean _initiallyEven = true;
private boolean _heavyweightComponentEnabled = false;
public WindowAdapter _windowDeactivatedListener;
private int _dividerStepSize = 0;
private boolean _dragResizable = true;
/**
* Creates a new <code>JideSplitPane</code> configured to arrange the child components side-by-side horizontally.
*/
public JideSplitPane() {
this(HORIZONTAL_SPLIT);
}
/**
* Creates a new <code>JideSplitPane</code> configured with the specified orientation.
*
* @param newOrientation <code>JideSplitPane.HORIZONTAL_SPLIT</code> or <code>JideSplitPane.VERTICAL_SPLIT</code>
* @throws IllegalArgumentException if <code>orientation</code> is not one of HORIZONTAL_SPLIT or VERTICAL_SPLIT.
*/
public JideSplitPane(int newOrientation) {
super();
_orientation = newOrientation;
if (_orientation != HORIZONTAL_SPLIT && _orientation != VERTICAL_SPLIT)
throw new IllegalArgumentException("cannot create JideSplitPane, " +
"orientation must be one of " +
"JideSplitPane.HORIZONTAL_SPLIT " +
"or JideSplitPane.VERTICAL_SPLIT");
// setup layout
LayoutManager layoutManager;
if (_orientation == HORIZONTAL_SPLIT) {
layoutManager = new JideSplitPaneLayout(this, JideSplitPaneLayout.X_AXIS);
}
else {
layoutManager = new JideSplitPaneLayout(this, JideSplitPaneLayout.Y_AXIS);
}
super.setLayout(layoutManager);
setOpaque(false);
// setup listener
installListeners();
}
/**
* Get the step size while dragging the divider.
* <p/>
* The default value of the step size is 0, which means no constraints on the dragging position
*
* @return the step size.
*/
public int getDividerStepSize() {
return _dividerStepSize;
}
/**
* Set the step size while dragging the divider.
* <p/>
* The step size cannot be negative.
*
* @param dividerStepSize the step size
*/
public void setDividerStepSize(int dividerStepSize) {
if (dividerStepSize < 0) {
return;
}
_dividerStepSize = dividerStepSize;
}
@Override
public void updateUI() {
if (UIDefaultsLookup.get("JideSplitPane.dividerSize") == null) {
LookAndFeelFactory.installJideExtension();
}
super.updateUI();
}
/**
* Install listeners
*/
private void installListeners() {
addContainerListener(this);
}
/**
* Sets the size of the divider.
*
* @param newSize an integer giving the size of the divider in pixels
*/
public void setDividerSize(int newSize) {
int oldSize = _dividerSize;
if (oldSize != newSize) {
_dividerSize = newSize;
firePropertyChange(DIVIDER_SIZE_PROPERTY, oldSize, newSize);
invalidate();
}
}
/**
* Returns the size of the divider.
*
* @return an integer giving the size of the divider in pixels
*/
public int getDividerSize() {
return _dividerSize;
}
/**
* Inserts the specified pane to this container at the given position. Note: Divider is not counted.
*
* @param pane the pane to be added
* @param index the position at which to insert the component.
* @return the component <code>pane</code>
*/
public Component insertPane(Component pane, int index) {
return insertPane(pane, null, index);
}
/**
* Inserts the specified pane to this container at the given position. Note: Divider is not counted.
*
* @param pane the pane to be added
* @param constraint an object expressing layout constraints for this component
* @param index the position at which to insert the component.
* @return the component <code>pane</code>
*/
public Component insertPane(Component pane, Object constraint, int index) {
if (index <= 0) {
addImpl(pane, constraint, 0);
}
else if (index >= getPaneCount()) {
addImpl(pane, constraint, -1);
}
else {
addImpl(pane, constraint, (index << 1) - 1);
}
return pane;
}
/**
* Adds the specified pane to this container at the end.
*
* @param pane the pane to be added
* @return the pane <code>pane</code>
*/
public Component addPane(Component pane) {
if (pane == null) {
return null;
}
return super.add(pane);
}
/**
* Removes the pane, specified by <code>index</code>, from this container.
*
* @param pane the pane to be removed.
*/
public void removePane(Component pane) {
removePane(indexOfPane(pane));
}
/**
* Replaces the pane at the position specified by index.
*
* @param pane new pane
* @param index position
*/
public void setPaneAt(Component pane, int index) {
setPaneAt(pane, null, index);
}
/**
* Replaces the pane at the position specified by index.
*
* @param pane new pane
* @param constraint an object expressing layout constraints for this component
* @param index position
*/
public void setPaneAt(Component pane, Object constraint, int index) {
double[] proportions = _proportions;
_proportions = null; // Just turn them off temporarily
removePane(index);
insertPane(pane, constraint, index);
_proportions = proportions;
}
/**
* Removes the pane, specified by <code>index</code>, from this container.
*
* @param index the index of the component to be removed.
*/
public void removePane(int index) {
if (index == 0) { // if first one
super.remove(0); // the component
}
else { // not first one. then remove itself and the divider before it
super.remove(index << 1); // component
}
}
/**
* Sets the orientation, or how the splitter is divided. The options are:<ul> <li>JideSplitPane.VERTICAL_SPLIT
* (above/below orientation of components) <li>JideSplitPane.HORIZONTAL_SPLIT (left/right orientation of
* components) </ul>
*
* @param orientation an integer specifying the orientation
* @throws IllegalArgumentException if orientation is not one of: HORIZONTAL_SPLIT or VERTICAL_SPLIT.
*/
public void setOrientation(int orientation) {
if ((orientation != VERTICAL_SPLIT) &&
(orientation != HORIZONTAL_SPLIT)) {
throw new IllegalArgumentException("JideSplitPane: orientation must " +
"be one of " +
"JideSplitPane.VERTICAL_SPLIT or " +
"JideSplitPane.HORIZONTAL_SPLIT");
}
if (_orientation == orientation)
return;
int oldOrientation = _orientation;
_orientation = orientation;
// if (_orientation == JideSplitPane.HORIZONTAL_SPLIT)
// setBorder(BorderFactory.createLineBorder(Color.RED));
// else
// setBorder(BorderFactory.createLineBorder(Color.CYAN));
- LayoutManager layoutManager;
+ JideSplitPaneLayout layoutManager;
if (_orientation == HORIZONTAL_SPLIT) {
layoutManager = new JideSplitPaneLayout(this, JideSplitPaneLayout.X_AXIS);
}
else {
layoutManager = new JideSplitPaneLayout(this, JideSplitPaneLayout.Y_AXIS);
}
+ Component[] components = getComponents();
+ LayoutManager oldManager = getLayout();
+ Map<Component,Object> constraintMap = null;
+ if (oldManager instanceof JideSplitPaneLayout) {
+ constraintMap = ((JideSplitPaneLayout) oldManager).getConstraintMap();
+ }
+ if (components != null && constraintMap != null) {
+ for (Component comp : components) {
+ layoutManager.addLayoutComponent(comp, constraintMap.get(comp));
+ }
+ }
super.setLayout(layoutManager);
doLayout();
firePropertyChange(ORIENTATION_PROPERTY, oldOrientation, orientation);
}
/**
* Returns the orientation.
*
* @return an integer giving the orientation
*
* @see #setOrientation
*/
public int getOrientation() {
return _orientation;
}
/**
* Lays out the <code>JideSplitPane</code> layout based on the preferred size children components, or based on the
* proportions if proportional layout is on. This will likely result in changing the divider location.
*/
public void resetToPreferredSizes() {
doLayout();
}
/**
* Sets this split pane to lay its constituents out proportionally if the given flag is true, or by preferred sizes
* otherwise.
*
* @param proportionalLayout true or false.
*/
public void setProportionalLayout(boolean proportionalLayout) {
if (proportionalLayout == _proportionalLayout)
return;
_proportionalLayout = proportionalLayout;
revalidate();
firePropertyChange(PROPORTIONAL_LAYOUT_PROPERTY, !proportionalLayout, proportionalLayout);
if (!proportionalLayout)
setProportions(null);
}
/**
* Returns the proportional layout flag.
*
* @return true or false.
*/
public boolean isProportionalLayout() {
return _proportionalLayout;
}
void internalSetProportions(double[] proportions) {
_proportions = proportions;
}
/**
* Sets the proportions to use in laying out this split pane's children. Only applicable when {@link
* #isProportionalLayout} is true; calling it when false will throw an exception. The given array must either be
* null, or have one fewer slots than there are {@linkplain #getPaneCount() contained panes}. Each item in the
* array (if not null) must be a number between 0 and 1, and the sum of all of them must be no more than 1.
*
* @param proportions the proportions of all the panes.
*/
public void setProportions(double[] proportions) {
// if ( ! _proportionalLayout )
if (!_proportionalLayout && proportions != null)
throw new IllegalStateException("Can't set proportions on a non-proportional split pane");
if (Arrays.equals(proportions, _proportions))
return;
if (proportions != null && proportions.length != getPaneCount() - 1)
throw new IllegalArgumentException(
"Must provide one fewer proportions than there are panes: got " + proportions.length
+ ", expected " + (getPaneCount() - 1));
if (proportions != null) {
double sum = 0.0;
for (int i = 0; i < proportions.length; ++i) {
if (proportions[i] < 0.0)
proportions[i] = 0.0;
if (proportions[i] > 1.0)
proportions[i] = 1.0;
sum += proportions[i];
}
if (sum > 1.0)
throw new IllegalArgumentException("Sum of proportions must be no more than 1, got " + sum);
}
double[] oldProportions = _proportions;
_proportions = (proportions == null) ? null : proportions.clone();
LayoutManager layoutManager = getLayout();
boolean reset = false;
if (layoutManager instanceof JideBoxLayout) {
reset = ((JideBoxLayout) layoutManager).isResetWhenInvalidate();
((JideBoxLayout) layoutManager).setResetWhenInvalidate(true);
}
revalidate();
if (reset) {
((JideBoxLayout) layoutManager).setResetWhenInvalidate(reset);
}
firePropertyChange(PROPORTIONS_PROPERTY, oldProportions, proportions);
}
/**
* Returns the current array of proportions used for proportional layout, or null if none has been established via
* {@link #setProportions} or via user action.
*
* @return the proportions.
*/
public double[] getProportions() {
double[] answer = _proportions;
if (answer != null)
answer = answer.clone();
return answer;
}
/**
* Sets the flag telling whether to do even proportions for the initial proportional layout, in the absence of
* explicit proportions.
*
* @param initiallyEven true or false.
*/
public void setInitiallyEven(boolean initiallyEven) {
_initiallyEven = initiallyEven;
}
/**
* Returns the flag that tells whether to do even proportions for the initial proportional layout, in the absence of
* explicit proportions.
*
* @return true or false.
*/
public boolean isInitiallyEven() {
return _initiallyEven;
}
/**
* Returns true, so that calls to <code>revalidate</code> on any descendant of this <code>JideSplitPane</code> will
* cause a request to be queued that will validate the <code>JideSplitPane</code> and all its descendants.
*
* @return true
*
* @see JComponent#revalidate
*/
@Override
public boolean isValidateRoot() {
return true;
}
/**
* Prepares dragging if it's not continuous layout. If it's continuous layout, do nothing.
*
* @param divider the divider
*/
protected void startDragging(JideSplitPaneDivider divider) {
if (!isContinuousLayout()) {
Component topLevelAncestor = getTopLevelAncestor();
if (_windowDeactivatedListener == null) {
// this a listener to remove the dragging outline when window is deactivated
_windowDeactivatedListener = new WindowAdapter() {
@Override
public void windowDeactivated(WindowEvent e) {
stopDragging();
if (e.getWindow() != null) {
e.getWindow().removeWindowListener(_windowDeactivatedListener);
}
}
};
}
if (topLevelAncestor instanceof Window)
((Window) topLevelAncestor).addWindowListener(_windowDeactivatedListener);
if (topLevelAncestor instanceof RootPaneContainer) {
_layeredPane = ((RootPaneContainer) topLevelAncestor).getLayeredPane();
// left over, remove them
if (_nonContinuousLayoutDividerWrapper == null) {
Contour nonContinuousLayoutDivider = new JideSplitPaneContour();
_nonContinuousLayoutDividerWrapper = new JideSplitPaneHeavyweightWrapper(nonContinuousLayoutDivider);
_nonContinuousLayoutDividerWrapper.setHeavyweight(isHeavyweightComponentEnabled());
}
_nonContinuousLayoutDividerWrapper.delegateSetCursor((_orientation == HORIZONTAL_SPLIT) ?
JideSplitPaneDivider.HORIZONTAL_CURSOR : JideSplitPaneDivider.VERTICAL_CURSOR);
_nonContinuousLayoutDividerWrapper.delegateSetVisible(false);
_nonContinuousLayoutDividerWrapper.delegateAdd(_layeredPane, JLayeredPane.DRAG_LAYER);
Rectangle bounds = getVisibleRect();
Rectangle layeredPaneBounds = SwingUtilities.convertRectangle(this, bounds, _layeredPane);
int dividerThickness = Math.min(4, getDividerSize());
if (getOrientation() == HORIZONTAL_SPLIT) {
_nonContinuousLayoutDividerWrapper.delegateSetBounds(layeredPaneBounds.x, layeredPaneBounds.y,
dividerThickness, layeredPaneBounds.height);
}
else {
_nonContinuousLayoutDividerWrapper.delegateSetBounds(layeredPaneBounds.x, layeredPaneBounds.y,
layeredPaneBounds.width, dividerThickness);
}
}
}
}
private void stopDragging() {
if (!isContinuousLayout() && _layeredPane != null && _nonContinuousLayoutDividerWrapper != null) {
_nonContinuousLayoutDividerWrapper.delegateSetVisible(false);
_nonContinuousLayoutDividerWrapper.delegateRemove(_layeredPane);
_nonContinuousLayoutDividerWrapper.delegateSetNull();
_nonContinuousLayoutDividerWrapper = null;
// add a protection in case there is another wrapper inside the layered pane
Component[] childComponents = _layeredPane.getComponents();
for (Component component : childComponents) {
if (component instanceof JideSplitPaneContour || component instanceof JideSplitPaneHeavyweightWrapper) {
_layeredPane.remove(component);
}
}
}
}
/**
* Drags divider to right location. If it's continuous layout, really drag the divider; if not, only drag the
* shadow.
*
* @param divider the divider
* @param location new location
*/
protected void dragDividerTo(JideSplitPaneDivider divider, int location) {
if (_layeredPane == null || isContinuousLayout()) {
setDividerLocation(divider, location);
}
else {
if (_nonContinuousLayoutDividerWrapper != null) {
Point p;
Dimension size = new Dimension();
Rectangle rect = getVisibleRect();
int dividerThickness = Math.min(4, getDividerSize());
Rectangle convertedRect = SwingUtilities.convertRectangle(this, rect, _layeredPane);
if (getOrientation() == HORIZONTAL_SPLIT) {
p = SwingUtilities.convertPoint(this, location, rect.y, _layeredPane);
p.x += ((getDividerSize() - dividerThickness) >> 1);
size.width = dividerThickness;
size.height = convertedRect.height;
}
else {
p = SwingUtilities.convertPoint(this, rect.x, location, _layeredPane);
p.y += ((getDividerSize() - dividerThickness) >> 1);
size.width = convertedRect.width;
size.height = dividerThickness;
}
_nonContinuousLayoutDividerWrapper.delegateSetBounds(new Rectangle(p, size));
_nonContinuousLayoutDividerWrapper.delegateSetVisible(true);
}
}
}
/**
* Finishes dragging. If it's not continuous layout, clear up the shadow component.
*
* @param divider the divider
* @param location new location
*/
protected void finishDraggingTo(JideSplitPaneDivider divider, int location) {
if (isContinuousLayout() || _nonContinuousLayoutDividerWrapper != null) {
stopDragging();
setDividerLocation(divider, location);
}
}
/**
* Returns the index of the divider. For example, the index of the first divider is 0, the index of the second is 1.
* Notes: Pane is not counted
*
* @param divider divider to get index
* @return index of the divider. -1 if comp doesn't exist in this container
*/
public int indexOfDivider(JideSplitPaneDivider divider) {
int index = indexOf(divider);
if (index == -1)
return index;
else {
if (index % 2 == 0)
//noinspection UseOfSystemOutOrSystemErr
System.err.println("Warning: divider's index is even. (index = " + index + ")");
return (index - 1) / 2;
}
}
/**
* Returns the index of the pane. For example, the index of the first pane is 0, the index of the second is 1.
* Notes: divider is not counted
*
* @param pane pane to get index
* @return index of the pane. -1 if comp doesn't exist in this container
*/
public int indexOfPane(Component pane) {
int index = indexOf(pane);
if (index == -1)
return -1;
else {
if (index % 2 != 0)
//noinspection UseOfSystemOutOrSystemErr
System.err.println("Warning: pane's index is odd. (index = " + index + ")");
return index >> 1;
}
}
/**
* Returns the index of the component.
*
* @param comp component to get index
* @return index of the comp. -1 if comp doesn't exist in this container
*/
public int indexOf(Component comp) {
for (int i = 0; i < getComponentCount(); i++) {
if (getComponent(i).equals(comp))
return i;
}
return -1;
}
/**
* Returns the divider at index.
*
* @param index index
* @return the divider at the index
*/
public JideSplitPaneDivider getDividerAt(int index) {
if (index < 0 || index * 2 + 1 >= getComponentCount())
return null;
return (JideSplitPaneDivider) getComponent(index * 2 + 1);
}
/**
* Returns the component at index.
*
* @param index index
* @return the component at the index
*/
public Component getPaneAt(int index) {
if (index < 0 || index << 1 >= getComponentCount())
return null;
return getComponent(index << 1);
}
/**
* Gets the count of panes, regardless of dividers.
*
* @return the count of panes
*/
public int getPaneCount() {
return (getComponentCount() + 1) >> 1;
}
/**
* Set the divider location.
*
* @param divider the divider
* @param location new location
*/
public void setDividerLocation(JideSplitPaneDivider divider, int location) {
setDividerLocation(indexOfDivider(divider), location);
}
/**
* Set the divider location. You can only call this method to set the divider location when the component is
* rendered on the screen. If the component has never been displayed before, this method call has no effect.
*
* @param dividerIndex the divider index, starting from 0 for the first divider.
* @param location new location
*/
public void setDividerLocation(int dividerIndex, int location) {
((JideSplitPaneLayout) getLayout()).setDividerLocation(dividerIndex, location, true);
}
/**
* Get the divider location. You can only get a valid divider location when the component is displayed on the
* screen. If the component has never been displayed on screen, -1 will be returned.
*
* @param dividerIndex the divider index
* @return the location of the divider.
*/
public int getDividerLocation(int dividerIndex) {
return ((JideSplitPaneLayout) getLayout()).getDividerLocation(dividerIndex);
}
/**
* Invoked when a component has been added to the container. Basically if you add anything which is not divider, a
* divider will automatically added before or after the component.
*
* @param e ContainerEvent
*/
public void componentAdded(ContainerEvent e) {
e.getChild().addComponentListener(this);
if (!(e.getChild() instanceof JideSplitPaneDivider)) {
addExtraDividers();
if (isOneTouchExpandable()) {
e.getChild().setMinimumSize(new Dimension(0, 0));
}
}
setDividersVisible();
resetToPreferredSizes();
}
/**
* Invoked when a component has been removed from the container. Basically if you remove anything which is not
* divider, a divider will automatically deleted before or after the component.
*
* @param e ContainerEvent
*/
public void componentRemoved(ContainerEvent e) {
e.getChild().removeComponentListener(this);
if (!(e.getChild() instanceof JideSplitPaneDivider)) {
removeExtraDividers();
}
setDividersVisible();
resetToPreferredSizes();
/*
if (getComponentCount() == 1 && getComponent(0) instanceof JideSplitPane) {
JideSplitPane childPane = (JideSplitPane)getComponent(0);
if(getOrientation() != childPane.getOrientation()) {
setOrientation(childPane.getOrientation());
}
// copy all children of its splitpane child to this
boolean savedAutoRemove = childPane.isAutomaticallyRemove();
childPane.setAutomaticallyRemove(false);
for(int i = 0; i < childPane.getComponentCount(); i ++) {
if(childPane.getComponent(i) instanceof JideSplitPaneDivider)
continue;
System.out.println("Adding " + childPane.getComponent(i));
add(childPane.getComponent(i));
i --;
}
childPane.setAutomaticallyRemove(savedAutoRemove);
System.out.println("Removing " + childPane);
remove(childPane);
}
if (isAutomaticallyRemove() && getComponentCount() == 0 && getParent() != null) {
System.out.println("Automatically Removing this " + this);
getParent().remove(this);
return;
}
*/
}
public void componentResized(ComponentEvent e) {
}
public void componentMoved(ComponentEvent e) {
}
public void componentShown(ComponentEvent e) {
if (e.getComponent() instanceof JideSplitPaneDivider) {
return;
}
setDividersVisible();
resetToPreferredSizes();
}
public void componentHidden(ComponentEvent e) {
if (e.getComponent() instanceof JideSplitPaneDivider) {
return;
}
setDividersVisible();
resetToPreferredSizes();
}
/**
* Remove extra divider. One is considered as extra dividers where two dividers are adjacent.
*
* @return true if dividers are removed.
*/
protected boolean removeExtraDividers() {
int extra = 0;
if (getComponentCount() == 0) {
if (_proportions != null)
setProportions(null);
return false;
}
boolean changed = false;
// remove first divider if it's one
if (getComponent(0) instanceof JideSplitPaneDivider) {
remove(0);
removeProportion(0);
changed = true;
}
for (int i = 0; i < getComponentCount(); i++) {
Component comp = getComponent(i);
if (comp instanceof JideSplitPaneDivider) {
extra++;
if (extra == 2) {
remove(comp);
if (_proportions != null && getPaneCount() == _proportions.length)
removeProportion(i / 2);
changed = true;
extra--;
i--;
}
}
else
extra = 0;
}
if (extra == 1) { // remove last one if it's a divider
remove(getComponentCount() - 1);
removeProportion((getComponentCount() + 1) / 2);
changed = true;
}
return changed;
}
/**
* Removes the proportion at the given pane index, spreading its value proportionally across the other proportions.
* If it's the last proportion being removed, sets the proportions to null.
*
* @param paneIndex the pane index.
*/
protected void removeProportion(int paneIndex) {
double[] oldProportions = _proportions;
if (oldProportions == null)
return;
if (oldProportions.length <= 1) {
setProportions(null);
return;
}
double[] newProportions = new double[oldProportions.length - 1];
double p;
if (paneIndex < oldProportions.length)
p = oldProportions[paneIndex];
else {
p = 1.0;
for (double proportion : oldProportions) p -= proportion;
}
double total = 1.0 - p;
for (int i = 0; i < newProportions.length; ++i) {
int j = (i < paneIndex) ? i : i + 1;
newProportions[i] = oldProportions[j] / total;
}
// to make sure the proportion adds up to 1 for this special case.
if (newProportions.length == 1) {
// newProportions[0] = 1.0;
}
setProportions(newProportions);
}
/**
* Add divider if there are two panes side by side without a divider in between.
*/
protected void addExtraDividers() {
int extra = 0;
for (int i = 0; i < getComponentCount(); i++) {
Component comp = getComponent(i);
if (!(comp instanceof JideSplitPaneDivider)) {
extra++;
if (extra == 2) {
add(createSplitPaneDivider(), JideSplitPaneLayout.FIX, i);
if (_proportions != null && getPaneCount() == _proportions.length + 2)
addProportion((i + 1) / 2);
extra = 0;
}
}
else
extra = 0;
}
}
/**
* Adds a proportion at the given pane index, taking a proportional amount from each of the existing proportions.
*
* @param paneIndex the pane index.
*/
protected void addProportion(int paneIndex) {
double[] oldProportions = _proportions;
if (oldProportions == null)
return;
double[] newProportions = new double[oldProportions.length + 1];
double p = 1.0 / (newProportions.length + 1);
double total = 1.0 - p;
for (int i = 0; i < newProportions.length; ++i) {
if (i == paneIndex)
newProportions[i] = p;
else {
int j = (i < paneIndex) ? i : i - 1;
if (j < oldProportions.length)
newProportions[i] = oldProportions[j] * total;
else
newProportions[i] = p;
}
}
setProportions(newProportions);
}
/**
* Before this method is call, the panes must be separated by dividers.
*/
protected void setDividersVisible() {
if (getComponentCount() == 1) {
setVisible(getComponent(0).isVisible());
}
else if (getComponentCount() > 1) {
boolean anyVisible = false;
boolean anyPrevVisible = false;
for (int i = 0; i < getComponentCount(); i++) {
Component comp = getComponent(i);
if (!(comp instanceof JideSplitPaneDivider)) {
if (comp.isVisible() && !anyVisible) {
anyVisible = true;
}
continue;
}
boolean visiblePrev = i - 1 >= 0 && getComponent(i - 1).isVisible();
boolean visibleNext = i + 1 < getComponentCount() && getComponent(i + 1).isVisible();
if (visiblePrev && visibleNext) {
comp.setVisible(true);
}
else if (!visiblePrev && !visibleNext) {
comp.setVisible(false);
}
else if (visiblePrev && !visibleNext) {
comp.setVisible(false);
anyPrevVisible = true;
}
else /*if (visibleNext && !visiblePrev)*/ {
if (anyPrevVisible) {
comp.setVisible(true);
anyPrevVisible = false;
}
else {
comp.setVisible(false);
}
}
}
setVisible(anyVisible);
}
}
protected JideSplitPaneDivider createSplitPaneDivider() {
return new JideSplitPaneDivider(this);
}
/**
* Get previous divider's, if any, location from current divider. If there is no previous divider, return 0.
*
* @param divider the divider
* @param ignoreVisibility true to not check if the pane is visible.
* @param reversed from left to right or reversed.
* @return the location of previous divider if any
*/
protected int getPreviousDividerLocation(JideSplitPaneDivider divider, boolean ignoreVisibility, boolean reversed) {
int index = indexOfDivider(divider);
int location = -1;
if (reversed) {
if (((index + 1) * 2) + 1 <= getComponentCount()) {
for (int i = index + 1; (i * 2) + 1 < getComponentCount(); i++) {
if (ignoreVisibility || getDividerAt(i).isVisible()) {
if (_orientation == HORIZONTAL_SPLIT) {
location = getDividerAt(i).getBounds().x;
}
else {
location = getDividerAt(i).getBounds().y;
}
break;
}
}
}
}
else {
if (index > 0) {
for (int i = index - 1; i >= 0; i--) {
if (ignoreVisibility || getDividerAt(i).isVisible()) {
if (_orientation == HORIZONTAL_SPLIT) {
location = getDividerAt(i).getBounds().x;
}
else {
location = getDividerAt(i).getBounds().y;
}
break;
}
}
}
}
if (location != -1) {
return location + getDividerSize();
}
return 0;
}
/**
* Get previous divider's, if any, location from current divider. If there is no previous divider, return 0.
*
* @param divider the divider
* @param ignoreVisibility true to not check if the pane is visible.
* @param reversed from left to right or reversed.
* @return the location of next divider if any
*/
public int getNextDividerLocation(JideSplitPaneDivider divider, boolean ignoreVisibility, boolean reversed) {
int index = indexOfDivider(divider);
int location = -1;
if (!reversed) {
if (((index + 1) * 2) + 1 <= getComponentCount()) {
for (int i = index + 1; (i * 2) + 1 < getComponentCount(); i++) {
if (ignoreVisibility || getDividerAt(i).isVisible()) {
if (_orientation == HORIZONTAL_SPLIT) {
location = getDividerAt(i).getBounds().x;
}
else {
location = getDividerAt(i).getBounds().y;
}
break;
}
}
}
}
else {
if (index > 0) {
for (int i = index - 1; i >= 0; i--) {
if (ignoreVisibility || getDividerAt(i).isVisible()) {
if (_orientation == HORIZONTAL_SPLIT) {
location = getDividerAt(i).getBounds().x;
}
else {
location = getDividerAt(i).getBounds().y;
}
break;
}
}
}
}
if (location != -1) {
return location - getDividerSize();
}
return getOrientation() == HORIZONTAL_SPLIT ? getWidth() - getDividerSize() : getHeight() - getDividerSize();
}
/**
* Checks if the gripper is visible.
*
* @return true if gripper is visible
*/
public boolean isShowGripper() {
return _showGripper;
}
/**
* Sets the visibility of gripper.
*
* @param showGripper true to show gripper
*/
public void setShowGripper(boolean showGripper) {
boolean oldShowGripper = _showGripper;
if (oldShowGripper != showGripper) {
_showGripper = showGripper;
firePropertyChange(GRIPPER_PROPERTY, oldShowGripper, _showGripper);
}
}
/**
* Causes this container to lay out its components. Most programs should not call this method directly, but should
* invoke the <code>validate</code> method instead.
*
* @see LayoutManager#layoutContainer
* @see #setLayout
* @see #validate
* @since JDK1.1
*/
@Override
public void doLayout() {
if (removeExtraDividers()) {
((JideSplitPaneLayout) getLayout()).invalidateLayout(this);
}
super.doLayout();
}
/**
* Determines whether the JSplitPane is set to use a continuous layout.
*
* @return true or false.
*/
public boolean isContinuousLayout() {
return _continuousLayout;
}
/**
* Turn continuous layout on/off.
*
* @param continuousLayout true or false.
*/
public void setContinuousLayout(boolean continuousLayout) {
boolean oldCD = _continuousLayout;
_continuousLayout = continuousLayout;
firePropertyChange(CONTINUOUS_LAYOUT_PROPERTY, oldCD, continuousLayout);
}
/**
* Gets the AccessibleContext associated with this JideSplitPane. For split panes, the AccessibleContext takes the
* form of an AccessibleJideSplitPane. A new AccessibleJideSplitPane instance is created if necessary.
*
* @return an AccessibleJideSplitPane that serves as the AccessibleContext of this JideSplitPane
*/
@Override
public AccessibleContext getAccessibleContext() {
if (accessibleContext == null) {
accessibleContext = new AccessibleJideSplitPane();
}
return accessibleContext;
}
/**
* Get the flag indicating if dragging the divider could resize the panes.
* <p/>
* By default, the value is true for JideSplitPane. You could set it to false if you don't like it.
*
* @return the flag.
*/
public boolean isDragResizable() {
return _dragResizable;
}
/**
* Set the flag indicating if dragging the divider could resize the panes.
*
* @param dragResizable the flag
*/
public void setDragResizable(boolean dragResizable) {
_dragResizable = dragResizable;
}
/**
* This class implements accessibility support for the <code>JideSplitPane</code> class. It provides an
* implementation of the Java Accessibility API appropriate to split pane user-interface elements.
*/
protected class AccessibleJideSplitPane extends AccessibleJComponent {
private static final long serialVersionUID = -6167624875135108683L;
/**
* Gets the state set of this object.
*
* @return an instance of AccessibleState containing the current state of the object
*
* @see javax.accessibility.AccessibleState
*/
@Override
public AccessibleStateSet getAccessibleStateSet() {
AccessibleStateSet states = super.getAccessibleStateSet();
if (getOrientation() == VERTICAL_SPLIT) {
states.add(AccessibleState.VERTICAL);
}
else {
states.add(AccessibleState.HORIZONTAL);
}
return states;
}
/**
* Gets the role of this object.
*
* @return an instance of AccessibleRole describing the role of the object
*
* @see AccessibleRole
*/
@Override
public AccessibleRole getAccessibleRole() {
return AccessibleRole.SPLIT_PANE;
}
} // inner class AccessibleJideSplitPane
/**
* @return true if the heavyweight component is enabled.
*/
public boolean isHeavyweightComponentEnabled() {
return _heavyweightComponentEnabled;
}
/**
* Enables heavyweight components. The difference is the divider. If true, the divider will be heavyweight divider.
* Otherwise it will use lightweight divider.
*
* @param heavyweightComponentEnabled true to enable the usage of heavyweight components.
*/
public void setHeavyweightComponentEnabled(boolean heavyweightComponentEnabled) {
boolean old = _heavyweightComponentEnabled;
if (_heavyweightComponentEnabled != heavyweightComponentEnabled) {
_heavyweightComponentEnabled = heavyweightComponentEnabled;
firePropertyChange(PROPERTY_HEAVYWEIGHT_COMPONENT_ENABLED, old, _heavyweightComponentEnabled);
}
}
/*
* Added on 05/14/2008 in response to http://www.jidesoft.com/forum/viewtopic.php?p=26074#26074,
* http://www.jidesoft.com/forum/viewtopic.php?p=5148#5148 and
* http://www.jidesoft.com/forum/viewtopic.php?p=23403#23403.
*
* The addition below provides the option of adding a one-touch button which is capable of expanding/collapsing the
* split pane (in one click of the mouse).
*
* @see #setOneTouchExpandable(boolean)
*/
/**
* Bound property for <code>oneTouchExpandable</code>.
*
* @see #setOneTouchExpandable
*/
public static final String ONE_TOUCH_EXPANDABLE_PROPERTY = "oneTouchExpandable";
/**
* Flag indicating whether the SplitPane's divider should be one-touch expandable/collapsible. The default value of
* this property is <code>false</code>
*
* @see #setOneTouchExpandable
* @see #isOneTouchExpandable
*/
private boolean _oneTouchExpandable = false;
/**
* The default width/height of the divider (when horizontally/vertically split respectively).
*/
private int oneTouchExpandableDividerSize = 8;
/**
* The image displayed on the left one-touch button. If no image is supplied, a default triangle will be painted
* onto the button.
*
* @see #setLeftOneTouchButtonImageIcon
*/
private ImageIcon _leftOneTouchButtonImageIcon = null;
/**
* The image displayed on the right one-touch button. If no image is supplied, a default triangle will be painted
* onto the button.
*
* @see #setRightOneTouchButtonImageIcon
*/
private ImageIcon _rightOneTouchButtonImageIcon = null;
/**
* Sets the value of the <code>oneTouchExpandable</code> property. If <code>true</code>, the <code>JSplitPane</code>
* will display a UI widget on the divider to quickly expand/collapse the divider.<p> </p> The default value of this
* property is <code>false</code>.<p> </p> Please note: Some look and feels might not support one-touch expanding;
* they will ignore this property.
*
* @param oneTouchExpandable <code>true</code> to specify that the split pane should provide a collapse/expand
* widget
* @see #isOneTouchExpandable
*/
public void setOneTouchExpandable(boolean oneTouchExpandable) {
boolean oldValue = _oneTouchExpandable;
if (oldValue != oneTouchExpandable) {
_oneTouchExpandable = oneTouchExpandable;
/*
* We need to widen/shrink the dividers width so that we can display/remove the one-touch buttons.
*/
LayoutManager layoutManager = getLayout();
if (layoutManager instanceof JideBoxLayout) {
((JideBoxLayout) layoutManager).setResetWhenInvalidate(true);
}
if (oneTouchExpandable) {
setDividerSize(oneTouchExpandableDividerSize);
}
else {
setDividerSize(UIDefaultsLookup.getInt("JideSplitPane.dividerSize"));
}
/*
* We now fire a bound property so each divider listening can set up its own one-touch buttons.
*/
firePropertyChange(ONE_TOUCH_EXPANDABLE_PROPERTY, oldValue, _oneTouchExpandable);
revalidate();
repaint();
if (layoutManager instanceof JideBoxLayout) {
((JideBoxLayout) layoutManager).setResetWhenInvalidate(false);
}
}
}
/**
* Returns whether one-touch expand/collapse is on.
*
* @return the value of the <code>oneTouchExpandable</code> property
*
* @see #setOneTouchExpandable
*/
public boolean isOneTouchExpandable() {
return _oneTouchExpandable;
}
/**
* Sets the left button's image icon. By default, the button has a width of 5 pixels and a height of 10 pixel in
* HORIZONTAL_SPLIT mode (and a width of 10 pixels and a height of 5 pixel in VERTICAL_SPLIT mode) -- this should be
* considered when assigning its imageIcon.
*
* @param leftButtonImageIcon the image to be displayed on the left one-touch button
*/
public void setLeftOneTouchButtonImageIcon(ImageIcon leftButtonImageIcon) {
_leftOneTouchButtonImageIcon = leftButtonImageIcon;
}
/**
* Gets the left button's image icon.
*
* @return the imageIcon used displayed on the left one-touch button
*/
public ImageIcon getLeftOneTouchButtonImageIcon() {
return _leftOneTouchButtonImageIcon;
}
/**
* Sets the right button's image icon. By default, the button has a width of 5 pixels and a height of 10 pixel in
* HORIZONTAL_SPLIT mode (and a width of 10 pixels and a height of 5 pixel in VERTICAL_SPLIT mode) -- this should be
* considered when assigning its imageIcon.
*
* @param rightButtonImageIcon the image to be displayed on the right one-touch button
*/
public void setRightOneTouchButtonImageIcon(ImageIcon rightButtonImageIcon) {
_rightOneTouchButtonImageIcon = rightButtonImageIcon;
}
/**
* Gets the right button's image icon.
*
* @return the imageIcon used displayed on the left one-touch button
*/
public ImageIcon getRightOneTouchButtonImageIcon() {
return _rightOneTouchButtonImageIcon;
}
/**
* Sets the divider locations.
*
* @param locations the new divider locations.
*/
public void setDividerLocations(int[] locations) {
for (int i = 0; i < locations.length; i++) {
int location = locations[i];
setDividerLocation(i, location);
}
}
/**
* Gets the divider locations.
*
* @return the divider locations.
*/
public int[] getDividerLocations() {
int count = getPaneCount();
if (getPaneCount() == 0) {
return new int[0];
}
int[] locations = new int[count - 1];
for (int i = 0; i < count - 1; i++) {
locations[i] = getDividerLocation(i);
}
return locations;
}
private class JideSplitPaneContour extends Contour {
public JideSplitPaneContour() {
super();
}
public JideSplitPaneContour(int tabHeight) {
super(tabHeight);
}
}
private class JideSplitPaneHeavyweightWrapper extends HeavyweightWrapper {
public JideSplitPaneHeavyweightWrapper(Component component) {
super(component);
}
}
}
| false | false | null | null |
diff --git a/src/optional/com/tacitknowledge/util/migration/jdbc/atg/ATGDistributedAutoPatchService.java b/src/optional/com/tacitknowledge/util/migration/jdbc/atg/ATGDistributedAutoPatchService.java
index ceab859..76b010f 100644
--- a/src/optional/com/tacitknowledge/util/migration/jdbc/atg/ATGDistributedAutoPatchService.java
+++ b/src/optional/com/tacitknowledge/util/migration/jdbc/atg/ATGDistributedAutoPatchService.java
@@ -1,138 +1,138 @@
/*
* Copyright 2006 Tacit Knowledge LLC
*
* Licensed under the Tacit Knowledge Open 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://www.tacitknowledge.com/licenses-1.0.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.tacitknowledge.util.migration.jdbc.atg;
import com.tacitknowledge.util.migration.MigrationException;
import com.tacitknowledge.util.migration.jdbc.DistributedAutoPatchService;
import atg.nucleus.Configuration;
import atg.nucleus.Nucleus;
import atg.nucleus.Service;
import atg.nucleus.ServiceEvent;
import atg.nucleus.ServiceException;
/**
* Automatically applies database DDL and SQL patches to all schemas on server startup.
*
* @author Mike Hardy ([email protected])
- * @url http://autopatch.sf.net/
+ * @link http://autopatch.sf.net/
*/
public class ATGDistributedAutoPatchService extends DistributedAutoPatchService implements Service
{
/** Our Nucleus */
private Nucleus nucleus = null;
/** The Configuration we have */
private Configuration configuration = null;
/** Whether we are running or not */
private boolean running = false;
/**
* Handle patching the database on startup
*
* @see atg.nucleus.ServiceListener#startService(atg.nucleus.ServiceEvent)
*/
public void startService(ServiceEvent se) throws ServiceException
{
if ((se.getService() == this) && (isRunning() == false))
{
setRunning(true);
setNucleus(se.getNucleus());
setServiceConfiguration(se.getServiceConfiguration());
doStartService();
}
}
/**
* @see com.tacitknowledge.util.migration.jdbc.AutoPatchService#patch()
*/
public void doStartService() throws ServiceException
{
try
{
patch();
}
catch (MigrationException me)
{
throw new ServiceException("There was a problem patching the database", me);
}
}
/**
* Resets the "running" state to false
*
* @see atg.nucleus.Service#stopService()
*/
public void stopService() throws ServiceException
{
setRunning(false);
}
/**
* Get the service configuration used to start us
* @return Configuration
*/
public Configuration getServiceConfiguration()
{
return configuration;
}
/**
* Set the service configuration the Nucleus is using for us
* @param configuration
*/
public void setServiceConfiguration(Configuration configuration)
{
this.configuration = configuration;
}
/**
* Get the Nucleus that started us
* @return Nucleus
*/
public Nucleus getNucleus()
{
return nucleus;
}
/**
* Set the Nucleus that started us
* @param nucleus
*/
public void setNucleus(Nucleus nucleus)
{
this.nucleus = nucleus;
}
/**
* Return boolean true if we are started
* @return true if we are started and running
*/
public boolean isRunning()
{
return running;
}
/**
* Set whether we are running
* @param running
*/
public void setRunning(boolean running)
{
this.running = running;
}
}
| true | false | null | null |
diff --git a/src/Runner/WorkflowManager.java b/src/Runner/WorkflowManager.java
index 4c0086a..8f8f140 100644
--- a/src/Runner/WorkflowManager.java
+++ b/src/Runner/WorkflowManager.java
@@ -1,61 +1,61 @@
package runner;
import channels.SocketChannel;
import controllers.*;
import controllers.client.ClientDetailsController;
import controllers.client.JoinGameController;
import controllers.client.WelcomeController;
import controllers.server.WaitForPlayersController;
import screens.*;
import screens.client.ClientDetailsScreen;
import screens.client.JoinGameScreen;
import screens.client.WelcomeScreen;
import screens.controls.MainFrame;
import screens.server.WaitForPlayersScreen;
public class WorkflowManager implements Workflow {
private MainFrame mainFrame;
public void start() {
mainFrame = new MainFrame();
HomeController controller =new HomeController(this);
controller.bind(new HomeScreen(mainFrame,controller));
controller.start();
}
@Override
public void startServer() {
WaitForPlayersController controller = new WaitForPlayersController(this);
controller.bind(new WaitForPlayersScreen(mainFrame,controller));
controller.start();
}
@Override
public void getClientDetails() {
- ClientDetailsController controller = new ClientDetailsController(this, new ConnectionFactory());
+ ClientDetailsController controller = new ClientDetailsController(this, new connectionFactory());
controller.bind(new ClientDetailsScreen(mainFrame,controller));
}
@Override
public void startGame() {
WelcomeController controller = new WelcomeController(this);
controller.bind(new WelcomeScreen(mainFrame,controller));
controller.start();
}
@Override
public void goBackToHome() {
HomeController controller = new HomeController(this);
controller.bind(new HomeScreen(mainFrame,controller));
controller.start();
}
@Override
public void connectedToServer(SocketChannel channel, String serverName, String playerName) {
JoinGameController controller = new JoinGameController(this,channel,serverName,playerName);
controller.bind(new JoinGameScreen(mainFrame,controller));
controller.start();
}
}
diff --git a/src/controllers/client/ClientDetailsController.java b/src/controllers/client/ClientDetailsController.java
index ba32375..55d2850 100644
--- a/src/controllers/client/ClientDetailsController.java
+++ b/src/controllers/client/ClientDetailsController.java
@@ -1,58 +1,54 @@
package controllers.client;
import channels.ConnectionListener;
import channels.SocketChannel;
-import channels.SocketChannelListener;
-import channels.messages.ChannelMessage;
-import controllers.ConnectionFactory;
import controllers.Workflow;
import view.ClientDetailsView;
import javax.swing.*;
-import java.io.IOException;
public class ClientDetailsController implements ConnectionListener {
private Workflow workflow;
private ClientDetailsView view;
- private ConnectionFactory connectionFactory;
+ private controllers.connectionFactory connectionFactory;
- public ClientDetailsController(Workflow workflow, ConnectionFactory connectionFactory) {
+ public ClientDetailsController(Workflow workflow, controllers.connectionFactory connectionFactory) {
this.workflow = workflow;
this.connectionFactory = connectionFactory;
}
public void bind(ClientDetailsView view) {
this.view = view;
}
public void connectToServer() {
connectionFactory.connectToServer(view.getServerName(), 1254, this);
}
@Override
public void onConnectionEstablished(SocketChannel channel) {
if (!view.getServerName().equals(""))
workflow.connectedToServer(channel, view.getServerName(), view.getPlayerName());
else
serverNotFound();
}
@Override
public void onConnectionFailed(String serverAddress, int serverPort, Exception e) {
serverNotFound();
}
private void serverNotFound() {
String connectedMessage = view.getServerName() + " : Server Not Found";
JOptionPane.showConfirmDialog(null, connectedMessage, "", JOptionPane.DEFAULT_OPTION);
workflow.getClientDetails();
}
public void disconnect() {
workflow.goBackToHome();
}
}
diff --git a/src/controllers/connectionFactory.java b/src/controllers/connectionFactory.java
index eec2c69..866a18f 100644
--- a/src/controllers/connectionFactory.java
+++ b/src/controllers/connectionFactory.java
@@ -1,10 +1,10 @@
package controllers;
import channels.ConnectionListener;
import channels.SocketChannel;
-public class ConnectionFactory {
+public class connectionFactory {
public void connectToServer(String serverName, int serverPort, ConnectionListener listener) {
SocketChannel.connectTo(serverName, serverPort, listener);
}
}
diff --git a/test/controllers/client/ClientDetailsControllerTest.java b/test/controllers/client/ClientDetailsControllerTest.java
index 1f05aa7..29954c5 100644
--- a/test/controllers/client/ClientDetailsControllerTest.java
+++ b/test/controllers/client/ClientDetailsControllerTest.java
@@ -1,22 +1,22 @@
package controllers.client;
-import controllers.ConnectionFactory;
+import controllers.connectionFactory;
import controllers.Workflow;
import org.junit.Test;
import view.ClientDetailsView;
import static org.mockito.Mockito.*;
public class ClientDetailsControllerTest {
@Test
public void connect_to_server_on_localhost_is_successful() {
Workflow workflow = mock(Workflow.class);
ClientDetailsView view = mock(ClientDetailsView.class);
- ConnectionFactory connectionFactory = mock(ConnectionFactory.class);
+ connectionFactory connectionFactory = mock(controllers.connectionFactory.class);
ClientDetailsController controller = new ClientDetailsController(workflow,connectionFactory);
controller.bind(view);
when(view.getServerName()).thenReturn("localhost");
controller.connectToServer();
verify(connectionFactory).connectToServer("localhost",1254,controller);
}
}
| false | false | null | null |
diff --git a/dspace-xmlui/dspace-xmlui-api/src/main/java/org/dspace/app/xmlui/aspect/artifactbrowser/ConfigurableBrowse.java b/dspace-xmlui/dspace-xmlui-api/src/main/java/org/dspace/app/xmlui/aspect/artifactbrowser/ConfigurableBrowse.java
index 614675fc3..c5d9e276c 100644
--- a/dspace-xmlui/dspace-xmlui-api/src/main/java/org/dspace/app/xmlui/aspect/artifactbrowser/ConfigurableBrowse.java
+++ b/dspace-xmlui/dspace-xmlui-api/src/main/java/org/dspace/app/xmlui/aspect/artifactbrowser/ConfigurableBrowse.java
@@ -1,980 +1,980 @@
/*
* ConfigurableBrowse.java
*
* Version: $Revision: 1.0 $
*
* Date: $Date: 2007/08/28 10:00:00 $
*
* Copyright (c) 2002-2005, Hewlett-Packard Company and Massachusetts
* Institute of Technology. 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 the Hewlett-Packard Company nor the name of the
* Massachusetts Institute of Technology nor the names of their
* 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
* HOLDERS 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.dspace.app.xmlui.aspect.artifactbrowser;
import java.io.IOException;
import java.io.Serializable;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import org.apache.cocoon.caching.CacheableProcessingComponent;
import org.apache.cocoon.environment.ObjectModelHelper;
import org.apache.cocoon.environment.Request;
import org.apache.cocoon.util.HashUtil;
import org.apache.excalibur.source.SourceValidity;
import org.dspace.app.xmlui.cocoon.AbstractDSpaceTransformer;
import org.dspace.app.xmlui.utils.ContextUtil;
import org.dspace.app.xmlui.utils.DSpaceValidity;
import org.dspace.app.xmlui.utils.HandleUtil;
import org.dspace.app.xmlui.utils.RequestUtils;
import org.dspace.app.xmlui.utils.UIException;
import org.dspace.app.xmlui.wing.Message;
import org.dspace.app.xmlui.wing.WingException;
import org.dspace.app.xmlui.wing.element.Body;
import org.dspace.app.xmlui.wing.element.Cell;
import org.dspace.app.xmlui.wing.element.Division;
import org.dspace.app.xmlui.wing.element.List;
import org.dspace.app.xmlui.wing.element.PageMeta;
import org.dspace.app.xmlui.wing.element.Para;
import org.dspace.app.xmlui.wing.element.ReferenceSet;
import org.dspace.app.xmlui.wing.element.Row;
import org.dspace.app.xmlui.wing.element.Select;
import org.dspace.app.xmlui.wing.element.Table;
import org.dspace.authorize.AuthorizeException;
import org.dspace.browse.BrowseEngine;
import org.dspace.browse.BrowseException;
import org.dspace.browse.BrowseIndex;
import org.dspace.browse.BrowseInfo;
import org.dspace.browse.BrowseItem;
import org.dspace.browse.BrowserScope;
import org.dspace.sort.SortOption;
import org.dspace.sort.SortException;
import org.dspace.content.Collection;
import org.dspace.content.Community;
import org.dspace.content.DCDate;
import org.dspace.content.DSpaceObject;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Context;
import org.xml.sax.SAXException;
/**
* Implements all the browse functionality (browse by title, subject, authors,
* etc.) The types of browse available are configurable by the implementor. See
* dspace.cfg and documentation for instructions on how to configure.
*
* @author Graham Triggs
*/
public class ConfigurableBrowse extends AbstractDSpaceTransformer implements
CacheableProcessingComponent
{
/**
* Static Messages for common text
*/
private final static Message T_dspace_home = message("xmlui.general.dspace_home");
private final static Message T_go = message("xmlui.general.go");
private final static Message T_update = message("xmlui.general.update");
private final static Message T_choose_month = message("xmlui.ArtifactBrowser.ConfigurableBrowse.general.choose_month");
private final static Message T_choose_year = message("xmlui.ArtifactBrowser.ConfigurableBrowse.general.choose_year");
private final static Message T_jump_year = message("xmlui.ArtifactBrowser.ConfigurableBrowse.general.jump_year");
private final static Message T_jump_year_help = message("xmlui.ArtifactBrowser.ConfigurableBrowse.general.jump_year_help");
private final static Message T_jump_select = message("xmlui.ArtifactBrowser.ConfigurableBrowse.general.jump_select");
private final static Message T_starts_with = message("xmlui.ArtifactBrowser.ConfigurableBrowse.general.starts_with");
private final static Message T_starts_with_help = message("xmlui.ArtifactBrowser.ConfigurableBrowse.general.starts_with_help");
private final static Message T_sort_by = message("xmlui.ArtifactBrowser.ConfigurableBrowse.general.sort_by");
private final static Message T_order = message("xmlui.ArtifactBrowser.ConfigurableBrowse.general.order");
private final static Message T_rpp = message("xmlui.ArtifactBrowser.ConfigurableBrowse.general.rpp");
private final static Message T_etal = message("xmlui.ArtifactBrowser.ConfigurableBrowse.general.etal");
private final static Message T_etal_all = message("xmlui.ArtifactBrowser.ConfigurableBrowse.etal.all");
private final static Message T_order_asc = message("xmlui.ArtifactBrowser.ConfigurableBrowse.order.asc");
private final static Message T_order_desc = message("xmlui.ArtifactBrowser.ConfigurableBrowse.order.desc");
private final static String BROWSE_URL_BASE = "browse";
/**
* These variables dictate when the drop down list of years is to break from
* 1 year increments, to 5 year increments, to 10 year increments, and
* finally to stop.
*/
private static final int ONE_YEAR_LIMIT = 10;
private static final int FIVE_YEAR_LIMIT = 30;
private static final int TEN_YEAR_LIMIT = 100;
/** The options for results per page */
private static final int[] RESULTS_PER_PAGE_PROGRESSION = {5,10,20,40,60,80,100};
/** Cached validity object */
private SourceValidity validity;
/** Cached UI parameters, results and messages */
private BrowseParams userParams;
private BrowseInfo browseInfo;
private Message titleMessage = null;
private Message trailMessage = null;
public Serializable getKey()
{
try
{
BrowseParams params = getUserParams();
String key = params.getKey();
if (key != null)
{
DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
if (dso != null)
key += "-" + dso.getHandle();
return HashUtil.hash(key);
}
}
catch (Exception e)
{
// Ignore all errors and just don't cache.
}
return "0";
}
public SourceValidity getValidity()
{
if (validity == null)
{
try
{
DSpaceValidity validity = new DSpaceValidity();
DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
if (dso != null)
validity.add(dso);
BrowseInfo info = getBrowseInfo();
// Are we browsing items, or unique metadata?
if (isItemBrowse(info))
{
// Add the browse items to the validity
for (BrowseItem item : (java.util.List<BrowseItem>) info.getResults())
{
validity.add(item);
}
}
else
{
// Add the metadata to the validity
for (String singleEntry : browseInfo.getStringResults())
{
validity.add(singleEntry);
}
}
}
catch (Exception e)
{
// Just ignore all errors and return an invalid cache.
}
}
return this.validity;
}
/**
* Add Page metadata.
*/
public void addPageMeta(PageMeta pageMeta) throws SAXException, WingException, UIException,
SQLException, IOException, AuthorizeException
{
BrowseInfo info = getBrowseInfo();
// Get the name of the index
String type = info.getBrowseIndex().getName();
pageMeta.addMetadata("title").addContent(getTitleMessage(info));
DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
pageMeta.addTrailLink(contextPath + "/", T_dspace_home);
if (dso != null)
HandleUtil.buildHandleTrail(dso, pageMeta, contextPath);
pageMeta.addTrail().addContent(getTrailMessage(info));
}
/**
* Add the browse-title division.
*/
public void addBody(Body body) throws SAXException, WingException, UIException, SQLException,
IOException, AuthorizeException
{
BrowseParams params = getUserParams();
BrowseInfo info = getBrowseInfo();
String type = info.getBrowseIndex().getName();
// Build the DRI Body
Division div = body.addDivision("browse-by-" + type, "primary");
div.setHead(getTitleMessage(info));
// Build the internal navigation (jump lists)
addBrowseJumpNavigation(div, info, params);
// Build the sort and display controls
addBrowseControls(div, info, params);
// This div will hold the browsing results
Division results = div.addDivision("browse-by-" + type + "-results", "primary");
// Add the pagination
//results.setSimplePagination(itemsTotal, firstItemIndex, lastItemIndex, previousPage, nextPage)
results.setSimplePagination(info.getTotal(), browseInfo.getOverallPosition() + 1,
browseInfo.getOverallPosition() + browseInfo.getResultCount(), getPreviousPageURL(
params, info), getNextPageURL(params, info));
// Reference all the browsed items
ReferenceSet referenceSet = results.addReferenceSet("browse-by-" + type,
ReferenceSet.TYPE_SUMMARY_LIST, type, null);
// Are we browsing items, or unique metadata?
if (isItemBrowse(info))
{
// Add the items to the browse results
for (BrowseItem item : (java.util.List<BrowseItem>) info.getResults())
{
referenceSet.addReference(item);
}
}
else // browsing a list of unique metadata entries
{
// Create a table for the results
Table singleTable = results.addTable("browse-by-" + type + "-results",
browseInfo.getResultCount() + 1, 1);
// Add the column heading
singleTable.addRow(Row.ROLE_HEADER).addCell().addContent(
message("xmlui.ArtifactBrowser.ConfigurableBrowse." + type + ".column_heading"));
// Iterate each result
for (String singleEntry : browseInfo.getStringResults())
{
// Create a Map of the query parameters for the link
Map<String, String> queryParams = new HashMap<String, String>();
queryParams.put(BrowseParams.TYPE, URLEncode(type));
queryParams.put(BrowseParams.FILTER_VALUE, URLEncode(singleEntry));
// Create an entry in the table, and a linked entry
Cell cell = singleTable.addRow().addCell();
cell.addXref(super.generateURL(BROWSE_URL_BASE, queryParams), singleEntry);
}
}
}
/**
* Recycle
*/
public void recycle()
{
this.validity = null;
this.userParams = null;
this.browseInfo = null;
this.titleMessage = null;
this.trailMessage = null;
super.recycle();
}
/**
* Makes the jump-list navigation for the results
*
* @param div
* @param info
* @param params
* @throws WingException
*/
private void addBrowseJumpNavigation(Division div, BrowseInfo info, BrowseParams params)
throws WingException
{
// Get the name of the index
String type = info.getBrowseIndex().getName();
// Prepare a Map of query parameters required for all links
Map<String, String> queryParams = new HashMap<String, String>();
queryParams.putAll(params.getCommonParameters());
queryParams.putAll(params.getControlParameters());
// Navigation aid (really this is a poor version of pagination)
Division jump = div.addInteractiveDivision("browse-navigation", BROWSE_URL_BASE,
Division.METHOD_POST, "secondary navigation");
// Add all the query parameters as hidden fields on the form
for (String key : queryParams.keySet())
jump.addHidden(key).setValue(queryParams.get(key));
// If this is a date based browse, render the date navigation
if (isSortedByDate(info))
{
Para jumpForm = jump.addPara();
// Create a select list to choose a month
jumpForm.addContent(T_jump_select);
Select month = jumpForm.addSelect(BrowseParams.MONTH);
month.addOption(false, "-1", T_choose_month);
for (int i = 1; i <= 12; i++)
{
month.addOption(false, String.valueOf(i), DCDate.getMonthName(i, Locale
.getDefault()));
}
// Create a select list to choose a year
Select year = jumpForm.addSelect(BrowseParams.YEAR);
year.addOption(false, "-1", T_choose_year);
int currentYear = DCDate.getCurrent().getYear();
int i = currentYear;
// Calculate where to move from 1, 5 to 10 year jumps
int oneYearBreak = ((currentYear - ONE_YEAR_LIMIT) / 5) * 5;
int fiveYearBreak = ((currentYear - FIVE_YEAR_LIMIT) / 10) * 10;
int tenYearBreak = (currentYear - TEN_YEAR_LIMIT);
do
{
year.addOption(false, String.valueOf(i), String.valueOf(i));
if (i <= fiveYearBreak)
i -= 10;
else if (i <= oneYearBreak)
i -= 5;
else
i--;
}
while (i > tenYearBreak);
// Create a free text entry box for the year
jumpForm = jump.addPara();
jumpForm.addContent(T_jump_year);
jumpForm.addText("start_with").setHelp(T_jump_year_help);
jumpForm.addButton("submit").setValue(T_go);
}
else
{
// Create a clickable list of the alphabet
List jumpList = jump.addList("jump-list", List.TYPE_SIMPLE, "alphabet");
Map<String, String> zeroQuery = new HashMap<String, String>(queryParams);
zeroQuery.put(BrowseParams.STARTS_WITH, "0");
jumpList.addItemXref(super.generateURL(BROWSE_URL_BASE, zeroQuery), "0-9");
for (char c = 'A'; c <= 'Z'; c++)
{
Map<String, String> cQuery = new HashMap<String, String>(queryParams);
cQuery.put(BrowseParams.STARTS_WITH, Character.toString(c));
jumpList.addItemXref(super.generateURL(BROWSE_URL_BASE, cQuery), Character
.toString(c));
}
// Create a free text field for the initial characters
Para jumpForm = jump.addPara();
jumpForm.addContent(T_starts_with);
jumpForm.addText(BrowseParams.STARTS_WITH).setHelp(T_starts_with_help);
jumpForm.addButton("submit").setValue(T_go);
}
}
/**
* Add the controls to changing sorting and display options.
*
* @param div
* @param info
* @param params
* @throws WingException
*/
private void addBrowseControls(Division div, BrowseInfo info, BrowseParams params)
throws WingException
{
// Prepare a Map of query parameters required for all links
Map<String, String> queryParams = new HashMap<String, String>();
queryParams.putAll(params.getCommonParameters());
Division controls = div.addInteractiveDivision("browse-controls", BROWSE_URL_BASE,
Division.METHOD_POST, "browse controls");
// Add all the query parameters as hidden fields on the form
for (String key : queryParams.keySet())
controls.addHidden(key).setValue(queryParams.get(key));
Para controlsForm = controls.addPara();
// If we are browsing a list of items
if (isItemBrowse(info)) // && info.isSecondLevel()
{
try
{
// Create a drop down of the different sort columns available
Set<SortOption> sortOptions = SortOption.getSortOptions();
// Only generate the list if we have multiple columns
if (sortOptions.size() > 1)
{
controlsForm.addContent(T_sort_by);
Select sortSelect = controlsForm.addSelect(BrowseParams.SORT_BY);
for (SortOption so : sortOptions)
{
if (so.isVisible())
{
sortSelect.addOption(so.equals(info.getSortOption()), so.getNumber(),
message("xmlui.ArtifactBrowser.ConfigurableBrowse.sort_by." + so.getName()));
}
}
}
}
catch (SortException se)
{
throw new WingException("Unable to get sort options", se);
}
}
// Create a control to changing ascending / descending order
controlsForm.addContent(T_order);
Select orderSelect = controlsForm.addSelect(BrowseParams.ORDER);
orderSelect.addOption("ASC".equals(params.scope.getOrder()), "ASC", T_order_asc);
orderSelect.addOption("DESC".equals(params.scope.getOrder()), "DESC", T_order_desc);
// Create a control for the number of records to display
controlsForm.addContent(T_rpp);
Select rppSelect = controlsForm.addSelect(BrowseParams.RESULTS_PER_PAGE);
for (int i : RESULTS_PER_PAGE_PROGRESSION)
{
rppSelect.addOption((i == info.getResultsPerPage()), i, Integer.toString(i));
}
// Create a control for the number of authors per item to display
// FIXME This is currently disabled, as the supporting functionality
// is not currently present in xmlui
//if (isItemBrowse(info))
//{
// controlsForm.addContent(T_etal);
// Select etalSelect = controlsForm.addSelect(BrowseParams.ETAL);
//
// etalSelect.addOption((info.getEtAl() < 0), 0, T_etal_all);
// etalSelect.addOption(1 == info.getEtAl(), 1, Integer.toString(1));
//
// for (int i = 5; i <= 50; i += 5)
// {
// etalSelect.addOption(i == info.getEtAl(), i, Integer.toString(i));
// }
//}
controlsForm.addButton("update").setValue(T_update);
}
/**
* The URL query string of of the previous page.
*
* Note: the query string does not start with a "?" or "&" those need to be
* added as appropriate by the caller.
*/
private String getPreviousPageURL(BrowseParams params, BrowseInfo info) throws SQLException,
UIException
{
// Don't create a previous page link if this is the first page
if (info.isFirst())
return null;
Map<String, String> parameters = new HashMap<String, String>();
parameters.putAll(params.getCommonParameters());
parameters.putAll(params.getControlParameters());
if (info.hasPrevPage())
{
parameters.put(BrowseParams.OFFSET, URLEncode(String.valueOf(info.getPrevOffset())));
}
return super.generateURL(BROWSE_URL_BASE, parameters);
}
/**
* The URL query string of of the next page.
*
* Note: the query string does not start with a "?" or "&" those need to be
* added as appropriate by the caller.
*/
private String getNextPageURL(BrowseParams params, BrowseInfo info) throws SQLException,
UIException
{
// Don't create a next page link if this is the last page
if (info.isLast())
return null;
Map<String, String> parameters = new HashMap<String, String>();
parameters.putAll(params.getCommonParameters());
parameters.putAll(params.getControlParameters());
if (info.hasNextPage())
{
parameters.put(BrowseParams.OFFSET, URLEncode(String.valueOf(info.getNextOffset())));
}
return super.generateURL(BROWSE_URL_BASE, parameters);
}
/**
* Get the query parameters supplied to the browse.
*
* @return
* @throws SQLException
* @throws UIException
*/
private BrowseParams getUserParams() throws SQLException, UIException
{
if (this.userParams != null)
return this.userParams;
Context context = ContextUtil.obtainContext(objectModel);
Request request = ObjectModelHelper.getRequest(objectModel);
BrowseParams params = new BrowseParams();
params.month = request.getParameter(BrowseParams.MONTH);
params.year = request.getParameter(BrowseParams.YEAR);
params.etAl = RequestUtils.getIntParameter(request, BrowseParams.ETAL);
params.scope = new BrowserScope(context);
// Are we in a community or collection?
DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
if (dso instanceof Community)
params.scope.setCommunity((Community) dso);
if (dso instanceof Collection)
params.scope.setCollection((Collection) dso);
try
{
String type = request.getParameter(BrowseParams.TYPE);
int sortBy = RequestUtils.getIntParameter(request, BrowseParams.SORT_BY);
BrowseIndex bi = BrowseIndex.getBrowseIndex(type);
if (bi == null)
{
throw new BrowseException("There is no browse index of the type: " + type);
}
// If we don't have a sort column
if (sortBy == -1)
{
// Get the default one
SortOption so = bi.getSortOption();
if (so != null)
{
sortBy = so.getNumber();
}
}
else if (bi.isItemIndex() && !bi.isInternalIndex())
{
try
{
// If a default sort option is specified by the index, but it isn't
// the same as sort option requested, attempt to find an index that
// is configured to use that sort by default
// This is so that we can then highlight the correct option in the navigation
SortOption bso = bi.getSortOption();
SortOption so = SortOption.getSortOption(sortBy);
if ( bso != null && bso != so)
{
BrowseIndex newBi = BrowseIndex.getBrowseIndex(so);
if (newBi != null)
{
bi = newBi;
type = bi.getName();
}
}
}
catch (SortException se)
{
throw new UIException("Unable to get sort options", se);
}
}
params.scope.setBrowseIndex(bi);
params.scope.setSortBy(sortBy);
params.scope.setJumpToItem(RequestUtils.getIntParameter(request, BrowseParams.JUMPTO_ITEM));
params.scope.setOrder(request.getParameter(BrowseParams.ORDER));
int offset = RequestUtils.getIntParameter(request, BrowseParams.OFFSET);
params.scope.setOffset(offset > 0 ? offset : 0);
params.scope.setResultsPerPage(RequestUtils.getIntParameter(request,
BrowseParams.RESULTS_PER_PAGE));
- params.scope.setStartsWith(request.getParameter(BrowseParams.STARTS_WITH));
- params.scope.setFilterValue(request.getParameter(BrowseParams.FILTER_VALUE));
- params.scope.setJumpToValue(request.getParameter(BrowseParams.JUMPTO_VALUE));
- params.scope.setJumpToValueLang(request.getParameter(BrowseParams.JUMPTO_VALUE_LANG));
- params.scope.setFilterValueLang(request.getParameter(BrowseParams.FILTER_VALUE_LANG));
+ params.scope.setStartsWith(URLDecode(request.getParameter(BrowseParams.STARTS_WITH)));
+ params.scope.setFilterValue(URLDecode(request.getParameter(BrowseParams.FILTER_VALUE)));
+ params.scope.setJumpToValue(URLDecode(request.getParameter(BrowseParams.JUMPTO_VALUE)));
+ params.scope.setJumpToValueLang(URLDecode(request.getParameter(BrowseParams.JUMPTO_VALUE_LANG)));
+ params.scope.setFilterValueLang(URLDecode(request.getParameter(BrowseParams.FILTER_VALUE_LANG)));
// Filtering to a value implies this is a second level browse
if (params.scope.getFilterValue() != null)
params.scope.setBrowseLevel(1);
// if year and perhaps month have been selected, we translate these
// into "startsWith"
// if startsWith has already been defined then it is overwritten
if (params.year != null && !"".equals(params.year) && !"-1".equals(params.year))
{
String startsWith = params.year;
if ((params.month != null) && !"-1".equals(params.month)
&& !"".equals(params.month))
{
// subtract 1 from the month, so the match works
// appropriately
if ("ASC".equals(params.scope.getOrder()))
{
params.month = Integer.toString((Integer.parseInt(params.month) - 1));
}
// They've selected a month as well
if (params.month.length() == 1)
{
// Ensure double-digit month number
params.month = "0" + params.month;
}
startsWith = params.year + "-" + params.month;
if ("ASC".equals(params.scope.getOrder()))
{
startsWith = startsWith + "-32";
}
}
params.scope.setStartsWith(startsWith);
}
}
catch (BrowseException bex)
{
throw new UIException("Unable to create browse parameters", bex);
}
this.userParams = params;
return params;
}
/**
* Get the results of the browse. If the results haven't been generated yet,
* then this will perform the browse.
*
* @return
* @throws SQLException
* @throws UIException
*/
private BrowseInfo getBrowseInfo() throws SQLException, UIException
{
if (this.browseInfo != null)
return this.browseInfo;
Context context = ContextUtil.obtainContext(objectModel);
// Get the parameters we will use for the browse
// (this includes a browse scope)
BrowseParams params = getUserParams();
try
{
// Create a new browse engine, and perform the browse
BrowseEngine be = new BrowseEngine(context);
this.browseInfo = be.browse(params.scope);
// figure out the setting for author list truncation
if (params.etAl < 0)
{
// there is no limit, or the UI says to use the default
int etAl = ConfigurationManager.getIntProperty("webui.browse.author-limit");
if (etAl != 0)
{
this.browseInfo.setEtAl(etAl);
}
}
else if (params.etAl == 0) // 0 is the user setting for unlimited
{
this.browseInfo.setEtAl(-1); // but -1 is the application
// setting for unlimited
}
else
// if the user has set a limit
{
this.browseInfo.setEtAl(params.etAl);
}
}
catch (BrowseException bex)
{
throw new UIException("Unable to process browse", bex);
}
return this.browseInfo;
}
/**
* Is this a browse on a list of items, or unique metadata values?
*
* @param info
* @return
*/
private boolean isItemBrowse(BrowseInfo info)
{
return info.getBrowseIndex().isItemIndex() || info.isSecondLevel();
}
/**
* Is this browse sorted by date?
* @param info
* @return
*/
private boolean isSortedByDate(BrowseInfo info)
{
return info.getSortOption().isDate() ||
(info.getBrowseIndex().isDate() && info.getSortOption().isDefault());
}
private Message getTitleMessage(BrowseInfo info)
{
if (titleMessage == null)
{
BrowseIndex bix = info.getBrowseIndex();
// For a second level browse (ie. items for author),
// get the value we are focussing on (ie. author).
// (empty string if none).
String value = (info.hasValue() ? "\"" + info.getValue() + "\"" : "");
// Get the name of any scoping element (collection / community)
String scopeName = "";
if (info.getBrowseContainer() != null)
scopeName = info.getBrowseContainer().getName();
else
scopeName = "";
if (bix.isMetadataIndex())
{
titleMessage = message("xmlui.ArtifactBrowser.ConfigurableBrowse.title.metadata." + bix.getName())
.parameterize(scopeName, value);
}
else if (info.getSortOption() != null)
{
titleMessage = message("xmlui.ArtifactBrowser.ConfigurableBrowse.title.item." + info.getSortOption().getName())
.parameterize(scopeName, value);
}
else
{
titleMessage = message("xmlui.ArtifactBrowser.ConfigurableBrowse.title.item." + bix.getSortOption().getName())
.parameterize(scopeName, value);
}
}
return titleMessage;
}
private Message getTrailMessage(BrowseInfo info)
{
if (trailMessage == null)
{
BrowseIndex bix = info.getBrowseIndex();
// Get the name of any scoping element (collection / community)
String scopeName = "";
if (info.getBrowseContainer() != null)
scopeName = info.getBrowseContainer().getName();
else
scopeName = "";
if (bix.isMetadataIndex())
{
trailMessage = message("xmlui.ArtifactBrowser.ConfigurableBrowse.trail.metadata." + bix.getName())
.parameterize(scopeName);
}
else if (info.getSortOption() != null)
{
trailMessage = message("xmlui.ArtifactBrowser.ConfigurableBrowse.trail.item." + info.getSortOption().getName())
.parameterize(scopeName);
}
else
{
trailMessage = message("xmlui.ArtifactBrowser.ConfigurableBrowse.trail.item." + bix.getSortOption().getName())
.parameterize(scopeName);
}
}
return trailMessage;
}
}
/*
* Helper class to track browse parameters
*/
class BrowseParams
{
String month;
String year;
int etAl;
BrowserScope scope;
final static String MONTH = "month";
final static String YEAR = "year";
final static String ETAL = "etal";
final static String TYPE = "type";
final static String JUMPTO_ITEM = "focus";
final static String JUMPTO_VALUE = "vfocus";
final static String JUMPTO_VALUE_LANG = "vfocus_lang";
final static String ORDER = "order";
final static String OFFSET = "offset";
final static String RESULTS_PER_PAGE = "rpp";
final static String SORT_BY = "sort_by";
final static String STARTS_WITH = "starts_with";
final static String FILTER_VALUE = "value";
final static String FILTER_VALUE_LANG = "value_lang";
/*
* Creates a map of the browse options common to all pages (type / value /
* value language)
*/
Map<String, String> getCommonParameters() throws UIException
{
Map<String, String> paramMap = new HashMap<String, String>();
paramMap.put(BrowseParams.TYPE, AbstractDSpaceTransformer.URLEncode(
scope.getBrowseIndex().getName()));
if (scope.getFilterValue() != null)
{
paramMap.put(BrowseParams.FILTER_VALUE, AbstractDSpaceTransformer.URLEncode(
scope.getFilterValue()));
}
if (scope.getFilterValueLang() != null)
{
paramMap.put(BrowseParams.FILTER_VALUE_LANG, AbstractDSpaceTransformer.URLEncode(
scope.getFilterValueLang()));
}
return paramMap;
}
/*
* Creates a Map of the browse control options (sort by / ordering / results
* per page / authors per item)
*/
Map<String, String> getControlParameters() throws UIException
{
Map<String, String> paramMap = new HashMap<String, String>();
paramMap.put(BrowseParams.SORT_BY, Integer.toString(this.scope.getSortBy()));
paramMap
.put(BrowseParams.ORDER, AbstractDSpaceTransformer.URLEncode(this.scope.getOrder()));
paramMap.put(BrowseParams.RESULTS_PER_PAGE, Integer
.toString(this.scope.getResultsPerPage()));
paramMap.put(BrowseParams.ETAL, Integer.toString(this.etAl));
return paramMap;
}
String getKey()
{
try
{
String key = "";
key += "-" + scope.getBrowseIndex().getName();
key += "-" + scope.getBrowseLevel();
key += "-" + scope.getStartsWith();
key += "-" + scope.getOrder();
key += "-" + scope.getResultsPerPage();
key += "-" + scope.getSortBy();
key += "-" + scope.getSortOption().getNumber();
key += "-" + scope.getOffset();
key += "-" + scope.getJumpToItem();
key += "-" + scope.getFilterValue();
key += "-" + scope.getFilterValueLang();
key += "-" + scope.getJumpToValue();
key += "-" + scope.getJumpToValueLang();
key += "-" + etAl;
return key;
}
catch (Exception e)
{
return null; // ignore exception and return no key
}
}
};
diff --git a/dspace-xmlui/dspace-xmlui-api/src/main/java/org/dspace/app/xmlui/cocoon/AbstractDSpaceTransformer.java b/dspace-xmlui/dspace-xmlui-api/src/main/java/org/dspace/app/xmlui/cocoon/AbstractDSpaceTransformer.java
index b19fa6a33..b40ffc664 100644
--- a/dspace-xmlui/dspace-xmlui-api/src/main/java/org/dspace/app/xmlui/cocoon/AbstractDSpaceTransformer.java
+++ b/dspace-xmlui/dspace-xmlui-api/src/main/java/org/dspace/app/xmlui/cocoon/AbstractDSpaceTransformer.java
@@ -1,310 +1,313 @@
/*
* AbstractDSpaceTransformer.java
*
* Version: $Revision: 1.14 $
*
* Date: $Date: 2006/05/02 05:30:55 $
*
* Copyright (c) 2002, Hewlett-Packard Company and Massachusetts
* Institute of Technology. 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 the Hewlett-Packard Company nor the name of the
* Massachusetts Institute of Technology nor the names of their
* 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
* HOLDERS 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.dspace.app.xmlui.cocoon;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.sql.SQLException;
import java.util.Map;
import org.apache.avalon.framework.parameters.Parameters;
import org.apache.cocoon.ProcessingException;
import org.apache.cocoon.components.flow.FlowHelper;
import org.apache.cocoon.components.flow.WebContinuation;
import org.apache.cocoon.environment.ObjectModelHelper;
import org.apache.cocoon.environment.Request;
import org.apache.cocoon.environment.SourceResolver;
import org.dspace.app.xmlui.objectmanager.DSpaceObjectManager;
import org.dspace.app.xmlui.utils.ContextUtil;
import org.dspace.app.xmlui.utils.UIException;
import org.dspace.app.xmlui.wing.AbstractWingTransformer;
import org.dspace.app.xmlui.wing.WingException;
import org.dspace.app.xmlui.wing.element.Body;
import org.dspace.app.xmlui.wing.element.Options;
import org.dspace.app.xmlui.wing.element.PageMeta;
import org.dspace.app.xmlui.wing.element.UserMeta;
import org.dspace.app.xmlui.wing.ObjectManager;
import org.dspace.authorize.AuthorizeException;
import org.dspace.core.Constants;
import org.dspace.core.Context;
import org.dspace.eperson.EPerson;
import org.xml.sax.SAXException;
/**
* @author Scott Phillips
*/
public abstract class AbstractDSpaceTransformer extends AbstractWingTransformer
implements DSpaceTransformer
{
private static final String NAME_TRIM = "org.dspace.app.xmlui.";
protected Map objectModel;
protected Context context;
protected String contextPath;
protected String servletPath;
protected String sitemapURI;
protected String url;
protected Parameters parameters;
protected EPerson eperson;
protected WebContinuation knot;
// Only access this through getObjectManager, so that we don't have to create one if we don't want too.
private ObjectManager objectManager;
public void setup(SourceResolver resolver, Map objectModel, String src,
Parameters parameters) throws ProcessingException, SAXException,
IOException
{
this.objectModel = objectModel;
this.parameters = parameters;
try
{
this.context = ContextUtil.obtainContext(objectModel);
this.eperson = context.getCurrentUser();
Request request = ObjectModelHelper.getRequest(objectModel);
this.contextPath = request.getContextPath();
if (contextPath == null)
contextPath = "/";
this.servletPath = request.getServletPath();
this.sitemapURI = request.getSitemapURI();
this.knot = FlowHelper.getWebContinuation(objectModel);
}
catch (SQLException sqle)
{
handleException(sqle);
}
// Initialize the Wing framework.
try
{
this.setupWing();
}
catch (WingException we)
{
throw new ProcessingException(we);
}
}
protected void handleException(Exception e) throws SAXException
{
throw new SAXException(
"An error was encountered while processing the '"+this.getComponentName()+"' Wing based component: "
+ this.getClass().getName(), e);
}
/** What to add at the end of the body */
public void addBody(Body body) throws SAXException, WingException,
UIException, SQLException, IOException, AuthorizeException
{
// Do nothing
}
/** What to add to the options list */
public void addOptions(Options options) throws SAXException, WingException,
UIException, SQLException, IOException, AuthorizeException
{
// Do nothing
}
/** What user metadata to add to the document */
public void addUserMeta(UserMeta userMeta) throws SAXException,
WingException, UIException, SQLException, IOException,
AuthorizeException
{
// Do nothing
}
/** What page metadata to add to the document */
public void addPageMeta(PageMeta pageMeta) throws SAXException,
WingException, UIException, SQLException, IOException,
AuthorizeException
{
// Do nothing
}
public ObjectManager getObjectManager()
{
if (this.objectManager == null)
this.objectManager = new DSpaceObjectManager();
return this.objectManager;
}
/** What is a unique name for this component? */
public String getComponentName()
{
String name = this.getClass().getName();
if (name.startsWith(NAME_TRIM))
name = name.substring(NAME_TRIM.length());
return name;
}
/**
* Encode the given string for URL transmission.
*
* @param unencodedString
* The unencoded string.
* @return The encoded string
*/
public static String URLEncode(String unencodedString) throws UIException
{
if (unencodedString == null)
return "";
try
{
return URLEncoder.encode(unencodedString,Constants.DEFAULT_ENCODING);
}
catch (UnsupportedEncodingException uee)
{
throw new UIException(uee);
}
}
/**
* Decode the given string from URL transmission.
*
* @param encodedString
* The encoded string.
* @return The unencoded string
*/
public static String URLDecode(String encodedString) throws UIException
{
+ if (encodedString == null)
+ return null;
+
try
{
return URLDecoder.decode(encodedString, Constants.DEFAULT_ENCODING);
}
catch (UnsupportedEncodingException uee)
{
throw new UIException(uee);
}
}
/**
* Generate a URL for the given base URL with the given parameters. This is
* a convenance method to make it easier to generate URL refrences with
* parameters.
*
* Example
* Map<String,String> parameters = new Map<String,String>();
* parameters.put("arg1","value1");
* parameters.put("arg2","value2");
* parameters.put("arg3","value3");
* String url = genrateURL("/my/url",parameters);
*
* would result in the string:
* url == "/my/url?arg1=value1&arg2=value2&arg3=value3"
*
* @param baseURL The baseURL without any parameters.
* @param parameters The parameters to be encoded on in the URL.
* @return The parameterized Post URL.
*/
public static String generateURL(String baseURL,
Map<String, String> parameters)
{
boolean first = true;
for (String key : parameters.keySet())
{
if (first)
{
baseURL += "?";
first = false;
}
else
{
baseURL += "&";
}
baseURL += key + "=" + parameters.get(key);
}
return baseURL;
}
/**
* Recyle
*/
public void recycle() {
this.objectModel = null;
this.context = null;
this.contextPath = null;
this.servletPath = null;
this.sitemapURI = null;
this.url=null;
this.parameters=null;
this.eperson=null;
this.knot=null;
this.objectManager=null;
super.recycle();
}
/**
* Dispose
*/
public void dispose() {
this.objectModel = null;
this.context = null;
this.contextPath = null;
this.servletPath = null;
this.sitemapURI = null;
this.url=null;
this.parameters=null;
this.eperson=null;
this.knot=null;
this.objectManager=null;
super.dispose();
}
}
| false | false | null | null |
diff --git a/src/parser/RVisitor.java b/src/parser/RVisitor.java
index 8fc955d..19f2e96 100644
--- a/src/parser/RVisitor.java
+++ b/src/parser/RVisitor.java
@@ -1,500 +1,536 @@
package parser;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import models.CallGraph;
import models.Clazz;
import models.Mapping;
import models.Method;
import org.eclipse.jdt.core.dom.Assignment;
import org.eclipse.jdt.core.dom.ASTVisitor;
import org.eclipse.jdt.core.dom.Block;
import org.eclipse.jdt.core.dom.BooleanLiteral;
import org.eclipse.jdt.core.dom.CastExpression;
import org.eclipse.jdt.core.dom.CharacterLiteral;
import org.eclipse.jdt.core.dom.ClassInstanceCreation;
import org.eclipse.jdt.core.dom.Expression;
import org.eclipse.jdt.core.dom.InfixExpression;
import org.eclipse.jdt.core.dom.InstanceofExpression;
import org.eclipse.jdt.core.dom.MethodInvocation;
import org.eclipse.jdt.core.dom.Name;
import org.eclipse.jdt.core.dom.NullLiteral;
import org.eclipse.jdt.core.dom.NumberLiteral;
import org.eclipse.jdt.core.dom.ParenthesizedExpression;
import org.eclipse.jdt.core.dom.PostfixExpression;
import org.eclipse.jdt.core.dom.PrefixExpression;
import org.eclipse.jdt.core.dom.QualifiedName;
import org.eclipse.jdt.core.dom.SimpleName;
import org.eclipse.jdt.core.dom.StringLiteral;
import org.eclipse.jdt.core.dom.SuperFieldAccess;
import org.eclipse.jdt.core.dom.SuperMethodInvocation;
import org.eclipse.jdt.core.dom.ThisExpression;
import org.eclipse.jdt.core.dom.TypeLiteral;
import org.eclipse.jdt.core.dom.VariableDeclarationExpression;
import org.eclipse.jdt.core.dom.VariableDeclarationFragment;
import org.eclipse.jdt.core.dom.VariableDeclarationStatement;
import callgraphanalyzer.Mappings;
public class RVisitor extends ASTVisitor {
private Resolver resolver;
private CallGraph callGraph;
private Clazz clazz;
private Method method;
private Mappings mappings = new Mappings();
public RVisitor(Resolver resolver, CallGraph callGraph, Clazz clazz, Method method) {
this.resolver = resolver;
this.callGraph = callGraph;
this.clazz = clazz;
this.method = method;
}
/**
* This is the main item we are looking for
* to resolve and will be our entry point.
*/
@Override
public boolean visit(MethodInvocation node) {
// Get the type
String type = null;
if(node.getExpression() != null)
type = resolveExpression(node.getExpression());
else
type = clazz.getName();
// This means we were unable to resolve the method invocation
if(type == null)
return super.visit(node);
// Get the method call
String methodName = node.getName().getFullyQualifiedName();
List<String> parameters = resolveParameters(node.arguments());
String methodToResolve = methodNameBuilder(type, methodName, parameters);
System.out.println("Need to resolve the method: " + methodToResolve);
Method resolved = lookupClassMethod(methodToResolve.substring(0, methodToResolve.lastIndexOf(".")),
methodToResolve.substring(methodToResolve.lastIndexOf(".")));
// The resolving has failed
if(resolved == null) {
return super.visit(node);
}
method.addMethodCall(resolved);
resolved.addCalledBy(method);
return super.visit(node);
}
/**
* This will be the main point for resolving expressions.
* We need to cover all the cases here of the Expression
* types we want to handle.
* @param expression
* @return
*/
private String resolveExpression(Expression expression) {
// Handle method invocation
if(expression instanceof MethodInvocation) {
return resolveMethodInvocation((MethodInvocation)expression);
}
// Handle variable
else if(expression instanceof SimpleName) {
return resolveSimpleName((SimpleName)expression);
}
// Handle boolean literal
else if(expression instanceof BooleanLiteral) {
return "boolean";
}
// Handle character literal
else if(expression instanceof CharacterLiteral) {
return "char";
}
// Handle null literal
else if(expression instanceof NullLiteral) {
return "null";
}
// Handle number literal
else if(expression instanceof NumberLiteral) {
return resolveNumberLiteral((NumberLiteral)expression);
}
// Handle String literal
else if(expression instanceof StringLiteral) {
return "String";
}
// Handle Type literal
else if(expression instanceof TypeLiteral) {
return ((TypeLiteral)expression).getType().toString();
}
// Handle cast expression
else if(expression instanceof CastExpression) {
return ((CastExpression)expression).getType().toString();
}
// Handle field access NOTE: Even though it says QualifiedName, it
// still behaves as a field access
else if(expression instanceof QualifiedName) {
return resolveQualifiedName((QualifiedName)expression);
}
// Handle explicit super field access
else if(expression instanceof SuperFieldAccess) {
return resolveSuperFieldAccess((SuperFieldAccess)expression);
}
// Handle explicit super method invocation
else if(expression instanceof SuperMethodInvocation) {
return resolveSuperMethodInvocation((SuperMethodInvocation)expression);
}
// Handle explicit use of "this"
else if(expression instanceof ThisExpression) {
return resolveThisExpression((ThisExpression)expression);
}
// Handle parathesized expression
else if(expression instanceof ParenthesizedExpression) {
return resolveExpression(((ParenthesizedExpression)expression).getExpression());
}
// Handle postfix operator
else if(expression instanceof PostfixExpression) {
return resolveExpression(((PostfixExpression)expression).getOperand());
}
// Handle prefix operator
else if(expression instanceof PrefixExpression) {
return resolveExpression(((PrefixExpression)expression).getOperand());
}
// Handle instanceof operator
// Defaults to bool for now.
else if(expression instanceof InstanceofExpression) {
return "boolean";
}
// Handle Infix operator
else if(expression instanceof InfixExpression) {
String left = resolveExpression(((InfixExpression)expression).getLeftOperand());
String right = resolveExpression(((InfixExpression)expression).getRightOperand());
if(!left.equals(right))
return binaryNumericPromotion(left, right);
else
return left;
}
// Handle class instance creation
else if(expression instanceof ClassInstanceCreation) {
return ((ClassInstanceCreation)expression).getType().toString();
}
// Handle assignment
else if(expression instanceof Assignment) {
return resolveExpression(((Assignment)expression).getLeftHandSide());
}
return null;
}
private String resolveMethodInvocation(MethodInvocation methodInvocation) {
// Get the type
String type = null;
if(methodInvocation.getExpression() != null)
type = resolveExpression(methodInvocation.getExpression());
else
type = clazz.getName();
// This means that the type was unresolvable and we have failed at resolving.
if(type == null)
return null;
// Get the method call
String methodName = methodInvocation.getName().getFullyQualifiedName();
List<String> parameters = resolveParameters(methodInvocation.arguments());
String methodToResolve = methodNameBuilder(type, methodName, parameters);
System.out.println("Need to look up the type of: " + methodToResolve);
Method resolved = lookupClassMethod(methodToResolve.substring(0, methodToResolve.lastIndexOf(".")),
methodToResolve.substring(methodToResolve.lastIndexOf(".")));
if(resolved != null) {
System.out.println(" " + "Return type: " +
resolved.getReturnType());
return resolved.getReturnType();
}
else {
System.out.println(" " + "Return type: unknown");
return null;
}
}
private String resolveSimpleName(SimpleName name) {
String type = mappings.lookupType(name.toString());
if(type == null)
return clazz.lookupField(name.toString());
return type;
}
private String resolveQualifiedName(QualifiedName qualifiedName) {
String type = null;
if(qualifiedName.getQualifier() instanceof SimpleName)
type = resolveSimpleName((SimpleName)qualifiedName.getQualifier());
else if(qualifiedName.getQualifier() instanceof QualifiedName)
type = resolveQualifiedName((QualifiedName)qualifiedName.getQualifier());
return lookupClassField(type, qualifiedName.getName().toString());
}
private String resolveNumberLiteral(NumberLiteral numberLiteral) {
if(numberLiteral.getToken().contains("F") || numberLiteral.getToken().contains("f"))
return "float";
if(numberLiteral.getToken().contains("D") || numberLiteral.getToken().contains("d") ||
numberLiteral.getToken().contains("E") || numberLiteral.getToken().contains("e"))
return "double";
if(numberLiteral.getToken().contains("L") || numberLiteral.getToken().contains("l"))
return "long";
if(!numberLiteral.getToken().contains("."))
return "int";
else
return "double";
}
private String resolveSuperFieldAccess(SuperFieldAccess access) {
Clazz superClazz = null;
String className = null;
if(access.getQualifier() == null)
superClazz = clazz.getSuperClazz();
else {
className = resolveExpression(access.getQualifier());
Clazz lookupClazz = lookupClassName(className);
if(lookupClazz != null)
superClazz = lookupClazz.getSuperClazz();
}
if(superClazz == null)
return null;
else
return superClazz.getName();
}
private String resolveSuperMethodInvocation(SuperMethodInvocation invocation) {
Clazz superClazz = null;
String className = null;
if(invocation.getQualifier() == null)
superClazz = clazz.getSuperClazz();
else {
className = resolveExpression(invocation.getQualifier());
Clazz lookupClazz = lookupClassName(className);
if(lookupClazz != null)
superClazz = lookupClazz.getSuperClazz();
}
if(superClazz == null)
return null;
else
return superClazz.getName();
}
private String resolveThisExpression(ThisExpression thisExpression) {
if(thisExpression.getQualifier() != null)
return resolveExpression(thisExpression.getQualifier());
else
return clazz.getName();
}
private String binaryNumericPromotion(String left, String right) {
if(left == "String" || right == "String")
return "String";
else if(left == "double" || right == "double")
return "double";
else if(left == "float" || right == "float")
return "float";
else if(left == "long" || right == "long")
return "long";
else
return "int";
}
private List<String> resolveParameters(List<Expression> parameters) {
List<String> types = new ArrayList<String>();
for(Expression expression: parameters)
types.add(resolveExpression(expression));
return types;
}
+ /**
+ * This function handles when we see a constructor call.
+ * We need to be able to link methods to other constructors
+ * for a dependency.
+ */
+ @Override
+ public boolean visit(ClassInstanceCreation node) {
+ // Get the type
+ String type = node.getType().toString();
+
+ // This means we were unable to resolve the method invocation
+ if(type == null)
+ return super.visit(node);
+
+ // Get the method call
+ // For constructors method name should be same as the type.
+ String methodName = node.getType().toString();
+
+ List<String> parameters = resolveParameters(node.arguments());
+
+ String methodToResolve = methodNameBuilder(type, methodName, parameters);
+
+ Method resolved = lookupClassMethod(methodToResolve.substring(0, methodToResolve.lastIndexOf(".")),
+ methodToResolve.substring(methodToResolve.lastIndexOf(".")));
+
+ // The resolving has failed
+ if(resolved == null) {
+ return super.visit(node);
+ }
+
+ method.addMethodCall(resolved);
+ resolved.addCalledBy(method);
+
+ return super.visit(node);
+ }
+
private String lookupClassField(String className, String field) {
if(className == null || field == null)
return null;
// Look through the package for the class name and field
for (Clazz packageClazz : getClazzesInPackage(clazz.getFile().getFilePackage())) {
if(packageClazz.hasUnqualifiedName(className))
return packageClazz.lookupField(field);
}
// Look through the imports for the class name and field
List<Clazz> imports = getClazzesInImports(clazz.getFile().getFileImports());
for (Clazz s : imports) {
if(s.hasUnqualifiedName(className))
return s.lookupField(field);
}
// Check the current class for the field
return clazz.lookupField(field);
}
private Method lookupClassMethod(String className, String method) {
// Look through the package for the class name and field
for (Clazz packageClazz : getClazzesInPackage(clazz.getFile().getFilePackage())) {
if(packageClazz.hasUnqualifiedName(className))
return packageClazz.hasUnqualifiedMethod(method);
}
// Look through the imports for the class name and field
List<Clazz> imports = getClazzesInImports(clazz.getFile().getFileImports());
for (Clazz s : imports) {
if(s.hasUnqualifiedName(className))
return s.hasUnqualifiedMethod(method);
}
// Check the current class for the field
return clazz.hasUnqualifiedMethod(method);
}
private Clazz lookupClassName(String className) {
// Look through the package for the class name
for (Clazz packageClazz : getClazzesInPackage(clazz.getFile().getFilePackage())) {
if(packageClazz.hasUnqualifiedName(className))
return packageClazz;
}
// Look through the imports for the class name
List<Clazz> imports = getClazzesInImports(clazz.getFile().getFileImports());
for (Clazz s : imports) {
if(s.hasUnqualifiedName(className))
return s;
}
// Check the current class for the name
if(clazz.hasUnqualifiedName(className))
return clazz;
return null;
}
/**
* This returns a list of all clazzes that are contained
* inside of the given package.
* @param pkg
* @return
*/
public List<Clazz> getClazzesInPackage(String pkg) {
List<Clazz> clazzes = new ArrayList<Clazz>();
for(Clazz clazz: callGraph.getAllClazzes()) {
if(clazz.getFile().getFilePackage().equals(pkg))
clazzes.add(clazz);
}
return clazzes;
}
/**
* This will return a list of clazzes that are inside the
* imported packages.
* @param imports
* @return
*/
public List<Clazz> getClazzesInImports(List<String> imports) {
Clazz tc = null;
try {
List<Clazz> clazzes = new ArrayList<Clazz>();
for(Clazz clazz: callGraph.getAllClazzes()) {
tc = clazz;
for(String imp: imports) {
tc = clazz;
if(clazz.getName().equals(imp) || clazz.getFile().getFilePackage().equals(imp))
clazzes.add(clazz);
}
}
return clazzes;
}
catch (NullPointerException e) {
e.printStackTrace();
return null;
}
}
private String methodNameBuilder(String type, String methodName, List<String> parameterTypes) {
String builder = "";
if(type != null && !type.equals(""))
builder += type + ".";
builder += methodName + "(";
for(String param: parameterTypes)
builder += param + ", ";
if(parameterTypes.size() != 0)
builder = builder.substring(0, builder.length()-2);
builder += ")";
return builder;
}
/***********************************************************************************
* This divider is here to break up this class into its two main components.
* The top half is dedicated to resolving method invocations.
* The bottom half is dedicated to creating the variable mapping so that we
* can look up the types of declared variables when we need to.
**********************************************************************************/
@Override
public boolean visit(VariableDeclarationExpression node)
{
SimpleName varName = null;
for (Iterator<VariableDeclarationFragment> i = node.fragments().iterator();i.hasNext();)
{
VariableDeclarationFragment frag = (VariableDeclarationFragment)i.next();
varName = frag.getName();
}
Mapping m = new Mapping(node.getType().toString(), varName.getFullyQualifiedName());
mappings.addMapping(node.fragments().get(0).toString(), m);
return super.visit(node);
}
@Override
public boolean visit(VariableDeclarationStatement node)
{
SimpleName varName = null;
for (Iterator<VariableDeclarationFragment> i = node.fragments().iterator();i.hasNext();)
{
VariableDeclarationFragment frag = (VariableDeclarationFragment)i.next();
varName = frag.getName();
}
Mapping m = new Mapping(node.getType().toString(), varName.getFullyQualifiedName());
mappings.addMapping(varName.getFullyQualifiedName(), m);
return super.visit(node);
}
@Override
public boolean visit(Block node)
{
mappings.newMap();
return super.visit(node);
}
@Override
public void endVisit(Block node)
{
mappings.removeMap();
}
}
| true | false | null | null |
diff --git a/src/com/zones/listeners/EventUtil.java b/src/com/zones/listeners/EventUtil.java
index ca8aebc..309ff8e 100644
--- a/src/com/zones/listeners/EventUtil.java
+++ b/src/com/zones/listeners/EventUtil.java
@@ -1,166 +1,166 @@
package com.zones.listeners;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.bukkit.event.Cancellable;
import com.zones.WorldManager;
import com.zones.Zones;
import com.zones.ZonesConfig;
import com.zones.accessresolver.AccessResolver;
import com.zones.accessresolver.interfaces.PlayerBlockResolver;
import com.zones.model.ZoneBase;
import com.zones.selection.ZoneSelection;
public class EventUtil {
public static final void onPlace(Zones plugin, Cancellable event, Player player, Block block) {
onPlace(plugin, event, player, block, -1);
}
public static final void onPlace(Zones plugin, Cancellable event, Player player, Block block, int typeId) {
WorldManager wm = plugin.getWorldManager(player);
if(!wm.getConfig().isProtectedPlaceBlock(player, typeId, true)) {
ZoneBase zone = wm.getActiveZone(block);
if(wm.getConfig().LIMIT_BUILD_BY_FLAG && !plugin.getPermissions().canUse(player,wm.getWorldName(),"zones.build")){
player.sendMessage(ZonesConfig.PLAYER_CANT_BUILD_WORLD);
event.setCancelled(true);
return;
}
if(zone == null){
if(wm.getConfig().LIMIT_BUILD_BY_FLAG && !plugin.getPermissions().canUse(player,wm.getWorldName(),"zones.inheritbuild")){
player.sendMessage(ZonesConfig.PLAYER_CANT_BUILD_WORLD);
event.setCancelled(true);
} else {
wm.getConfig().logBlockPlace(player, block);
}
} else {
if(!((PlayerBlockResolver)zone.getResolver(AccessResolver.PLAYER_BLOCK_CREATE)).isAllowed(zone, player, block, typeId)) {
((PlayerBlockResolver)zone.getResolver(AccessResolver.PLAYER_BLOCK_CREATE)).sendDeniedMessage(zone, player);
event.setCancelled(true);
return;
}
typeId = typeId == -1 ? block.getTypeId() : typeId;
if((typeId == Material.FURNACE.getId() || typeId == Material.CHEST.getId() || typeId == Material.DISPENSER.getId()) &&
!((PlayerBlockResolver)zone.getResolver(AccessResolver.PLAYER_BLOCK_MODIFY)).isAllowed(zone, player, block, typeId)) {
zone.sendMarkupMessage(ZonesConfig.PLAYER_CANT_PLACE_CHEST_IN_ZONE, player);
event.setCancelled(true);
return;
}
wm.getConfig().logBlockPlace(player, block);
}
} else {
event.setCancelled(true);
}
}
public static final void onHitPlace(Zones plugin, Cancellable event, Player player, Block block, int typeId) {
WorldManager wm = plugin.getWorldManager(player);
if(!wm.getConfig().isProtectedPlaceBlock(player, typeId, true)) {
ZoneBase zone = wm.getActiveZone(block);
if(zone != null) {
if(!((PlayerBlockResolver)zone.getResolver(AccessResolver.PLAYER_BLOCK_HIT)).isAllowed(zone, player, block, typeId)) {
((PlayerBlockResolver)zone.getResolver(AccessResolver.PLAYER_BLOCK_HIT)).sendDeniedMessage(zone, player);
event.setCancelled(true);
return;
}
}
} else {
event.setCancelled(true);
}
}
public static final void onModify(Zones plugin, Cancellable event, Player player, Block block, int blockType) {
WorldManager wm = plugin.getWorldManager(player);
ZoneBase zone = wm.getActiveZone(block);
if(wm.getConfig().LIMIT_BUILD_BY_FLAG && !plugin.getPermissions().canUse(player,wm.getWorldName(), "zones.build")) {
- if (blockType == Material.CHEST.getId())
+ if (blockType == Material.CHEST.getId() || blockType == Material.TRAPPED_CHEST.getId())
player.sendMessage(ChatColor.RED + "You cannot change chests in this world!");
else if (blockType == Material.FURNACE.getId() || blockType == Material.BURNING_FURNACE.getId())
player.sendMessage(ChatColor.RED + "You cannot change furnaces in this world!");
else if (blockType == Material.DISPENSER.getId())
player.sendMessage(ChatColor.RED + "You cannot change dispensers in this world!");
else if (blockType == Material.NOTE_BLOCK.getId())
player.sendMessage(ChatColor.RED + "You cannot change note blocks in this world!");
event.setCancelled(true);
return;
}
if(zone == null) {
if(wm.getConfig().LIMIT_BUILD_BY_FLAG && !plugin.getPermissions().canUse(player,wm.getWorldName(), "zones.inheritbuild")) {
- if (blockType == Material.CHEST.getId())
+ if (blockType == Material.CHEST.getId() || blockType == Material.TRAPPED_CHEST.getId())
player.sendMessage(ChatColor.RED + "You cannot change chests in this world!");
else if (blockType == Material.FURNACE.getId() || blockType == Material.BURNING_FURNACE.getId())
player.sendMessage(ChatColor.RED + "You cannot change furnaces in this world!");
else if (blockType == Material.DISPENSER.getId())
player.sendMessage(ChatColor.RED + "You cannot change dispensers in this world!");
else if (blockType == Material.NOTE_BLOCK.getId())
player.sendMessage(ChatColor.RED + "You cannot change note blocks in this world!");
event.setCancelled(true);
return;
}
} else {
if(!((PlayerBlockResolver)zone.getResolver(AccessResolver.PLAYER_BLOCK_MODIFY)).isAllowed(zone, player, block, -1)) {
((PlayerBlockResolver)zone.getResolver(AccessResolver.PLAYER_BLOCK_MODIFY)).sendDeniedMessage(zone, player);
event.setCancelled(true);
return;
}
}
}
public static final void onBreak(Zones plugin, Cancellable event, Player player, Block block) {
WorldManager wm = plugin.getWorldManager(block.getWorld());
if(!wm.getConfig().isProtectedBreakBlock(player, block)) {
if (player.getItemInHand().getTypeId() == ZonesConfig.CREATION_TOOL_TYPE) {
ZoneSelection selection = plugin.getZoneManager().getSelection(player.getEntityId());
if (selection != null) {
selection.onLeftClick(block);
event.setCancelled(true);
return;
}
}
if(wm.getConfig().LIMIT_BUILD_BY_FLAG && !plugin.getPermissions().canUse(player,wm.getWorldName(), "zones.build")){
player.sendMessage(ZonesConfig.PLAYER_CANT_DESTROY_WORLD);
event.setCancelled(true);
return;
}
ZoneBase zone = wm.getActiveZone(block);
if(zone == null) {
if(wm.getConfig().LIMIT_BUILD_BY_FLAG && !plugin.getPermissions().canUse(player,wm.getWorldName(), "zones.inheritbuild")){
player.sendMessage(ZonesConfig.PLAYER_CANT_DESTROY_WORLD);
event.setCancelled(true);
} else {
wm.getConfig().logBlockBreak(player, block);
}
} else {
if(!((PlayerBlockResolver)zone.getResolver(AccessResolver.PLAYER_BLOCK_DESTROY)).isAllowed(zone, player, block, -1)) {
((PlayerBlockResolver)zone.getResolver(AccessResolver.PLAYER_BLOCK_DESTROY)).sendDeniedMessage(zone, player);
event.setCancelled(true);
return;
}
int typeId = block.getTypeId();
if((typeId == Material.FURNACE.getId() || typeId == Material.CHEST.getId() || typeId == Material.DISPENSER.getId()) &&
!((PlayerBlockResolver)zone.getResolver(AccessResolver.PLAYER_BLOCK_MODIFY)).isAllowed(zone, player, block, typeId)) {
zone.sendMarkupMessage(ZonesConfig.PLAYER_CANT_DESTROY_CHEST_IN_ZONE, player);
event.setCancelled(true);
return;
}
wm.getConfig().logBlockBreak(player, block);
}
} else {
event.setCancelled(true);
}
}
}
diff --git a/src/com/zones/listeners/ZonesPlayerListener.java b/src/com/zones/listeners/ZonesPlayerListener.java
index 94fb823..5cf5618 100644
--- a/src/com/zones/listeners/ZonesPlayerListener.java
+++ b/src/com/zones/listeners/ZonesPlayerListener.java
@@ -1,470 +1,465 @@
package com.zones.listeners;
import java.util.Arrays;
import java.util.List;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.entity.PoweredMinecart;
import org.bukkit.entity.Sheep;
import org.bukkit.entity.StorageMinecart;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerBucketEmptyEvent;
import org.bukkit.event.player.PlayerBucketFillEvent;
import org.bukkit.event.player.PlayerDropItemEvent;
import org.bukkit.event.player.PlayerInteractEntityEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.event.player.PlayerPickupItemEvent;
import org.bukkit.event.player.PlayerPortalEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.event.player.PlayerRespawnEvent;
import org.bukkit.event.player.PlayerTeleportEvent;
import com.zones.WorldManager;
import com.zones.Zones;
import com.zones.ZonesConfig;
import com.zones.accessresolver.AccessResolver;
import com.zones.accessresolver.interfaces.PlayerBlockResolver;
import com.zones.accessresolver.interfaces.PlayerHitEntityResolver;
import com.zones.accessresolver.interfaces.PlayerLocationResolver;
import com.zones.model.ZoneBase;
import com.zones.model.ZonesAccess.Rights;
import com.zones.model.settings.ZoneVar;
import com.zones.model.types.ZoneNormal;
import com.zones.selection.ZoneSelection;
import com.zones.selection.ZoneSelection.Confirm;
/**
*
* @author Meaglin
*
*/
public class ZonesPlayerListener implements Listener {
private Zones plugin;
public ZonesPlayerListener(Zones plugin) {
this.plugin = plugin;
}
@EventHandler
public void onPlayerJoin(PlayerJoinEvent event) {
plugin.getWorldManager(event.getPlayer()).getRegion(event.getPlayer()).revalidateZones(event.getPlayer());
for(WorldManager wm : plugin.getWorlds())
if(wm.getConfig().GOD_MODE_ENABLED)
wm.getConfig().setGodMode(event.getPlayer(), wm.getConfig().GOD_MODE_AUTOMATIC);
}
@EventHandler
public void onPlayerQuit(PlayerQuitEvent event) {
Player player = event.getPlayer();
List<ZoneBase> zones = plugin.getWorldManager(player).getActiveZones(player);
for(ZoneBase z : zones)
z.removePlayer(player,true);
ZoneSelection selection = plugin.getZoneManager().getSelection(player.getEntityId());
if (selection != null) {
selection.setConfirm(Confirm.STOP);
selection.confirm();
}
for(WorldManager wm : plugin.getWorlds())
if(wm.getConfig().GOD_MODE_ENABLED)
wm.getConfig().setGodMode(event.getPlayer(), true); // remove from list.
}
@EventHandler(ignoreCancelled = true)
public void onPlayerMove(PlayerMoveEvent event) {
Player player = event.getPlayer();
Location from = event.getFrom();
Location to = event.getTo();
/*
* We only revalidate when we change actually change from 1 block to another.
* and since bukkits "check" is allot smaller we have to do this properly ourselves, sadly.
*/
if(WorldManager.toInt(from.getX()) == WorldManager.toInt(to.getX()) && WorldManager.toInt(from.getY()) == WorldManager.toInt(to.getY()) && WorldManager.toInt(from.getZ()) == WorldManager.toInt(to.getZ()))
return;
/*
* For the heck of it al:
* if you're wondering why we use the same world manager for both aZone and bZone it's because as far as i know you cant MOVE to another world
* and always get teleported.
*/
WorldManager wm = plugin.getWorldManager(from);
ZoneBase aZone = wm.getActiveZone(from);
ZoneBase bZone = wm.getActiveZone(to);
if (bZone != null) {
if(!((PlayerLocationResolver)bZone.getResolver(AccessResolver.PLAYER_ENTER)).isAllowed(bZone, player, from, to)) {
((PlayerLocationResolver)bZone.getResolver(AccessResolver.PLAYER_ENTER)).sendDeniedMessage(bZone, player);
/*
* In principle this should only occur when someones access to a zone gets revoked when still inside the zone.
* This prevents players getting stuck ;).
*/
if (aZone != null && !((PlayerLocationResolver)aZone.getResolver(AccessResolver.PLAYER_ENTER)).isAllowed(aZone, player, from, to)) {
player.sendMessage(ZonesConfig.PLAYER_ILLIGAL_POSITION);
player.teleport(from.getWorld().getSpawnLocation());
event.setCancelled(false);
//wm.revalidateZones(player, from, player.getWorld().getSpawnLocation());
return;
}
player.teleport(from);
event.setCancelled(false);
return;
} else if (wm.getConfig().BORDER_ENABLED && wm.getConfig().BORDER_ENFORCE) {
if(wm.getConfig().isOutsideBorder(to) && (!wm.getConfig().BORDER_OVERRIDE_ENABLED || !plugin.getPermissions().canUse(player, wm.getWorldName(), "zones.override.border"))) {
if(wm.getConfig().isOutsideBorder(from)) {
player.sendMessage(ZonesConfig.PLAYER_ILLIGAL_POSITION);
player.teleport(from.getWorld().getSpawnLocation());
event.setCancelled(false);
//wm.revalidateZones(player, from, wm.getWorld().getSpawnLocation());
return;
}
player.sendMessage(ZonesConfig.PLAYER_REACHED_BORDER);
player.teleport(from);
event.setCancelled(false);
return;
}
}
} else if(wm.getConfig().BORDER_ENABLED) {
if(wm.getConfig().isOutsideBorder(to) && (!wm.getConfig().BORDER_OVERRIDE_ENABLED || !plugin.getPermissions().canUse(player, wm.getWorldName(), "zones.override.border"))) {
if(wm.getConfig().isOutsideBorder(from) &&
(
wm.getConfig().BORDER_ENFORCE ||
aZone == null ||
!((PlayerLocationResolver)aZone.getResolver(AccessResolver.PLAYER_ENTER)).isAllowed(aZone, player, from, to)
)
) {
player.sendMessage(ZonesConfig.PLAYER_ILLIGAL_POSITION);
player.teleport(from.getWorld().getSpawnLocation());
event.setCancelled(false);
//wm.revalidateZones(player, from, wm.getWorld().getSpawnLocation());
return;
}
player.sendMessage(ZonesConfig.PLAYER_REACHED_BORDER);
player.teleport(from);
event.setCancelled(false);
return;
}
}
wm.revalidateZones(player, from, to);
}
@EventHandler(ignoreCancelled = true)
public void onPlayerPortal(PlayerPortalEvent event) {
if(event.getTo() == null) return;
if(event.getTo().getWorld() == null) return;
onPlayerTeleport(event);
}
@EventHandler(ignoreCancelled = true)
public void onPlayerTeleport(PlayerTeleportEvent event) {
Player player = event.getPlayer();
Location from = event.getFrom();
Location to = event.getTo();
WorldManager wmfrom = plugin.getWorldManager(from);
WorldManager wmto = plugin.getWorldManager(to);
ZoneBase aZone = wmfrom.getActiveZone(from);
ZoneBase bZone = wmto.getActiveZone(to);
if(aZone != null) {
// TODO: fix properly.
if(!aZone.getFlag(ZoneVar.TELEPORT) && !aZone.canAdministrate(player)) {
aZone.sendMarkupMessage(ZonesConfig.TELEPORT_INTO_ZONE_DISABLED, player);
event.setCancelled(true);
return;
}
}
if(bZone != null){
if(!((PlayerLocationResolver)bZone.getResolver(AccessResolver.PLAYER_TELEPORT)).isAllowed(bZone, player, from, to)) {
((PlayerLocationResolver)bZone.getResolver(AccessResolver.PLAYER_TELEPORT)).sendDeniedMessage(bZone, player);
event.setCancelled(true);
return;
} else if (wmto.getConfig().BORDER_ENABLED && wmto.getConfig().BORDER_ENFORCE) {
if(wmto.getConfig().isOutsideBorder(to) && (!wmto.getConfig().BORDER_OVERRIDE_ENABLED || !plugin.getPermissions().canUse(player, wmto.getWorldName(), "zones.override.border"))) {
player.sendMessage(ZonesConfig.PLAYER_CANT_WARP_OUTSIDE_BORDER);
event.setCancelled(true);
return;
}
}
} else if(wmto.getConfig().BORDER_ENABLED) {
if(wmto.getConfig().isOutsideBorder(to) && (!wmto.getConfig().BORDER_OVERRIDE_ENABLED || !plugin.getPermissions().canUse(player, wmto.getWorldName(), "zones.override.border"))) {
player.sendMessage(ZonesConfig.PLAYER_CANT_WARP_OUTSIDE_BORDER);
event.setCancelled(true);
return;
}
}
if(from.getWorld() != to.getWorld())
wmfrom.revalidateOutZones(player, from);
wmto.revalidateZones(player, from, to);
}
/**
* Called when a player uses an item
*
* @param event
* Relevant event details
*/
/*
* Some might say that referencing to the items like this might not be efficient
* however the actual materials are only requested when the array gets initialized
* (this happens when it gets called for the first time) and after that its
* just a list of Integers in the memory.
*/
private static final List<Integer> placeItems = Arrays.asList(
Material.FLINT_AND_STEEL.getId(),
Material.LAVA_BUCKET.getId(),
Material.WATER_BUCKET.getId(),
Material.SEEDS.getId(),
Material.SIGN.getId(),
Material.REDSTONE.getId(),
Material.INK_SACK.getId(),
Material.PAINTING.getId(),
Material.WOOD_DOOR.getId(),
Material.IRON_DOOR.getId(),
Material.TNT.getId(),
Material.REDSTONE_TORCH_ON.getId(),
Material.PUMPKIN.getId(),
Material.ITEM_FRAME.getId()
);
private static final List<Integer> placeHitItems = Arrays.asList(
Material.MINECART.getId(),
Material.STORAGE_MINECART.getId(),
Material.BOAT.getId(),
Material.POWERED_MINECART.getId()
);
private static final List<Integer> destroyItems = Arrays.asList(
Material.BUCKET.getId()
);
private static final List<Integer> placeBlocks = Arrays.asList(
Material.DIODE_BLOCK_OFF.getId(),
Material.DIODE_BLOCK_ON.getId()
);
private static final List<Integer> hitBlocks = Arrays.asList(
Material.CAKE_BLOCK.getId(),
Material.LEVER.getId(),
Material.STONE_PLATE.getId(),
Material.WOOD_PLATE.getId(),
Material.STONE_BUTTON.getId(),
Material.WOODEN_DOOR.getId(),
Material.TRAP_DOOR.getId(),
Material.FENCE_GATE.getId(),
Material.TRIPWIRE.getId(),
Material.TRIPWIRE_HOOK.getId(),
Material.WOOD_BUTTON.getId()
);
private static final List<Integer> modifyBlocks = Arrays.asList(
Material.NOTE_BLOCK.getId(),
Material.JUKEBOX.getId(),
Material.FURNACE.getId(),
Material.BURNING_FURNACE.getId(),
Material.CHEST.getId(),
Material.DISPENSER.getId(),
Material.BREWING_STAND.getId(),
Material.BEACON.getId(),
Material.COMMAND.getId(),
- Material.ANVIL.getId()
+ Material.ANVIL.getId(),
+ Material.TRAPPED_CHEST.getId()
);
@EventHandler(ignoreCancelled = true)
public void onPlayerInteract(PlayerInteractEvent event) {
/*
System.out.println( event.getAction().name() +
"\t i:" + event.getItem().getTypeId() +
"\t b:" + event.getClickedBlock().getTypeId() +
"\t p:" + event.getClickedBlock().getRelative(event.getBlockFace()).getTypeId());
*/
Player player = event.getPlayer();
int blockType = (event.getClickedBlock() != null ? event.getClickedBlock().getTypeId() : 0);
int toolType = (event.getItem() != null ? event.getItem().getTypeId() : 0);
-// Temp hack to disable ender chest until proper api came availeble.
-// if(blockType == 130) {
-// event.setCancelled(true);
-// return;
-// }
-
/*
* Using a huge ass if(...) would have been possible too however this seems more elegant and prolly is a little bit faster
* (however this speed difference would be very hard to determine :P )
*/
switch(event.getAction()) {
case RIGHT_CLICK_BLOCK:
case LEFT_CLICK_BLOCK:
case PHYSICAL:
if(hitBlocks.contains(blockType)) {
// Allow people to play a note block, shouldn't be protected imho.
// if(event.getAction() == Action.LEFT_CLICK_BLOCK && blockType == 25) break;
WorldManager wm = plugin.getWorldManager(player.getWorld());
ZoneBase zone = wm.getActiveZone(event.getClickedBlock());
if(zone == null) {
if(wm.getConfig().LIMIT_BUILD_BY_FLAG && !plugin.getPermissions().canUse(player, wm.getWorldName(), "zones.build")) {
player.sendMessage(ZonesConfig.PLAYER_CANT_CHANGE_WORLD);
event.setCancelled(true);
return;
}
} else {
if(!((PlayerBlockResolver)zone.getResolver(AccessResolver.PLAYER_BLOCK_HIT)).isAllowed(zone, player, event.getClickedBlock(), blockType)) {
zone.sendMarkupMessage(ZonesConfig.PLAYER_CANT_HIT_ENTITYS_IN_ZONE, player);
event.setCancelled(true);
return;
}
}
}
break;
}
switch(event.getAction()) {
case RIGHT_CLICK_BLOCK:
if (toolType == ZonesConfig.CREATION_TOOL_TYPE) {
ZoneSelection selection = plugin.getZoneManager().getSelection(player.getEntityId());
if (selection != null) {
if(event.getClickedBlock() != null) {
Block block = event.getClickedBlock();
selection.onRightClick(block);
event.setCancelled(true);
return;
}
}
}
if(modifyBlocks.contains(blockType))
EventUtil.onModify(plugin, event, player, event.getClickedBlock(), blockType);
else if(placeItems.contains(toolType))
EventUtil.onPlace(plugin, event, player, event.getClickedBlock().getRelative(event.getBlockFace()), toolType);
else if(placeHitItems.contains(toolType))
EventUtil.onHitPlace(plugin, event, player, event.getClickedBlock().getRelative(event.getBlockFace()), toolType);
else if(placeBlocks.contains(blockType))
EventUtil.onPlace(plugin, event, player, event.getClickedBlock(), blockType);
else if(destroyItems.contains(toolType))
EventUtil.onBreak(plugin, event, player, event.getClickedBlock().getRelative(event.getBlockFace()));
else if((blockType == 2 || blockType == 3) && toolType > 289 && toolType < 295) {
EventUtil.onPlace(plugin, event, player, event.getClickedBlock(), blockType);
}
break;
}
if(!event.isCancelled() && event.getAction() == Action.PHYSICAL &&
event.getClickedBlock() != null && event.getClickedBlock().getTypeId() == 60) {
WorldManager wm = plugin.getWorldManager(player.getWorld());
ZoneBase zone = wm.getActiveZone(event.getClickedBlock());
if(zone == null) {
if(wm.getConfig().CROP_PROTECTION_ENABLED)
event.setCancelled(true);
} else {
if(zone.getFlag(ZoneVar.CROP_PROTECTION))
event.setCancelled(true);
}
}
}
@EventHandler
public void onPlayerRespawn(PlayerRespawnEvent event) {
ZoneBase z = plugin.getWorldManager(event.getPlayer()).getActiveZone(event.getPlayer());
if(z != null) {
Location loc = z.getSpawnLocation(event.getPlayer());
if(loc != null) {
loc.setY(loc.getY()+1);
event.setRespawnLocation(loc);
}
}
}
@EventHandler(ignoreCancelled = true)
public void onPlayerDropItem(PlayerDropItemEvent event) {
ZoneBase zone = plugin.getWorldManager(event.getItemDrop().getWorld()).getActiveZone(event.getItemDrop().getLocation());
if(zone != null && !((ZoneNormal)zone).canModify(event.getPlayer(), Rights.HIT)) {
zone.sendMarkupMessage(ZonesConfig.PLAYER_CANT_PICKUP_ITEMS_IN_ZONE, event.getPlayer());
event.setCancelled(true);
}
// if(zone != null && !((PlayerHitEntityResolver)zone.getResolver(AccessResolver.PLAYER_ENTITY_HIT)).isAllowed(zone, event.getPlayer(), event.getItemDrop(), -1)) {
// zone.sendMarkupMessage(ZonesConfig.PLAYER_CANT_PICKUP_ITEMS_IN_ZONE, event.getPlayer());
// event.setCancelled(true);
// }
}
@EventHandler
public void onPlayerPickupItem(PlayerPickupItemEvent event) {
if(event.isCancelled()) return;
ZoneBase zone = plugin.getWorldManager(event.getItem().getWorld()).getActiveZone(event.getItem().getLocation());
if(zone != null && !((ZoneNormal)zone).canModify(event.getPlayer(), Rights.HIT)) {
zone.sendMarkupMessage(ZonesConfig.PLAYER_CANT_DROP_ITEMS_IN_ZONE, event.getPlayer());
event.setCancelled(true);
}
// if(zone != null && !((PlayerHitEntityResolver)zone.getResolver(AccessResolver.PLAYER_ENTITY_HIT)).isAllowed(zone, event.getPlayer(), event.getItem(), -1)) {
// zone.sendMarkupMessage(ZonesConfig.PLAYER_CANT_DROP_ITEMS_IN_ZONE, event.getPlayer());
// event.setCancelled(true);
// }
}
@EventHandler
public void onPlayerBucketFill(PlayerBucketFillEvent event) {
if(event.isCancelled()) return;
Block block = event.getBlockClicked().getRelative(event.getBlockFace());
Player player = event.getPlayer();
EventUtil.onBreak(plugin, event, player, block);
}
@EventHandler(ignoreCancelled = true)
public void onPlayerBucketEmpty(PlayerBucketEmptyEvent event) {
Player player = event.getPlayer();
Block blockPlaced = event.getBlockClicked().getRelative(event.getBlockFace());
EventUtil.onPlace(plugin, event, player, blockPlaced, event.getItemStack().getTypeId());
}
@EventHandler(ignoreCancelled = true)
public void onPlayerInteractEntity(PlayerInteractEntityEvent event) {
Player player = event.getPlayer();
Entity target = event.getRightClicked();
if(target == null) return;
if(target instanceof Sheep) {
ZoneBase zone = plugin.getWorldManager(target.getWorld()).getActiveZone(target.getLocation());
if(zone != null && !((PlayerHitEntityResolver)zone.getResolver(AccessResolver.PLAYER_ENTITY_HIT)).isAllowed(zone, player, target, -1)){
zone.sendMarkupMessage(ZonesConfig.PLAYER_CANT_SHEAR_IN_ZONE, player);
event.setCancelled(true);
return;
}
} else if (target instanceof StorageMinecart) {
ZoneBase zone = plugin.getWorldManager(target.getWorld()).getActiveZone(target.getLocation());
if(zone != null && zone instanceof ZoneNormal && !((ZoneNormal)zone).canModify(player, Rights.MODIFY)){
zone.sendMarkupMessage(ZonesConfig.PLAYER_CANT_MODIFY_BLOCKS_IN_ZONE, player);
event.setCancelled(true);
return;
}
} else if (target instanceof PoweredMinecart && player.getItemInHand() != null && player.getItemInHand().getTypeId() == 263) {
ZoneBase zone = plugin.getWorldManager(target.getWorld()).getActiveZone(target.getLocation());
if(zone != null && zone instanceof ZoneNormal && !((ZoneNormal)zone).canModify(player, Rights.HIT)){
zone.sendMarkupMessage(ZonesConfig.PLAYER_CANT_HIT_ENTITYS_IN_ZONE, player);
event.setCancelled(true);
return;
}
}
}
}
| false | false | null | null |
diff --git a/org.eclipse.jdt.debug/eval/org/eclipse/jdt/internal/debug/eval/ast/ASTEvaluationEngine.java b/org.eclipse.jdt.debug/eval/org/eclipse/jdt/internal/debug/eval/ast/ASTEvaluationEngine.java
index 7bf0d282e..8122d5b25 100644
--- a/org.eclipse.jdt.debug/eval/org/eclipse/jdt/internal/debug/eval/ast/ASTEvaluationEngine.java
+++ b/org.eclipse.jdt.debug/eval/org/eclipse/jdt/internal/debug/eval/ast/ASTEvaluationEngine.java
@@ -1,269 +1,260 @@
/*
* (c) Copyright IBM Corp. 2002.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.debug.eval.ast;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.debug.core.DebugException;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.Message;
import org.eclipse.jdt.debug.core.IJavaDebugTarget;
import org.eclipse.jdt.debug.core.IJavaObject;
import org.eclipse.jdt.debug.core.IJavaStackFrame;
import org.eclipse.jdt.debug.core.IJavaThread;
import org.eclipse.jdt.debug.core.IJavaValue;
import org.eclipse.jdt.debug.eval.IEvaluationEngine;
import org.eclipse.jdt.debug.eval.IEvaluationListener;
import org.eclipse.jdt.debug.eval.ast.model.ICompiledExpression;
import org.eclipse.jdt.debug.eval.ast.model.IRuntimeContext;
import org.eclipse.jdt.debug.eval.ast.model.IValue;
import org.eclipse.jdt.debug.eval.ast.model.IVariable;
import org.eclipse.jdt.internal.debug.eval.ast.engine.ASTAPIVisitor;
import org.eclipse.jdt.internal.debug.eval.ast.engine.InstructionSequence;
import org.eclipse.jdt.internal.debug.core.model.JDIThread;
import org.eclipse.jdt.internal.debug.eval.EvaluationResult;
/**
* @version 1.0
* @author
*/
public class ASTEvaluationEngine implements IEvaluationEngine {
private IJavaProject fProject;
private IJavaDebugTarget fDebugTarget;
private boolean fEvaluationCancelled;
private boolean fEvaluationComplete;
public ASTEvaluationEngine(IJavaProject project, IJavaDebugTarget debugTarget) {
setJavaProject(project);
setDebugTarget(debugTarget);
}
public void setJavaProject(IJavaProject project) {
fProject = project;
}
public void setDebugTarget(IJavaDebugTarget debugTarget) {
fDebugTarget = debugTarget;
}
/*
* @see IEvaluationEngine#evaluate(String, IJavaThread, IEvaluationListener)
*/
public void evaluate(String snippet, IJavaThread thread, IEvaluationListener listener) throws DebugException {
}
/**
* @see IEvaluationEngine#evaluate(String, IJavaStackFrame, IEvaluationListener)
*/
public void evaluate(String snippet, IJavaStackFrame frame, IEvaluationListener listener) throws DebugException {
ICompiledExpression expression= getCompiledExpression(snippet, frame);
evaluate(expression, frame, listener);
}
/**
* @see IEvaluationEngine#evaluate(ICompiledExpression, IJavaStackFrame, IEvaluationListener)
*/
public void evaluate(final ICompiledExpression expression, final IJavaStackFrame frame, final IEvaluationListener listener) {
RuntimeContext context = new RuntimeContext(getJavaProject(), frame);
evaluate(expression, context, (IJavaThread)frame.getThread(), listener);
}
/**
* @see IEvaluationEngine#evaluate(String, IJavaObject, IJavaThread, IEvaluationListener)
*/
public void evaluate(String snippet, IJavaObject thisContext, IJavaThread thread, IEvaluationListener listener) throws DebugException {
ICompiledExpression expression= getCompiledExpression(snippet, thisContext, thread);
evaluate(expression, thisContext, thread, listener);
}
/**
* @see IEvaluationEngine#evaluate(ICompiledExpression, IJavaObject, IJavaThread, IEvaluationListener)
*/
public void evaluate(final ICompiledExpression expression, final IJavaObject thisContext, final IJavaThread thread, final IEvaluationListener listener) {
IRuntimeContext context = new JavaObjectRuntimeContext(thisContext, getJavaProject(), thread);
evaluate(expression, context, thread, listener);
}
/**
* Performs the evaluation.
*/
public void evaluate(final ICompiledExpression expression, final IRuntimeContext context, final IJavaThread thread, final IEvaluationListener listener) {
Thread evaluationThread= new Thread(new Runnable() {
public void run() {
fEvaluationCancelled= false;
fEvaluationComplete= false;
EvaluationResult result = new EvaluationResult(ASTEvaluationEngine.this, expression.getSnippet(), thread);
if (expression.hasErrors()) {
Message[] errors= expression.getErrors();
for (int i= 0, numErrors= errors.length; i < numErrors; i++) {
result.addError(errors[i]);
}
listener.evaluationComplete(result);
return;
}
IValue value = null;
Thread timeoutThread= new Thread(new Runnable() {
public void run() {
while (!fEvaluationComplete && !fEvaluationCancelled) {
try {
Thread.currentThread().sleep(3000); // 10 second timeout for now
} catch(InterruptedException e) {
}
- if (!fEvaluationComplete) {
- try {
- ((JDIThread)thread).suspendQuiet();
- if (!listener.evaluationTimedOut(thread)) {
- fEvaluationCancelled= true;
- } else {
- // Keep waiting
- ((JDIThread)thread).resumeQuiet();
- }
- } catch(DebugException e) {
- }
+ if (!fEvaluationComplete && !listener.evaluationTimedOut(thread)) {
+ fEvaluationCancelled= true;
}
}
}
}, "Evaluation timeout thread");
timeoutThread.start();
value= expression.evaluate(context);
fEvaluationComplete= true;
if (fEvaluationCancelled) {
// Don't notify the listener if the evaluation has been cancelled
return;
}
CoreException exception= expression.getException();
if (value != null) {
IJavaValue jv = ((EvaluationValue)value).getJavaValue();
result.setValue(jv);
}
result.setException(exception);
listener.evaluationComplete(result);
}
}, "Evaluation thread");
evaluationThread.start();
}
/*
* @see IEvaluationEngine#getCompiledExpression(String, IJavaStackFrame)
*/
public ICompiledExpression getCompiledExpression(String snippet, IJavaStackFrame frame) throws DebugException {
IJavaProject javaProject = getJavaProject();
RuntimeContext context = new RuntimeContext(javaProject, frame);
ASTCodeSnippetToCuMapper mapper = null;
CompilationUnit unit = null;
try {
IVariable[] locals = context.getLocals();
int numLocals= locals.length;
int[] localModifiers = new int[locals.length];
String[] localTypesNames= new String[numLocals];
String[] localVariables= new String[numLocals];
for (int i = 0; i < numLocals; i++) {
localVariables[i] = locals[i].getName();
localTypesNames[i] = ((EvaluationValue)locals[i].getValue()).getJavaValue().getReferenceTypeName();
localModifiers[i]= 0;
}
mapper = new ASTCodeSnippetToCuMapper(new String[0], localModifiers, localTypesNames, localVariables, snippet);
unit = AST.parseCompilationUnit(mapper.getSource(frame).toCharArray(), mapper.getCompilationUnitName(), javaProject);
} catch (JavaModelException e) {
throw new DebugException(e.getStatus());
} catch (CoreException e) {
throw new DebugException(e.getStatus());
}
return genExpressionFromAST(snippet, mapper, unit);
}
public ICompiledExpression getCompiledExpression(String snippet, IJavaObject thisContext, IJavaThread thread) throws DebugException {
IJavaProject javaProject = getJavaProject();
ASTCodeSnippetToCuMapper mapper = null;
CompilationUnit unit = null;
try {
mapper = new ASTCodeSnippetToCuMapper(new String[0], new int[0], new String[0], new String[0], snippet);
unit = AST.parseCompilationUnit(mapper.getSource(thisContext, javaProject).toCharArray(), mapper.getCompilationUnitName(), javaProject);
} catch (CoreException e) {
throw new DebugException(e.getStatus());
}
return genExpressionFromAST(snippet, mapper, unit);
}
private ICompiledExpression genExpressionFromAST(String snippet, ASTCodeSnippetToCuMapper mapper, CompilationUnit unit) {
Message[] messages= unit.getMessages();
if (messages.length != 0) {
boolean error= false;
InstructionSequence errorSequence= new InstructionSequence(snippet);
int codeSnippetStartOffset= mapper.getStartPosition();
int codeSnippetEndOffset= codeSnippetStartOffset + snippet.length();
for (int i = 0; i < messages.length; i++) {
Message message= messages[i];
int errorOffset= message.getSourcePosition();
// TO DO: Internationalize "void method..." error message check
if (codeSnippetStartOffset <= errorOffset && errorOffset <= codeSnippetEndOffset && !"Void methods cannot return a value".equals(message.getMessage())) {
errorSequence.addError(message);
error = true;
}
}
if (error) {
return errorSequence;
}
}
ASTAPIVisitor visitor = new ASTAPIVisitor(mapper.getStartPosition(), snippet);
unit.accept(visitor);
return visitor.getInstructions();
}
/*
* @see IEvaluationEngine#getJavaProject()
*/
public IJavaProject getJavaProject() {
return fProject;
}
/*
* @see IEvaluationEngine#getDebugTarget()
*/
public IJavaDebugTarget getDebugTarget() {
return fDebugTarget;
}
/*
* @see IEvaluationEngine#dispose()
*/
public void dispose() {
}
/**
* @see IEvaluationEngine#evaluate(ICompiledExpression, IJavaThread, IEvaluationListener)
*/
public void evaluate(ICompiledExpression expression, IJavaThread thread, IEvaluationListener listener) throws DebugException {
}
/**
* @see IEvaluationEngine#getCompiledExpression(String, IJavaThread)
*/
public ICompiledExpression getCompiledExpression(String snippet, IJavaThread thread) throws DebugException {
return null;
}
}
| true | true | public void evaluate(final ICompiledExpression expression, final IRuntimeContext context, final IJavaThread thread, final IEvaluationListener listener) {
Thread evaluationThread= new Thread(new Runnable() {
public void run() {
fEvaluationCancelled= false;
fEvaluationComplete= false;
EvaluationResult result = new EvaluationResult(ASTEvaluationEngine.this, expression.getSnippet(), thread);
if (expression.hasErrors()) {
Message[] errors= expression.getErrors();
for (int i= 0, numErrors= errors.length; i < numErrors; i++) {
result.addError(errors[i]);
}
listener.evaluationComplete(result);
return;
}
IValue value = null;
Thread timeoutThread= new Thread(new Runnable() {
public void run() {
while (!fEvaluationComplete && !fEvaluationCancelled) {
try {
Thread.currentThread().sleep(3000); // 10 second timeout for now
} catch(InterruptedException e) {
}
if (!fEvaluationComplete) {
try {
((JDIThread)thread).suspendQuiet();
if (!listener.evaluationTimedOut(thread)) {
fEvaluationCancelled= true;
} else {
// Keep waiting
((JDIThread)thread).resumeQuiet();
}
} catch(DebugException e) {
}
}
}
}
}, "Evaluation timeout thread");
timeoutThread.start();
value= expression.evaluate(context);
fEvaluationComplete= true;
if (fEvaluationCancelled) {
// Don't notify the listener if the evaluation has been cancelled
return;
}
CoreException exception= expression.getException();
if (value != null) {
IJavaValue jv = ((EvaluationValue)value).getJavaValue();
result.setValue(jv);
}
result.setException(exception);
listener.evaluationComplete(result);
}
}, "Evaluation thread");
evaluationThread.start();
}
| public void evaluate(final ICompiledExpression expression, final IRuntimeContext context, final IJavaThread thread, final IEvaluationListener listener) {
Thread evaluationThread= new Thread(new Runnable() {
public void run() {
fEvaluationCancelled= false;
fEvaluationComplete= false;
EvaluationResult result = new EvaluationResult(ASTEvaluationEngine.this, expression.getSnippet(), thread);
if (expression.hasErrors()) {
Message[] errors= expression.getErrors();
for (int i= 0, numErrors= errors.length; i < numErrors; i++) {
result.addError(errors[i]);
}
listener.evaluationComplete(result);
return;
}
IValue value = null;
Thread timeoutThread= new Thread(new Runnable() {
public void run() {
while (!fEvaluationComplete && !fEvaluationCancelled) {
try {
Thread.currentThread().sleep(3000); // 10 second timeout for now
} catch(InterruptedException e) {
}
if (!fEvaluationComplete && !listener.evaluationTimedOut(thread)) {
fEvaluationCancelled= true;
}
}
}
}, "Evaluation timeout thread");
timeoutThread.start();
value= expression.evaluate(context);
fEvaluationComplete= true;
if (fEvaluationCancelled) {
// Don't notify the listener if the evaluation has been cancelled
return;
}
CoreException exception= expression.getException();
if (value != null) {
IJavaValue jv = ((EvaluationValue)value).getJavaValue();
result.setValue(jv);
}
result.setException(exception);
listener.evaluationComplete(result);
}
}, "Evaluation thread");
evaluationThread.start();
}
|
diff --git a/src/com/kmagic/solitaire/CardAnchor.java b/src/com/kmagic/solitaire/CardAnchor.java
index 773f0ea..8da2342 100644
--- a/src/com/kmagic/solitaire/CardAnchor.java
+++ b/src/com/kmagic/solitaire/CardAnchor.java
@@ -1,1122 +1,1128 @@
/*
Copyright 2008 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.kmagic.solitaire;
import android.graphics.Canvas;
import android.util.Log;
class CardAnchor {
public static final int MAX_CARDS = 104;
public static final int SEQ_SINK = 1;
public static final int SUIT_SEQ_STACK = 2;
public static final int DEAL_FROM = 3;
public static final int DEAL_TO = 4;
public static final int SPIDER_STACK = 5;
public static final int FREECELL_STACK = 6;
public static final int FREECELL_HOLD = 7;
public static final int GENERIC_ANCHOR = 8;
private int mNumber;
protected Rules mRules;
protected float mX;
protected float mY;
protected Card[] mCard;
protected int mCardCount;
protected int mHiddenCount;
protected float mLeftEdge;
protected float mRightEdge;
protected float mBottom;
protected boolean mDone;
//Variables for GenericAnchor
protected int mBUILDSEQ;
protected int mMOVESEQ;
protected int mBUILDSUIT;
protected int mMOVESUIT;
protected boolean mBUILDWRAP;
protected boolean mMOVEWRAP;
protected int mDROPOFF;
protected int mPICKUP;
protected int mDISPLAY;
protected int mHACK;
// ==========================================================================
// Create a CardAnchor
// -------------------
public static CardAnchor CreateAnchor(int type, int number, Rules rules) {
CardAnchor ret = null;
switch (type) {
case SEQ_SINK:
ret = new SeqSink();
break;
case SUIT_SEQ_STACK:
ret = new SuitSeqStack();
break;
case DEAL_FROM:
ret = new DealFrom();
break;
case DEAL_TO:
ret = new DealTo();
break;
case SPIDER_STACK:
ret = new SpiderStack();
break;
case FREECELL_STACK:
ret = new FreecellStack();
break;
case FREECELL_HOLD:
ret = new FreecellHold();
break;
case GENERIC_ANCHOR:
ret = new GenericAnchor();
break;
}
ret.SetRules(rules);
ret.SetNumber(number);
return ret;
}
public CardAnchor() {
mX = 1;
mY = 1;
mCard = new Card[MAX_CARDS];
mCardCount = 0;
mHiddenCount = 0;
mLeftEdge = -1;
mRightEdge = -1;
mBottom = -1;
mNumber = -1;
mDone = false;
}
// ==========================================================================
// Getters and Setters
// -------------------
public Card[] GetCards() { return mCard; }
public int GetCount() { return mCardCount; }
public int GetHiddenCount() { return mHiddenCount; }
public float GetLeftEdge() { return mLeftEdge; }
public int GetNumber() { return mNumber; }
public float GetRightEdge() { return mRightEdge; }
public int GetVisibleCount() { return mCardCount - mHiddenCount; }
public int GetMovableCount() { return mCardCount > 0 ? 1 : 0; }
public float GetX() { return mX; }
public float GetNewY() { return mY; }
public boolean IsDone() { return mDone; }
public void SetBottom(float edge) { mBottom = edge; }
public void SetHiddenCount(int count) { mHiddenCount = count; }
public void SetLeftEdge(float edge) { mLeftEdge = edge; }
public void SetMaxHeight(int maxHeight) { }
public void SetNumber(int number) { mNumber = number; }
public void SetRightEdge(float edge) { mRightEdge = edge; }
public void SetRules(Rules rules) { mRules = rules; }
public void SetShowing(int showing) { }
protected void SetCardPosition(int idx) { mCard[idx].SetPosition(mX, mY); }
public void SetDone(boolean done) { mDone = done; }
//Methods for GenericAnchor
public void SetSeq(int seq){ mBUILDSEQ = seq; mMOVESEQ = seq; }
public void SetBuildSeq(int buildseq){ mBUILDSEQ = buildseq; }
public void SetMoveSeq(int moveseq){ mMOVESEQ = moveseq; }
public void SetWrap(boolean wrap){ mBUILDWRAP = wrap; mMOVEWRAP = wrap; }
public void SetMoveWrap(boolean movewrap){ mMOVEWRAP = movewrap; }
public void SetBuildWrap(boolean buildwrap){ mBUILDWRAP = buildwrap; }
public void SetSuit(int suit){ mBUILDSUIT = suit; mMOVESUIT = suit; }
public void SetBuildSuit(int buildsuit){ mBUILDSUIT = buildsuit; }
public void SetMoveSuit(int movesuit){ mMOVESUIT = movesuit; }
public void SetBehavior(int beh){ mDROPOFF = beh; mPICKUP = beh; }
public void SetDropoff(int dropoff){ mDROPOFF = dropoff; }
public void SetPickup(int pickup){ mPICKUP = pickup; }
public void SetDisplay(int display){ mDISPLAY = display; }
public void SetHack(int hack){ mHACK = hack; }
//End Methods for Generic Anchor
public void SetPosition(float x, float y) {
mX = x;
mY = y;
for (int i = 0; i < mCardCount; i++) {
SetCardPosition(i);
}
}
// ==========================================================================
// Functions to add cards
// ----------------------
public void AddCard(Card card) {
mCard[mCardCount++] = card;
SetCardPosition(mCardCount - 1);
}
public void AddMoveCard(MoveCard moveCard) {
int count = moveCard.GetCount();
Card[] cards = moveCard.DumpCards();
for (int i = 0; i < count; i++) {
AddCard(cards[i]);
}
}
public boolean DropSingleCard(Card card) { return false; }
public boolean CanDropCard(MoveCard moveCard, int close) { return false; }
// ==========================================================================
// Functions to take cards
// -----------------------
public Card[] GetCardStack() { return null; }
public Card GrabCard(float x, float y) {
Card ret = null;
if (mCardCount > 0 && IsOverCard(x, y)) {
ret = PopCard();
}
return ret;
}
public Card PopCard() {
Card ret = mCard[--mCardCount];
mCard[mCardCount] = null;
return ret;
}
// ==========================================================================
// Functions to interact with cards
// --------------------------------
public boolean TapCard(float x, float y) { return false; }
public boolean UnhideTopCard() {
if (mCardCount > 0 && mHiddenCount > 0 && mHiddenCount == mCardCount) {
mHiddenCount--;
return true;
}
return false;
}
public boolean ExpandStack(float x, float y) { return false; }
public boolean CanMoveStack(float x, float y) { return false; }
// ==========================================================================
// Functions to check locations
// ----------------------------
private boolean IsOver(float x, float y, boolean deck, int close) {
float clx = mCardCount == 0 ? mX : mCard[mCardCount - 1].GetX();
float leftX = mLeftEdge == -1 ? clx : mLeftEdge;
float rightX = mRightEdge == -1 ? clx + Card.WIDTH : mRightEdge;
float topY = (mCardCount == 0 || deck) ? mY : mCard[mCardCount-1].GetY();
float botY = mCardCount > 0 ? mCard[mCardCount - 1].GetY() : mY;
botY += Card.HEIGHT;
leftX -= close*Card.WIDTH/2;
rightX += close*Card.WIDTH/2;
topY -= close*Card.HEIGHT/2;
botY += close*Card.HEIGHT/2;
if (mBottom != -1 && botY + 10 >= mBottom)
botY = mBottom;
if (x >= leftX && x <= rightX && y >= topY && y <= botY) {
return true;
}
return false;
}
protected boolean IsOverCard(float x, float y) {
return IsOver(x, y, false, 0);
}
protected boolean IsOverCard(float x, float y, int close) {
return IsOver(x, y, false, close);
}
protected boolean IsOverDeck(float x, float y) {
return IsOver(x, y, true, 0);
}
// ==========================================================================
// Functions to Draw
// ----------------------------
public void Draw(DrawMaster drawMaster, Canvas canvas) {
if (mCardCount == 0) {
drawMaster.DrawEmptyAnchor(canvas, mX, mY, mDone);
} else {
drawMaster.DrawCard(canvas, mCard[mCardCount-1]);
}
}
}
// Straight up default
class DealTo extends CardAnchor {
private int mShowing;
public DealTo() {
super();
mShowing = 1;
}
@Override
public void SetShowing(int showing) { mShowing = showing; }
@Override
protected void SetCardPosition(int idx) {
if (mShowing == 1) {
mCard[idx].SetPosition(mX, mY);
} else {
if (idx < mCardCount - mShowing) {
mCard[idx].SetPosition(mX, mY);
} else {
int offset = mCardCount - mShowing;
offset = offset < 0 ? 0 : offset;
mCard[idx].SetPosition(mX + (idx - offset) * Card.WIDTH/2, mY);
}
}
}
@Override
public void AddCard(Card card) {
super.AddCard(card);
SetPosition(mX, mY);
}
@Override
public boolean UnhideTopCard() {
SetPosition(mX, mY);
return false;
}
@Override
public Card PopCard() {
Card ret = super.PopCard();
SetPosition(mX, mY);
return ret;
}
@Override
public void Draw(DrawMaster drawMaster, Canvas canvas) {
if (mCardCount == 0) {
drawMaster.DrawEmptyAnchor(canvas, mX, mY, mDone);
} else {
for (int i = mCardCount - mShowing; i < mCardCount; i++) {
if (i >= 0) {
drawMaster.DrawCard(canvas, mCard[i]);
}
}
}
}
}
// Abstract stack anchor
class SeqStack extends CardAnchor {
protected static final int SMALL_SPACING = 7;
protected static final int HIDDEN_SPACING = 3;
protected int mSpacing;
protected boolean mHideHidden;
protected int mMaxHeight;
public SeqStack() {
super();
mSpacing = GetMaxSpacing();
mHideHidden = false;
mMaxHeight = Card.HEIGHT;
}
@Override
public void SetMaxHeight(int maxHeight) {
mMaxHeight = maxHeight;
CheckSizing();
SetPosition(mX, mY);
}
// This can't be a constant as Card.HEIGHT isn't constant.
protected int GetMaxSpacing() {
return Card.HEIGHT/3;
}
@Override
protected void SetCardPosition(int idx) {
if (idx < mHiddenCount) {
if (mHideHidden) {
mCard[idx].SetPosition(mX, mY);
} else {
mCard[idx].SetPosition(mX, mY + HIDDEN_SPACING * idx);
}
} else {
int startY = mHideHidden ? HIDDEN_SPACING : mHiddenCount * HIDDEN_SPACING;
int y = (int)mY + startY + (idx - mHiddenCount) * mSpacing;
mCard[idx].SetPosition(mX, y);
}
}
@Override
public void SetHiddenCount(int count) {
super.SetHiddenCount(count);
CheckSizing();
SetPosition(mX, mY);
}
@Override
public void AddCard(Card card) {
super.AddCard(card);
CheckSizing();
}
@Override
public Card PopCard() {
Card ret = super.PopCard();
CheckSizing();
return ret;
}
@Override
public boolean ExpandStack(float x, float y) {
if (IsOverDeck(x, y)) {
if (mHiddenCount >= mCardCount) {
mHiddenCount = mCardCount == 0 ? 0 : mCardCount - 1;
} else if (mCardCount - mHiddenCount > 1) {
return true;
}
}
return false;
}
@Override
public int GetMovableCount() { return GetVisibleCount(); }
@Override
public void Draw(DrawMaster drawMaster, Canvas canvas) {
if (mCardCount == 0) {
drawMaster.DrawEmptyAnchor(canvas, mX, mY, mDone);
} else {
for (int i = 0; i < mCardCount; i++) {
if (i < mHiddenCount) {
drawMaster.DrawHiddenCard(canvas, mCard[i]);
} else {
drawMaster.DrawCard(canvas, mCard[i]);
}
}
}
}
private void CheckSizing() {
if (mCardCount < 2 || mCardCount - mHiddenCount < 2) {
mSpacing = GetMaxSpacing();
mHideHidden = false;
return;
}
int max = mMaxHeight;
int hidden = mHiddenCount;
int showing = mCardCount - hidden;
int spaceLeft = max - (hidden * HIDDEN_SPACING) - Card.HEIGHT;
int spacing = spaceLeft / (showing - 1);
if (spacing < SMALL_SPACING && hidden > 1) {
mHideHidden = true;
spaceLeft = max - HIDDEN_SPACING - Card.HEIGHT;
spacing = spaceLeft / (showing - 1);
} else {
mHideHidden = false;
if (spacing > GetMaxSpacing()) {
spacing = GetMaxSpacing();
}
}
if (spacing != mSpacing) {
mSpacing = spacing;
SetPosition(mX, mY);
}
}
public float GetNewY() {
if (mCardCount == 0) {
return mY;
}
return mCard[mCardCount-1].GetY() + mSpacing;
}
}
// Anchor where cards to deal come from
class DealFrom extends CardAnchor {
@Override
public Card GrabCard(float x, float y) { return null; }
@Override
public boolean TapCard(float x, float y) {
if (IsOverCard(x, y)) {
mRules.EventAlert(Rules.EVENT_DEAL, this);
return true;
}
return false;
}
@Override
public void Draw(DrawMaster drawMaster, Canvas canvas) {
if (mCardCount == 0) {
drawMaster.DrawEmptyAnchor(canvas, mX, mY, mDone);
} else {
drawMaster.DrawHiddenCard(canvas, mCard[mCardCount-1]);
}
}
}
// Anchor that holds increasing same suited cards
class SeqSink extends CardAnchor {
@Override
public void AddCard(Card card) {
super.AddCard(card);
mRules.EventAlert(Rules.EVENT_STACK_ADD, this);
}
@Override
public boolean CanDropCard(MoveCard moveCard, int close) {
Card card = moveCard.GetTopCard();
float x = card.GetX() + Card.WIDTH/2;
float y = card.GetY() + Card.HEIGHT/2;
Card topCard = mCardCount > 0 ? mCard[mCardCount - 1] : null;
float my = mCardCount > 0 ? topCard.GetY() : mY;
if (IsOverCard(x, y, close)) {
if (moveCard.GetCount() == 1) {
if ((topCard == null && card.GetValue() == 1) ||
(topCard != null && card.GetSuit() == topCard.GetSuit() &&
card.GetValue() == topCard.GetValue() + 1)) {
return true;
}
}
}
return false;
}
@Override
public boolean DropSingleCard(Card card) {
Card topCard = mCardCount > 0 ? mCard[mCardCount - 1] : null;
if ((topCard == null && card.GetValue() == 1) ||
(topCard != null && card.GetSuit() == topCard.GetSuit() &&
card.GetValue() == topCard.GetValue() + 1)) {
//AddCard(card);
return true;
}
return false;
}
}
// Regular color alternating solitaire stack
class SuitSeqStack extends SeqStack {
@Override
public boolean CanDropCard(MoveCard moveCard, int close) {
Card card = moveCard.GetTopCard();
float x = card.GetX() + Card.WIDTH/2;
float y = card.GetY() + Card.HEIGHT/2;
Card topCard = mCardCount > 0 ? mCard[mCardCount - 1] : null;
float my = mCardCount > 0 ? topCard.GetY() : mY;
if (IsOverCard(x, y, close)) {
if (topCard == null) {
if (card.GetValue() == Card.KING) {
return true;
}
} else if ((card.GetSuit()&1) != (topCard.GetSuit()&1) &&
card.GetValue() == topCard.GetValue() - 1) {
return true;
}
}
return false;
}
@Override
public Card[] GetCardStack() {
int visibleCount = GetVisibleCount();
Card[] ret = new Card[visibleCount];
for (int i = visibleCount-1; i >= 0; i--) {
ret[i] = PopCard();
}
return ret;
}
@Override
public boolean CanMoveStack(float x, float y) { return super.ExpandStack(x, y); }
}
// Spider solitaire style stack
class SpiderStack extends SeqStack {
@Override
public void AddCard(Card card) {
super.AddCard(card);
mRules.EventAlert(Rules.EVENT_STACK_ADD, this);
}
@Override
public boolean CanDropCard(MoveCard moveCard, int close) {
Card card = moveCard.GetTopCard();
float x = card.GetX() + Card.WIDTH/2;
float y = card.GetY() + Card.HEIGHT/2;
Card topCard = mCardCount > 0 ? mCard[mCardCount - 1] : null;
float my = mCardCount > 0 ? topCard.GetY() : mY;
if (IsOverCard(x, y, close)) {
if (topCard == null || card.GetValue() == topCard.GetValue() - 1) {
return true;
}
}
return false;
}
@Override
public int GetMovableCount() {
if (mCardCount < 2)
return mCardCount;
int retCount = 1;
int suit = mCard[mCardCount-1].GetSuit();
int val = mCard[mCardCount-1].GetValue();
for (int i = mCardCount-2; i >= mHiddenCount; i--, retCount++, val++) {
if (mCard[i].GetSuit() != suit || mCard[i].GetValue() != val + 1) {
break;
}
}
return retCount;
}
@Override
public Card[] GetCardStack() {
int retCount = GetMovableCount();
Card[] ret = new Card[retCount];
for (int i = retCount-1; i >= 0; i--) {
ret[i] = PopCard();
}
return ret;
}
@Override
public boolean ExpandStack(float x, float y) {
if (super.ExpandStack(x, y)) {
Card bottom = mCard[mCardCount-1];
Card second = mCard[mCardCount-2];
if (bottom.GetSuit() == second.GetSuit() &&
bottom.GetValue() == second.GetValue() - 1) {
return true;
}
}
return false;
}
@Override
public boolean CanMoveStack(float x, float y) {
if (super.ExpandStack(x, y)) {
float maxY = mCard[mCardCount-GetMovableCount()].GetY();
if (y >= maxY - Card.HEIGHT/2) {
return true;
}
}
return false;
}
}
// Freecell stack
class FreecellStack extends SeqStack {
@Override
public boolean CanDropCard(MoveCard moveCard, int close) {
Card card = moveCard.GetTopCard();
float x = card.GetX() + Card.WIDTH/2;
float y = card.GetY() + Card.HEIGHT/2;
Card topCard = mCardCount > 0 ? mCard[mCardCount - 1] : null;
float my = mCardCount > 0 ? topCard.GetY() : mY;
if (IsOverCard(x, y, close)) {
if (topCard == null) {
if (mRules.CountFreeSpaces() >= moveCard.GetCount()) {
return true;
}
} else if ((card.GetSuit()&1) != (topCard.GetSuit()&1) &&
card.GetValue() == topCard.GetValue() - 1) {
return true;
}
}
return false;
}
@Override
public int GetMovableCount() {
if (mCardCount < 2)
return mCardCount;
int retCount = 1;
int maxMoveCount = mRules.CountFreeSpaces() + 1;
for (int i = mCardCount - 2; i >= 0 && retCount < maxMoveCount; i--, retCount++) {
if ((mCard[i].GetSuit()&1) == (mCard[i+1].GetSuit()&1) ||
mCard[i].GetValue() != mCard[i+1].GetValue() + 1) {
break;
}
}
return retCount;
}
@Override
public Card[] GetCardStack() {
int retCount = GetMovableCount();
Card[] ret = new Card[retCount];
for (int i = retCount-1; i >= 0; i--) {
ret[i] = PopCard();
}
return ret;
}
@Override
public boolean ExpandStack(float x, float y) {
if (super.ExpandStack(x, y)) {
if (mRules.CountFreeSpaces() > 0) {
Card bottom = mCard[mCardCount-1];
Card second = mCard[mCardCount-2];
if ((bottom.GetSuit()&1) != (second.GetSuit()&1) &&
bottom.GetValue() == second.GetValue() - 1) {
return true;
}
}
}
return false;
}
@Override
public boolean CanMoveStack(float x, float y) {
if (super.ExpandStack(x, y)) {
float maxY = mCard[mCardCount-GetMovableCount()].GetY();
if (y >= maxY - Card.HEIGHT/2) {
return true;
}
}
return false;
}
}
// Freecell holding pen
class FreecellHold extends CardAnchor {
@Override
public boolean CanDropCard(MoveCard moveCard, int close) {
Card card = moveCard.GetTopCard();
if (mCardCount == 0 && moveCard.GetCount() == 1 &&
IsOverCard(card.GetX() + Card.WIDTH/2, card.GetY() + Card.HEIGHT/2, close)) {
return true;
}
return false;
}
}
// New Abstract
class GenericAnchor extends CardAnchor {
//Value Sequences
public static final int SEQ_ANY=1; //You can build as you like
public static final int SEQ_SEQ=2; //Building only allows sequential
public static final int SEQ_ASC=3; //Ascending only
public static final int SEQ_DSC=4; //Descending only
//Suit Sequences that limits how adding cards to the stack works
public static final int SUIT_ANY=1; //Build doesn't care about suite
public static final int SUIT_RB=2; //Must alternate Red & Black
public static final int SUIT_OTHER=3;//As long as different
public static final int SUIT_COLOR=4;//As long as same color
public static final int SUIT_SAME=5; //As long as same suit
//Pickup & Dropoff Behavior
public static final int PACK_NONE=1; // Interaction in this mode not allowed
public static final int PACK_ONE=2; //Can only accept 1 card
public static final int PACK_MULTI=3; //Can accept multiple cards
public static final int PACK_FIXED=4; //Don't think this will ever be used
public static final int PACK_LIMIT_BY_FREE=5; //For freecell style movement
//Anchor Display (Hidden vs. Shown faces)
public static final int DISPLAY_ALL=1; //All cards are shown
public static final int DISPLAY_HIDE=2; //All cards are hidden
public static final int DISPLAY_MIX=3; //Uses a mixture
public static final int DISPLAY_ONE=4; //Displays one only
//Hack to fix Spider Dealing
public static final int DEALHACK=1;
protected static final int SMALL_SPACING = 7;
protected static final int HIDDEN_SPACING = 3;
protected int mSpacing;
protected boolean mHideHidden;
protected int mMaxHeight;
public GenericAnchor(){
super();
SetBuildSeq(GenericAnchor.SEQ_ANY);
SetBuildWrap(false);
SetBuildSuit(GenericAnchor.SUIT_ANY);
SetDropoff(GenericAnchor.PACK_NONE);
SetPickup(GenericAnchor.PACK_NONE);
SetDisplay(GenericAnchor.DISPLAY_ALL);
mSpacing = GetMaxSpacing();
mHideHidden = false;
mMaxHeight = Card.HEIGHT;
}
@Override
public void SetMaxHeight(int maxHeight) {
mMaxHeight = maxHeight;
CheckSizing();
SetPosition(mX, mY);
}
@Override
protected void SetCardPosition(int idx) {
if (idx < mHiddenCount) {
if (mHideHidden) {
mCard[idx].SetPosition(mX, mY);
} else {
mCard[idx].SetPosition(mX, mY + HIDDEN_SPACING * idx);
}
} else {
int startY = mHideHidden ? HIDDEN_SPACING : mHiddenCount * HIDDEN_SPACING;
int y = (int)mY + startY + (idx - mHiddenCount) * mSpacing;
mCard[idx].SetPosition(mX, y);
}
}
@Override
public void SetHiddenCount(int count) {
super.SetHiddenCount(count);
CheckSizing();
SetPosition(mX, mY);
}
@Override
public void AddCard(Card card) {
super.AddCard(card);
CheckSizing();
if (mHACK == GenericAnchor.DEALHACK){
mRules.EventAlert(Rules.EVENT_STACK_ADD, this);
}
}
@Override
public Card PopCard() {
Card ret = super.PopCard();
CheckSizing();
return ret;
}
@Override
public boolean CanDropCard(MoveCard moveCard, int close) {
if (mDROPOFF == GenericAnchor.PACK_NONE){
return false;
}
Card card = moveCard.GetTopCard();
float x = card.GetX() + Card.WIDTH/2;
float y = card.GetY() + Card.HEIGHT/2;
//Card topCard = mCardCount > 0 ? mCard[mCardCount - 1] : null;
//float my = mCardCount > 0 ? topCard.GetY() : mY;
if (IsOverCard(x, y, close)) {
return CanBuildCard(card);
}
return false;
}
public boolean CanBuildCard(Card card){
// SEQ_ANY will allow all
if (mBUILDSEQ == GenericAnchor.SEQ_ANY){
return true;
}
Card topCard = mCardCount > 0 ? mCard[mCardCount - 1] : null;
// Rules for empty stacks
if (topCard == null) {
//No rules for this yet
return true;
}
int value = card.GetValue();
int suit = card.GetSuit();
int tvalue = topCard.GetValue();
int tsuit = topCard.GetSuit();
// Fail if sequence is wrong
switch (mBUILDSEQ){
//WRAP_NOWRAP=1; //Building stacks do not wrap
//WRAP_WRAP=2; //Building stacks wraps around
case GenericAnchor.SEQ_ASC:
if (value - tvalue != 1){
return false;
}
break;
case GenericAnchor.SEQ_DSC:
if (tvalue - value != 1){
return false;
}
break;
case GenericAnchor.SEQ_SEQ:
if (Math.abs(tvalue - value) != 1){
return false;
}
break;
}
// Fail if suit is wrong
switch (mBUILDSUIT){
case GenericAnchor.SUIT_RB:
if (Math.abs(tsuit - suit)%2 == 0){ return false; }
break;
case GenericAnchor.SUIT_OTHER:
if (tsuit == suit){ return false; }
break;
case GenericAnchor.SUIT_COLOR:
if (Math.abs(tsuit - suit) != 2){ return false; }
break;
case GenericAnchor.SUIT_SAME:
if (tsuit != suit){ return false; }
break;
}
// Passes all rules
return true;
}
@Override
public void Draw(DrawMaster drawMaster, Canvas canvas) {
if (mCardCount == 0) {
drawMaster.DrawEmptyAnchor(canvas, mX, mY, mDone);
return;
}
switch (mDISPLAY){
case GenericAnchor.DISPLAY_ALL:
for (int i = 0; i < mCardCount; i++) {
drawMaster.DrawCard(canvas, mCard[i]);
}
break;
case GenericAnchor.DISPLAY_HIDE:
for (int i = 0; i < mCardCount; i++) {
drawMaster.DrawHiddenCard(canvas, mCard[i]);
}
break;
case GenericAnchor.DISPLAY_MIX:
for (int i = 0; i < mCardCount; i++) {
if (i < mHiddenCount) {
drawMaster.DrawHiddenCard(canvas, mCard[i]);
} else {
drawMaster.DrawCard(canvas, mCard[i]);
}
}
break;
case GenericAnchor.DISPLAY_ONE:
for (int i = 0; i < mCardCount; i++) {
if (i < mCardCount-1) {
drawMaster.DrawHiddenCard(canvas, mCard[i]);
} else {
drawMaster.DrawCard(canvas, mCard[i]);
}
}
break;
}
}
@Override
public boolean ExpandStack(float x, float y) {
if (IsOverDeck(x, y)) {
return (GetMovableCount() > 0);
/*
if (mHiddenCount >= mCardCount) {
mHiddenCount = mCardCount == 0 ? 0 : mCardCount - 1;
} else if (mCardCount - mHiddenCount > 1) {
return true;
}
*/
}
return false;
}
@Override
public boolean CanMoveStack(float x, float y) { return ExpandStack(x, y); }
@Override
public Card[] GetCardStack() {
int movableCount = GetMovableCount();
Card[] ret = new Card[movableCount];
for (int i = movableCount-1; i >= 0; i--) {
ret[i] = PopCard();
}
return ret;
}
@Override
public int GetMovableCount() {
int visibleCount = GetVisibleCount();
if (visibleCount == 0 || mPICKUP == GenericAnchor.PACK_NONE){
return 0;
}
int seq_allowed = 1;
if (visibleCount > 1){
int i = mCardCount-1;
boolean g;
boolean h;
do {
g = true;
h = true;
switch (mMOVESEQ){
case GenericAnchor.SEQ_ANY:
h = true;
break;
case GenericAnchor.SEQ_ASC:
- h = this.is_seq_asc(i-1, i, mMOVEWRAP) == false;
+ h = this.is_seq_asc(i-1, i, mMOVEWRAP);
break;
case GenericAnchor.SEQ_DSC:
- h = this.is_seq_asc(i, i-1, mMOVEWRAP) == false;
+ h = this.is_seq_asc(i, i-1, mMOVEWRAP);
break;
case GenericAnchor.SEQ_SEQ:
h = (this.is_seq_asc(i, i-1, mMOVEWRAP) ||
this.is_seq_asc(i-1, i, mMOVEWRAP));
break;
}
if (h == false){
g = false;
}
switch (mMOVESUIT){
case GenericAnchor.SUIT_ANY:
h = true;
break;
case GenericAnchor.SUIT_COLOR:
h = !this.is_suit_rb(i-1,i);
break;
case GenericAnchor.SUIT_OTHER:
h = this.is_suit_other(i-1, i);
break;
case GenericAnchor.SUIT_RB:
h = this.is_suit_rb(i-1, i);
break;
case GenericAnchor.SUIT_SAME:
h = this.is_suit_same(i-1, i);
break;
}
if (h == false){
g = false;
}
if (g){ seq_allowed++; }
i--;
}while(g && (mCardCount - i) < visibleCount);
}
switch (mPICKUP){
case GenericAnchor.PACK_NONE:
return 0;
case GenericAnchor.PACK_ONE:
seq_allowed = Math.min(1, seq_allowed);
break;
case GenericAnchor.PACK_MULTI:
break;
case GenericAnchor.PACK_FIXED:
//seq_allowed = Math.min( xmin, seq_allowed);
break;
case GenericAnchor.PACK_LIMIT_BY_FREE:
seq_allowed = Math.min(mRules.CountFreeSpaces()+1, seq_allowed);
break;
}
return seq_allowed;
}
public boolean is_seq_asc(int p1, int p2, boolean wrap){
Card c1 = mCard[p1];
Card c2 = mCard[p2];
int v1 = c1.GetValue();
int v2 = c2.GetValue();
- if (v2 == v1 + 1){
+ if (v2 + 1 == v1){
return true;
}
if (wrap){
if (v2 == Card.KING && v1 == Card.ACE){
return true;
}
}
return false;
}
public boolean is_suit_rb(int p1, int p2){
Card c1 = mCard[p1];
Card c2 = mCard[p2];
int s1 = c1.GetSuit();
int s2 = c2.GetSuit();
if ( (s1 == Card.CLUBS || s1 == Card.SPADES) &&
(s2 == Card.HEARTS || s2 == Card.DIAMONDS) ){
return true;
}
if ( (s1 == Card.HEARTS || s1 == Card.DIAMONDS) &&
(s2 == Card.CLUBS || s2 == Card.SPADES) ){
return true;
}
return false;
}
public boolean is_suit_same(int p1, int p2){
return (mCard[p1].GetSuit() == mCard[p2].GetSuit());
}
public boolean is_suit_other(int p1, int p2){
return (mCard[p1].GetSuit() != mCard[p2].GetSuit());
}
private void CheckSizing() {
if (mCardCount < 2 || mCardCount - mHiddenCount < 2) {
mSpacing = GetMaxSpacing();
mHideHidden = false;
return;
}
int max = mMaxHeight;
int hidden = mHiddenCount;
int showing = mCardCount - hidden;
int spaceLeft = max - (hidden * HIDDEN_SPACING) - Card.HEIGHT;
int spacing = spaceLeft / (showing - 1);
if (spacing < SMALL_SPACING && hidden > 1) {
mHideHidden = true;
spaceLeft = max - HIDDEN_SPACING - Card.HEIGHT;
spacing = spaceLeft / (showing - 1);
} else {
mHideHidden = false;
if (spacing > GetMaxSpacing()) {
spacing = GetMaxSpacing();
}
}
if (spacing != mSpacing) {
mSpacing = spacing;
SetPosition(mX, mY);
}
}
// This can't be a constant as Card.HEIGHT isn't constant.
protected int GetMaxSpacing() {
return Card.HEIGHT/3;
}
+ public float GetNewY() {
+ if (mCardCount == 0) {
+ return mY;
+ }
+ return mCard[mCardCount-1].GetY() + mSpacing;
+ }
}
| false | false | null | null |
diff --git a/jbossas71/subsystem/src/main/java/com/camunda/fox/platform/subsystem/impl/platform/ContainerPlatformService.java b/jbossas71/subsystem/src/main/java/com/camunda/fox/platform/subsystem/impl/platform/ContainerPlatformService.java
index 37d7d1a87..d6e066732 100755
--- a/jbossas71/subsystem/src/main/java/com/camunda/fox/platform/subsystem/impl/platform/ContainerPlatformService.java
+++ b/jbossas71/subsystem/src/main/java/com/camunda/fox/platform/subsystem/impl/platform/ContainerPlatformService.java
@@ -1,175 +1,182 @@
package com.camunda.fox.platform.subsystem.impl.platform;
import java.util.concurrent.Future;
import java.util.logging.Logger;
import javax.transaction.TransactionManager;
import org.jboss.as.connector.subsystems.datasources.DataSourceReferenceFactoryService;
import org.jboss.as.naming.ManagedReferenceFactory;
import org.jboss.as.naming.ServiceBasedNamingStore;
import org.jboss.as.naming.deployment.ContextNames;
import org.jboss.as.naming.service.BinderService;
import org.jboss.msc.service.AbstractServiceListener;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.msc.service.ServiceContainer;
import org.jboss.msc.service.ServiceController;
import org.jboss.msc.service.ServiceController.Mode;
import org.jboss.msc.service.ServiceController.Substate;
import org.jboss.msc.service.ServiceController.Transition;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
import com.camunda.fox.platform.FoxPlatformException;
import com.camunda.fox.platform.impl.service.PlatformService;
import com.camunda.fox.platform.spi.ProcessEngineConfiguration;
import com.camunda.fox.platform.subsystem.impl.util.PlatformServiceReferenceFactory;
/**
* @author Daniel Meyer
*/
public class ContainerPlatformService extends PlatformService implements Service<ContainerPlatformService> {
private static Logger log = Logger.getLogger(ContainerPlatformService.class.getName());
// state ///////////////////////////////////////////
// jndi bindings
protected ServiceController<ManagedReferenceFactory> processArchiveServiceBinding;
protected ServiceController<ManagedReferenceFactory> processEngineServiceBinding;
private ServiceContainer serviceContainer;
///////////////////////////////////////////////////
@Override
public void start(StartContext context) throws StartException {
serviceContainer = context.getController().getServiceContainer();
createJndiBindings(context);
}
@Override
public void stop(StopContext context) {
removeJndiBindings();
}
protected void createJndiBindings(StartContext context) {
final String prefix = "java:global/camunda-fox-platform/";
final String processArchiveServiceSuffix = "PlatformService!com.camunda.fox.platform.api.ProcessArchiveService";
final String processEngineServiceSuffix = "PlatformService!com.camunda.fox.platform.api.ProcessEngineService";
String moduleName = "process-engine";
final String processArchiveServiceBindingName = prefix + moduleName + "/"+ processArchiveServiceSuffix;
final String processEngineServiceBindingName = prefix + moduleName + "/"+ processEngineServiceSuffix;
final ServiceName processEngineServiceBindingServiceName = ContextNames.GLOBAL_CONTEXT_SERVICE_NAME
.append("camunda-fox-platform")
.append(moduleName)
.append(processEngineServiceSuffix);
final ServiceName processArchiveServiceBindingServiceName = ContextNames.GLOBAL_CONTEXT_SERVICE_NAME
.append("camunda-fox-platform")
.append(moduleName)
.append(processArchiveServiceSuffix);
final ServiceContainer serviceContainer = context.getController().getServiceContainer();
BinderService processEngineServiceBinder = new BinderService(processEngineServiceBindingName);
ServiceBuilder<ManagedReferenceFactory> processEngineServiceBuilder = serviceContainer
.addService(processEngineServiceBindingServiceName, processEngineServiceBinder);
processEngineServiceBuilder.addDependency(ContextNames.GLOBAL_CONTEXT_SERVICE_NAME, ServiceBasedNamingStore.class, processEngineServiceBinder.getNamingStoreInjector());
processEngineServiceBinder.getManagedObjectInjector().inject(new PlatformServiceReferenceFactory(this));
BinderService processArchiveServiceBinder = new BinderService(processEngineServiceBindingName);
ServiceBuilder<ManagedReferenceFactory> processArchiveServiceBuilder = serviceContainer.addService(processArchiveServiceBindingServiceName, processArchiveServiceBinder);
processArchiveServiceBuilder.addDependency(ContextNames.GLOBAL_CONTEXT_SERVICE_NAME, ServiceBasedNamingStore.class, processArchiveServiceBinder.getNamingStoreInjector());
processArchiveServiceBinder.getManagedObjectInjector().inject(new PlatformServiceReferenceFactory(this));
processEngineServiceBinding = processEngineServiceBuilder.install();
processArchiveServiceBinding = processArchiveServiceBuilder.install();
log.info("the bindings for the fox platform services are as follows: \n\n"
+ " "
+ processArchiveServiceBindingName + "\n"
+ " "
+ processEngineServiceBindingName + "\n");
}
protected void removeJndiBindings() {
processEngineServiceBinding.setMode(Mode.REMOVE);
processArchiveServiceBinding.setMode(Mode.REMOVE);
}
public Future<ProcessEngineStartOperation> startProcessEngine(ProcessEngineConfiguration processEngineConfiguration) {
final ProcessEngineControllerService processEngineController = new ProcessEngineControllerService(processEngineConfiguration);
final ContextNames.BindInfo datasourceBindInfo = ContextNames.bindInfoFor(processEngineConfiguration.getDatasourceJndiName());
final ServiceListenerFuture<ProcessEngineControllerService, ProcessEngineStartOperation> listener = new ServiceListenerFuture<ProcessEngineControllerService, ProcessEngineStartOperation>(processEngineController) {
protected void serviceAvailable() {
this.value = new ProcessEngineStartOperationImpl(serviceInstance.getProcessEngine());
}
};
serviceContainer.addService(ProcessEngineControllerService.createServiceName(processEngineConfiguration.getProcessEngineName()), processEngineController)
.addDependency(ServiceName.JBOSS.append("txn").append("TransactionManager"), TransactionManager.class, processEngineController.getTransactionManagerInjector())
.addDependency(datasourceBindInfo.getBinderServiceName(), DataSourceReferenceFactoryService.class, processEngineController.getDatasourceBinderServiceInjector())
.addDependency(getServiceName(), ContainerPlatformService.class, processEngineController.getContainerPlatformServiceInjector())
.setInitialMode(Mode.ACTIVE)
.addListener(listener)
.install();
return listener;
}
@SuppressWarnings("unchecked")
public void stopProcessEngine(String name) {
if(!processEngineRegistry.getProcessEngineNames().contains(name)) {
throw new FoxPlatformException("Cannot stop process engine '"+name+"': no such process engine found");
} else {
- ServiceController<ProcessEngineControllerService> service =
- (ServiceController<ProcessEngineControllerService>) serviceContainer.getService(ProcessEngineControllerService.createServiceName(name));
+
+ final ServiceName createServiceName = ProcessEngineControllerService.createServiceName(name);
+ final ServiceController<ProcessEngineControllerService> service = (ServiceController<ProcessEngineControllerService>) serviceContainer.getService(createServiceName);
final Object shutdownMonitor = new Object();
service.addListener(new AbstractServiceListener<ProcessEngineControllerService>() {
public void transition(ServiceController< ? extends ProcessEngineControllerService> controller, Transition transition) {
- if(transition.getAfter().equals(Substate.DOWN)) {
+ if(isDown(transition.getAfter())) {
synchronized (shutdownMonitor) {
shutdownMonitor.notifyAll();
}
}
}
});
- // block until the service is down (give up after 2 minutes):
+
synchronized (shutdownMonitor) {
- service.setMode(Mode.REMOVE);
- try {
- shutdownMonitor.wait(2*60*1000);
- if(!service.getSubstate().equals(Substate.DOWN)) {
- throw new FoxPlatformException("Timeout while waiting for process engine '"+name+"' to shut down.");
+ service.setMode(Mode.REMOVE);
+ if (!isDown(service.getSubstate())) {
+ try {
+ // block until the service is down (give up after 2 minutes):
+ shutdownMonitor.wait(2 * 60 * 1000);
+ } catch (InterruptedException e) {
+ throw new FoxPlatformException("Interrupted while waiting for process engine '" + name + "' to shut down.");
}
- } catch (InterruptedException e) {
- throw new FoxPlatformException("Interrupted while waiting for process engine '"+name+"' to shut down.");
- }
+ }
}
+
}
}
+
+ private boolean isDown(Substate state) {
+ return state.equals(Substate.DOWN)||state.equals(Substate.REMOVED);
+ }
+
public ContainerPlatformService getValue() throws IllegalStateException, IllegalArgumentException {
return this;
}
public static ServiceName getServiceName() {
return ServiceName.of("foxPlatform", "platformService");
}
}
| false | false | null | null |
diff --git a/Lab0/src/MessagePasser.java b/Lab0/src/MessagePasser.java
index ad276bc..1ffe834 100644
--- a/Lab0/src/MessagePasser.java
+++ b/Lab0/src/MessagePasser.java
@@ -1,263 +1,299 @@
import java.io.*;
import java.security.AccessControlException;
import java.security.AccessController;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.net.*;
import org.yaml.snakeyaml.Yaml;
/* The next three comments may all need to be handled in the MessagePasser class instead of here. */
/*Check if a file has been modified since last time by storing an MD5 hash
of the file and checking before each send and receive method...*/
/* Setup sockets for each of the nodes identified in the config file here. */
/* Whenever we call receive, we should get the frontmost msg in the recv queue. */
/* MessagePasser is responsible for keeping track of all IDs assigned and for
* ensuring monotonicity and uniqueness. The source:ID pair must be unique, but
* IDs can be reused across different nodes. */
public class MessagePasser {
//public MessagePasser(String configuration_filename, String local_name); //constructor
public MessagePasser(String configuration_filename, String local_name) {
/* Create send and recv buffers of 1 MB each */
String[] send_buf = null; //where we'll store the send buffered messages per connection.
String[] recv_buf = null;
//create (from the ArrayList class in Java) sockets for the nodes.
//Using TCP sockets, so keep the connection alive for more than just the send/receive of a message.
}
void send(Message message) {
/*Should keep track of IDs and make sure to send next unused ID (should be
*monotonically increasing). Need to write the code for set_id in the
*Message class. ALSO, this should check the message against the send
*rules to handle the message appropriately. */
int id = 0; //placeholder for now
message.set_id(id);
/* Upon sending of a message, check the size and then free that amount from the buffer. */
}
Message receive( ) {
/*check if anything in the receive buffer to be processed according to the rules.
* If above check is passed (ie. a message should be delivered) we should get the
* front-most msg in the recv queue. As of 01/15/13, we plan to make the receiver
* block.
*/
/* Upon receiving a message, check the size and then remove that amount from the buffer's free space. */
return null;
} // may block
void parseConfig(String fname) {
/*Parses the configuration file. Not sure where to put this. ALSO, not finished.
* Taken from a Yaml tutorial on SnakeYaml's Google code page.
*/
InputStream yamlInput = null;
Yaml yaml = new Yaml();
String config = "";
String[] conf2 = null;
FilePermission perm = null;
/*Configuration conf_obj = new Configuration();
SendRule send_obj = new SendRule();
ReceiveRule recv_obj = new ReceiveRule();*/
/*perm = new FilePermission(fname, "read"); //Currently not working correctly...
try {
AccessController.checkPermission(perm);
} catch (AccessControlException e) {
System.out.println("File "+fname+" is not readable.\n");
System.exit(-1); //probably want to just return -1
}*/
try {
yamlInput = new FileInputStream(new File(fname));
} catch (FileNotFoundException e) {
//error out if not found
System.out.println("File "+fname+" does not exist.\n");
System.exit(-1); //probably want to just return -1
}
Object data = yaml.load(yamlInput);
LinkedHashMap<String,String> file_map = (LinkedHashMap<String,String>) data;
String whole = "";
String[] elements = new String[10]; //figure out appropriate size for these
String[] pairs = new String[10];
String[] choices = new String[10];
String file_part = "";
Set set = file_map.entrySet();
Iterator i = set.iterator();
HashMap configuration = new HashMap<String, String>();
HashMap send_rules = new HashMap<String, String>();
HashMap recv_rules = new HashMap<String, String>();
int j = 0;
ArrayList names = new ArrayList<String>();
ArrayList ip_addys = new ArrayList();
ArrayList ports = new ArrayList();
ArrayList sr_act = new ArrayList<String>();
ArrayList sr_src = new ArrayList();
ArrayList sr_dst = new ArrayList();
ArrayList sr_kind = new ArrayList<String>();
ArrayList sr_id = new ArrayList();
ArrayList sr_nth = new ArrayList();
ArrayList sr_every = new ArrayList();
ArrayList rr_act = new ArrayList<String>();
ArrayList rr_src = new ArrayList();
ArrayList rr_dst = new ArrayList();
ArrayList rr_kind = new ArrayList<String>();
ArrayList rr_id = new ArrayList();
ArrayList rr_nth = new ArrayList();
ArrayList rr_every = new ArrayList();
while(i.hasNext())
{
Map.Entry me = (Map.Entry)i.next();
file_part = me.getKey().toString().toLowerCase();
System.out.print("\nRaw parsed data --> "+file_part + ": ");
System.out.println(me.getValue());
ArrayList<String> inner = new ArrayList<String>();
inner.add(me.getValue().toString());
whole = inner.toString();
whole = whole.replaceAll("[\\[\\]\\{]", "");
//System.out.println("Whole is: "+whole);
elements = whole.split("\\},?");
//System.out.println("element is: "+elements[0]);
for(j=0; j<elements.length; j++) //fix this stuff, make it scalable, etc...
{
pairs = elements[j].split(", ");
if(file_part.equals("sendrules"))
{
//System.out.println("inner: "+elements[j]);
//System.out.println(pairs.length+" pairs are: "+pairs[0]+" "+pairs[1]+" "+pairs[2]);
for(int k=0; k<pairs.length; k++)
{
choices = pairs[k].split("=");
choices[0] = choices[0].trim().toLowerCase();
//System.out.println("Pairs: "+pairs[0].toLowerCase()+" "+pairs[1]);
if(choices[0].equals("action"))
sr_act.add(choices[1]);
else if(choices[0].equals("src"))
sr_src.add(choices[1]);
else if(choices[0].equals("dst"))
sr_dst.add(choices[1]);
else if(choices[0].equals("kind"))
sr_kind.add(choices[1]);
else if(choices[0].equals("id"))
sr_id.add(choices[1]);
else if(choices[0].equals("nth"))
sr_nth.add(choices[1]);
else if(choices[0].equals("everynth"))
sr_every.add(choices[1]);
- //need to figure out how to make each of the lists the same length by adding wildcards to all empty fields
+
+ if(k == pairs.length-1) //make each of the lists the same length by adding wildcards to all empty fields
+ {
+ int l_len = sr_act.size();
+ if(sr_src.size() < l_len)
+ sr_src.add("*");
+ if(sr_dst.size() < l_len)
+ sr_dst.add("*");
+ if(sr_kind.size() < l_len)
+ sr_kind.add("*");
+ if(sr_id.size() < l_len)
+ sr_id.add("*");
+ if(sr_nth.size() < l_len)
+ sr_nth.add("*");
+ if(sr_every.size() < l_len)
+ sr_every.add("*");
+ //System.out.println("ID list length is "+sr_id.size()+" instead of "+sr_act.size());
+ }
}
}
else if(file_part.equals("receiverules"))
{
//System.out.println("inner: "+elements[j]);
//System.out.println(pairs.length+" pairs are: "+pairs[0]+" "+pairs[1]+" "+pairs[2]);
for(int k=0; k<pairs.length; k++)
{
choices = pairs[k].split("=");
choices[0] = choices[0].trim().toLowerCase();
//System.out.println("Pairs: "+pairs[0].toLowerCase()+" "+pairs[1]);
if(choices[0].equals("action"))
rr_act.add(choices[1]);
else if(choices[0].equals("src"))
rr_src.add(choices[1]);
else if(choices[0].equals("dst"))
rr_dst.add(choices[1]);
else if(choices[0].equals("kind"))
rr_kind.add(choices[1]);
else if(choices[0].equals("id"))
rr_id.add(choices[1]);
else if(choices[0].equals("nth"))
rr_nth.add(choices[1]);
else if(choices[0].equals("everynth"))
rr_every.add(choices[1]);
//need to figure out how to make each of the lists the same length by adding wildcards to all empty fields in the right place
+ //check pairs.length and once (pairs.length-1) is reached, fill in all empty fields.
+
+ if(k == pairs.length-1) //make each of the lists the same length by adding wildcards to all empty fields
+ {
+ int l_len = rr_act.size();
+ if(rr_src.size() < l_len)
+ rr_src.add("*");
+ if(rr_dst.size() < l_len)
+ rr_dst.add("*");
+ if(rr_kind.size() < l_len)
+ rr_kind.add("*");
+ if(rr_id.size() < l_len)
+ rr_id.add("*");
+ if(rr_nth.size() < l_len)
+ rr_nth.add("*");
+ if(rr_every.size() < l_len)
+ rr_every.add("*");
+ //System.out.println("ID list length is "+sr_id.size()+" instead of "+sr_act.size());
+ }
}
}
else if(file_part.equals("configuration")) //handle config third because it happens least often?
{
//System.out.println("inner: "+elements[j]);
//System.out.println(pairs.length+" pairs are: "+pairs[0]+" "+pairs[1]+" "+pairs[2]);
for(int k=0; k<pairs.length; k++)
{
choices = pairs[k].split("=");
choices[0] = choices[0].trim();
//System.out.println("Pairs: "+pairs[0].toLowerCase()+" "+pairs[1]);
if(choices[0].toLowerCase().equals("name"))
names.add(choices[1]);
else if(choices[0].toLowerCase().equals("ip"))
ip_addys.add(choices[1]);
else if(choices[0].toLowerCase().equals("port"))
ports.add(choices[1]);
//System.out.println("First of pair is "+pairs[0]);
/*if(configuration.containsKey(pairs[0]))
configuration.put(pairs[0], configuration.get(pairs[0])+" "+pairs[1]); //append to the value of that key
configuration.put(pairs[0], pairs[1]);*/
}
}
else
{
System.out.println("Error!");
break;
}
}
}
send_rules.put("action", sr_act);
send_rules.put("src", sr_src);
send_rules.put("dst", sr_dst);
send_rules.put("kind", sr_kind);
send_rules.put("id", sr_id);
send_rules.put("nth", sr_nth);
send_rules.put("everynth", sr_every);
recv_rules.put("action", rr_act);
recv_rules.put("src", rr_src);
recv_rules.put("dst", rr_dst);
recv_rules.put("kind", rr_kind);
recv_rules.put("id", rr_id);
recv_rules.put("nth", rr_nth);
recv_rules.put("everynth", rr_every);
configuration.put("name", names);
configuration.put("ip", ip_addys);
configuration.put("port", ports);
//Just temporary print statements for reference
System.out.println("Config Dict contains "+ configuration.keySet()+" and "+ configuration.values());
System.out.println("Send Dict contains "+ send_rules.keySet()+" and "+ send_rules.values());
System.out.println("Recv Dict contains "+ recv_rules.keySet()+" and "+ recv_rules.values());
try {
yamlInput.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//TODO: Check to see if localName was found in the NAMES section of the config file; if not, return -1 ?
}
}
\ No newline at end of file
| false | false | null | null |
diff --git a/edu/cmu/sphinx/result/Node.java b/edu/cmu/sphinx/result/Node.java
index 2798e3c3..f08a300b 100644
--- a/edu/cmu/sphinx/result/Node.java
+++ b/edu/cmu/sphinx/result/Node.java
@@ -1,556 +1,556 @@
/*
* Copyright 1999-2002 Carnegie Mellon University.
* Portions Copyright 2002 Sun Microsystems, Inc.
* Portions Copyright 2002 Mitsubishi Electric Research Laboratories.
* All Rights Reserved. Use is subject to license terms.
*
* See the file "license.terms" for information on usage and
* redistribution of this file, and for a DISCLAIMER OF ALL
* WARRANTIES.
*
*/
package edu.cmu.sphinx.result;
import edu.cmu.sphinx.linguist.dictionary.Word;
import edu.cmu.sphinx.result.Lattice;
import edu.cmu.sphinx.result.Edge;
import edu.cmu.sphinx.util.LogMath;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.Iterator;
import java.util.Vector;
import java.util.Collection;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
/**
* Nodes are part of Lattices. The represent theories that words were spoken over a given time.
*/
public class Node {
protected static int nodeCount = 0; // used to generate unique IDs for new Nodes.
protected String id;
protected Word word;
protected int beginTime = -1;
protected int endTime = -1;
protected Vector enteringEdges;
protected Vector leavingEdges;
protected double forwardScore;
protected double backwardScore;
protected double posterior;
protected Node bestPredecessor;
protected double viterbiScore;
protected Set descendants;
{
enteringEdges = new Vector();
leavingEdges = new Vector();
nodeCount++;
}
/**
* Create a new Node
*
* @param word the word of this node
* @param beginTime the start time of the word
* @param endTime the end time of the word
*/
protected Node(Word word, int beginTime, int endTime) {
this(getNextNodeId(), word, beginTime, endTime);
}
/**
* Create a new Node with given ID.
* Used when creating a Lattice from a .LAT file
*
* @param id
* @param word
* @param beginTime
* @param endTime
*/
protected Node(String id, Word word, int beginTime, int endTime) {
this.id = id;
this.word = word;
this.beginTime = beginTime;
this.endTime = endTime;
this.forwardScore = LogMath.getLogZero();
this.backwardScore = LogMath.getLogZero();
this.posterior = LogMath.getLogZero();
}
/**
* Get a unique ID for a new Node.
* Used when creating a Lattice from a .LAT file
*
* @return the unique ID for a new node
*/
protected static String getNextNodeId() {
return Integer.toString(nodeCount);
}
/**
* Test if a node has an Edge to a Node
* @param n
* @return unique Node ID
*/
protected boolean hasEdgeToNode(Node n) {
return getEdgeToNode(n) != null;
}
/**
* given a node find the edge to that node
*
* @param n the node of interest
*
* @return the edge to that node or <code> null</code> if no edge
* could be found.
*/
public Edge getEdgeToNode(Node n) {
for (Iterator j = leavingEdges.iterator(); j.hasNext();) {
Edge e = (Edge) j.next();
if (e.getToNode() == n) {
return e;
}
}
return null;
}
/**
* Test is a Node has an Edge from a Node
*
* @param n
* @return true if this node has an Edge from n
*/
protected boolean hasEdgeFromNode(Node n) {
return getEdgeFromNode(n) != null;
}
/**
* given a node find the edge from that node
*
* @param n the node of interest
*
* @return the edge from that node or <code> null</code> if no edge
* could be found.
*/
public Edge getEdgeFromNode(Node n) {
for (Iterator j = enteringEdges.iterator(); j.hasNext();) {
Edge e = (Edge) j.next();
if (e.getFromNode() == n) {
return e;
}
}
return null;
}
/**
* Test if a Node has all Edges from the same Nodes and another Node.
*
* @param n
* @return true if this Node has Edges from the same Nodes as n
*/
protected boolean hasEquivalentEnteringEdges(Node n) {
if (enteringEdges.size() != n.getEnteringEdges().size()) {
return false;
}
for (Iterator i = enteringEdges.iterator(); i.hasNext();) {
Edge e = (Edge) i.next();
Node fromNode = e.getFromNode();
if (!n.hasEdgeFromNode(fromNode)) {
return false;
}
}
return true;
}
/**
* Test if a Node has all Edges to the same Nodes and another Node.
*
* @param n the node of interest
* @return true if this Node has all Edges to the sames Nodes as n
*/
public boolean hasEquivalentLeavingEdges(Node n) {
if (leavingEdges.size() != n.getLeavingEdges().size()) {
return false;
}
for (Iterator i = leavingEdges.iterator(); i.hasNext();) {
Edge e = (Edge) i.next();
Node toNode = e.getToNode();
if (!n.hasEdgeToNode(toNode)) {
return false;
}
}
return true;
}
/**
* Get the Edges to this Node
*
* @return Edges to this Node
*/
public Collection getEnteringEdges() {
return enteringEdges;
}
/**
* Get the Edges from this Node
*
* @return Edges from this Node
*/
public Collection getLeavingEdges() {
return leavingEdges;
}
/**
* Returns a copy of the Edges from this Node, so that the underlying
* data structure will not be modified.
*
* @return a copy of the edges from this node
*/
public Collection getCopyOfLeavingEdges() {
return new Vector(leavingEdges);
}
/**
* Add an Edge from this Node
*
* @param e
*/
protected void addEnteringEdge(Edge e) {
enteringEdges.add(e);
}
/**
* Add an Edge to this Node
*
* @param e
*/
protected void addLeavingEdge(Edge e) {
leavingEdges.add(e);
}
/**
* Remove an Edge from this Node
*
* @param e
*/
protected void removeEnteringEdge(Edge e) {
enteringEdges.remove(e);
}
/**
* Remove an Edge to this Node
*
* @param e the edge to remove
*/
public void removeLeavingEdge(Edge e) {
leavingEdges.remove(e);
}
/**
* Get the ID associated with this Node
*
* @return the ID
*/
public String getId() {
return id;
}
/**
* Get the word associated with this Node
*
* @return the word
*/
public Word getWord() {
return word;
}
/**
* Get the frame number when the word began
*
* @return the begin frame number, or -1 if the frame number is unknown
*/
public int getBeginTime() {
if (beginTime == -1) {
calculateBeginTime();
}
return beginTime;
}
/**
* Get the frame number when the word ends
*
* @return the end time, or -1 if the frame number if is unknown
*/
public int getEndTime() {
return endTime;
}
/**
* Returns a description of this Node that contains the word, the
* start time, and the end time.
*
* @return a description of this Node
*/
public String toString() {
return ("Node(" + word.getSpelling() + "," + getBeginTime() + "|" +
getEndTime() + ")");
}
/**
* Internal routine when dumping Lattices as AiSee files
*
* @param f
* @throws IOException
*/
void dumpAISee(FileWriter f) throws IOException {
String posterior = "" + getPosterior();
if (getPosterior() == LogMath.getLogZero()) {
posterior = "log zero";
}
f.write("node: { title: \"" + id + "\" label: \""
+ getWord() + "[" + getBeginTime() + "," + getEndTime() +
" p:" + posterior + "]\" }\n");
}
/**
* Internal routine used when dumping Lattices as .LAT files
* @param f
* @throws IOException
*/
void dump(PrintWriter f) throws IOException {
f.println("node: " + id + " " + word.getSpelling() +
//" a:" + getForwardProb() + " b:" + getBackwardProb()
" p:" + getPosterior());
}
/**
* Internal routine used when loading Lattices from .LAT files
* @param lattice
* @param tokens
*/
static void load(Lattice lattice, StringTokenizer tokens) {
String id = tokens.nextToken();
String label = tokens.nextToken();
lattice.addNode(id, label, 0, 0);
}
/**
* @return Returns the backwardScore.
*/
public double getBackwardScore() {
return backwardScore;
}
/**
* @param backwardScore The backwardScore to set.
*/
public void setBackwardScore(double backwardScore) {
this.backwardScore = backwardScore;
}
/**
* @return Returns the forwardScore.
*/
public double getForwardScore() {
return forwardScore;
}
/**
* @param forwardScore The forwardScore to set.
*/
public void setForwardScore(double forwardScore) {
this.forwardScore = forwardScore;
}
/**
* @return Returns the posterior probability of this node.
*/
public double getPosterior() {
return posterior;
}
/**
* @param posterior The node posterior probability to set.
*/
public void setPosterior(double posterior) {
this.posterior = posterior;
}
/**
* @see java.lang.Object#hashCode()
*/
public int hashCode() {
return id.hashCode();
}
/**
* Assumes ids are unique node identifiers
*
* @see java.lang.Object#equals(java.lang.Object)
*/
public boolean equals(Object obj) {
return id.equals(((Node)obj).getId());
}
/**
* Calculates the begin time of this node, in the event that the
* begin time was not specified. The begin time is the latest of the
* end times of its predecessor nodes.
*/
private void calculateBeginTime() {
beginTime = 0;
Iterator e = enteringEdges.iterator();
while (e.hasNext()) {
Edge edge = (Edge)e.next();
if (edge.getFromNode().getEndTime() > beginTime) {
beginTime = edge.getFromNode().getEndTime();
}
}
}
/**
* Get the nodes at the other ends of outgoing edges of this node.
*
* @return a list of child nodes
*/
public List getChildNodes() {
LinkedList childNodes = new LinkedList();
Iterator e = leavingEdges.iterator();
while (e.hasNext()) {
Edge edge = (Edge)e.next();
childNodes.add(edge.getToNode());
}
return childNodes;
}
protected void cacheDescendants() {
descendants = new HashSet();
Set seenNodes = new HashSet();
cacheDescendantsHelper(this);
}
protected void cacheDescendantsHelper(Node n) {
Iterator i = n.getChildNodes().iterator();
while (i.hasNext()) {
Node child = (Node)i.next();
if (descendants.contains(child)) {
continue;
}
descendants.add(child);
cacheDescendantsHelper(child);
}
}
protected boolean isAncestorHelper(List children, Node node, Set seenNodes) {
Iterator i = children.iterator();
while(i.hasNext()) {
Node n = (Node)i.next();
if (seenNodes.contains(n)) {
continue;
}
seenNodes.add(n);
if (n.equals(node)) {
return true;
}
if (isAncestorHelper(n.getChildNodes(),node, seenNodes)) {
return true;
}
}
return false;
}
/**
* Check whether this node is an ancestor of another node.
*
* @param node the Node to check
* @return whether this node is an ancestor of the passed in node.
*/
public boolean isAncestorOf(Node node) {
if (descendants != null) {
return descendants.contains(node);
}
if (this.equals(node)) {
return true; // node is its own ancestor
}
Set seenNodes = new HashSet();
seenNodes.add(this);
return isAncestorHelper(this.getChildNodes(),node, seenNodes);
}
/**
* Check whether this node has an ancestral relationship with another node
* (i.e. either this node is an ancestor of the other node, or vice versa)
*
* @param node the Node to check for a relationship
* @return whether a relationship exists
*/
public boolean hasAncestralRelationship(Node node) {
return this.isAncestorOf(node) || node.isAncestorOf(this);
}
/**
* Returns true if the given node is equivalent to this node.
* Two nodes are equivalent only if they have the same word,
* the same number of entering and leaving edges,
* and that their begin and end times are the same.
*
* @param other the Node we're comparing to
*
* @return true if the Node is equivalent; false otherwise
*/
public boolean isEquivalent(Node other) {
return
((word.getSpelling().equals(other.getWord().getSpelling()) &&
(getEnteringEdges().size() == other.getEnteringEdges().size() &&
getLeavingEdges().size() == other.getLeavingEdges().size())) &&
(beginTime == other.getBeginTime() &&
endTime == other.getEndTime()));
}
/**
* Returns a leaving edge that is equivalent to the given edge.
* Two edges are eqivalent if Edge.isEquivalent() returns true.
*
* @param edge the Edge to compare the leaving edges of this node against
*
* @return an equivalent edge, if any; or null if no equivalent edge
*/
public Edge findEquivalentLeavingEdge(Edge edge) {
for (Iterator i = leavingEdges.iterator(); i.hasNext(); ) {
Edge e = (Edge) i.next();
if (e.isEquivalent(edge)) {
return e;
}
}
return null;
}
/**
* @return Returns the bestPredecessor.
*/
public Node getBestPredecessor() {
return bestPredecessor;
}
/**
* @param bestPredecessor The bestPredecessor to set.
*/
public void setBestPredecessor(Node bestPredecessor) {
this.bestPredecessor = bestPredecessor;
}
/**
* @return Returns the viterbiScore.
*/
public double getViterbiScore() {
return viterbiScore;
}
/**
* @param viterbiScore The viterbiScore to set.
*/
- public void setViterbiScore(double bestForwardScore) {
- this.viterbiScore = bestForwardScore;
+ public void setViterbiScore(double viterbiScore) {
+ this.viterbiScore = viterbiScore;
}
}
| true | false | null | null |
diff --git a/support/src/java/org/openqa/selenium/support/ui/Select.java b/support/src/java/org/openqa/selenium/support/ui/Select.java
index b2b95ec4..a4805ae4 100644
--- a/support/src/java/org/openqa/selenium/support/ui/Select.java
+++ b/support/src/java/org/openqa/selenium/support/ui/Select.java
@@ -1,276 +1,280 @@
/*
Copyright 2007-2009 WebDriver committers
Copyright 2007-2009 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.openqa.selenium.support.ui;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebElement;
import java.util.*;
/**
* Models a SELECT tag, providing helper methods to select and deselect options.
*/
public class Select {
private final WebElement element;
private boolean isMulti;
/**
* Constructor. A check is made that the given element is, indeed, a SELECT tag. If it is not,
* then an UnexpectedTagNameException is thrown.
*
* @param element SELECT element to wrap
* @throws UnexpectedTagNameException when element is not a SELECT
*/
public Select(WebElement element) {
String tagName = element.getTagName();
if (null == tagName || !"select".equals(tagName.toLowerCase())) {
throw new UnexpectedTagNameException("select", tagName);
}
this.element = element;
String value = element.getAttribute("multiple");
isMulti = value != null && "multiple".equals(value.toLowerCase());
}
/**
* @return Whether this select element support selecting multiple options at the same time? This
* is done by checking the value of the "multiple" attribute.
*/
public boolean isMultiple() {
return isMulti;
}
/**
* @return All options belonging to this select tag
*/
public List<WebElement> getOptions() {
return element.findElements(By.tagName("option"));
}
/**
* @return All selected options belonging to this select tag
*/
public List<WebElement> getAllSelectedOptions() {
List<WebElement> toReturn = new ArrayList<WebElement>();
for (WebElement option : getOptions()) {
if (option.isSelected()) {
toReturn.add(option);
}
}
return toReturn;
}
/**
* @return The first selected option in this select tag (or the currently selected option in a
* normal select)
*/
public WebElement getFirstSelectedOption() {
for (WebElement option : getOptions()) {
if (option.isSelected()) {
return option;
}
}
throw new NoSuchElementException("No options are selected");
}
/**
* Select all options that display text matching the argument. That is, when given "Bar" this
* would select an option like:
*
* <option value="foo">Bar</option>
*
* @param text The visible text to match against
*/
public void selectByVisibleText(String text) {
// try to find the option via XPATH ...
List<WebElement> options = element.findElements(By.xpath(".//option[. = " + escapeQuotes(text) + "]"));
for (WebElement option : options) {
option.setSelected();
if (!isMultiple()) { return; }
}
if (options.size() == 0 && text.contains(" ")) {
String subStringWithoutSpace = getLongestSubstringWithoutSpace(text);
List<WebElement> candidates;
if ("".equals(subStringWithoutSpace)) {
// hmm, text is either empty or contains only spaces - get all options ...
candidates = element.findElements(By.tagName("option"));
} else {
// get candidates via XPATH ...
candidates = element.findElements(By.xpath(".//option[contains(., " + escapeQuotes(subStringWithoutSpace) + ")]"));
}
for (WebElement option : candidates) {
if (text.equals(option.getText())) {
option.setSelected();
if (!isMultiple()) { return; }
}
}
}
}
private String getLongestSubstringWithoutSpace(String s) {
String result = "";
StringTokenizer st = new StringTokenizer(s, " ");
while (st.hasMoreTokens()) {
String t = st.nextToken();
if (t.length() > result.length()) {
result = t;
}
}
return result;
}
/**
* Select the option at the given index. This is done by examing the "index" attribute of an
* element, and not merely by counting.
*
* @param index The option at this index will be selected
*/
public void selectByIndex(int index) {
String match = String.valueOf(index);
for (WebElement option : getOptions()) {
if (match.equals(option.getAttribute("index"))) {
option.setSelected();
if (isMultiple()) { return; }
}
}
}
/**
* Select all options that have a value matching the argument. That is, when given "foo" this
* would select an option like:
*
* <option value="foo">Bar</option>
*
* @param value The value to match against
*/
public void selectByValue(String value) {
StringBuilder builder = new StringBuilder(".//option[@value = ");
builder.append(escapeQuotes(value));
builder.append("]");
List<WebElement> options = element.findElements(By.xpath(builder.toString()));
for (WebElement option : options) {
option.setSelected();
if (isMultiple()) { return; }
}
}
/**
* Clear all selected entries. This is only valid when the SELECT supports multiple selections.
*
* @throws UnsupportedOperationException If the SELECT does not support multiple selections
*/
public void deselectAll() {
if (!isMultiple()) {
throw new UnsupportedOperationException(
"You may only deselect all options of a multi-select");
}
for (WebElement option : getOptions()) {
if (option.isSelected()) {
option.toggle();
}
}
}
/**
* Deselect all options that have a value matching the argument. That is, when given "foo" this
* would deselect an option like:
*
* <option value="foo">Bar</option>
*
* @param value The value to match against
*/
public void deselectByValue(String value) {
StringBuilder builder = new StringBuilder(".//option[@value = ");
builder.append(escapeQuotes(value));
builder.append("]");
List<WebElement> options = element.findElements(By.xpath(builder.toString()));
for (WebElement option : options) {
if (option.isSelected()) {
option.toggle();
}
}
}
/**
* Deselect the option at the given index. This is done by examing the "index" attribute of an
* element, and not merely by counting.
*
* @param index The option at this index will be deselected
*/
public void deselectByIndex(int index) {
String match = String.valueOf(index);
for (WebElement option : getOptions()) {
if (match.equals(option.getAttribute("index")) && option.isSelected()) {
option.toggle();
}
}
}
/**
* Deselect all options that display text matching the argument. That is, when given "Bar" this
* would deselect an option like:
*
* <option value="foo">Bar</option>
*
* @param text The visible text to match against
*/
public void deselectByVisibleText(String text) {
StringBuilder builder = new StringBuilder(".//option[. = ");
builder.append(escapeQuotes(text));
builder.append("]");
List<WebElement> options = element.findElements(By.xpath(builder.toString()));
for (WebElement option : options) {
if (option.isSelected()) {
option.toggle();
}
}
}
protected String escapeQuotes(String toEscape) {
// Convert strings with both quotes and ticks into: foo'"bar -> concat("foo'", '"', "bar")
if (toEscape.indexOf("\"") > -1 && toEscape.indexOf("'") > -1) {
+ boolean quoteIsLast = false;
+ if (toEscape.indexOf("\"") == toEscape.length() -1) {
+ quoteIsLast = true;
+ }
String[] substrings = toEscape.split("\"");
StringBuilder quoted = new StringBuilder("concat(");
- for (int i = 0; i < substrings.length - 1; i++) {
- quoted.append("\"").append(substrings[i]).append("\", '\"', ");
+ for (int i = 0; i < substrings.length; i++) {
+ quoted.append("\"").append(substrings[i]).append("\"");
+ quoted.append(((i == substrings.length -1) ? (quoteIsLast ? ", '\"')" : ")") : ", '\"', "));
}
- quoted.append("\"").append(substrings[substrings.length - 1]).append("\")");
return quoted.toString();
}
// Escape string with just a quote into being single quoted: f"oo -> 'f"oo'
if (toEscape.indexOf("\"") > -1) {
return String.format("'%s'", toEscape);
}
// Otherwise return the quoted string
return String.format("\"%s\"", toEscape);
}
}
diff --git a/support/test/java/org/openqa/selenium/support/ui/SelectTest.java b/support/test/java/org/openqa/selenium/support/ui/SelectTest.java
index e2eea575..d6c20708 100644
--- a/support/test/java/org/openqa/selenium/support/ui/SelectTest.java
+++ b/support/test/java/org/openqa/selenium/support/ui/SelectTest.java
@@ -1,375 +1,392 @@
/*
Copyright 2007-2009 WebDriver committers
Copyright 2007-2009 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.openqa.selenium.support.ui;
import org.jmock.Expectations;
-import org.jmock.Sequence;
import org.jmock.integration.junit3.MockObjectTestCase;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebElement;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class SelectTest extends MockObjectTestCase {
public void testShouldThrowAnExceptionIfTheElementIsNotASelectElement() {
final WebElement element = mock(WebElement.class);
checking(new Expectations() {{
exactly(1).of(element).getTagName(); will(returnValue("a"));
}});
try {
new Select(element);
fail("Should not have passed");
} catch (UnexpectedTagNameException e) {
// This is expected
}
}
public void testShouldIndicateThatASelectCanSupportMultipleOptions() {
final WebElement element = mock(WebElement.class);
checking(new Expectations() {{
allowing(element).getTagName(); will(returnValue("select"));
exactly(1).of(element).getAttribute("multiple"); will(returnValue("multiple"));
}});
Select select = new Select(element);
assertTrue(select.isMultiple());
}
public void testShouldNotIndicateThatANormalSelectSupportsMulitpleOptions() {
final WebElement element = mock(WebElement.class);
checking(new Expectations() {{
allowing(element).getTagName(); will(returnValue("select"));
exactly(1).of(element).getAttribute("multiple"); will(returnValue(null));
}});
Select select = new Select(element);
assertFalse(select.isMultiple());
}
public void testShouldReturnAllOptionsWhenAsked() {
final WebElement element = mock(WebElement.class);
final List<WebElement> options = Collections.emptyList();
checking(new Expectations() {{
allowing(element).getTagName(); will(returnValue("select"));
allowing(element).getAttribute("multiple"); will(returnValue("multiple"));
exactly(1).of(element).findElements(By.tagName("option")); will(returnValue(options));
}});
Select select = new Select(element);
List<WebElement> returnedOptions = select.getOptions();
assertSame(options, returnedOptions);
}
public void testShouldReturnOptionsWhichAreSelected() {
final WebElement element = mock(WebElement.class);
final WebElement optionGood = mock(WebElement.class, "good");
final WebElement optionBad = mock(WebElement.class, "bad");
final List<WebElement> options = Arrays.asList(optionBad, optionGood);
checking(new Expectations() {{
allowing(element).getTagName(); will(returnValue("select"));
allowing(element).getAttribute("multiple"); will(returnValue("multiple"));
exactly(1).of(element).findElements(By.tagName("option")); will(returnValue(options));
exactly(1).of(optionBad).isSelected(); will(returnValue(false));
exactly(1).of(optionGood).isSelected(); will(returnValue(true));
}});
Select select = new Select(element);
List<WebElement> returnedOptions = select.getAllSelectedOptions();
assertEquals(1, returnedOptions.size());
assertSame(optionGood, returnedOptions.get(0));
}
public void testShouldReturnFirstSelectedOptions() {
final WebElement element = mock(WebElement.class);
final WebElement firstOption = mock(WebElement.class, "first");
final WebElement secondOption = mock(WebElement.class, "second");
final List<WebElement> options = Arrays.asList(firstOption, secondOption);
checking(new Expectations() {{
allowing(element).getTagName(); will(returnValue("select"));
allowing(element).getAttribute("multiple"); will(returnValue("multiple"));
exactly(1).of(element).findElements(By.tagName("option")); will(returnValue(options));
exactly(1).of(firstOption).isSelected(); will(returnValue(true));
never(secondOption).isSelected(); will(returnValue(true));
}});
Select select = new Select(element);
WebElement firstSelected = select.getFirstSelectedOption();
assertSame(firstOption, firstSelected);
}
public void testShouldThrowANoSuchElementExceptionIfNothingIsSelected() {
final WebElement element = mock(WebElement.class);
final WebElement firstOption = mock(WebElement.class, "first");
final List<WebElement> options = Arrays.asList(firstOption);
checking(new Expectations() {{
allowing(element).getTagName(); will(returnValue("select"));
allowing(element).getAttribute("multiple"); will(returnValue("multiple"));
exactly(1).of(element).findElements(By.tagName("option")); will(returnValue(options));
exactly(1).of(firstOption).isSelected(); will(returnValue(false));
}});
Select select = new Select(element);
try {
select.getFirstSelectedOption();
fail();
} catch (NoSuchElementException e) {
// this is expected
}
}
public void testShouldAllowOptionsToBeSelectedByVisibleText() {
final WebElement element = mock(WebElement.class);
final WebElement firstOption = mock(WebElement.class, "first");
final List<WebElement> options = Arrays.asList(firstOption);
checking(new Expectations() {{
allowing(element).getTagName(); will(returnValue("select"));
allowing(element).getAttribute("multiple"); will(returnValue("multiple"));
exactly(1).of(element).findElements(By.xpath(".//option[. = \"fish\"]")); will(returnValue(options));
exactly(1).of(firstOption).setSelected();
}});
Select select = new Select(element);
select.selectByVisibleText("fish");
}
public void testShouldAllowOptionsToBeSelectedByIndex() {
final WebElement element = mock(WebElement.class);
final WebElement firstOption = mock(WebElement.class, "first");
final WebElement secondOption = mock(WebElement.class, "second");
final List<WebElement> options = Arrays.asList(firstOption, secondOption);
checking(new Expectations() {{
allowing(element).getTagName(); will(returnValue("select"));
allowing(element).getAttribute("multiple"); will(returnValue("multiple"));
exactly(1).of(element).findElements(By.tagName("option")); will(returnValue(options));
exactly(1).of(firstOption).getAttribute("index"); will(returnValue("0"));
never(firstOption).setSelected();
exactly(1).of(secondOption).getAttribute("index"); will(returnValue("1"));
exactly(1).of(secondOption).setSelected();
}});
Select select = new Select(element);
select.selectByIndex(1);
}
public void testShouldAllowOptionsToBeSelectedByReturnedValue() {
final WebElement element = mock(WebElement.class);
final WebElement firstOption = mock(WebElement.class, "first");
final List<WebElement> options = Arrays.asList(firstOption);
checking(new Expectations() {{
allowing(element).getTagName(); will(returnValue("select"));
allowing(element).getAttribute("multiple"); will(returnValue("multiple"));
exactly(1).of(element).findElements(By.xpath(".//option[@value = \"b\"]")); will(returnValue(options));
exactly(1).of(firstOption).setSelected();
}});
Select select = new Select(element);
select.selectByValue("b");
}
public void testShouldAllowUserToDeselectAllWhenSelectSupportsMultipleSelections() {
final WebElement element = mock(WebElement.class);
final WebElement firstOption = mock(WebElement.class, "first");
final WebElement secondOption = mock(WebElement.class, "second");
final List<WebElement> options = Arrays.asList(firstOption, secondOption);
checking(new Expectations() {{
allowing(element).getTagName(); will(returnValue("select"));
allowing(element).getAttribute("multiple"); will(returnValue("multiple"));
allowing(element).getAttribute("multiple"); will(returnValue("multiple"));
exactly(1).of(element).findElements(By.tagName("option")); will(returnValue(options));
exactly(1).of(firstOption).isSelected(); will(returnValue(true));
exactly(1).of(firstOption).toggle();
exactly(1).of(secondOption).isSelected(); will(returnValue(false));
never(secondOption).toggle();
}});
Select select = new Select(element);
select.deselectAll();
}
public void testShouldNotAllowUserToDeselectAllWhenSelectDoesNotSupportMultipleSelections() {
final WebElement element = mock(WebElement.class);
checking(new Expectations() {{
allowing(element).getTagName(); will(returnValue("select"));
exactly(1).of(element).getAttribute("multiple"); will(returnValue(""));
}});
Select select = new Select(element);
try {
select.deselectAll();
fail();
} catch (UnsupportedOperationException e) {
// expected
}
}
public void testShouldAllowUserToDeselectOptionsByVisibleText() {
final WebElement element = mock(WebElement.class);
final WebElement firstOption = mock(WebElement.class, "first");
final WebElement secondOption = mock(WebElement.class, "second");
final List<WebElement> options = Arrays.asList(firstOption, secondOption);
checking(new Expectations() {{
allowing(element).getTagName(); will(returnValue("select"));
allowing(element).getAttribute("multiple"); will(returnValue("multiple"));
exactly(1).of(element).findElements(By.xpath(".//option[. = \"b\"]")); will(returnValue(options));
exactly(1).of(firstOption).isSelected(); will(returnValue(true));
exactly(1).of(firstOption).toggle();
exactly(1).of(secondOption).isSelected(); will(returnValue(false));
never(secondOption).toggle();
}});
Select select = new Select(element);
select.deselectByVisibleText("b");
}
public void testShouldAllowOptionsToBeDeselectedByIndex() {
final WebElement element = mock(WebElement.class);
final WebElement firstOption = mock(WebElement.class, "first");
final WebElement secondOption = mock(WebElement.class, "second");
final List<WebElement> options = Arrays.asList(firstOption, secondOption);
checking(new Expectations() {{
allowing(element).getTagName(); will(returnValue("select"));
allowing(element).getAttribute("multiple"); will(returnValue("multiple"));
exactly(1).of(element).findElements(By.tagName("option")); will(returnValue(options));
exactly(1).of(firstOption).getAttribute("index"); will(returnValue("2"));
exactly(1).of(firstOption).isSelected(); will(returnValue(true));
exactly(1).of(firstOption).toggle();
exactly(1).of(secondOption).getAttribute("index"); will(returnValue("1"));
never(secondOption).setSelected();
}});
Select select = new Select(element);
select.deselectByIndex(2);
}
public void testShouldAllowOptionsToBeDeselectedByReturnedValue() {
final WebElement element = mock(WebElement.class);
final WebElement firstOption = mock(WebElement.class, "first");
final WebElement secondOption = mock(WebElement.class, "third");
final List<WebElement> options = Arrays.asList(firstOption, secondOption);
checking(new Expectations() {{
allowing(element).getTagName(); will(returnValue("select"));
allowing(element).getAttribute("multiple"); will(returnValue("multiple"));
exactly(1).of(element).findElements(By.xpath(".//option[@value = \"b\"]")); will(returnValue(options));
exactly(1).of(firstOption).isSelected(); will(returnValue(true));
exactly(1).of(firstOption).toggle();
exactly(1).of(secondOption).isSelected(); will(returnValue(false));
never(secondOption).toggle();
}});
Select select = new Select(element);
select.deselectByValue("b");
}
public void testShouldConvertAnUnquotedStringIntoOneWithQuotes() {
final WebElement element = mock(WebElement.class);
checking(new Expectations() {{
allowing(element).getTagName(); will(returnValue("select"));
allowing(element).getAttribute("multiple"); will(returnValue("multiple"));
}});
Select select = new Select(element);
String result = select.escapeQuotes("foo");
assertEquals("\"foo\"", result);
}
public void testShouldConvertAStringWithATickIntoOneWithQuotes() {
final WebElement element = mock(WebElement.class);
checking(new Expectations() {{
allowing(element).getTagName(); will(returnValue("select"));
allowing(element).getAttribute("multiple"); will(returnValue("multiple"));
}});
Select select = new Select(element);
String result = select.escapeQuotes("f'oo");
assertEquals("\"f'oo\"", result);
}
public void testShouldConvertAStringWithAQuotIntoOneWithTicks() {
final WebElement element = mock(WebElement.class);
checking(new Expectations() {{
allowing(element).getTagName(); will(returnValue("select"));
allowing(element).getAttribute("multiple"); will(returnValue("multiple"));
}});
Select select = new Select(element);
String result = select.escapeQuotes("f\"oo");
assertEquals("'f\"oo'", result);
}
public void testShouldProvideConcatenatedStringsWhenStringToEscapeContainsTicksAndQuotes() {
final WebElement element = mock(WebElement.class);
checking(new Expectations() {{
allowing(element).getTagName(); will(returnValue("select"));
allowing(element).getAttribute("multiple"); will(returnValue("multiple"));
}});
Select select = new Select(element);
String result = select.escapeQuotes("f\"o'o");
assertEquals("concat(\"f\", '\"', \"o'o\")", result);
}
+
+ /**
+ * Tests that escapeQuotes returns concatenated strings when the given
+ * string contains a tick and and ends with a quote.
+ */
+ public void testShouldProvideConcatenatedStringsWhenStringEndsWithQuote() {
+ final WebElement element = mock(WebElement.class);
+
+ checking(new Expectations() {{
+ allowing(element).getTagName(); will(returnValue("select"));
+ allowing(element).getAttribute("multiple"); will(returnValue("multiple"));
+ }});
+
+ Select select = new Select(element);
+ String result = select.escapeQuotes("'\"");
+
+ assertEquals("concat(\"'\", '\"')", result);
+ }
public void testShouldFallBackToSlowLooksUpsWhenGetByVisibleTextFailsAndThereIsASpace() {
final WebElement element = mock(WebElement.class);
final WebElement firstOption = mock(WebElement.class, "first");
final By xpath1 = By.xpath(".//option[. = \"foo bar\"]");
final By xpath2 = By.xpath(".//option[contains(., \"foo\")]");
checking(new Expectations() {{
allowing(element).getTagName(); will(returnValue("select"));
allowing(element).getAttribute("multiple"); will(returnValue(""));
one(element).findElements(xpath1); will(returnValue(Collections.EMPTY_LIST));
one(element).findElements(xpath2); will(returnValue(Collections.singletonList(firstOption)));
one(firstOption).getText(); will(returnValue("foo bar"));
one(firstOption).setSelected();
}});
Select select = new Select(element);
select.selectByVisibleText("foo bar");
}
}
| false | false | null | null |
diff --git a/src/integrationtest/org/asteriskjava/live/OriginateTest.java b/src/integrationtest/org/asteriskjava/live/OriginateTest.java
index d353309f..6018cf3c 100644
--- a/src/integrationtest/org/asteriskjava/live/OriginateTest.java
+++ b/src/integrationtest/org/asteriskjava/live/OriginateTest.java
@@ -1,102 +1,114 @@
/*
* (c) 2004 Stefan Reuter
*
* Created on Oct 28, 2004
*/
package org.asteriskjava.live;
/**
* @author srt
* @version $Id$
*/
public class OriginateTest extends AsteriskServerTestCase
{
private AsteriskChannel channel;
private Long timeout = 10000L;
@Override
public void setUp() throws Exception
{
super.setUp();
this.channel = null;
}
public void XtestOriginate() throws Exception
{
AsteriskChannel channel;
channel = server.originateToExtension("Local/1310@default", "from-local", "1330", 1, timeout);
System.err.println(channel);
System.err.println(channel.getVariable("AJ_TRACE_ID"));
Thread.sleep(20000L);
System.err.println(channel);
System.err.println(channel.getVariable("AJ_TRACE_ID"));
}
public void testOriginateAsync() throws Exception
{
final String source;
- //source = "SIP/1301";
- source = "Local/1313@from-local";
+ //source = "SIP/1313";
+ source = "Local/1313@from-local/n";
server.originateToExtensionAsync(source, "from-local", "1399", 1, timeout,
new CallerId("AJ Test Call", "08003301000"), null,
new OriginateCallback()
{
public void onSuccess(AsteriskChannel c)
{
channel = c;
System.err.println("Success: " + c);
showInfo(c);
+ try
+ {
+ c.setVariable(AsteriskChannel.VARIABLE_MONITOR_EXEC, "/usr/local/bin/2wav2mp3");
+ c.setVariable(AsteriskChannel.VARIABLE_MONITOR_EXEC_ARGS, "a b");
+ c.startMonitoring("mtest", "wav", true);
+ Thread.sleep(2000L);
+ c.stopMonitoring();
+ }
+ catch (Exception e)
+ {
+ e.printStackTrace();
+ }
}
public void onNoAnswer(AsteriskChannel c)
{
channel = c;
System.err.println("No Answer: " + c);
showInfo(c);
}
public void onBusy(AsteriskChannel c)
{
channel = c;
System.err.println("Busy: " + c);
showInfo(c);
}
public void onFailure(LiveException cause)
{
System.err.println("Failed: " + cause.getMessage());
}
});
Thread.sleep(20000L);
System.err.println("final state: " + channel);
if (channel != null)
{
System.err.println("final state linked channels: " + channel.getLinkedChannelHistory());
}
}
void showInfo(AsteriskChannel channel)
{
String name;
String otherName;
AsteriskChannel otherChannel;
System.err.println("linkedChannelHistory: " + channel.getLinkedChannelHistory());
System.err.println("dialedChannelHistory: " + channel.getDialedChannelHistory());
name = channel.getName();
if (name.startsWith("Local/"))
{
otherName = name.substring(0, name.length() - 1) + "2";
System.err.println("other name: " + otherName);
otherChannel = server.getChannelByName(otherName);
System.err.println("other channel: " + otherChannel);
System.err.println("other dialedChannel: " + otherChannel.getDialedChannel());
System.err.println("other linkedChannelHistory: " + otherChannel.getLinkedChannelHistory());
System.err.println("other dialedChannelHistory: " + otherChannel.getDialedChannelHistory());
}
}
}
| false | true | public void testOriginateAsync() throws Exception
{
final String source;
//source = "SIP/1301";
source = "Local/1313@from-local";
server.originateToExtensionAsync(source, "from-local", "1399", 1, timeout,
new CallerId("AJ Test Call", "08003301000"), null,
new OriginateCallback()
{
public void onSuccess(AsteriskChannel c)
{
channel = c;
System.err.println("Success: " + c);
showInfo(c);
}
public void onNoAnswer(AsteriskChannel c)
{
channel = c;
System.err.println("No Answer: " + c);
showInfo(c);
}
public void onBusy(AsteriskChannel c)
{
channel = c;
System.err.println("Busy: " + c);
showInfo(c);
}
public void onFailure(LiveException cause)
{
System.err.println("Failed: " + cause.getMessage());
}
});
Thread.sleep(20000L);
System.err.println("final state: " + channel);
if (channel != null)
{
System.err.println("final state linked channels: " + channel.getLinkedChannelHistory());
}
}
| public void testOriginateAsync() throws Exception
{
final String source;
//source = "SIP/1313";
source = "Local/1313@from-local/n";
server.originateToExtensionAsync(source, "from-local", "1399", 1, timeout,
new CallerId("AJ Test Call", "08003301000"), null,
new OriginateCallback()
{
public void onSuccess(AsteriskChannel c)
{
channel = c;
System.err.println("Success: " + c);
showInfo(c);
try
{
c.setVariable(AsteriskChannel.VARIABLE_MONITOR_EXEC, "/usr/local/bin/2wav2mp3");
c.setVariable(AsteriskChannel.VARIABLE_MONITOR_EXEC_ARGS, "a b");
c.startMonitoring("mtest", "wav", true);
Thread.sleep(2000L);
c.stopMonitoring();
}
catch (Exception e)
{
e.printStackTrace();
}
}
public void onNoAnswer(AsteriskChannel c)
{
channel = c;
System.err.println("No Answer: " + c);
showInfo(c);
}
public void onBusy(AsteriskChannel c)
{
channel = c;
System.err.println("Busy: " + c);
showInfo(c);
}
public void onFailure(LiveException cause)
{
System.err.println("Failed: " + cause.getMessage());
}
});
Thread.sleep(20000L);
System.err.println("final state: " + channel);
if (channel != null)
{
System.err.println("final state linked channels: " + channel.getLinkedChannelHistory());
}
}
|
diff --git a/src/infinity/resource/graphics/TisResource2.java b/src/infinity/resource/graphics/TisResource2.java
index d473d48..2556e82 100644
--- a/src/infinity/resource/graphics/TisResource2.java
+++ b/src/infinity/resource/graphics/TisResource2.java
@@ -1,670 +1,671 @@
// Near Infinity - An Infinity Engine Browser and Editor
// Copyright (C) 2001 - 2005 Jon Olav Hauglid
// See LICENSE.txt for license information
package infinity.resource.graphics;
import infinity.NearInfinity;
import infinity.datatype.DecNumber;
import infinity.datatype.ResourceRef;
import infinity.gui.ButtonPopupMenu;
import infinity.gui.TileGrid;
import infinity.gui.WindowBlocker;
import infinity.icon.Icons;
import infinity.resource.Closeable;
import infinity.resource.Resource;
import infinity.resource.ResourceFactory;
import infinity.resource.ViewableContainer;
import infinity.resource.key.ResourceEntry;
import infinity.resource.wed.Overlay;
import infinity.resource.wed.WedResource;
import infinity.util.DynamicArray;
import infinity.util.IntegerHashMap;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.Transparency;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferInt;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.ByteArrayOutputStream;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Vector;
import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSlider;
import javax.swing.JTextField;
import javax.swing.ProgressMonitor;
import javax.swing.RootPaneContainer;
import javax.swing.SwingWorker;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class TisResource2 implements Resource, Closeable, ActionListener, ChangeListener,
ItemListener, KeyListener, PropertyChangeListener
{
private static final int DEFAULT_COLUMNS = 5;
private static boolean showGrid = false;
private final ResourceEntry entry;
private TisDecoder decoder;
private List<Image> tileImages; // stores one tile per image
private TileGrid tileGrid; // the main component for displaying the tileset
private JSlider slCols; // changes the tiles per row
private JTextField tfCols; // input/output tiles per row
private JCheckBox cbGrid; // show/hide frame around each tile
private ButtonPopupMenu bpmExport; // "Export..." button menu
private JMenuItem miExport, miExportLegacyTis, miExportPNG;
private JPanel panel; // top-level panel of the viewer
private RootPaneContainer rpc;
private SwingWorker<List<byte[]>, Void> workerConvert, workerExport;
private WindowBlocker blocker;
public TisResource2(ResourceEntry entry) throws Exception
{
this.entry = entry;
initTileset();
}
//--------------------- Begin Interface ActionListener ---------------------
@Override
public void actionPerformed(ActionEvent event)
{
if (event.getSource() == miExport) {
ResourceFactory.getInstance().exportResource(entry, panel.getTopLevelAncestor());
} else if (event.getSource() == miExportLegacyTis) {
blocker = new WindowBlocker(rpc);
blocker.setBlocked(true);
workerConvert = new SwingWorker<List<byte[]>, Void>() {
@Override
public List<byte[]> doInBackground()
{
List<byte[]> list = new Vector<byte[]>(1);
try {
byte[] buf = convertToLegacyTis();
if (buf != null) {
list.add(buf);
}
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
};
workerConvert.addPropertyChangeListener(this);
workerConvert.execute();
} else if (event.getSource() == miExportPNG) {
blocker = new WindowBlocker(rpc);
blocker.setBlocked(true);
workerExport = new SwingWorker<List<byte[]>, Void>() {
@Override
public List<byte[]> doInBackground()
{
List<byte[]> list = new Vector<byte[]>(1);
try {
byte[] buf = exportPNG();
if (buf != null) {
list.add(buf);
}
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
};
workerExport.addPropertyChangeListener(this);
workerExport.execute();
}
}
//--------------------- End Interface ActionListener ---------------------
//--------------------- Begin Interface ChangeListener ---------------------
@Override
public void stateChanged(ChangeEvent event)
{
if (event.getSource() == slCols) {
int cols = slCols.getValue();
tfCols.setText(Integer.toString(cols));
tileGrid.setGridSize(calcGridSize(tileGrid.getImageCount(), cols));
}
}
//--------------------- End Interface ChangeListener ---------------------
//--------------------- Begin Interface ItemListener ---------------------
@Override
public void itemStateChanged(ItemEvent event)
{
if (event.getSource() == cbGrid) {
showGrid = cbGrid.isSelected();
tileGrid.setShowGrid(showGrid);
}
}
//--------------------- End Interface ChangeListener ---------------------
//--------------------- Begin Interface KeyListener ---------------------
@Override
public void keyPressed(KeyEvent event)
{
if (event.getSource() == tfCols) {
if (event.getKeyCode() == KeyEvent.VK_ENTER) {
int cols;
try {
cols = Integer.parseInt(tfCols.getText());
} catch (NumberFormatException e) {
cols = slCols.getValue();
tfCols.setText(Integer.toString(slCols.getValue()));
}
if (cols != slCols.getValue()) {
if (cols <= 0)
cols = 1;
if (cols >= decoder.info().tileCount())
cols = decoder.info().tileCount();
slCols.setValue(cols);
tfCols.setText(Integer.toString(slCols.getValue()));
tileGrid.setGridSize(calcGridSize(tileGrid.getImageCount(), cols));
}
slCols.requestFocus(); // remove focus from textfield
}
}
}
@Override
public void keyReleased(KeyEvent event)
{
// nothing to do
}
@Override
public void keyTyped(KeyEvent event)
{
// nothing to do
}
//--------------------- End Interface KeyListener ---------------------
//--------------------- Begin Interface PropertyChangeListener ---------------------
@Override
public void propertyChange(PropertyChangeEvent event)
{
if (event.getSource() == workerConvert) {
if ("state".equals(event.getPropertyName()) &&
SwingWorker.StateValue.DONE == event.getNewValue()) {
if (blocker != null) {
blocker.setBlocked(false);
blocker = null;
}
byte[] tisData = null;
try {
List<byte[]> l = workerConvert.get();
if (l != null && !l.isEmpty()) {
tisData = l.get(0);
l.clear();
l = null;
}
} catch (Exception e) {
e.printStackTrace();
}
if (tisData != null) {
if (tisData.length > 0) {
ResourceFactory.getInstance().exportResource(entry, tisData, entry.toString(),
panel.getTopLevelAncestor());
} else {
JOptionPane.showMessageDialog(panel.getTopLevelAncestor(),
"Export has been cancelled.", "Information",
JOptionPane.INFORMATION_MESSAGE);
}
tisData = null;
} else {
JOptionPane.showMessageDialog(panel.getTopLevelAncestor(),
"Error while exporting " + entry, "Error",
JOptionPane.ERROR_MESSAGE);
}
}
} else if (event.getSource() == workerExport) {
if ("state".equals(event.getPropertyName()) &&
SwingWorker.StateValue.DONE == event.getNewValue()) {
if (blocker != null) {
blocker.setBlocked(false);
blocker = null;
}
byte[] pngData = null;
try {
List<byte[]> l = workerExport.get();
if (l != null && !l.isEmpty()) {
pngData = l.get(0);
l.clear();
l = null;
}
} catch (Exception e) {
e.printStackTrace();
}
if (pngData != null) {
if (pngData.length > 0) {
String fileName = entry.toString().replace(".TIS", ".PNG");
ResourceFactory.getInstance().exportResource(entry, pngData, fileName,
panel.getTopLevelAncestor());
} else {
JOptionPane.showMessageDialog(panel.getTopLevelAncestor(),
"Export has been cancelled.", "Information",
JOptionPane.INFORMATION_MESSAGE);
}
pngData = null;
} else {
JOptionPane.showMessageDialog(panel.getTopLevelAncestor(),
"Error while exporting " + entry, "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
}
//--------------------- End Interface PropertyChangeListener ---------------------
//--------------------- Begin Interface Closeable ---------------------
@Override
public void close() throws Exception
{
if (workerConvert != null) {
if (!workerConvert.isDone()) {
workerConvert.cancel(true);
}
workerConvert = null;
}
tileImages.clear();
tileImages = null;
tileGrid.clearImages();
tileGrid = null;
if (decoder != null) {
decoder.close();
decoder = null;
}
System.gc();
}
//--------------------- End Interface Closeable ---------------------
//--------------------- Begin Interface Resource ---------------------
@Override
public ResourceEntry getResourceEntry()
{
return entry;
}
//--------------------- End Interface Resource ---------------------
//--------------------- Begin Interface Viewable ---------------------
@Override
public JComponent makeViewer(ViewableContainer container)
{
if (container instanceof RootPaneContainer) {
rpc = (RootPaneContainer)container;
} else {
rpc = NearInfinity.getInstance();
}
int tileCount = decoder.info().tileCount();
+ int defaultColumns = Math.min(tileCount, DEFAULT_COLUMNS);
// 1. creating top panel
// 1.1. creating label with text field
JLabel lblTPR = new JLabel("Tiles per row:");
- tfCols = new JTextField(Integer.toString(DEFAULT_COLUMNS), 5);
+ tfCols = new JTextField(Integer.toString(defaultColumns), 5);
tfCols.addKeyListener(this);
JPanel tPanel1 = new JPanel(new FlowLayout(FlowLayout.CENTER));
tPanel1.add(lblTPR);
tPanel1.add(tfCols);
// 1.2. creating slider
- slCols = new JSlider(JSlider.HORIZONTAL, 1, tileCount, DEFAULT_COLUMNS);
+ slCols = new JSlider(JSlider.HORIZONTAL, 1, tileCount, defaultColumns);
if (tileCount > 1000) {
slCols.setMinorTickSpacing(100);
slCols.setMajorTickSpacing(1000);
} else if (tileCount > 100) {
slCols.setMinorTickSpacing(10);
slCols.setMajorTickSpacing(100);
} else {
slCols.setMinorTickSpacing(1);
slCols.setMajorTickSpacing(10);
}
slCols.setPaintTicks(true);
slCols.addChangeListener(this);
// 1.3. adding left side of the top panel together
JPanel tlPanel = new JPanel(new GridLayout(2, 1));
tlPanel.add(tPanel1);
tlPanel.add(slCols);
// 1.4. configuring checkbox
cbGrid = new JCheckBox("Show Grid", showGrid);
cbGrid.addItemListener(this);
JPanel trPanel = new JPanel(new GridLayout());
trPanel.add(cbGrid);
// 1.5. putting top panel together
BorderLayout bl = new BorderLayout();
JPanel topPanel = new JPanel(bl);
topPanel.add(tlPanel, BorderLayout.CENTER);
topPanel.add(trPanel, BorderLayout.LINE_END);
// 2. creating main panel
// 2.1. creating tiles table and scroll pane
- tileGrid = new TileGrid(1, DEFAULT_COLUMNS, decoder.info().tileWidth(), decoder.info().tileHeight());
+ tileGrid = new TileGrid(1, defaultColumns, decoder.info().tileWidth(), decoder.info().tileHeight());
tileGrid.addImage(tileImages);
if (tileGrid.getImageCount() > 6) {
int colSize = calcTileWidth(entry, tileGrid.getImageCount());
tileGrid.setGridSize(calcGridSize(tileGrid.getImageCount(), colSize));
} else {
// displaying overlay tilesets in a single row
tileGrid.setGridSize(new Dimension(tileGrid.getImageCount(), 1));
}
tileGrid.setShowGrid(showGrid);
slCols.setValue(tileGrid.getTileColumns());
tfCols.setText(Integer.toString(tileGrid.getTileColumns()));
JScrollPane scroll = new JScrollPane(tileGrid);
scroll.getVerticalScrollBar().setUnitIncrement(16);
scroll.getHorizontalScrollBar().setUnitIncrement(16);
// 2.2. putting main panel together
JPanel centerPanel = new JPanel(new BorderLayout());
centerPanel.add(scroll, BorderLayout.CENTER);
// 3. creating bottom panel
// 3.1. creating export button
miExport = new JMenuItem("original");
miExport.addActionListener(this);
if (decoder.info().type() == TisDecoder.TisInfo.TisType.PVRZ) {
miExportLegacyTis = new JMenuItem("as legacy TIS");
miExportLegacyTis.addActionListener(this);
}
miExportPNG = new JMenuItem("as PNG");
miExportPNG.addActionListener(this);
List<JMenuItem> list = new ArrayList<JMenuItem>();
if (miExport != null)
list.add(miExport);
if (miExportLegacyTis != null)
list.add(miExportLegacyTis);
if (miExportPNG != null)
list.add(miExportPNG);
JMenuItem[] mi = new JMenuItem[list.size()];
for (int i = 0; i < mi.length; i++) {
mi[i] = list.get(i);
}
bpmExport = new ButtonPopupMenu("Export...", mi);
bpmExport.setIcon(Icons.getIcon("Export16.gif"));
bpmExport.setMnemonic('e');
// 3.2. putting bottom panel together
JPanel bottomPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
bottomPanel.add(bpmExport);
// 4. packing all together
panel = new JPanel(new BorderLayout());
panel.add(topPanel, BorderLayout.NORTH);
panel.add(centerPanel, BorderLayout.CENTER);
panel.add(bottomPanel, BorderLayout.SOUTH);
centerPanel.setBorder(BorderFactory.createLoweredBevelBorder());
return panel;
}
//--------------------- End Interface Viewable ---------------------
private void initTileset()
{
try {
WindowBlocker.blockWindow(true);
decoder = new TisDecoder(entry);
int tileCount = decoder.info().tileCount();
tileImages = new ArrayList<Image>(tileCount);
for (int tileIdx = 0; tileIdx < tileCount; tileIdx++) {
final BufferedImage image = decoder.decodeTile(tileIdx);
if (image != null) {
tileImages.add(image);
} else {
tileImages.add(ColorConvert.createCompatibleImage(decoder.info().tileWidth(),
decoder.info().tileHeight(),
Transparency.BITMASK));
}
}
decoder.flush();
WindowBlocker.blockWindow(false);
} catch (Exception e) {
e.printStackTrace();
WindowBlocker.blockWindow(false);
if (tileImages == null)
tileImages = new ArrayList<Image>();
if (tileImages.isEmpty())
tileImages.add(ColorConvert.createCompatibleImage(1, 1, Transparency.BITMASK));
JOptionPane.showMessageDialog(NearInfinity.getInstance(),
"Error while loading TIS resource: " + entry.getResourceName(),
"Error", JOptionPane.ERROR_MESSAGE);
}
}
// Converts the current PVRZ-based tileset into the old tileset variant. DO NOT call directly!
private byte[] convertToLegacyTis()
{
byte[] buf = null;
if (tileImages != null && !tileImages.isEmpty()) {
String note = "Converting tile %1$d / %2$d";
int progressIndex = 0, progressMax = decoder.info().tileCount();
ProgressMonitor progress =
new ProgressMonitor(panel.getTopLevelAncestor(), "Converting TIS...",
String.format(note, progressIndex, progressMax), 0, progressMax);
progress.setMillisToDecideToPopup(500);
progress.setMillisToPopup(2000);
buf = new byte[24 + decoder.info().tileCount()*5120];
// writing header data
System.arraycopy("TIS V1 ".getBytes(Charset.forName("US-ASCII")), 0, buf, 0, 8);
DynamicArray.putInt(buf, 8, decoder.info().tileCount());
DynamicArray.putInt(buf, 12, 0x1400);
DynamicArray.putInt(buf, 16, 0x18);
DynamicArray.putInt(buf, 20, 0x40);
// writing tiles
int bufOfs = 24;
int[] palette = new int[255];
int[] hslPalette = new int[255];
byte[] tilePalette = new byte[1024];
byte[] tileData = new byte[64*64];
BufferedImage image = ColorConvert.createCompatibleImage(decoder.info().tileWidth(),
decoder.info().tileHeight(), Transparency.BITMASK);
IntegerHashMap<Byte> colorCache = new IntegerHashMap<Byte>(1536); // caching RGBColor -> index
for (int tileIdx = 0; tileIdx < decoder.info().tileCount(); tileIdx++) {
colorCache.clear();
if (progress.isCanceled()) {
buf = new byte[0];
break;
}
progressIndex++;
if ((progressIndex % 100) == 0) {
progress.setProgress(progressIndex);
progress.setNote(String.format(note, progressIndex, progressMax));
}
int[] pixels = ((DataBufferInt)image.getRaster().getDataBuffer()).getData();
Arrays.fill(pixels, 0); // clearing garbage data
Graphics2D g = (Graphics2D)image.getGraphics();
g.drawImage(tileImages.get(tileIdx), 0, 0, null);
g.dispose();
g = null;
if (ColorConvert.medianCut(pixels, 255, palette, false)) {
ColorConvert.toHslPalette(palette, hslPalette);
// filling palette
// first palette entry denotes transparency
tilePalette[0] = tilePalette[2] = tilePalette[3] = 0; tilePalette[1] = (byte)255;
for (int i = 1; i < 256; i++) {
tilePalette[(i << 2) + 0] = (byte)(palette[i - 1] & 0xff);
tilePalette[(i << 2) + 1] = (byte)((palette[i - 1] >>> 8) & 0xff);
tilePalette[(i << 2) + 2] = (byte)((palette[i - 1] >>> 16) & 0xff);
tilePalette[(i << 2) + 3] = 0;
colorCache.put(palette[i - 1], (byte)(i - 1));
}
// filling pixel data
for (int i = 0; i < tileData.length; i++) {
if ((pixels[i] & 0xff000000) == 0) {
tileData[i] = 0;
} else {
Byte palIndex = colorCache.get(pixels[i]);
if (palIndex != null) {
tileData[i] = (byte)(palIndex + 1);
} else {
byte color = (byte)ColorConvert.nearestColor(pixels[i], hslPalette);
tileData[i] = (byte)(color + 1);
colorCache.put(pixels[i], color);
}
}
}
} else {
buf = null;
break;
}
System.arraycopy(tilePalette, 0, buf, bufOfs, 1024);
bufOfs += 1024;
System.arraycopy(tileData, 0, buf, bufOfs, 4096);
bufOfs += 4096;
}
image.flush(); image = null;
tileData = null; tilePalette = null; hslPalette = null; palette = null;
progress.close();
}
return buf;
}
// Converts the tileset into the PNG format. DO NOT call directly!
private byte[] exportPNG()
{
byte[] buffer = null;
if (tileImages != null && !tileImages.isEmpty()) {
int tilesX = tileGrid.getTileColumns();
int tilesY = tileGrid.getTileRows();
if (tilesX > 0 && tilesY > 0) {
BufferedImage image = null;
ProgressMonitor progress = new ProgressMonitor(panel.getTopLevelAncestor(),
"Exporting TIS to PNG...", "", 0, 2);
progress.setMillisToDecideToPopup(0);
progress.setMillisToPopup(0);
progress.setProgress(0);
try {
image = ColorConvert.createCompatibleImage(tilesX*64, tilesY*64, Transparency.BITMASK);
Graphics2D g = (Graphics2D)image.getGraphics();
for (int idx = 0; idx < tileImages.size(); idx++) {
if (tileImages.get(idx) != null) {
int tx = idx % tilesX;
int ty = idx / tilesX;
g.drawImage(tileImages.get(idx), tx*64, ty*64, null);
}
}
g.dispose();
progress.setProgress(1);
ByteArrayOutputStream os = new ByteArrayOutputStream();
if (ImageIO.write(image, "png", os)) {
buffer = os.toByteArray();
}
} catch (Exception e) {
}
if (progress.isCanceled()) {
buffer = new byte[0];
}
progress.close();
}
}
return buffer;
}
// calculates a Dimension structure with the correct number of columns and rows from the specified arguments
private static Dimension calcGridSize(int imageCount, int colSize)
{
if (imageCount >= 0 && colSize > 0) {
int rowSize = imageCount / colSize;
if (imageCount % colSize > 0)
rowSize++;
return new Dimension(colSize, Math.max(1, rowSize));
}
return null;
}
// attempts to calculate the TIS width from an associated WED file
private static int calcTileWidth(ResourceEntry entry, int tileCount)
{
// Try to fetch the correct width from an associated WED if available
if (entry != null) {
try {
String tisNameBase = entry.getResourceName();
if (tisNameBase.lastIndexOf('.') > 0)
tisNameBase = tisNameBase.substring(0, tisNameBase.lastIndexOf('.'));
ResourceEntry wedEntry = null;
while (tisNameBase.length() >= 6) {
String wedFileName = tisNameBase + ".WED";
wedEntry = ResourceFactory.getInstance().getResourceEntry(wedFileName);
if (wedEntry != null)
break;
else
tisNameBase = tisNameBase.substring(0, tisNameBase.length() - 1);
}
if (wedEntry != null) {
WedResource wedResource = new WedResource(wedEntry);
Overlay overlay = (Overlay)wedResource.getAttribute("Overlay 0");
ResourceRef tisRef = (ResourceRef)overlay.getAttribute("Tileset");
ResourceEntry tisEntry = ResourceFactory.getInstance().getResourceEntry(tisRef.getResourceName());
if (tisEntry != null) {
String tisName = tisEntry.getResourceName();
if (tisName.lastIndexOf('.') > 0)
tisName = tisName.substring(0, tisName.lastIndexOf('.'));
int maxLen = Math.min(tisNameBase.length(), tisName.length());
if (tisNameBase.startsWith(tisName.substring(0, maxLen))) {
return ((DecNumber)overlay.getAttribute("Width")).getValue();
}
}
}
} catch (Exception e) {
}
}
// If WED is not available: approximate the most commonly used aspect ratio found in TIS files
// Disadvantage: does not take extra tiles into account
return (int)(Math.sqrt(tileCount)*1.18);
}
}
| false | true | public JComponent makeViewer(ViewableContainer container)
{
if (container instanceof RootPaneContainer) {
rpc = (RootPaneContainer)container;
} else {
rpc = NearInfinity.getInstance();
}
int tileCount = decoder.info().tileCount();
// 1. creating top panel
// 1.1. creating label with text field
JLabel lblTPR = new JLabel("Tiles per row:");
tfCols = new JTextField(Integer.toString(DEFAULT_COLUMNS), 5);
tfCols.addKeyListener(this);
JPanel tPanel1 = new JPanel(new FlowLayout(FlowLayout.CENTER));
tPanel1.add(lblTPR);
tPanel1.add(tfCols);
// 1.2. creating slider
slCols = new JSlider(JSlider.HORIZONTAL, 1, tileCount, DEFAULT_COLUMNS);
if (tileCount > 1000) {
slCols.setMinorTickSpacing(100);
slCols.setMajorTickSpacing(1000);
} else if (tileCount > 100) {
slCols.setMinorTickSpacing(10);
slCols.setMajorTickSpacing(100);
} else {
slCols.setMinorTickSpacing(1);
slCols.setMajorTickSpacing(10);
}
slCols.setPaintTicks(true);
slCols.addChangeListener(this);
// 1.3. adding left side of the top panel together
JPanel tlPanel = new JPanel(new GridLayout(2, 1));
tlPanel.add(tPanel1);
tlPanel.add(slCols);
// 1.4. configuring checkbox
cbGrid = new JCheckBox("Show Grid", showGrid);
cbGrid.addItemListener(this);
JPanel trPanel = new JPanel(new GridLayout());
trPanel.add(cbGrid);
// 1.5. putting top panel together
BorderLayout bl = new BorderLayout();
JPanel topPanel = new JPanel(bl);
topPanel.add(tlPanel, BorderLayout.CENTER);
topPanel.add(trPanel, BorderLayout.LINE_END);
// 2. creating main panel
// 2.1. creating tiles table and scroll pane
tileGrid = new TileGrid(1, DEFAULT_COLUMNS, decoder.info().tileWidth(), decoder.info().tileHeight());
tileGrid.addImage(tileImages);
if (tileGrid.getImageCount() > 6) {
int colSize = calcTileWidth(entry, tileGrid.getImageCount());
tileGrid.setGridSize(calcGridSize(tileGrid.getImageCount(), colSize));
} else {
// displaying overlay tilesets in a single row
tileGrid.setGridSize(new Dimension(tileGrid.getImageCount(), 1));
}
tileGrid.setShowGrid(showGrid);
slCols.setValue(tileGrid.getTileColumns());
tfCols.setText(Integer.toString(tileGrid.getTileColumns()));
JScrollPane scroll = new JScrollPane(tileGrid);
scroll.getVerticalScrollBar().setUnitIncrement(16);
scroll.getHorizontalScrollBar().setUnitIncrement(16);
// 2.2. putting main panel together
JPanel centerPanel = new JPanel(new BorderLayout());
centerPanel.add(scroll, BorderLayout.CENTER);
// 3. creating bottom panel
// 3.1. creating export button
miExport = new JMenuItem("original");
miExport.addActionListener(this);
if (decoder.info().type() == TisDecoder.TisInfo.TisType.PVRZ) {
miExportLegacyTis = new JMenuItem("as legacy TIS");
miExportLegacyTis.addActionListener(this);
}
miExportPNG = new JMenuItem("as PNG");
miExportPNG.addActionListener(this);
List<JMenuItem> list = new ArrayList<JMenuItem>();
if (miExport != null)
list.add(miExport);
if (miExportLegacyTis != null)
list.add(miExportLegacyTis);
if (miExportPNG != null)
list.add(miExportPNG);
JMenuItem[] mi = new JMenuItem[list.size()];
for (int i = 0; i < mi.length; i++) {
mi[i] = list.get(i);
}
bpmExport = new ButtonPopupMenu("Export...", mi);
bpmExport.setIcon(Icons.getIcon("Export16.gif"));
bpmExport.setMnemonic('e');
// 3.2. putting bottom panel together
JPanel bottomPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
bottomPanel.add(bpmExport);
// 4. packing all together
panel = new JPanel(new BorderLayout());
panel.add(topPanel, BorderLayout.NORTH);
panel.add(centerPanel, BorderLayout.CENTER);
panel.add(bottomPanel, BorderLayout.SOUTH);
centerPanel.setBorder(BorderFactory.createLoweredBevelBorder());
return panel;
}
| public JComponent makeViewer(ViewableContainer container)
{
if (container instanceof RootPaneContainer) {
rpc = (RootPaneContainer)container;
} else {
rpc = NearInfinity.getInstance();
}
int tileCount = decoder.info().tileCount();
int defaultColumns = Math.min(tileCount, DEFAULT_COLUMNS);
// 1. creating top panel
// 1.1. creating label with text field
JLabel lblTPR = new JLabel("Tiles per row:");
tfCols = new JTextField(Integer.toString(defaultColumns), 5);
tfCols.addKeyListener(this);
JPanel tPanel1 = new JPanel(new FlowLayout(FlowLayout.CENTER));
tPanel1.add(lblTPR);
tPanel1.add(tfCols);
// 1.2. creating slider
slCols = new JSlider(JSlider.HORIZONTAL, 1, tileCount, defaultColumns);
if (tileCount > 1000) {
slCols.setMinorTickSpacing(100);
slCols.setMajorTickSpacing(1000);
} else if (tileCount > 100) {
slCols.setMinorTickSpacing(10);
slCols.setMajorTickSpacing(100);
} else {
slCols.setMinorTickSpacing(1);
slCols.setMajorTickSpacing(10);
}
slCols.setPaintTicks(true);
slCols.addChangeListener(this);
// 1.3. adding left side of the top panel together
JPanel tlPanel = new JPanel(new GridLayout(2, 1));
tlPanel.add(tPanel1);
tlPanel.add(slCols);
// 1.4. configuring checkbox
cbGrid = new JCheckBox("Show Grid", showGrid);
cbGrid.addItemListener(this);
JPanel trPanel = new JPanel(new GridLayout());
trPanel.add(cbGrid);
// 1.5. putting top panel together
BorderLayout bl = new BorderLayout();
JPanel topPanel = new JPanel(bl);
topPanel.add(tlPanel, BorderLayout.CENTER);
topPanel.add(trPanel, BorderLayout.LINE_END);
// 2. creating main panel
// 2.1. creating tiles table and scroll pane
tileGrid = new TileGrid(1, defaultColumns, decoder.info().tileWidth(), decoder.info().tileHeight());
tileGrid.addImage(tileImages);
if (tileGrid.getImageCount() > 6) {
int colSize = calcTileWidth(entry, tileGrid.getImageCount());
tileGrid.setGridSize(calcGridSize(tileGrid.getImageCount(), colSize));
} else {
// displaying overlay tilesets in a single row
tileGrid.setGridSize(new Dimension(tileGrid.getImageCount(), 1));
}
tileGrid.setShowGrid(showGrid);
slCols.setValue(tileGrid.getTileColumns());
tfCols.setText(Integer.toString(tileGrid.getTileColumns()));
JScrollPane scroll = new JScrollPane(tileGrid);
scroll.getVerticalScrollBar().setUnitIncrement(16);
scroll.getHorizontalScrollBar().setUnitIncrement(16);
// 2.2. putting main panel together
JPanel centerPanel = new JPanel(new BorderLayout());
centerPanel.add(scroll, BorderLayout.CENTER);
// 3. creating bottom panel
// 3.1. creating export button
miExport = new JMenuItem("original");
miExport.addActionListener(this);
if (decoder.info().type() == TisDecoder.TisInfo.TisType.PVRZ) {
miExportLegacyTis = new JMenuItem("as legacy TIS");
miExportLegacyTis.addActionListener(this);
}
miExportPNG = new JMenuItem("as PNG");
miExportPNG.addActionListener(this);
List<JMenuItem> list = new ArrayList<JMenuItem>();
if (miExport != null)
list.add(miExport);
if (miExportLegacyTis != null)
list.add(miExportLegacyTis);
if (miExportPNG != null)
list.add(miExportPNG);
JMenuItem[] mi = new JMenuItem[list.size()];
for (int i = 0; i < mi.length; i++) {
mi[i] = list.get(i);
}
bpmExport = new ButtonPopupMenu("Export...", mi);
bpmExport.setIcon(Icons.getIcon("Export16.gif"));
bpmExport.setMnemonic('e');
// 3.2. putting bottom panel together
JPanel bottomPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
bottomPanel.add(bpmExport);
// 4. packing all together
panel = new JPanel(new BorderLayout());
panel.add(topPanel, BorderLayout.NORTH);
panel.add(centerPanel, BorderLayout.CENTER);
panel.add(bottomPanel, BorderLayout.SOUTH);
centerPanel.setBorder(BorderFactory.createLoweredBevelBorder());
return panel;
}
|
diff --git a/src/Generator/NFA/NFASimulator.java b/src/Generator/NFA/NFASimulator.java
index 1069023..2fd41d9 100644
--- a/src/Generator/NFA/NFASimulator.java
+++ b/src/Generator/NFA/NFASimulator.java
@@ -1,109 +1,110 @@
package Generator.NFA;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
public class NFASimulator {
private Queue<Clone> Q;
private int numMoves;
private NFA regex;
private String code;
public NFASimulator(NFA nfa) {
regex = nfa;
reset();
}
public NFASimulator() {
this(null);
}
public void reset() {
Q = new LinkedList<Clone>();
numMoves = 0;
}
public void setNFA(NFA nfa) {
regex = nfa;
reset();
}
public void setCode(String in) {
code = in;
reset();
}
public Result parse(NFA nfa, String in) {
regex = nfa;
code = in;
return parse();
}
public Result parse(String in) {
code = in;
return parse();
}
public Result parse() {
Q.add(new Clone(regex.start(), 0, ""));
Result r = null;
while(!Q.isEmpty()) {
Clone c = Q.poll();
Node u = c.node;
List<Transition> adj = u.adjacencyList();
for(Transition e : adj) {
if(e.isEpsilonTransition()) {
Q.add(new Clone(e.end(), c.pos, c.token));
numMoves ++;
} else if(c.pos != code.length()) {
char m = code.charAt(c.pos);
if(e.isTriggered(m)) {
Q.add(new Clone(e.end(), c.pos+1, c.token + m));
numMoves ++;
}
}
}
//System.out.println(c);
if(u.isFinal() && c.pos == code.length()) {
r = new Result(c.token, numMoves);
+ break;
}
}
if(r == null) {
r = new Result("Failed", numMoves);
}
reset();
return r;
}
private class Clone {
Node node;
int pos;
String token;
private Clone(Node u, int p, String t) {
node = u;
pos = p;
token = t;
}
public String toString() {
- return token + " at " + pos;
+ return token + " at " + pos + " " + node;
}
}
public class Result {
public String token;
public int numMoves;
private Result(String t, int m) {
token = t;
numMoves = m;
}
public String toString() {
return token + " in " + numMoves + " moves.";
}
}
}
diff --git a/src/Test/NFAFactoryTest.java b/src/Test/NFAFactoryTest.java
index 81b2f08..8d3a14b 100644
--- a/src/Test/NFAFactoryTest.java
+++ b/src/Test/NFAFactoryTest.java
@@ -1,53 +1,70 @@
package Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import org.junit.Before;
import org.junit.Test;
import Generator.NFA.NFA;
import Generator.NFA.NFAFactory;
import Generator.NFA.NFASimulator;
import Generator.Token.op_code;
public class NFAFactoryTest {
NFASimulator NFASim;
NFAFactory Factory;
@Before
public void setUp() throws Exception {
NFASim = new NFASimulator();
Factory = new NFAFactory();
}
- @Test
+ //@Test
public void testEpsilon() {
NFA epsNFA = NFA.EpsilonNFA();
epsNFA = Factory.build("$NULL ()()()()()*||||a");
//System.out.println(epsNFA);
assertEquals("a", NFASim.parse(epsNFA, "a").token);
assertEquals("Failed", NFASim.parse(epsNFA, " ").token);
}
- @Test
+ //@Test
public void testSample() {
NFA test = Factory.build("$TEST (1)(2)*(3)(4|5|6)+(|^-)");
//System.out.println(test);
assertEquals("135", NFASim.parse(test, "135").token);
assertEquals("1223654^-", NFASim.parse(test, "1223654^-").token);
assertEquals("1223654", NFASim.parse(test, "1223654").token);
assertEquals("13555^-", NFASim.parse(test, "13555^-").token);
test = Factory.build("$TEST \\[(\\ )*\\]");
String code = "[ ]";
assertEquals(code, NFASim.parse(test, code).token);
code = "[ ]";
assertEquals(code, NFASim.parse(test, code).token);
}
+
+ @Test
+ public void testAddMultExpr() {
+ NFA test = Factory.build("$TEST (0|1|2|3|4|5|6|7|8|9)+(\\ |((\\+|\\*)(\\ )*(0|1|2|3|4|5|6|7|8|9)+)*)*");
+ String code = "12 + 56 + 78 * 9";
+ System.out.println(NFASim.parse(test, code));
+ assertEquals(code, NFASim.parse(test, code).token);
+ }
+
+ @Test
+ public void testDoubleStar() {
+ NFA test = Factory.build("$TEST (a|()*)*");
+ System.out.println(test);
+ String code = "aaaaaa";
+ System.out.println(NFASim.parse(test, code));
+ assertEquals(code, NFASim.parse(test, code).token);
+ }
}
| false | false | null | null |
diff --git a/core/src/main/java/com/github/tranchis/wire/App.java b/core/src/main/java/com/github/tranchis/wire/App.java
deleted file mode 100644
index 97527e4..0000000
--- a/core/src/main/java/com/github/tranchis/wire/App.java
+++ /dev/null
@@ -1,13 +0,0 @@
-package com.github.tranchis.wire;
-
-/**
- * Hello world!
- *
- */
-public class App
-{
- public static void main( String[] args )
- {
- System.out.println( "Hello World!" );
- }
-}
diff --git a/core/src/main/java/net/sf/ictalive/monitoring/domain/Formula.java b/core/src/main/java/net/sf/ictalive/monitoring/domain/Formula.java
index 6b42c06..35b610e 100644
--- a/core/src/main/java/net/sf/ictalive/monitoring/domain/Formula.java
+++ b/core/src/main/java/net/sf/ictalive/monitoring/domain/Formula.java
@@ -1,108 +1,112 @@
package net.sf.ictalive.monitoring.domain;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import clojure.lang.Obj;
import net.sf.ictalive.operetta.OM.Atom;
import net.sf.ictalive.operetta.OM.Constant;
import net.sf.ictalive.operetta.OM.Term;
import net.sf.ictalive.operetta.OM.Variable;
public class Formula
{
private Formula content;
private Set<Value> grounding;
private Obj logic;
public Formula(Obj logic)
{
this.setLogic(logic);
}
public Object substitute(Set<Value> grounding)
{
Object res, value;
Atom a;
Proposition p;
Term t;
Iterator<Term> it;
Iterator<Value> itv;
int i;
Constant c;
Variable v;
Value vl;
Map<String,Object> map;
map = new TreeMap<String,Object>();
itv = grounding.iterator();
while(itv.hasNext())
{
vl = itv.next();
map.put(vl.getKey(), vl.getValue());
}
res = this;
if(logic instanceof Atom)
{
a = (Atom)logic;
p = new Proposition(a.getPredicate());
it = a.getArguments().iterator();
i = 0;
while(it.hasNext())
{
t = it.next();
if(t instanceof Constant)
{
c = (Constant)t;
p.getParams()[i] = c.getName();
}
else if(t instanceof Variable)
{
v = (Variable)t;
value = map.get(v.getName() + "");
if(value != null)
{
p.getParams()[i] = (String)value; // TODO: Check this cast
}
}
i = i + 1;
}
res = p;
}
+ else
+ {
+ throw new UnsupportedOperationException("Class unsupported: " + logic.getClass());
+ }
return res;
}
public void setContent(Formula content)
{
this.content = content;
}
public Formula getContent()
{
return content;
}
public void setGrounding(Set<Value> grounding)
{
this.grounding = grounding;
}
public Set<Value> getGrounding()
{
return grounding;
}
public void setLogic(Obj logic)
{
this.logic = logic;
}
public Obj getLogic()
{
return logic;
}
}
| false | false | null | null |
diff --git a/adl-frontend/src/main/java/org/ow2/mind/adl/parameter/ParametricDefinitionReferenceResolver.java b/adl-frontend/src/main/java/org/ow2/mind/adl/parameter/ParametricDefinitionReferenceResolver.java
index a78842d..212ca67 100644
--- a/adl-frontend/src/main/java/org/ow2/mind/adl/parameter/ParametricDefinitionReferenceResolver.java
+++ b/adl-frontend/src/main/java/org/ow2/mind/adl/parameter/ParametricDefinitionReferenceResolver.java
@@ -1,283 +1,295 @@
/**
* Copyright (C) 2009 STMicroelectronics
*
* This file is part of "Mind Compiler" 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 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, see <http://www.gnu.org/licenses/>.
*
* Contact: [email protected]
*
* Authors: Matthieu Leclercq
* Contributors:
*/
package org.ow2.mind.adl.parameter;
import static org.ow2.mind.adl.parameter.ast.ParameterASTHelper.getInferredParameterType;
import static org.ow2.mind.adl.parameter.ast.ParameterASTHelper.setInferredParameterType;
import static org.ow2.mind.adl.parameter.ast.ParameterASTHelper.setUsedFormalParameter;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import org.objectweb.fractal.adl.ADLException;
import org.objectweb.fractal.adl.CompilerError;
import org.objectweb.fractal.adl.ContextLocal;
import org.objectweb.fractal.adl.Definition;
import org.objectweb.fractal.adl.error.GenericErrors;
import org.objectweb.fractal.adl.error.NodeErrorLocator;
import org.ow2.mind.adl.ADLErrors;
import org.ow2.mind.adl.DefinitionReferenceResolver;
import org.ow2.mind.adl.DefinitionReferenceResolver.AbstractDelegatingDefinitionReferenceResolver;
import org.ow2.mind.adl.ast.ASTHelper;
import org.ow2.mind.adl.ast.DefinitionReference;
import org.ow2.mind.adl.parameter.ast.Argument;
import org.ow2.mind.adl.parameter.ast.ArgumentContainer;
import org.ow2.mind.adl.parameter.ast.FormalParameter;
import org.ow2.mind.adl.parameter.ast.FormalParameterContainer;
import org.ow2.mind.adl.parameter.ast.ParameterASTHelper.ParameterType;
import org.ow2.mind.error.ErrorManager;
import org.ow2.mind.value.ast.Reference;
import org.ow2.mind.value.ast.Value;
import com.google.inject.Inject;
/**
* This delegating {@link DefinitionReferenceResolver} checks that
* {@link Argument} nodes contained by the {@link DefinitionReference} to
* resolve, match {@link FormalParameter} contained by the resolved
* {@link Definition}.
*/
public class ParametricDefinitionReferenceResolver
extends
AbstractDelegatingDefinitionReferenceResolver {
// define a class to alias this too long generic type
protected static final class FormalParameterCache
extends
ContextLocal<Map<Definition, Map<String, FormalParameter>>> {
}
protected final FormalParameterCache contextualParameters = new FormalParameterCache();
@Inject
protected ErrorManager errorManagerItf;
// ---------------------------------------------------------------------------
// Implementation of the DefinitionReferenceResolver interface
// ---------------------------------------------------------------------------
public Definition resolve(final DefinitionReference reference,
final Definition encapsulatingDefinition,
final Map<Object, Object> context) throws ADLException {
return resolve(reference, encapsulatingDefinition,
getParameters(encapsulatingDefinition, context), context);
}
// ---------------------------------------------------------------------------
// Utility methods
// ---------------------------------------------------------------------------
protected Definition resolve(final DefinitionReference reference,
final Definition encapsulatingDefinition,
final Map<String, FormalParameter> formalParameters,
final Map<Object, Object> context) throws ADLException {
final Definition d = clientResolverItf.resolve(reference,
encapsulatingDefinition, context);
// Map argument values to formal parameters.
// argumentMap associates formal parameter names to actual arguments;
final Map<String, Argument> argumentMap = mapArguments(reference, d);
if (argumentMap != null) {
// referenced definition has formal parameters.
// Check argument values
for (final FormalParameter parameter : ((FormalParameterContainer) d)
.getFormalParameters()) {
final ParameterType type = getInferredParameterType(parameter);
final Argument argumentValue = argumentMap.get(parameter.getName());
final Value value = argumentValue.getValue();
if (value instanceof Reference) {
// the argument references a formal parameter
final String ref = ((Reference) value).getRef();
final FormalParameter referencedParameter = formalParameters.get(ref);
if (referencedParameter == null) {
errorManagerItf.logError(ADLErrors.UNDEFINED_PARAMETER, value, ref);
continue;
}
setUsedFormalParameter(referencedParameter);
final ParameterType referencedType = getInferredParameterType(referencedParameter);
if (referencedType == null) {
setInferredParameterType(referencedParameter, type);
} else if (type != null && type != referencedType) {
errorManagerItf.logError(ADLErrors.INCOMPATIBLE_ARGUMENT_TYPE,
value, ref);
}
} else if (type != null && !type.isCompatible(value)) {
errorManagerItf.logError(ADLErrors.INCOMPATIBLE_ARGUMENT_VALUE,
value, parameter.getName());
}
}
}
return d;
}
protected Map<String, Argument> mapArguments(
final DefinitionReference reference, final Definition definition)
throws ADLException {
final Argument[] arguments = (reference instanceof ArgumentContainer)
? ((ArgumentContainer) reference).getArguments()
: null;
final FormalParameter[] parameters = (definition instanceof FormalParameterContainer)
? ((FormalParameterContainer) definition).getFormalParameters()
: null;
if (parameters == null || parameters.length == 0) {
if (arguments != null && arguments.length > 0
&& !ASTHelper.isUnresolvedDefinitionNode(definition)) {
+ removeArguments((ArgumentContainer) reference);
errorManagerItf.logError(ADLErrors.INVALID_REFERENCE_NO_PARAMETER,
reference);
}
return null;
} else {
// there are parameters
if (arguments == null || arguments.length == 0) {
errorManagerItf.logError(ADLErrors.INVALID_REFERENCE_MISSING_ARGUMENT,
reference);
return null;
}
if (arguments.length > 0 && arguments[0].getName() == null) {
// argument values are specified by ordinal position.
if (parameters.length > arguments.length) {
// missing parameter values
+ removeArguments((ArgumentContainer) reference);
errorManagerItf.logError(
ADLErrors.INVALID_REFERENCE_MISSING_ARGUMENT, reference);
return null;
}
if (parameters.length < arguments.length
&& !ASTHelper.isUnresolvedDefinitionNode(definition)) {
+ removeArguments((ArgumentContainer) reference);
errorManagerItf.logError(
ADLErrors.INVALID_REFERENCE_TOO_MANY_ARGUMENT, reference);
return null;
}
final Map<String, Argument> result = new HashMap<String, Argument>(
parameters.length);
for (int i = 0; i < parameters.length; i++) {
final Argument value = arguments[i];
// sanity check.
if (value.getName() != null) {
throw new CompilerError(GenericErrors.INTERNAL_ERROR,
new NodeErrorLocator(value),
"Cannot mix ordinal and name-based template values.");
}
final String varName = parameters[i].getName();
value.setName(varName);
result.put(varName, value);
}
return result;
} else {
// template values are specified by name
final Map<String, Argument> valuesByName = new HashMap<String, Argument>(
arguments.length);
for (final Argument value : arguments) {
// sanity check.
if (value.getName() == null) {
throw new CompilerError(GenericErrors.INTERNAL_ERROR,
new NodeErrorLocator(value),
"Cannot mix ordinal and name-based argument values.");
}
// remove argument and re-add them latter in the formal parameter
// declaration order.
((ArgumentContainer) reference).removeArgument(value);
valuesByName.put(value.getName(), value);
}
final Map<String, Argument> result = new HashMap<String, Argument>();
for (final FormalParameter variable : parameters) {
final Argument value = valuesByName.remove(variable.getName());
if (value == null) {
// missing parameter values
+ removeArguments((ArgumentContainer) reference);
errorManagerItf.logError(
ADLErrors.INVALID_REFERENCE_MISSING_ARGUMENT, reference,
variable.getName());
return null;
}
result.put(variable.getName(), value);
((ArgumentContainer) reference).addArgument(value);
}
if (!valuesByName.isEmpty()) {
// too many parameter values
if (!ASTHelper.isUnresolvedDefinitionNode(definition)) {
for (final Map.Entry<String, Argument> value : valuesByName
.entrySet()) {
+ // remove faulty argument
+ ((ArgumentContainer) reference).removeArgument(value.getValue());
errorManagerItf.logError(
ADLErrors.INVALID_REFERENCE_NO_SUCH_PARAMETER,
value.getValue(), value.getKey());
}
}
return null;
}
return result;
}
}
}
+ protected void removeArguments(final ArgumentContainer container) {
+ for (final Argument argument : container.getArguments()) {
+ container.removeArgument(argument);
+ }
+ }
+
protected Map<String, FormalParameter> getParameters(final Definition d,
final Map<Object, Object> context) throws ADLException {
Map<Definition, Map<String, FormalParameter>> parameters = contextualParameters
.get(context);
if (parameters == null) {
parameters = new IdentityHashMap<Definition, Map<String, FormalParameter>>();
contextualParameters.set(context, parameters);
}
Map<String, FormalParameter> result = parameters.get(d);
if (result == null) {
result = new LinkedHashMap<String, FormalParameter>();
if (d instanceof FormalParameterContainer) {
final FormalParameter[] formalParameters = ((FormalParameterContainer) d)
.getFormalParameters();
if (formalParameters.length > 0) {
for (final FormalParameter parameter : formalParameters) {
result.put(parameter.getName(), parameter);
}
}
}
parameters.put(d, result);
}
return result;
}
}
| false | false | null | null |
diff --git a/test/org/apache/pig/test/TestTypeCheckingValidator.java b/test/org/apache/pig/test/TestTypeCheckingValidator.java
index 7e7c02d9..e39d376b 100644
--- a/test/org/apache/pig/test/TestTypeCheckingValidator.java
+++ b/test/org/apache/pig/test/TestTypeCheckingValidator.java
@@ -1,5778 +1,5778 @@
/*
* 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.pig.test;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.ArrayList;
import junit.framework.AssertionFailedError;
import junit.framework.TestCase;
import org.apache.pig.EvalFunc;
import org.apache.pig.ExecType;
import org.apache.pig.FuncSpec;
import org.apache.pig.PigServer;
import org.apache.pig.impl.logicalLayer.validators.*;
import org.apache.pig.impl.logicalLayer.* ;
import org.apache.pig.impl.logicalLayer.schema.Schema;
import org.apache.pig.impl.logicalLayer.schema.Schema.FieldSchema ;
import org.apache.pig.impl.plan.DepthFirstWalker;
import org.apache.pig.impl.plan.PlanValidationException;
import org.apache.pig.impl.plan.CompilationMessageCollector;
import org.apache.pig.impl.plan.VisitorException;
import org.apache.pig.impl.util.MultiMap;
import org.apache.pig.data.*;
import org.apache.pig.impl.io.FileSpec;
import org.apache.pig.builtin.PigStorage;
import org.junit.Test;
import static org.apache.pig.test.utils.TypeCheckingTestUtil.* ;
import org.apache.pig.test.utils.LogicalPlanTester;
import org.apache.pig.test.utils.TypeCheckingTestUtil;
public class TestTypeCheckingValidator extends TestCase {
LogicalPlanTester planTester;
/* (non-Javadoc)
* @see junit.framework.TestCase#setUp()
*/
@Override
protected void setUp() throws Exception {
// create a new instance of the plan tester
// for each test so that different tests do not
// interact with each other's plans
planTester = new LogicalPlanTester() ;
}
private static final String simpleEchoStreamingCommand;
static {
if (System.getProperty("os.name").toUpperCase().startsWith("WINDOWS"))
simpleEchoStreamingCommand = "perl -ne 'print \\\"$_\\\"'";
else
simpleEchoStreamingCommand = "perl -ne 'print \"$_\"'";
File fileA = new File("a");
File fileB = new File("b");
try {
fileA.delete();
fileB.delete();
if(!fileA.createNewFile() || !fileB.createNewFile())
fail("Unable to create input files");
} catch (IOException e) {
fail("Unable to create input files:" + e.getMessage());
}
fileA.deleteOnExit();
fileB.deleteOnExit();
}
@Test
public void testExpressionTypeChecking1() throws Throwable {
LogicalPlan plan = new LogicalPlan() ;
LOConst constant1 = new LOConst(plan, genNewOperatorKey(), 10) ;
constant1.setType(DataType.INTEGER) ;
LOConst constant2 = new LOConst(plan, genNewOperatorKey(), 20D) ;
constant2.setType(DataType.DOUBLE) ;
LOConst constant3 = new LOConst(plan, genNewOperatorKey(), 123f) ;
constant3.setType(DataType.FLOAT) ;
LOAdd add1 = new LOAdd(plan, genNewOperatorKey()) ;
LOCast cast1 = new LOCast(plan, genNewOperatorKey(), DataType.DOUBLE) ;
LOMultiply mul1 = new LOMultiply(plan, genNewOperatorKey()) ;
plan.add(constant1) ;
plan.add(constant2) ;
plan.add(constant3) ;
plan.add(cast1) ;
plan.add(add1) ;
plan.add(mul1) ;
plan.connect(constant1, add1) ;
plan.connect(constant2, add1) ;
plan.connect(add1, mul1) ;
plan.connect(constant3, cast1) ;
plan.connect(cast1, mul1) ;
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
typeValidator.validate(plan, collector) ;
printMessageCollector(collector) ;
printTypeGraph(plan) ;
if (collector.hasError()) {
throw new Exception("Error during type checking") ;
}
// Induction check
assertEquals(DataType.DOUBLE, add1.getType()) ;
assertEquals(DataType.DOUBLE, mul1.getType()) ;
// Cast insertion check
assertEquals(DataType.DOUBLE, add1.getLhsOperand().getType()) ;
assertEquals(DataType.DOUBLE, mul1.getRhsOperand().getType()) ;
}
@Test
public void testExpressionTypeCheckingFail1() throws Throwable {
LogicalPlan plan = new LogicalPlan() ;
LOConst constant1 = new LOConst(plan, genNewOperatorKey(), 10) ;
constant1.setType(DataType.INTEGER) ;
LOConst constant2 = new LOConst(plan, genNewOperatorKey(), 20D) ;
constant2.setType(DataType.DOUBLE) ;
LOConst constant3 = new LOConst(plan, genNewOperatorKey(), "123") ;
constant3.setType(DataType.CHARARRAY) ;
LOAdd add1 = new LOAdd(plan, genNewOperatorKey()) ;
LOCast cast1 = new LOCast(plan, genNewOperatorKey(), DataType.BYTEARRAY) ;
LOMultiply mul1 = new LOMultiply(plan, genNewOperatorKey()) ;
plan.add(constant1) ;
plan.add(constant2) ;
plan.add(constant3) ;
plan.add(cast1) ;
plan.add(add1) ;
plan.add(mul1) ;
plan.connect(constant1, add1) ;
plan.connect(constant2, add1) ;
plan.connect(add1, mul1) ;
plan.connect(constant3, cast1) ;
plan.connect(cast1, mul1) ;
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
try {
typeValidator.validate(plan, collector) ;
fail("Exception expected") ;
}
catch (PlanValidationException pve) {
// good
}
printMessageCollector(collector) ;
printTypeGraph(plan) ;
if (!collector.hasError()) {
throw new Exception("Error during type checking") ;
}
}
@Test
public void testExpressionTypeChecking2() throws Throwable {
LogicalPlan plan = new LogicalPlan() ;
LOConst constant1 = new LOConst(plan, genNewOperatorKey(), 10) ;
constant1.setType(DataType.INTEGER) ;
LOConst constant2 = new LOConst(plan, genNewOperatorKey(), new DataByteArray()) ;
constant2.setType(DataType.BYTEARRAY) ;
LOConst constant3 = new LOConst(plan, genNewOperatorKey(), 123L) ;
constant3.setType(DataType.LONG) ;
LOConst constant4 = new LOConst(plan, genNewOperatorKey(), true) ;
constant4.setType(DataType.BOOLEAN) ;
LOSubtract sub1 = new LOSubtract(plan, genNewOperatorKey()) ;
LOGreaterThan gt1 = new LOGreaterThan(plan, genNewOperatorKey()) ;
LOAnd and1 = new LOAnd(plan, genNewOperatorKey()) ;
LONot not1 = new LONot(plan, genNewOperatorKey()) ;
plan.add(constant1) ;
plan.add(constant2) ;
plan.add(constant3) ;
plan.add(constant4) ;
plan.add(sub1) ;
plan.add(gt1) ;
plan.add(and1) ;
plan.add(not1) ;
plan.connect(constant1, sub1) ;
plan.connect(constant2, sub1) ;
plan.connect(sub1, gt1) ;
plan.connect(constant3, gt1) ;
plan.connect(gt1, and1) ;
plan.connect(constant4, and1) ;
plan.connect(and1, not1) ;
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
typeValidator.validate(plan, collector) ;
printMessageCollector(collector) ;
printTypeGraph(plan) ;
if (collector.hasError()) {
throw new Exception("Error not expected during type checking") ;
}
// Induction check
assertEquals(DataType.INTEGER, sub1.getType()) ;
assertEquals(DataType.BOOLEAN, gt1.getType()) ;
assertEquals(DataType.BOOLEAN, and1.getType()) ;
assertEquals(DataType.BOOLEAN, not1.getType()) ;
// Cast insertion check
assertEquals(DataType.INTEGER, sub1.getRhsOperand().getType()) ;
assertEquals(DataType.LONG, gt1.getLhsOperand().getType()) ;
}
@Test
public void testExpressionTypeChecking3() throws Throwable {
LogicalPlan plan = new LogicalPlan() ;
LOConst constant1 = new LOConst(plan, genNewOperatorKey(), 10) ;
constant1.setType(DataType.INTEGER) ;
LOConst constant2 = new LOConst(plan, genNewOperatorKey(), 20L) ;
constant2.setType(DataType.LONG) ;
LOConst constant3 = new LOConst(plan, genNewOperatorKey(), 123) ;
constant3.setType(DataType.INTEGER) ;
LOMod mod1 = new LOMod(plan, genNewOperatorKey()) ;
LOEqual equal1 = new LOEqual(plan, genNewOperatorKey()) ;
plan.add(constant1) ;
plan.add(constant2) ;
plan.add(constant3) ;
plan.add(equal1) ;
plan.add(mod1) ;
plan.connect(constant1, mod1) ;
plan.connect(constant2, mod1) ;
plan.connect(mod1, equal1) ;
plan.connect(constant3, equal1) ;
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
typeValidator.validate(plan, collector) ;
printMessageCollector(collector) ;
printTypeGraph(plan) ;
if (collector.hasError()) {
throw new Exception("Error during type checking") ;
}
// Induction check
assertEquals(DataType.LONG, mod1.getType()) ;
assertEquals(DataType.BOOLEAN, equal1.getType()) ;
// Cast insertion check
assertEquals(DataType.LONG, mod1.getLhsOperand().getType()) ;
assertEquals(DataType.LONG, equal1.getRhsOperand().getType()) ;
}
@Test
public void testExpressionTypeChecking4() throws Throwable {
LogicalPlan plan = new LogicalPlan() ;
LOConst constant1 = new LOConst(plan, genNewOperatorKey(), 10) ;
constant1.setType(DataType.INTEGER) ;
LOConst constant2 = new LOConst(plan, genNewOperatorKey(), 20D) ;
constant2.setType(DataType.DOUBLE) ;
LOConst constant3 = new LOConst(plan, genNewOperatorKey(), 123f) ;
constant3.setType(DataType.FLOAT) ;
LODivide div1 = new LODivide(plan, genNewOperatorKey()) ;
LOCast cast1 = new LOCast(plan, genNewOperatorKey(), DataType.DOUBLE) ;
LONotEqual notequal1 = new LONotEqual(plan, genNewOperatorKey()) ;
plan.add(constant1) ;
plan.add(constant2) ;
plan.add(constant3) ;
plan.add(div1) ;
plan.add(cast1) ;
plan.add(notequal1) ;
plan.connect(constant1, div1) ;
plan.connect(constant2, div1) ;
plan.connect(constant3, cast1) ;
plan.connect(div1, notequal1) ;
plan.connect(cast1, notequal1) ;
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
typeValidator.validate(plan, collector) ;
printMessageCollector(collector) ;
printTypeGraph(plan) ;
if (collector.hasError()) {
throw new Exception("Error during type checking") ;
}
// Induction check
assertEquals(DataType.DOUBLE, div1.getType()) ;
assertEquals(DataType.BOOLEAN, notequal1.getType()) ;
// Cast insertion check
assertEquals(DataType.DOUBLE, div1.getLhsOperand().getType()) ;
assertEquals(DataType.DOUBLE, notequal1.getRhsOperand().getType()) ;
}
@Test
public void testExpressionTypeCheckingFail4() throws Throwable {
LogicalPlan plan = new LogicalPlan() ;
LOConst constant1 = new LOConst(plan, genNewOperatorKey(), 10) ;
constant1.setType(DataType.INTEGER) ;
LOConst constant2 = new LOConst(plan, genNewOperatorKey(), 20D) ;
constant2.setType(DataType.DOUBLE) ;
LOConst constant3 = new LOConst(plan, genNewOperatorKey(), "123") ;
constant3.setType(DataType.CHARARRAY) ;
LODivide div1 = new LODivide(plan, genNewOperatorKey()) ;
LOCast cast1 = new LOCast(plan, genNewOperatorKey(), DataType.BYTEARRAY) ;
LONotEqual notequal1 = new LONotEqual(plan, genNewOperatorKey()) ;
plan.add(constant1) ;
plan.add(constant2) ;
plan.add(constant3) ;
plan.add(div1) ;
plan.add(cast1) ;
plan.add(notequal1) ;
plan.connect(constant1, div1) ;
plan.connect(constant2, div1) ;
plan.connect(constant3, cast1) ;
plan.connect(div1, notequal1) ;
plan.connect(cast1, notequal1) ;
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
try{
typeValidator.validate(plan, collector) ;
fail("Exception expected") ;
}
catch (PlanValidationException pve) {
// good
}
printMessageCollector(collector) ;
printTypeGraph(plan) ;
if (!collector.hasError()) {
throw new Exception("Error during type checking") ;
}
}
@Test
public void testExpressionTypeChecking5() throws Throwable {
LogicalPlan plan = new LogicalPlan() ;
LOConst constant1 = new LOConst(plan, genNewOperatorKey(), 10F) ;
constant1.setType(DataType.FLOAT) ;
LOConst constant2 = new LOConst(plan, genNewOperatorKey(), 20L) ;
constant2.setType(DataType.LONG) ;
LOConst constant3 = new LOConst(plan, genNewOperatorKey(), 123F) ;
constant3.setType(DataType.FLOAT) ;
LOConst constant4 = new LOConst(plan, genNewOperatorKey(), 123D) ;
constant4.setType(DataType.DOUBLE) ;
LOLesserThanEqual lesser1 = new LOLesserThanEqual(plan, genNewOperatorKey()) ;
LOBinCond bincond1 = new LOBinCond(plan, genNewOperatorKey()) ;
plan.add(constant1) ;
plan.add(constant2) ;
plan.add(constant3) ;
plan.add(constant4) ;
plan.add(lesser1) ;
plan.add(bincond1) ;
plan.connect(constant1, lesser1) ;
plan.connect(constant2, lesser1) ;
plan.connect(lesser1, bincond1) ;
plan.connect(constant3, bincond1) ;
plan.connect(constant4, bincond1) ;
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
typeValidator.validate(plan, collector) ;
printMessageCollector(collector) ;
printTypeGraph(plan) ;
if (collector.hasError()) {
throw new Exception("Error during type checking") ;
}
// Induction check
assertEquals(DataType.BOOLEAN, lesser1.getType()) ;
assertEquals(DataType.DOUBLE, bincond1.getType()) ;
// Cast insertion check
assertEquals(DataType.FLOAT, lesser1.getLhsOperand().getType()) ;
assertEquals(DataType.FLOAT, lesser1.getRhsOperand().getType()) ;
assertEquals(DataType.DOUBLE, bincond1.getLhsOp().getType()) ;
assertEquals(DataType.DOUBLE, bincond1.getRhsOp().getType()) ;
}
@Test
public void testExpressionTypeChecking6() throws Throwable {
LogicalPlan plan = new LogicalPlan() ;
LOConst constant1 = new LOConst(plan, genNewOperatorKey(), "10") ;
constant1.setType(DataType.CHARARRAY) ;
LOConst constant2 = new LOConst(plan, genNewOperatorKey(), 20L) ;
constant2.setType(DataType.LONG) ;
LOAdd add1 = new LOAdd(plan, genNewOperatorKey()) ;
plan.add(constant1) ;
plan.add(constant2) ;
plan.add(add1) ;
plan.connect(constant1, add1) ;
plan.connect(constant2, add1) ;
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
try {
typeValidator.validate(plan, collector) ;
fail("Exception expected") ;
}
catch (PlanValidationException pve) {
// good
}
printMessageCollector(collector) ;
printTypeGraph(plan) ;
if (!collector.hasError()) {
throw new AssertionError("Error expected") ;
}
}
@Test
public void testExpressionTypeChecking7() throws Throwable {
LogicalPlan plan = new LogicalPlan() ;
LOConst constant1 = new LOConst(plan, genNewOperatorKey(), 10) ;
constant1.setType(DataType.INTEGER) ;
LOConst constant2 = new LOConst(plan, genNewOperatorKey(), 20D) ;
constant2.setType(DataType.BYTEARRAY) ;
LOConst constant3 = new LOConst(plan, genNewOperatorKey(), 123L) ;
constant3.setType(DataType.LONG) ;
LOGreaterThan gt1 = new LOGreaterThan(plan, genNewOperatorKey()) ;
LOEqual equal1 = new LOEqual(plan, genNewOperatorKey()) ;
plan.add(constant1) ;
plan.add(constant2) ;
plan.add(constant3) ;
plan.add(gt1) ;
plan.add(equal1) ;
plan.connect(constant1, gt1) ;
plan.connect(constant2, gt1) ;
plan.connect(gt1, equal1) ;
plan.connect(constant3, equal1) ;
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
try {
typeValidator.validate(plan, collector) ;
fail("Exception expected") ;
}
catch (PlanValidationException pve) {
// good
}
printMessageCollector(collector) ;
printTypeGraph(plan) ;
if (!collector.hasError()) {
throw new AssertionError("Error expected") ;
}
}
@Test
public void testExpressionTypeChecking8() throws Throwable {
LogicalPlan plan = new LogicalPlan() ;
TupleFactory tupleFactory = TupleFactory.getInstance();
ArrayList<Object> innerObjList = new ArrayList<Object>();
ArrayList<Object> objList = new ArrayList<Object>();
innerObjList.add(10);
innerObjList.add(3);
innerObjList.add(7);
innerObjList.add(17);
Tuple innerTuple = tupleFactory.newTuple(innerObjList);
objList.add("World");
objList.add(42);
objList.add(innerTuple);
Tuple tuple = tupleFactory.newTuple(objList);
ArrayList<Schema.FieldSchema> innerFss = new ArrayList<Schema.FieldSchema>();
ArrayList<Schema.FieldSchema> fss = new ArrayList<Schema.FieldSchema>();
ArrayList<Schema.FieldSchema> castFss = new ArrayList<Schema.FieldSchema>();
Schema.FieldSchema stringFs = new Schema.FieldSchema(null, DataType.CHARARRAY);
Schema.FieldSchema intFs = new Schema.FieldSchema(null, DataType.INTEGER);
for(int i = 0; i < innerObjList.size(); ++i) {
innerFss.add(intFs);
}
Schema innerTupleSchema = new Schema(innerFss);
fss.add(stringFs);
fss.add(intFs);
fss.add(new Schema.FieldSchema(null, innerTupleSchema, DataType.TUPLE));
Schema tupleSchema = new Schema(fss);
for(int i = 0; i < 3; ++i) {
castFss.add(stringFs);
}
Schema castSchema = new Schema(castFss);
LOConst constant1 = new LOConst(plan, genNewOperatorKey(), innerTuple) ;
constant1.setType(DataType.TUPLE) ;
constant1.setFieldSchema(new Schema.FieldSchema(null, innerTupleSchema, DataType.TUPLE));
LOConst constant2 = new LOConst(plan, genNewOperatorKey(), tuple) ;
constant2.setType(DataType.TUPLE) ;
constant2.setFieldSchema(new Schema.FieldSchema(null, tupleSchema, DataType.TUPLE));
LOCast cast1 = new LOCast(plan, genNewOperatorKey(), DataType.TUPLE) ;
cast1.setFieldSchema(new FieldSchema(null, castSchema, DataType.TUPLE));
LOEqual equal1 = new LOEqual(plan, genNewOperatorKey()) ;
plan.add(constant1) ;
plan.add(constant2) ;
plan.add(cast1) ;
plan.add(equal1) ;
plan.connect(constant1, cast1) ;
plan.connect(cast1, equal1) ;
plan.connect(constant2, equal1) ;
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
typeValidator.validate(plan, collector) ;
printMessageCollector(collector) ;
printTypeGraph(plan) ;
if (collector.hasError()) {
throw new Exception("Error during type checking") ;
}
assertEquals(DataType.BOOLEAN, equal1.getType()) ;
assertEquals(DataType.TUPLE, equal1.getRhsOperand().getType()) ;
assertEquals(DataType.TUPLE, equal1.getLhsOperand().getType()) ;
}
/*
* chararray can been cast to int when jira-893 been resolved
*/
@Test
public void testExpressionTypeChecking9() throws Throwable {
LogicalPlan plan = new LogicalPlan() ;
TupleFactory tupleFactory = TupleFactory.getInstance();
ArrayList<Object> innerObjList = new ArrayList<Object>();
ArrayList<Object> objList = new ArrayList<Object>();
innerObjList.add("10");
innerObjList.add("3");
innerObjList.add(7);
innerObjList.add("17");
Tuple innerTuple = tupleFactory.newTuple(innerObjList);
objList.add("World");
objList.add(42);
objList.add(innerTuple);
Tuple tuple = tupleFactory.newTuple(objList);
ArrayList<Schema.FieldSchema> innerFss = new ArrayList<Schema.FieldSchema>();
ArrayList<Schema.FieldSchema> fss = new ArrayList<Schema.FieldSchema>();
ArrayList<Schema.FieldSchema> castFss = new ArrayList<Schema.FieldSchema>();
Schema.FieldSchema stringFs = new Schema.FieldSchema(null, DataType.CHARARRAY);
Schema.FieldSchema intFs = new Schema.FieldSchema(null, DataType.INTEGER);
Schema.FieldSchema doubleFs = new Schema.FieldSchema(null, DataType.DOUBLE);
innerFss.add(stringFs);
innerFss.add(stringFs);
innerFss.add(intFs);
innerFss.add(stringFs);
Schema innerTupleSchema = new Schema(innerFss);
fss.add(stringFs);
fss.add(intFs);
fss.add(new Schema.FieldSchema(null, innerTupleSchema, DataType.TUPLE));
Schema tupleSchema = new Schema(fss);
castFss.add(stringFs);
castFss.add(stringFs);
castFss.add(doubleFs);
castFss.add(intFs);
Schema castSchema = new Schema(castFss);
LOConst constant1 = new LOConst(plan, genNewOperatorKey(), innerTuple) ;
constant1.setType(DataType.TUPLE) ;
constant1.setFieldSchema(new Schema.FieldSchema(null, innerTupleSchema, DataType.TUPLE));
LOConst constant2 = new LOConst(plan, genNewOperatorKey(), tuple) ;
constant2.setType(DataType.TUPLE) ;
constant2.setFieldSchema(new Schema.FieldSchema(null, tupleSchema, DataType.TUPLE));
LOCast cast1 = new LOCast(plan, genNewOperatorKey(), DataType.TUPLE) ;
cast1.setFieldSchema(new FieldSchema(null, castSchema, DataType.TUPLE));
LOEqual equal1 = new LOEqual(plan, genNewOperatorKey()) ;
plan.add(constant1) ;
plan.add(constant2) ;
plan.add(cast1) ;
plan.add(equal1) ;
plan.connect(constant1, cast1) ;
plan.connect(cast1, equal1) ;
plan.connect(constant2, equal1) ;
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
try {
typeValidator.validate(plan, collector) ;
} catch(PlanValidationException pve) {
fail("Exception expected") ;
}
printMessageCollector(collector) ;
printTypeGraph(plan) ;
if (collector.hasError()) {
throw new Exception("Error expected") ;
}
}
@Test
public void testArithmeticOpCastInsert1() throws Throwable {
LogicalPlan plan = new LogicalPlan() ;
LOConst constant1 = new LOConst(plan, genNewOperatorKey(), 10) ;
constant1.setType(DataType.INTEGER) ;
LOConst constant2 = new LOConst(plan, genNewOperatorKey(), 20D) ;
constant2.setType(DataType.DOUBLE) ;
LOMultiply mul1 = new LOMultiply(plan, genNewOperatorKey()) ;
plan.add(constant1) ;
plan.add(constant2) ;
plan.add(mul1) ;
plan.connect(constant1, mul1) ;
plan.connect(constant2, mul1) ;
// Before type checking its set correctly - PIG-421
System.out.println(DataType.findTypeName(mul1.getType())) ;
assertEquals(DataType.DOUBLE, mul1.getType()) ;
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
typeValidator.validate(plan, collector) ;
printMessageCollector(collector) ;
printTypeGraph(plan) ;
// After type checking
System.out.println(DataType.findTypeName(mul1.getType())) ;
assertEquals(DataType.DOUBLE, mul1.getType()) ;
}
@Test
public void testArithmeticOpCastInsert2() throws Throwable {
LogicalPlan plan = new LogicalPlan() ;
LOConst constant1 = new LOConst(plan, genNewOperatorKey(), 10) ;
constant1.setType(DataType.INTEGER) ;
LOConst constant2 = new LOConst(plan, genNewOperatorKey(), 20L) ;
constant2.setType(DataType.LONG) ;
LONegative neg1 = new LONegative(plan, genNewOperatorKey()) ;
LOSubtract subtract1 = new LOSubtract(plan, genNewOperatorKey()) ;
plan.add(constant1) ;
plan.add(neg1) ;
plan.add(constant2) ;
plan.add(subtract1) ;
plan.connect(constant1, neg1) ;
plan.connect(neg1, subtract1) ;
plan.connect(constant2, subtract1) ;
// Before type checking its set correctly = PIG-421
assertEquals(DataType.LONG, subtract1.getType()) ;
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
typeValidator.validate(plan, collector) ;
printMessageCollector(collector) ;
printTypeGraph(plan) ;
// After type checking
System.out.println(DataType.findTypeName(subtract1.getType())) ;
assertEquals(DataType.LONG, subtract1.getType()) ;
assertTrue(subtract1.getLhsOperand() instanceof LOCast);
assertEquals(((LOCast)subtract1.getLhsOperand()).getType(), DataType.LONG);
assertTrue(((LOCast)subtract1.getLhsOperand()).getExpression() == neg1);
}
@Test
public void testModCastInsert1() throws Throwable {
LogicalPlan plan = new LogicalPlan() ;
LOConst constant1 = new LOConst(plan, genNewOperatorKey(), 10) ;
constant1.setType(DataType.BYTEARRAY) ;
LOConst constant2 = new LOConst(plan, genNewOperatorKey(), 20L) ;
constant2.setType(DataType.LONG) ;
LOMod mod1 = new LOMod(plan, genNewOperatorKey()) ;
plan.add(constant1) ;
plan.add(constant2) ;
plan.add(mod1) ;
plan.connect(constant1, mod1) ;
plan.connect(constant2, mod1) ;
// Before type checking its set correctly = PIG-421
assertEquals(DataType.LONG, mod1.getType()) ;
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
typeValidator.validate(plan, collector) ;
printMessageCollector(collector) ;
printTypeGraph(plan) ;
// After type checking
System.out.println(DataType.findTypeName(mod1.getType())) ;
assertEquals(DataType.LONG, mod1.getType()) ;
assertTrue(mod1.getLhsOperand() instanceof LOCast);
assertEquals(((LOCast)mod1.getLhsOperand()).getType(), DataType.LONG);
assertTrue(((LOCast)mod1.getLhsOperand()).getExpression() == constant1);
}
// Positive case
@Test
public void testRegexTypeChecking1() throws Throwable {
LogicalPlan plan = new LogicalPlan() ;
LOConst constant1 = new LOConst(plan, genNewOperatorKey(), "10") ;
LOConst constant2 = new LOConst(plan, genNewOperatorKey(), "Regex");
constant1.setType(DataType.CHARARRAY) ;
LORegexp regex = new LORegexp(plan, genNewOperatorKey()) ;
plan.add(constant1) ;
plan.add(constant2) ;
plan.add(regex) ;
plan.connect(constant1, regex) ;
plan.connect(constant2, regex) ;
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
typeValidator.validate(plan, collector) ;
printMessageCollector(collector) ;
printTypeGraph(plan) ;
// After type checking
System.out.println(DataType.findTypeName(regex.getType())) ;
assertEquals(DataType.BOOLEAN, regex.getType()) ;
}
// Positive case with cast insertion
@Test
public void testRegexTypeChecking2() throws Throwable {
LogicalPlan plan = new LogicalPlan() ;
LOConst constant1 = new LOConst(plan, genNewOperatorKey(), new DataByteArray()) ;
LOConst constant2 = new LOConst(plan, genNewOperatorKey(), "Regex");
constant1.setType(DataType.BYTEARRAY) ;
LORegexp regex = new LORegexp(plan, genNewOperatorKey());
plan.add(constant1) ;
plan.add(constant2) ;
plan.add(regex) ;
plan.connect(constant1, regex) ;
plan.connect(constant2, regex) ;
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
typeValidator.validate(plan, collector) ;
printMessageCollector(collector) ;
printTypeGraph(plan) ;
// After type checking
if (collector.hasError()) {
throw new Exception("Error not expected during type checking") ;
}
// check type
System.out.println(DataType.findTypeName(regex.getType())) ;
assertEquals(DataType.BOOLEAN, regex.getType()) ;
// check wiring
LOCast cast = (LOCast) regex.getOperand() ;
assertEquals(cast.getType(), DataType.CHARARRAY);
assertEquals(cast.getExpression(), constant1) ;
}
// Negative case
@Test
public void testRegexTypeChecking3() throws Throwable {
LogicalPlan plan = new LogicalPlan() ;
LOConst constant1 = new LOConst(plan, genNewOperatorKey(), 10) ;
LOConst constant2 = new LOConst(plan, genNewOperatorKey(), "Regex");
constant1.setType(DataType.INTEGER) ;
LORegexp regex = new LORegexp(plan, genNewOperatorKey());
plan.add(constant1) ;
plan.add(constant2) ;
plan.add(regex) ;
plan.connect(constant1, regex) ;
plan.connect(constant2, regex) ;
try {
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
typeValidator.validate(plan, collector) ;
printMessageCollector(collector) ;
fail("Exception expected") ;
}
catch (PlanValidationException pve) {
// good
}
}
// Expression plan has to support DAG before this can be used.
// Currently it supports only tree.
/*
@Test
public void testDiamondShapedExpressionPlan1() throws Throwable {
LogicalPlan plan = new LogicalPlan() ;
LOConst constant1 = new LOConst(plan, genNewOperatorKey(), 10) ;
constant1.setType(DataType.LONG) ;
LONegative neg1 = new LONegative(plan, genNewOperatorKey(), constant1) ;
LONegative neg2 = new LONegative(plan, genNewOperatorKey(), constant1) ;
LODivide div1 = new LODivide(plan, genNewOperatorKey(), neg1, neg2) ;
LONegative neg3 = new LONegative(plan, genNewOperatorKey(), div1) ;
LONegative neg4 = new LONegative(plan, genNewOperatorKey(), div1) ;
LOAdd add1 = new LOAdd(plan, genNewOperatorKey(), neg3, neg4) ;
plan.add(constant1) ;
plan.add(neg1) ;
plan.add(neg2) ;
plan.add(div1) ;
plan.add(neg3) ;
plan.add(neg4) ;
plan.add(add1) ;
plan.connect(constant1, neg1) ;
plan.connect(constant1, neg2) ;
plan.connect(neg1, div1) ;
plan.connect(neg2, div1) ;
plan.connect(div1, neg3) ;
plan.connect(div1, neg3) ;
plan.connect(neg3, add1) ;
plan.connect(neg4, add1) ;
// Before type checking
assertEquals(DataType.UNKNOWN, add1.getType()) ;
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
typeValidator.validate(plan, collector) ;
printMessageCollector(collector) ;
printTypeGraph(plan) ;
// After type checking
assertEquals(DataType.LONG, div1.getType()) ;
assertEquals(DataType.LONG, add1.getType()) ;
}
*/
// This tests when both inputs need casting
@Test
public void testUnionCastingInsert1() throws Throwable {
printCurrentMethodName();
LogicalPlan plan = new LogicalPlan() ;
String pigStorage = PigStorage.class.getName() ;
LOLoad load1 = new LOLoad(plan,
genNewOperatorKey(),
new FileSpec("pi", new FuncSpec(pigStorage)),
null) ;
LOLoad load2 = new LOLoad(plan,
genNewOperatorKey(),
new FileSpec("pi", new FuncSpec(pigStorage)),
null) ;
// schema for input#1
Schema inputSchema1 = null ;
{
List<FieldSchema> fsList1 = new ArrayList<FieldSchema>() ;
fsList1.add(new FieldSchema("field1a", DataType.INTEGER)) ;
fsList1.add(new FieldSchema("field2a", DataType.LONG)) ;
fsList1.add(new FieldSchema(null, DataType.BYTEARRAY)) ;
fsList1.add(new FieldSchema(null, DataType.CHARARRAY)) ;
inputSchema1 = new Schema(fsList1) ;
}
// schema for input#2
Schema inputSchema2 = null ;
{
List<FieldSchema> fsList2 = new ArrayList<FieldSchema>() ;
fsList2.add(new FieldSchema("field1b", DataType.DOUBLE)) ;
fsList2.add(new FieldSchema(null, DataType.INTEGER)) ;
fsList2.add(new FieldSchema("field3b", DataType.FLOAT)) ;
fsList2.add(new FieldSchema("field4b", DataType.CHARARRAY)) ;
inputSchema2 = new Schema(fsList2) ;
}
// set schemas
load1.setEnforcedSchema(inputSchema1) ;
load2.setEnforcedSchema(inputSchema2) ;
// create union operator
ArrayList<LogicalOperator> inputList = new ArrayList<LogicalOperator>() ;
inputList.add(load1) ;
inputList.add(load2) ;
LOUnion union = new LOUnion(plan, genNewOperatorKey()) ;
// wiring
plan.add(load1) ;
plan.add(load2) ;
plan.add(union) ;
plan.connect(load1, union);
plan.connect(load2, union);
// validate
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
typeValidator.validate(plan, collector) ;
printMessageCollector(collector) ;
// check end result schema
Schema outputSchema = union.getSchema() ;
Schema expectedSchema = null ;
{
List<FieldSchema> fsListExpected = new ArrayList<FieldSchema>() ;
fsListExpected.add(new FieldSchema("field1a", DataType.DOUBLE)) ;
fsListExpected.add(new FieldSchema("field2a", DataType.LONG)) ;
fsListExpected.add(new FieldSchema("field3b", DataType.FLOAT)) ;
fsListExpected.add(new FieldSchema("field4b", DataType.CHARARRAY)) ;
expectedSchema = new Schema(fsListExpected) ;
}
assertTrue(Schema.equals(outputSchema, expectedSchema, true, false)) ;
printTypeGraph(plan) ;
// check the inserted casting of input1
{
// Check wiring
List<LogicalOperator> sucList1 = plan.getSuccessors(load1) ;
assertEquals(sucList1.size(), 1);
LOForEach foreach = (LOForEach) sucList1.get(0) ;
assertTrue(foreach instanceof LOForEach) ;
List<LogicalOperator> sucList2 = plan.getSuccessors(foreach) ;
assertEquals(sucList2.size(), 1);
assertTrue(sucList2.get(0) instanceof LOUnion) ;
// Check inserted casting
checkForEachCasting(foreach, 0, true, DataType.DOUBLE) ;
checkForEachCasting(foreach, 1, false, DataType.UNKNOWN) ;
checkForEachCasting(foreach, 2, true, DataType.FLOAT) ;
checkForEachCasting(foreach, 3, false, DataType.UNKNOWN) ;
}
// check the inserted casting of input2
{
// Check wiring
List<LogicalOperator> sucList1 = plan.getSuccessors(load2) ;
assertEquals(sucList1.size(), 1);
LOForEach foreach = (LOForEach) sucList1.get(0) ;
assertTrue(foreach instanceof LOForEach) ;
List<LogicalOperator> sucList2 = plan.getSuccessors(foreach) ;
assertEquals(sucList2.size(), 1);
assertTrue(sucList2.get(0) instanceof LOUnion) ;
// Check inserted casting
checkForEachCasting(foreach, 0, false, DataType.UNKNOWN) ;
checkForEachCasting(foreach, 1, true, DataType.LONG) ;
checkForEachCasting(foreach, 2, false, DataType.UNKNOWN) ;
checkForEachCasting(foreach, 3, false, DataType.UNKNOWN) ;
}
}
// This tests when both only on input needs casting
@Test
public void testUnionCastingInsert2() throws Throwable {
printCurrentMethodName();
LogicalPlan plan = new LogicalPlan() ;
String pigStorage = PigStorage.class.getName() ;
LOLoad load1 = new LOLoad(plan,
genNewOperatorKey(),
new FileSpec("pi", new FuncSpec(pigStorage)),
null) ;
LOLoad load2 = new LOLoad(plan,
genNewOperatorKey(),
new FileSpec("pi", new FuncSpec(pigStorage)),
null) ;
// schema for input#1
Schema inputSchema1 = null ;
{
List<FieldSchema> fsList1 = new ArrayList<FieldSchema>() ;
fsList1.add(new FieldSchema("field1a", DataType.INTEGER)) ;
fsList1.add(new FieldSchema("field2a", DataType.BYTEARRAY)) ;
inputSchema1 = new Schema(fsList1) ;
}
// schema for input#2
Schema inputSchema2 = null ;
{
List<FieldSchema> fsList2 = new ArrayList<FieldSchema>() ;
fsList2.add(new FieldSchema("field1b", DataType.DOUBLE)) ;
fsList2.add(new FieldSchema("field2b", DataType.DOUBLE)) ;
inputSchema2 = new Schema(fsList2) ;
}
// set schemas
load1.setEnforcedSchema(inputSchema1) ;
load2.setEnforcedSchema(inputSchema2) ;
// create union operator
ArrayList<LogicalOperator> inputList = new ArrayList<LogicalOperator>() ;
inputList.add(load1) ;
inputList.add(load2) ;
LOUnion union = new LOUnion(plan, genNewOperatorKey()) ;
// wiring
plan.add(load1) ;
plan.add(load2) ;
plan.add(union) ;
plan.connect(load1, union);
plan.connect(load2, union);
// validate
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
typeValidator.validate(plan, collector) ;
printMessageCollector(collector) ;
// check end result schema
Schema outputSchema = union.getSchema() ;
Schema expectedSchema = null ;
{
List<FieldSchema> fsListExpected = new ArrayList<FieldSchema>() ;
fsListExpected.add(new FieldSchema("field1a", DataType.DOUBLE)) ;
fsListExpected.add(new FieldSchema("field2a", DataType.DOUBLE)) ;
expectedSchema = new Schema(fsListExpected) ;
}
assertTrue(Schema.equals(outputSchema, expectedSchema, true, false)) ;
printTypeGraph(plan) ;
// check the inserted casting of input1
{
// Check wiring
List<LogicalOperator> sucList1 = plan.getSuccessors(load1) ;
assertEquals(sucList1.size(), 1);
LOForEach foreach = (LOForEach) sucList1.get(0) ;
assertTrue(foreach instanceof LOForEach) ;
List<LogicalOperator> sucList2 = plan.getSuccessors(foreach) ;
assertEquals(sucList2.size(), 1);
assertTrue(sucList2.get(0) instanceof LOUnion) ;
// Check inserted casting
checkForEachCasting(foreach, 0, true, DataType.DOUBLE) ;
checkForEachCasting(foreach, 1, true, DataType.DOUBLE) ;
}
// check the inserted casting of input2
{
// Check wiring
List<LogicalOperator> sucList1 = plan.getSuccessors(load2) ;
assertEquals(sucList1.size(), 1);
assertTrue(sucList1.get(0) instanceof LOUnion) ;
}
}
// This has to fail under strict typing mode
/*
// This is a negative test
// Two inputs cannot be merged due to incompatible schemas
@Test
public void testUnionCastingInsert3() throws Throwable {
LogicalPlan plan = new LogicalPlan() ;
String pigStorage = PigStorage.class.getName() ;
LOLoad load1 = new LOLoad(plan,
genNewOperatorKey(),
new FileSpec("pi", new FuncSpec(pigStorage)),
null) ;
LOLoad load2 = new LOLoad(plan,
genNewOperatorKey(),
new FileSpec("pi", new FuncSpec(pigStorage)),
null) ;
// schema for input#1
Schema inputSchema1 = null ;
{
List<FieldSchema> fsList1 = new ArrayList<FieldSchema>() ;
fsList1.add(new FieldSchema("field1a", DataType.INTEGER)) ;
fsList1.add(new FieldSchema("field2a", DataType.BYTEARRAY)) ;
inputSchema1 = new Schema(fsList1) ;
}
// schema for input#2
Schema inputSchema2 = null ;
{
List<FieldSchema> fsList2 = new ArrayList<FieldSchema>() ;
fsList2.add(new FieldSchema("field1b", DataType.CHARARRAY)) ;
fsList2.add(new FieldSchema("field2b", DataType.DOUBLE)) ;
inputSchema2 = new Schema(fsList2) ;
}
// set schemas
load1.setEnforcedSchema(inputSchema1) ;
load2.setEnforcedSchema(inputSchema2) ;
// create union operator
ArrayList<LogicalOperator> inputList = new ArrayList<LogicalOperator>() ;
inputList.add(load1) ;
inputList.add(load2) ;
LOUnion union = new LOUnion(plan, genNewOperatorKey(), inputList) ;
// wiring
plan.add(load1) ;
plan.add(load2) ;
plan.add(union) ;
plan.connect(load1, union);
plan.connect(load2, union);
// validate
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
try {
typeValidator.validate(plan, collector) ;
fail("Exception expected") ;
}
catch (PlanValidationException pve) {
// good
}
printMessageCollector(collector) ;
}
*/
@Test
public void testDistinct1() throws Throwable {
printCurrentMethodName();
LogicalPlan plan = new LogicalPlan() ;
String pigStorage = PigStorage.class.getName() ;
LOLoad load1 = new LOLoad(plan,
genNewOperatorKey(),
new FileSpec("pi", new FuncSpec(pigStorage)),
null) ;
// schema for input#1
Schema inputSchema1 = null ;
{
List<FieldSchema> innerList = new ArrayList<FieldSchema>() ;
innerList.add(new FieldSchema("innerfield1", DataType.BAG)) ;
innerList.add(new FieldSchema("innerfield2", DataType.FLOAT)) ;
Schema innerSchema = new Schema(innerList) ;
List<FieldSchema> fsList1 = new ArrayList<FieldSchema>() ;
fsList1.add(new FieldSchema("field1", DataType.INTEGER)) ;
fsList1.add(new FieldSchema("field2", DataType.BYTEARRAY)) ;
fsList1.add(new FieldSchema("field3", innerSchema)) ;
fsList1.add(new FieldSchema("field4", DataType.BAG)) ;
inputSchema1 = new Schema(fsList1) ;
}
// set schemas
load1.setEnforcedSchema(inputSchema1) ;
// create union operator
ArrayList<LogicalOperator> inputList = new ArrayList<LogicalOperator>() ;
inputList.add(load1) ;
LODistinct distinct1 = new LODistinct(plan, genNewOperatorKey()) ;
// wiring
plan.add(load1) ;
plan.add(distinct1) ;
plan.connect(load1, distinct1);
// validate
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
typeValidator.validate(plan, collector) ;
printMessageCollector(collector) ;
// check end result schema
Schema outputSchema = distinct1.getSchema() ;
assertTrue(Schema.equals(load1.getSchema(), outputSchema, false, false)) ;
}
// Positive test
@Test
public void testFilterWithInnerPlan1() throws Throwable {
testFilterWithInnerPlan(DataType.INTEGER, DataType.LONG) ;
}
// Positive test
@Test
public void testFilterWithInnerPlan2() throws Throwable {
testFilterWithInnerPlan(DataType.INTEGER, DataType.BYTEARRAY) ;
}
// Filter test helper
public void testFilterWithInnerPlan(byte field1Type, byte field2Type) throws Throwable {
// Create outer plan
printCurrentMethodName();
LogicalPlan plan = new LogicalPlan() ;
String pigStorage = PigStorage.class.getName() ;
LOLoad load1 = new LOLoad(plan,
genNewOperatorKey(),
new FileSpec("pi", new FuncSpec(pigStorage)),
null) ;
// schema for input#1
Schema inputSchema1 = null ;
{
List<FieldSchema> fsList1 = new ArrayList<FieldSchema>() ;
fsList1.add(new FieldSchema("field1", field1Type)) ;
fsList1.add(new FieldSchema("field2", field2Type)) ;
inputSchema1 = new Schema(fsList1) ;
}
// set schemas
load1.setEnforcedSchema(inputSchema1) ;
// Create inner plan
LogicalPlan innerPlan = new LogicalPlan() ;
LOProject project1 = new LOProject(innerPlan, genNewOperatorKey(), load1, 0) ;
project1.setSentinel(true);
LOProject project2 = new LOProject(innerPlan, genNewOperatorKey(), load1, 1) ;
project2.setSentinel(true);
LOGreaterThan gt1 = new LOGreaterThan(innerPlan,
genNewOperatorKey()) ;
innerPlan.add(project1) ;
innerPlan.add(project2) ;
innerPlan.add(gt1) ;
innerPlan.connect(project1, gt1) ;
innerPlan.connect(project2, gt1) ;
// filter
LOFilter filter1 = new LOFilter(plan, genNewOperatorKey(), innerPlan) ;
plan.add(load1);
plan.add(filter1);
plan.connect(load1, filter1) ;
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
typeValidator.validate(plan, collector) ;
printMessageCollector(collector) ;
printTypeGraph(plan) ;
if (collector.hasError()) {
throw new AssertionError("Expect no error") ;
}
Schema endResultSchema = filter1.getSchema() ;
assertEquals(endResultSchema.getField(0).type, field1Type) ;
assertEquals(endResultSchema.getField(1).type, field2Type) ;
}
// Negative test
@Test
public void testFilterWithInnerPlan3() throws Throwable {
// Create outer plan
printCurrentMethodName();
LogicalPlan plan = new LogicalPlan() ;
String pigStorage = PigStorage.class.getName() ;
LOLoad load1 = new LOLoad(plan,
genNewOperatorKey(),
new FileSpec("pi", new FuncSpec(pigStorage)),
null) ;
// schema for input#1
Schema inputSchema1 = null ;
{
List<FieldSchema> fsList1 = new ArrayList<FieldSchema>() ;
fsList1.add(new FieldSchema("field1", DataType.INTEGER)) ;
fsList1.add(new FieldSchema("field2", DataType.LONG)) ;
inputSchema1 = new Schema(fsList1) ;
}
// set schemas
load1.setEnforcedSchema(inputSchema1) ;
// Create inner plan
LogicalPlan innerPlan = new LogicalPlan() ;
LOProject project1 = new LOProject(innerPlan, genNewOperatorKey(), load1, 0) ;
project1.setSentinel(true);
LOProject project2 = new LOProject(innerPlan, genNewOperatorKey(), load1, 1) ;
project2.setSentinel(true);
LOAdd add1 = new LOAdd(innerPlan, genNewOperatorKey()) ;
innerPlan.add(project1) ;
innerPlan.add(project2) ;
innerPlan.add(add1) ;
innerPlan.connect(project1, add1) ;
innerPlan.connect(project2, add1) ;
// filter
LOFilter filter1 = new LOFilter(plan, genNewOperatorKey(), innerPlan) ;
plan.add(load1);
plan.add(filter1);
plan.connect(load1, filter1) ;
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
try {
typeValidator.validate(plan, collector) ;
fail("Error expected") ;
}
catch (Exception t) {
// good
}
printMessageCollector(collector) ;
printTypeGraph(plan) ;
if (!collector.hasError()) {
throw new AssertionError("Expect error") ;
}
}
// Simple project sort columns
@Test
public void testSortWithInnerPlan1() throws Throwable {
// Create outer plan
printCurrentMethodName();
LogicalPlan plan = new LogicalPlan() ;
String pigStorage = PigStorage.class.getName() ;
LOLoad load1 = new LOLoad(plan,
genNewOperatorKey(),
new FileSpec("pi", new FuncSpec(pigStorage)),
null) ;
// schema for input#1
Schema inputSchema1 = null ;
{
List<FieldSchema> fsList1 = new ArrayList<FieldSchema>() ;
fsList1.add(new FieldSchema("field1", DataType.LONG)) ;
fsList1.add(new FieldSchema("field2", DataType.INTEGER)) ;
inputSchema1 = new Schema(fsList1) ;
}
// set schemas
load1.setEnforcedSchema(inputSchema1) ;
// Create project inner plan #1
LogicalPlan innerPlan1 = new LogicalPlan() ;
LOProject project1 = new LOProject(innerPlan1, genNewOperatorKey(), load1, 1) ;
project1.setSentinel(true);
innerPlan1.add(project1) ;
// Create project inner plan #2
LogicalPlan innerPlan2 = new LogicalPlan() ;
LOProject project2 = new LOProject(innerPlan2, genNewOperatorKey(), load1, 0) ;
project1.setSentinel(true);
innerPlan2.add(project2) ;
// List of innerplans
List<LogicalPlan> innerPlans = new ArrayList<LogicalPlan>() ;
innerPlans.add(innerPlan1) ;
innerPlans.add(innerPlan2) ;
// List of ASC flags
List<Boolean> ascList = new ArrayList<Boolean>() ;
ascList.add(true);
ascList.add(true);
// Sort
LOSort sort1 = new LOSort(plan, genNewOperatorKey(), innerPlans, ascList, null) ;
plan.add(load1);
plan.add(sort1);
plan.connect(load1, sort1) ;
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
typeValidator.validate(plan, collector) ;
printMessageCollector(collector) ;
printTypeGraph(plan) ;
if (collector.hasError()) {
throw new AssertionError("Expect no error") ;
}
Schema endResultSchema = sort1.getSchema() ;
// outer
assertEquals(endResultSchema.getField(0).type, DataType.LONG) ;
assertEquals(endResultSchema.getField(1).type, DataType.INTEGER) ;
// inner
assertEquals(innerPlan1.getSingleLeafPlanOutputType(), DataType.INTEGER);
assertEquals(innerPlan2.getSingleLeafPlanOutputType(), DataType.LONG);
}
// Positive expression sort columns
@Test
public void testSortWithInnerPlan2() throws Throwable {
// Create outer plan
printCurrentMethodName();
LogicalPlan plan = new LogicalPlan() ;
String pigStorage = PigStorage.class.getName() ;
LOLoad load1 = new LOLoad(plan,
genNewOperatorKey(),
new FileSpec("pi", new FuncSpec(pigStorage)),
null) ;
// schema for input#1
Schema inputSchema1 = null ;
{
List<FieldSchema> fsList1 = new ArrayList<FieldSchema>() ;
fsList1.add(new FieldSchema("field1", DataType.BYTEARRAY)) ;
fsList1.add(new FieldSchema("field2", DataType.INTEGER)) ;
inputSchema1 = new Schema(fsList1) ;
}
// set schemas
load1.setEnforcedSchema(inputSchema1) ;
// Create expression inner plan #1
LogicalPlan innerPlan1 = new LogicalPlan() ;
LOProject project11 = new LOProject(innerPlan1, genNewOperatorKey(), load1, 0) ;
project11.setSentinel(true);
LOProject project12 = new LOProject(innerPlan1, genNewOperatorKey(), load1, 1) ;
project11.setSentinel(true);
LOMultiply mul1 = new LOMultiply(innerPlan1, genNewOperatorKey()) ;
innerPlan1.add(project11) ;
innerPlan1.add(project12) ;
innerPlan1.add(mul1) ;
innerPlan1.connect(project11, mul1);
innerPlan1.connect(project12, mul1);
// Create expression inner plan #2
LogicalPlan innerPlan2 = new LogicalPlan() ;
LOProject project21 = new LOProject(innerPlan2, genNewOperatorKey(), load1, 0) ;
project21.setSentinel(true);
LOConst const21 = new LOConst(innerPlan2, genNewOperatorKey(), 26L) ;
const21.setType(DataType.LONG);
LOMod mod21 = new LOMod(innerPlan2, genNewOperatorKey()) ;
innerPlan2.add(project21) ;
innerPlan2.add(const21) ;
innerPlan2.add(mod21) ;
innerPlan2.connect(project21, mod21);
innerPlan2.connect(const21, mod21) ;
// List of innerplans
List<LogicalPlan> innerPlans = new ArrayList<LogicalPlan>() ;
innerPlans.add(innerPlan1) ;
innerPlans.add(innerPlan2) ;
// List of ASC flags
List<Boolean> ascList = new ArrayList<Boolean>() ;
ascList.add(true);
ascList.add(true);
// Sort
LOSort sort1 = new LOSort(plan, genNewOperatorKey(), innerPlans, ascList, null) ;
plan.add(load1);
plan.add(sort1);
plan.connect(load1, sort1) ;
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
typeValidator.validate(plan, collector) ;
printMessageCollector(collector) ;
printTypeGraph(plan) ;
if (collector.hasError()) {
throw new AssertionError("Expect no error") ;
}
Schema endResultSchema = sort1.getSchema() ;
// outer
assertEquals(endResultSchema.getField(0).type, DataType.BYTEARRAY) ;
assertEquals(endResultSchema.getField(1).type, DataType.INTEGER) ;
// inner
assertEquals(innerPlan1.getSingleLeafPlanOutputType(), DataType.INTEGER);
assertEquals(innerPlan2.getSingleLeafPlanOutputType(), DataType.LONG);
}
// Negative test on expression sort columns
@Test
public void testSortWithInnerPlan3() throws Throwable {
// Create outer plan
printCurrentMethodName();
LogicalPlan plan = new LogicalPlan() ;
String pigStorage = PigStorage.class.getName() ;
LOLoad load1 = new LOLoad(plan,
genNewOperatorKey(),
new FileSpec("pi", new FuncSpec(pigStorage)),
null) ;
// schema for input#1
Schema inputSchema1 = null ;
{
List<FieldSchema> fsList1 = new ArrayList<FieldSchema>() ;
fsList1.add(new FieldSchema("field1", DataType.BYTEARRAY)) ;
fsList1.add(new FieldSchema("field2", DataType.INTEGER)) ;
inputSchema1 = new Schema(fsList1) ;
}
// set schemas
load1.setEnforcedSchema(inputSchema1) ;
// Create expression inner plan #1
LogicalPlan innerPlan1 = new LogicalPlan() ;
LOProject project11 = new LOProject(innerPlan1, genNewOperatorKey(), load1, 0) ;
project11.setSentinel(true);
LOProject project12 = new LOProject(innerPlan1, genNewOperatorKey(), load1, 1) ;
project11.setSentinel(true);
LOMultiply mul1 = new LOMultiply(innerPlan1, genNewOperatorKey()) ;
innerPlan1.add(project11) ;
innerPlan1.add(project12) ;
innerPlan1.add(mul1) ;
innerPlan1.connect(project11, mul1);
innerPlan1.connect(project12, mul1);
// Create expression inner plan #2
LogicalPlan innerPlan2 = new LogicalPlan() ;
LOProject project21 = new LOProject(innerPlan2, genNewOperatorKey(), load1, 0) ;
project21.setSentinel(true);
LOConst const21 = new LOConst(innerPlan2, genNewOperatorKey(), "26") ;
const21.setType(DataType.CHARARRAY);
LOMod mod21 = new LOMod(innerPlan2, genNewOperatorKey()) ;
innerPlan2.add(project21) ;
innerPlan2.add(const21) ;
innerPlan2.add(mod21) ;
innerPlan2.connect(project21, mod21);
innerPlan2.connect(const21, mod21) ;
// List of innerplans
List<LogicalPlan> innerPlans = new ArrayList<LogicalPlan>() ;
innerPlans.add(innerPlan1) ;
innerPlans.add(innerPlan2) ;
// List of ASC flags
List<Boolean> ascList = new ArrayList<Boolean>() ;
ascList.add(true);
ascList.add(true);
// Sort
LOSort sort1 = new LOSort(plan, genNewOperatorKey(), innerPlans, ascList, null) ;
plan.add(load1);
plan.add(sort1);
plan.connect(load1, sort1) ;
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
try {
typeValidator.validate(plan, collector) ;
fail("Error expected") ;
}
catch (Exception t) {
// good
}
printMessageCollector(collector) ;
printTypeGraph(plan) ;
if (!collector.hasError()) {
throw new AssertionError("Error expected") ;
}
}
// Positive expression cond columns
@Test
public void testSplitWithInnerPlan1() throws Throwable {
// Create outer plan
printCurrentMethodName();
LogicalPlan plan = new LogicalPlan() ;
String pigStorage = PigStorage.class.getName() ;
LOLoad load1 = new LOLoad(plan,
genNewOperatorKey(),
new FileSpec("pi", new FuncSpec(pigStorage)),
null) ;
// schema for input#1
Schema inputSchema1 = null ;
{
List<FieldSchema> fsList1 = new ArrayList<FieldSchema>() ;
fsList1.add(new FieldSchema("field1", DataType.BYTEARRAY)) ;
fsList1.add(new FieldSchema("field2", DataType.INTEGER)) ;
inputSchema1 = new Schema(fsList1) ;
}
// set schemas
load1.setEnforcedSchema(inputSchema1) ;
// Create expression inner plan #1
LogicalPlan innerPlan1 = new LogicalPlan() ;
LOProject project11 = new LOProject(innerPlan1, genNewOperatorKey(), load1, 0) ;
project11.setSentinel(true);
LOProject project12 = new LOProject(innerPlan1, genNewOperatorKey(), load1, 1) ;
project11.setSentinel(true);
LONotEqual notequal1 = new LONotEqual(innerPlan1, genNewOperatorKey()) ;
innerPlan1.add(project11) ;
innerPlan1.add(project12) ;
innerPlan1.add(notequal1) ;
innerPlan1.connect(project11, notequal1);
innerPlan1.connect(project12, notequal1);
// Create expression inner plan #2
LogicalPlan innerPlan2 = new LogicalPlan() ;
LOProject project21 = new LOProject(innerPlan2, genNewOperatorKey(), load1, 0) ;
project21.setSentinel(true);
LOConst const21 = new LOConst(innerPlan2, genNewOperatorKey(), 26) ;
const21.setType(DataType.LONG);
LOLesserThanEqual lesser21 = new LOLesserThanEqual(innerPlan2,
genNewOperatorKey()) ;
innerPlan2.add(project21) ;
innerPlan2.add(const21) ;
innerPlan2.add(lesser21) ;
innerPlan2.connect(project21, lesser21);
innerPlan2.connect(const21, lesser21) ;
// List of innerplans
List<LogicalPlan> innerPlans = new ArrayList<LogicalPlan>() ;
innerPlans.add(innerPlan1) ;
innerPlans.add(innerPlan2) ;
// split
LOSplit split1 = new LOSplit(plan,
genNewOperatorKey(),
new ArrayList<LogicalOperator>());
// output1
LOSplitOutput splitOutput1 = new LOSplitOutput(plan, genNewOperatorKey(), 0, innerPlan1) ;
split1.addOutput(splitOutput1);
// output2
LOSplitOutput splitOutput2 = new LOSplitOutput(plan, genNewOperatorKey(), 1, innerPlan2) ;
split1.addOutput(splitOutput2);
plan.add(load1);
plan.add(split1);
plan.add(splitOutput1);
plan.add(splitOutput2);
plan.connect(load1, split1) ;
plan.connect(split1, splitOutput1) ;
plan.connect(split1, splitOutput2) ;
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
typeValidator.validate(plan, collector) ;
printMessageCollector(collector) ;
printTypeGraph(plan) ;
if (collector.hasError()) {
throw new AssertionError("Expect no error") ;
}
// check split itself
{
Schema endResultSchema1 = split1.getSchema() ;
// outer
assertEquals(endResultSchema1.getField(0).type, DataType.BYTEARRAY) ;
assertEquals(endResultSchema1.getField(1).type, DataType.INTEGER) ;
}
// check split output #1
{
Schema endResultSchema1 = splitOutput1.getSchema() ;
// outer
assertEquals(endResultSchema1.getField(0).type, DataType.BYTEARRAY) ;
assertEquals(endResultSchema1.getField(1).type, DataType.INTEGER) ;
}
// check split output #2
{
Schema endResultSchema2 = splitOutput2.getSchema() ;
// outer
assertEquals(endResultSchema2.getField(0).type, DataType.BYTEARRAY) ;
assertEquals(endResultSchema2.getField(1).type, DataType.INTEGER) ;
}
// inner conditions: all have to be boolean
assertEquals(innerPlan1.getSingleLeafPlanOutputType(), DataType.BOOLEAN);
assertEquals(innerPlan2.getSingleLeafPlanOutputType(), DataType.BOOLEAN);
}
// Negative test: expression cond columns not evaluate to boolean
@Test
public void testSplitWithInnerPlan2() throws Throwable {
// Create outer plan
printCurrentMethodName();
LogicalPlan plan = new LogicalPlan() ;
String pigStorage = PigStorage.class.getName() ;
LOLoad load1 = new LOLoad(plan,
genNewOperatorKey(),
new FileSpec("pi", new FuncSpec(pigStorage)),
null) ;
// schema for input#1
Schema inputSchema1 = null ;
{
List<FieldSchema> fsList1 = new ArrayList<FieldSchema>() ;
fsList1.add(new FieldSchema("field1", DataType.BYTEARRAY)) ;
fsList1.add(new FieldSchema("field2", DataType.INTEGER)) ;
inputSchema1 = new Schema(fsList1) ;
}
// set schemas
load1.setEnforcedSchema(inputSchema1) ;
// Create expression inner plan #1
LogicalPlan innerPlan1 = new LogicalPlan() ;
LOProject project11 = new LOProject(innerPlan1, genNewOperatorKey(), load1, 0) ;
project11.setSentinel(true);
LOProject project12 = new LOProject(innerPlan1, genNewOperatorKey(), load1, 1) ;
project11.setSentinel(true);
LONotEqual notequal1 = new LONotEqual(innerPlan1, genNewOperatorKey()) ;
innerPlan1.add(project11) ;
innerPlan1.add(project12) ;
innerPlan1.add(notequal1) ;
innerPlan1.connect(project11, notequal1);
innerPlan1.connect(project12, notequal1);
// Create expression inner plan #2
LogicalPlan innerPlan2 = new LogicalPlan() ;
LOProject project21 = new LOProject(innerPlan2, genNewOperatorKey(), load1, 0) ;
project21.setSentinel(true);
LOConst const21 = new LOConst(innerPlan2, genNewOperatorKey(), 26) ;
const21.setType(DataType.LONG);
LOSubtract subtract21 = new LOSubtract(innerPlan2,
genNewOperatorKey()) ;
innerPlan2.add(project21) ;
innerPlan2.add(const21) ;
innerPlan2.add(subtract21) ;
innerPlan2.connect(project21, subtract21);
innerPlan2.connect(const21, subtract21) ;
// List of innerplans
List<LogicalPlan> innerPlans = new ArrayList<LogicalPlan>() ;
innerPlans.add(innerPlan1) ;
innerPlans.add(innerPlan2) ;
// split
LOSplit split1 = new LOSplit(plan,
genNewOperatorKey(),
new ArrayList<LogicalOperator>());
// output1
LOSplitOutput splitOutput1 = new LOSplitOutput(plan, genNewOperatorKey(), 0, innerPlan1) ;
split1.addOutput(splitOutput1);
// output2
LOSplitOutput splitOutput2 = new LOSplitOutput(plan, genNewOperatorKey(), 1, innerPlan2) ;
split1.addOutput(splitOutput2);
plan.add(load1);
plan.add(split1);
plan.add(splitOutput1);
plan.add(splitOutput2);
plan.connect(load1, split1) ;
plan.connect(split1, splitOutput1) ;
plan.connect(split1, splitOutput2) ;
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
try {
typeValidator.validate(plan, collector) ;
}
catch (Exception t) {
// good
}
printMessageCollector(collector) ;
printTypeGraph(plan) ;
if (!collector.hasError()) {
throw new AssertionError("Error expected") ;
}
}
// Positive test
@Test
public void testCOGroupWithInnerPlan1GroupByTuple1() throws Throwable {
printCurrentMethodName();
LogicalPlan plan = new LogicalPlan() ;
String pigStorage = PigStorage.class.getName() ;
LOLoad load1 = new LOLoad(plan,
genNewOperatorKey(),
new FileSpec("pi", new FuncSpec(pigStorage)),
null) ;
LOLoad load2 = new LOLoad(plan,
genNewOperatorKey(),
new FileSpec("pi", new FuncSpec(pigStorage)),
null) ;
// schema for input#1
Schema inputSchema1 = null ;
{
List<FieldSchema> fsList1 = new ArrayList<FieldSchema>() ;
fsList1.add(new FieldSchema("field1a", DataType.INTEGER)) ;
fsList1.add(new FieldSchema("field2a", DataType.LONG)) ;
inputSchema1 = new Schema(fsList1) ;
}
// schema for input#2
Schema inputSchema2 = null ;
{
List<FieldSchema> fsList2 = new ArrayList<FieldSchema>() ;
fsList2.add(new FieldSchema("field1b", DataType.DOUBLE)) ;
fsList2.add(new FieldSchema(null, DataType.INTEGER)) ;
inputSchema2 = new Schema(fsList2) ;
}
// set schemas
load1.setEnforcedSchema(inputSchema1) ;
load2.setEnforcedSchema(inputSchema2) ;
// Create expression inner plan #1 of input #1
LogicalPlan innerPlan11 = new LogicalPlan() ;
LOProject project111 = new LOProject(innerPlan11, genNewOperatorKey(), load1, 0) ;
project111.setSentinel(true);
LOConst const111 = new LOConst(innerPlan11, genNewOperatorKey(), 26F) ;
const111.setType(DataType.FLOAT);
LOSubtract subtract111 = new LOSubtract(innerPlan11,
genNewOperatorKey()) ;
innerPlan11.add(project111) ;
innerPlan11.add(const111) ;
innerPlan11.add(subtract111) ;
innerPlan11.connect(project111, subtract111);
innerPlan11.connect(const111, subtract111) ;
// Create expression inner plan #2 of input #1
LogicalPlan innerPlan21 = new LogicalPlan() ;
LOProject project211 = new LOProject(innerPlan21, genNewOperatorKey(), load1, 0) ;
project211.setSentinel(true);
LOProject project212 = new LOProject(innerPlan21, genNewOperatorKey(), load1, 1) ;
project212.setSentinel(true);
LOAdd add211 = new LOAdd(innerPlan21,
genNewOperatorKey()) ;
innerPlan21.add(project211) ;
innerPlan21.add(project212) ;
innerPlan21.add(add211) ;
innerPlan21.connect(project211, add211);
innerPlan21.connect(project212, add211) ;
// Create expression inner plan #1 of input #2
LogicalPlan innerPlan12 = new LogicalPlan() ;
LOProject project121 = new LOProject(innerPlan12, genNewOperatorKey(), load2, 0) ;
project121.setSentinel(true);
LOConst const121 = new LOConst(innerPlan12, genNewOperatorKey(), 26) ;
const121.setType(DataType.INTEGER);
LOSubtract subtract121 = new LOSubtract(innerPlan12,
genNewOperatorKey()) ;
innerPlan12.add(project121) ;
innerPlan12.add(const121) ;
innerPlan12.add(subtract121) ;
innerPlan12.connect(project121, subtract121);
innerPlan12.connect(const121, subtract121) ;
// Create expression inner plan #2 of input #2
LogicalPlan innerPlan22 = new LogicalPlan() ;
LOConst const122 = new LOConst(innerPlan22, genNewOperatorKey(), 26) ;
const122.setType(DataType.INTEGER);
innerPlan22.add(const122) ;
// Create Cogroup
ArrayList<LogicalOperator> inputs = new ArrayList<LogicalOperator>() ;
inputs.add(load1) ;
inputs.add(load2) ;
MultiMap<LogicalOperator, LogicalPlan> maps
= new MultiMap<LogicalOperator, LogicalPlan>() ;
maps.put(load1, innerPlan11);
maps.put(load1, innerPlan21);
maps.put(load2, innerPlan12);
maps.put(load2, innerPlan22);
boolean[] isInner = new boolean[inputs.size()] ;
for (int i=0; i < isInner.length ; i++) {
isInner[i] = false ;
}
LOCogroup cogroup1 = new LOCogroup(plan,
genNewOperatorKey(),
maps,
isInner) ;
// construct the main plan
plan.add(load1) ;
plan.add(load2) ;
plan.add(cogroup1) ;
plan.connect(load1, cogroup1);
plan.connect(load2, cogroup1);
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
typeValidator.validate(plan, collector) ;
printMessageCollector(collector) ;
printTypeGraph(plan) ;
if (collector.hasError()) {
throw new AssertionError("Expect no error") ;
}
// check outer schema
Schema endResultSchema = cogroup1.getSchema() ;
// Tuple group column
assertEquals(endResultSchema.getField(0).type, DataType.TUPLE) ;
assertEquals(endResultSchema.getField(0).schema.getField(0).type, DataType.DOUBLE) ;
assertEquals(endResultSchema.getField(0).schema.getField(1).type, DataType.LONG);
assertEquals(endResultSchema.getField(1).type, DataType.BAG) ;
assertEquals(endResultSchema.getField(2).type, DataType.BAG) ;
// check inner schema1
Schema innerSchema1 = endResultSchema.getField(1).schema ;
assertEquals(innerSchema1.getField(0).type, DataType.INTEGER);
assertEquals(innerSchema1.getField(1).type, DataType.LONG);
// check inner schema2
Schema innerSchema2 = endResultSchema.getField(2).schema ;
assertEquals(innerSchema2.getField(0).type, DataType.DOUBLE);
assertEquals(innerSchema2.getField(1).type, DataType.INTEGER);
// check group by col end result
assertEquals(innerPlan11.getSingleLeafPlanOutputType(), DataType.DOUBLE) ;
assertEquals(innerPlan21.getSingleLeafPlanOutputType(), DataType.LONG) ;
assertEquals(innerPlan12.getSingleLeafPlanOutputType(), DataType.DOUBLE) ;
assertEquals(innerPlan22.getSingleLeafPlanOutputType(), DataType.LONG) ;
}
// Positive test
@Test
public void testCOGroupWithInnerPlan1GroupByAtom1() throws Throwable {
printCurrentMethodName();
LogicalPlan plan = new LogicalPlan() ;
String pigStorage = PigStorage.class.getName() ;
LOLoad load1 = new LOLoad(plan,
genNewOperatorKey(),
new FileSpec("pi", new FuncSpec(pigStorage)),
null) ;
LOLoad load2 = new LOLoad(plan,
genNewOperatorKey(),
new FileSpec("pi", new FuncSpec(pigStorage)),
null) ;
// schema for input#1
Schema inputSchema1 = null ;
{
List<FieldSchema> fsList1 = new ArrayList<FieldSchema>() ;
fsList1.add(new FieldSchema("field1a", DataType.INTEGER)) ;
fsList1.add(new FieldSchema("field2a", DataType.LONG)) ;
inputSchema1 = new Schema(fsList1) ;
}
// schema for input#2
Schema inputSchema2 = null ;
{
List<FieldSchema> fsList2 = new ArrayList<FieldSchema>() ;
fsList2.add(new FieldSchema("field1b", DataType.DOUBLE)) ;
fsList2.add(new FieldSchema(null, DataType.INTEGER)) ;
inputSchema2 = new Schema(fsList2) ;
}
// set schemas
load1.setEnforcedSchema(inputSchema1) ;
load2.setEnforcedSchema(inputSchema2) ;
// Create expression inner plan #1 of input #1
LogicalPlan innerPlan11 = new LogicalPlan() ;
LOProject project111 = new LOProject(innerPlan11, genNewOperatorKey(), load1, 0) ;
project111.setSentinel(true);
LOConst const111 = new LOConst(innerPlan11, genNewOperatorKey(), 26F) ;
const111.setType(DataType.FLOAT);
LOSubtract subtract111 = new LOSubtract(innerPlan11,
genNewOperatorKey()) ;
innerPlan11.add(project111) ;
innerPlan11.add(const111) ;
innerPlan11.add(subtract111) ;
innerPlan11.connect(project111, subtract111);
innerPlan11.connect(const111, subtract111) ;
// Create expression inner plan #1 of input #2
LogicalPlan innerPlan12 = new LogicalPlan() ;
LOProject project121 = new LOProject(innerPlan12, genNewOperatorKey(), load2, 0) ;
project121.setSentinel(true);
LOConst const121 = new LOConst(innerPlan12, genNewOperatorKey(), 26) ;
const121.setType(DataType.INTEGER);
LOSubtract subtract121 = new LOSubtract(innerPlan12,
genNewOperatorKey()) ;
innerPlan12.add(project121) ;
innerPlan12.add(const121) ;
innerPlan12.add(subtract121) ;
innerPlan12.connect(project121, subtract121);
innerPlan12.connect(const121, subtract121) ;
// Create Cogroup
ArrayList<LogicalOperator> inputs = new ArrayList<LogicalOperator>() ;
inputs.add(load1) ;
inputs.add(load2) ;
MultiMap<LogicalOperator, LogicalPlan> maps
= new MultiMap<LogicalOperator, LogicalPlan>() ;
maps.put(load1, innerPlan11);
maps.put(load2, innerPlan12);
boolean[] isInner = new boolean[inputs.size()] ;
for (int i=0; i < isInner.length ; i++) {
isInner[i] = false ;
}
LOCogroup cogroup1 = new LOCogroup(plan,
genNewOperatorKey(),
maps,
isInner) ;
// construct the main plan
plan.add(load1) ;
plan.add(load2) ;
plan.add(cogroup1) ;
plan.connect(load1, cogroup1);
plan.connect(load2, cogroup1);
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
typeValidator.validate(plan, collector) ;
printMessageCollector(collector) ;
printTypeGraph(plan) ;
if (collector.hasError()) {
throw new AssertionError("Expect no error") ;
}
// check outer schema
Schema endResultSchema = cogroup1.getSchema() ;
// Tuple group column
assertEquals(endResultSchema.getField(0).type, DataType.DOUBLE) ;
assertEquals(endResultSchema.getField(1).type, DataType.BAG) ;
assertEquals(endResultSchema.getField(2).type, DataType.BAG) ;
// check inner schema1
Schema innerSchema1 = endResultSchema.getField(1).schema ;
assertEquals(innerSchema1.getField(0).type, DataType.INTEGER);
assertEquals(innerSchema1.getField(1).type, DataType.LONG);
// check inner schema2
Schema innerSchema2 = endResultSchema.getField(2).schema ;
assertEquals(innerSchema2.getField(0).type, DataType.DOUBLE);
assertEquals(innerSchema2.getField(1).type, DataType.INTEGER);
// check group by col end result
assertEquals(innerPlan11.getSingleLeafPlanOutputType(), DataType.DOUBLE) ;
assertEquals(innerPlan12.getSingleLeafPlanOutputType(), DataType.DOUBLE) ;
}
// Positive test
@Test
public void testCOGroupWithInnerPlan1GroupByIncompatibleAtom1() throws Throwable {
printCurrentMethodName();
LogicalPlan plan = new LogicalPlan() ;
String pigStorage = PigStorage.class.getName() ;
LOLoad load1 = new LOLoad(plan,
genNewOperatorKey(),
new FileSpec("pi", new FuncSpec(pigStorage)),
null) ;
LOLoad load2 = new LOLoad(plan,
genNewOperatorKey(),
new FileSpec("pi", new FuncSpec(pigStorage)),
null) ;
// schema for input#1
Schema inputSchema1 = null ;
{
List<FieldSchema> fsList1 = new ArrayList<FieldSchema>() ;
fsList1.add(new FieldSchema("field1a", DataType.INTEGER)) ;
fsList1.add(new FieldSchema("field2a", DataType.LONG)) ;
inputSchema1 = new Schema(fsList1) ;
}
// schema for input#2
Schema inputSchema2 = null ;
{
List<FieldSchema> fsList2 = new ArrayList<FieldSchema>() ;
fsList2.add(new FieldSchema("field1b", DataType.DOUBLE)) ;
fsList2.add(new FieldSchema(null, DataType.INTEGER)) ;
inputSchema2 = new Schema(fsList2) ;
}
// set schemas
load1.setEnforcedSchema(inputSchema1) ;
load2.setEnforcedSchema(inputSchema2) ;
// Create expression inner plan #1
LogicalPlan innerPlan11 = new LogicalPlan() ;
LOProject project111 = new LOProject(innerPlan11, genNewOperatorKey(), load1, 0) ;
project111.setSentinel(true);
LOConst const111 = new LOConst(innerPlan11, genNewOperatorKey(), 26F) ;
const111.setType(DataType.FLOAT);
LOSubtract subtract111 = new LOSubtract(innerPlan11,
genNewOperatorKey()) ;
innerPlan11.add(project111) ;
innerPlan11.add(const111) ;
innerPlan11.add(subtract111) ;
innerPlan11.connect(project111, subtract111);
innerPlan11.connect(const111, subtract111) ;
// Create expression inner plan #2
LogicalPlan innerPlan12 = new LogicalPlan() ;
LOConst const121 = new LOConst(innerPlan12, genNewOperatorKey(), 26) ;
const121.setType(DataType.INTEGER);
innerPlan12.add(const121) ;
// Create Cogroup
ArrayList<LogicalOperator> inputs = new ArrayList<LogicalOperator>() ;
inputs.add(load1) ;
inputs.add(load2) ;
MultiMap<LogicalOperator, LogicalPlan> maps
= new MultiMap<LogicalOperator, LogicalPlan>() ;
maps.put(load1, innerPlan11);
maps.put(load2, innerPlan12);
boolean[] isInner = new boolean[inputs.size()] ;
for (int i=0; i < isInner.length ; i++) {
isInner[i] = false ;
}
LOCogroup cogroup1 = new LOCogroup(plan,
genNewOperatorKey(),
maps,
isInner) ;
// construct the main plan
plan.add(load1) ;
plan.add(load2) ;
plan.add(cogroup1) ;
plan.connect(load1, cogroup1);
plan.connect(load2, cogroup1);
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
typeValidator.validate(plan, collector) ;
printMessageCollector(collector) ;
printTypeGraph(plan) ;
if (collector.hasError()) {
throw new AssertionError("Expect no error") ;
}
// check outer schema
Schema endResultSchema = cogroup1.getSchema() ;
// Tuple group column
assertEquals(endResultSchema.getField(0).type, DataType.FLOAT) ;
assertEquals(endResultSchema.getField(1).type, DataType.BAG) ;
assertEquals(endResultSchema.getField(2).type, DataType.BAG) ;
// check inner schema1
Schema innerSchema1 = endResultSchema.getField(1).schema ;
assertEquals(innerSchema1.getField(0).type, DataType.INTEGER);
assertEquals(innerSchema1.getField(1).type, DataType.LONG);
// check inner schema2
Schema innerSchema2 = endResultSchema.getField(2).schema ;
assertEquals(innerSchema2.getField(0).type, DataType.DOUBLE);
assertEquals(innerSchema2.getField(1).type, DataType.INTEGER);
// check group by col end result
assertEquals(innerPlan11.getSingleLeafPlanOutputType(), DataType.FLOAT) ;
assertEquals(innerPlan12.getSingleLeafPlanOutputType(), DataType.FLOAT) ;
}
// Positive test
@Test
public void testForEachGenerate1() throws Throwable {
printCurrentMethodName() ;
LogicalPlan plan = new LogicalPlan() ;
LOLoad load1 = genDummyLOLoad(plan) ;
// schema for input#1
Schema inputSchema1 = null ;
{
List<FieldSchema> fsList1 = new ArrayList<FieldSchema>() ;
fsList1.add(new FieldSchema("field1a", DataType.INTEGER)) ;
fsList1.add(new FieldSchema("field2a", DataType.LONG)) ;
inputSchema1 = new Schema(fsList1) ;
}
// set schemas
load1.setEnforcedSchema(inputSchema1) ;
// Create expression inner plan #1
LogicalPlan innerPlan1 = new LogicalPlan() ;
LOProject project11 = new LOProject(innerPlan1, genNewOperatorKey(), load1, 0) ;
project11.setSentinel(true);
LOConst const11 = new LOConst(innerPlan1, genNewOperatorKey(), 26F) ;
const11.setType(DataType.FLOAT);
LOSubtract subtract11 = new LOSubtract(innerPlan1,
genNewOperatorKey()) ;
innerPlan1.add(project11) ;
innerPlan1.add(const11) ;
innerPlan1.add(subtract11) ;
innerPlan1.connect(project11, subtract11);
innerPlan1.connect(const11, subtract11) ;
// Create expression inner plan #2
LogicalPlan innerPlan2 = new LogicalPlan() ;
LOProject project21 = new LOProject(innerPlan2, genNewOperatorKey(), load1, 0) ;
project21.setSentinel(true);
LOProject project22 = new LOProject(innerPlan2, genNewOperatorKey(), load1, 1) ;
project21.setSentinel(true);
LOAdd add21 = new LOAdd(innerPlan2,
genNewOperatorKey()) ;
innerPlan2.add(project21) ;
innerPlan2.add(project22) ;
innerPlan2.add(add21) ;
innerPlan2.connect(project21, add21);
innerPlan2.connect(project22, add21);
// List of plans
ArrayList<LogicalPlan> generatePlans = new ArrayList<LogicalPlan>() ;
generatePlans.add(innerPlan1);
generatePlans.add(innerPlan2);
// List of flatten flags
ArrayList<Boolean> flattens = new ArrayList<Boolean>() ;
flattens.add(true) ;
flattens.add(false) ;
// Create LOForEach
LOForEach foreach1 = new LOForEach(plan, genNewOperatorKey(), generatePlans, flattens) ;
// construct the main plan
plan.add(load1) ;
plan.add(foreach1) ;
plan.connect(load1, foreach1);
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
typeValidator.validate(plan, collector) ;
printMessageCollector(collector) ;
printTypeGraph(plan) ;
if (collector.hasError()) {
throw new AssertionError("Expect no error") ;
}
// check outer schema
Schema endResultSchema = foreach1.getSchema() ;
assertEquals(endResultSchema.getField(0).type, DataType.FLOAT) ;
assertEquals(endResultSchema.getField(1).type, DataType.LONG) ;
}
// Negative test
@Test
public void testForEachGenerate2() throws Throwable {
printCurrentMethodName() ;
LogicalPlan plan = new LogicalPlan() ;
LOLoad load1 = genDummyLOLoad(plan) ;
// schema for input#1
Schema inputSchema1 = null ;
{
List<FieldSchema> fsList1 = new ArrayList<FieldSchema>() ;
fsList1.add(new FieldSchema("field1a", DataType.INTEGER)) ;
fsList1.add(new FieldSchema("field2a", DataType.LONG)) ;
inputSchema1 = new Schema(fsList1) ;
}
// set schemas
load1.setEnforcedSchema(inputSchema1) ;
// Create expression inner plan #1
LogicalPlan innerPlan1 = new LogicalPlan() ;
LOProject project11 = new LOProject(innerPlan1, genNewOperatorKey(), load1, 0) ;
project11.setSentinel(true);
LOConst const11 = new LOConst(innerPlan1, genNewOperatorKey(), "26F") ;
const11.setType(DataType.CHARARRAY);
LOSubtract subtract11 = new LOSubtract(innerPlan1,
genNewOperatorKey()) ;
innerPlan1.add(project11) ;
innerPlan1.add(const11) ;
innerPlan1.add(subtract11) ;
innerPlan1.connect(project11, subtract11);
innerPlan1.connect(const11, subtract11) ;
// Create expression inner plan #2
LogicalPlan innerPlan2 = new LogicalPlan() ;
LOProject project21 = new LOProject(innerPlan2, genNewOperatorKey(), load1, 0) ;
project21.setSentinel(true);
LOProject project22 = new LOProject(innerPlan2, genNewOperatorKey(), load1, 1) ;
project21.setSentinel(true);
LOAdd add21 = new LOAdd(innerPlan2,
genNewOperatorKey()) ;
innerPlan2.add(project21) ;
innerPlan2.add(project22) ;
innerPlan2.add(add21) ;
innerPlan2.connect(project21, add21);
innerPlan2.connect(project22, add21);
// List of plans
ArrayList<LogicalPlan> generatePlans = new ArrayList<LogicalPlan>() ;
generatePlans.add(innerPlan1);
generatePlans.add(innerPlan2);
// List of flatten flags
ArrayList<Boolean> flattens = new ArrayList<Boolean>() ;
flattens.add(true) ;
flattens.add(false) ;
// Create LOForEach
LOForEach foreach1 = new LOForEach(plan, genNewOperatorKey(), generatePlans, flattens) ;
// construct the main plan
plan.add(load1) ;
plan.add(foreach1) ;
plan.connect(load1, foreach1);
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
try {
typeValidator.validate(plan, collector) ;
fail("Exception expected") ;
}
catch (PlanValidationException pve) {
// good
}
printMessageCollector(collector) ;
printTypeGraph(plan) ;
if (!collector.hasError()) {
throw new AssertionError("Expect error") ;
}
}
/*
// Positive test
// This one does project bag in inner plans
@Test
public void testForEachGenerate3() throws Throwable {
printCurrentMethodName() ;
LogicalPlan plan = new LogicalPlan() ;
LOLoad load1 = genDummyLOLoad(plan) ;
String[] aliases = new String[]{ "a", "b", "c" } ;
byte[] types = new byte[] { DataType.INTEGER, DataType.LONG, DataType.BYTEARRAY } ;
Schema innerSchema1 = genFlatSchema(aliases, types) ;
// schema for input#1
Schema inputSchema1 = null ;
{
List<FieldSchema> fsList1 = new ArrayList<FieldSchema>() ;
fsList1.add(new FieldSchema("field1a", DataType.INTEGER)) ;
fsList1.add(new FieldSchema("field2a", DataType.LONG)) ;
fsList1.add(new FieldSchema("field3a", innerSchema1, DataType.BAG)) ;
inputSchema1 = new Schema(fsList1) ;
}
// set schemas
load1.setEnforcedSchema(inputSchema1) ;
// Create expression inner plan #1 of input #1
LogicalPlan innerPlan1 = new LogicalPlan() ;
LOProject project11 = new LOProject(innerPlan1, genNewOperatorKey(), load1, 2) ;
project11.setSentinel(true);
List<Integer> projections1 = new ArrayList<Integer>() ;
projections1.add(1) ;
projections1.add(2) ;
LOProject project12 = new LOProject(innerPlan1, genNewOperatorKey(), project11, projections1) ;
project12.setSentinel(false);
innerPlan1.add(project12) ;
// Create expression inner plan #1 of input #2
LogicalPlan innerPlan2 = new LogicalPlan() ;
LOProject project21 = new LOProject(innerPlan1, genNewOperatorKey(), load1, 0) ;
project21.setSentinel(true);
LOProject project22 = new LOProject(innerPlan1, genNewOperatorKey(), load1, 1) ;
project21.setSentinel(true);
LOAdd add21 = new LOAdd(innerPlan1,
genNewOperatorKey(),
project21,
project22) ;
innerPlan2.add(project21) ;
innerPlan2.add(project22) ;
innerPlan2.add(add21) ;
innerPlan2.connect(project21, add21);
innerPlan2.connect(project22, add21);
// List of plans
ArrayList<LogicalPlan> generatePlans = new ArrayList<LogicalPlan>() ;
generatePlans.add(innerPlan1);
generatePlans.add(innerPlan2);
// List of flatten flags
ArrayList<Boolean> flattens = new ArrayList<Boolean>() ;
flattens.add(false) ;
flattens.add(false) ;
// Create LOGenerate
LOGenerate generate1 = new LOGenerate(plan, genNewOperatorKey(), generatePlans, flattens) ;
LogicalPlan foreachPlan = new LogicalPlan() ;
foreachPlan.add(generate1) ;
// Create LOForEach
LOForEach foreach1 = new LOForEach(plan, genNewOperatorKey(), foreachPlan) ;
// construct the main plan
plan.add(load1) ;
plan.add(foreach1) ;
plan.connect(load1, foreach1);
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
typeValidator.validate(plan, collector) ;
printMessageCollector(collector) ;
printTypeGraph(plan) ;
if (collector.hasError()) {
throw new AssertionError("Expect no error") ;
}
// check outer schema
Schema endResultSchema = foreach1.getSchema() ;
assertEquals(endResultSchema.getField(0).type, DataType.BAG) ;
assertEquals(endResultSchema.getField(1).type, DataType.LONG) ;
// check inner bag schema
Schema bagSchema = endResultSchema.getField(0).schema ;
assertEquals(bagSchema.getField(0).type, DataType.LONG) ;
assertEquals(bagSchema.getField(1).type, DataType.BYTEARRAY) ;
}
*/
// Positive test
// This one does project bag in inner plans with flatten
@Test
public void testForEachGenerate4() throws Throwable {
printCurrentMethodName() ;
LogicalPlan plan = new LogicalPlan() ;
LOLoad load1 = genDummyLOLoad(plan) ;
String[] aliases = new String[]{ "a", "b", "c" } ;
byte[] types = new byte[] { DataType.INTEGER, DataType.LONG, DataType.BYTEARRAY } ;
Schema innerSchema1 = genFlatSchema(aliases, types) ;
// schema for input#1
Schema inputSchema1 = null ;
{
List<FieldSchema> fsList1 = new ArrayList<FieldSchema>() ;
fsList1.add(new FieldSchema("field1a", DataType.INTEGER)) ;
fsList1.add(new FieldSchema("field2a", DataType.LONG)) ;
fsList1.add(new FieldSchema("field3a", innerSchema1, DataType.BAG)) ;
inputSchema1 = new Schema(fsList1) ;
}
// set schemas
load1.setEnforcedSchema(inputSchema1) ;
// Create expression inner plan #1 of input #1
LogicalPlan innerPlan1 = new LogicalPlan() ;
LOProject project11 = new LOProject(innerPlan1, genNewOperatorKey(), load1, 2) ;
project11.setSentinel(true);
List<Integer> projections1 = new ArrayList<Integer>() ;
projections1.add(1) ;
projections1.add(2) ;
LOProject project12 = new LOProject(innerPlan1, genNewOperatorKey(), project11, projections1) ;
project12.setSentinel(false);
innerPlan1.add(project12) ;
// Create expression inner plan #1 of input #2
LogicalPlan innerPlan2 = new LogicalPlan() ;
LOProject project21 = new LOProject(innerPlan2, genNewOperatorKey(), load1, 0) ;
project21.setSentinel(true);
LOProject project22 = new LOProject(innerPlan2, genNewOperatorKey(), load1, 1) ;
project21.setSentinel(true);
LOAdd add21 = new LOAdd(innerPlan2,
genNewOperatorKey()) ;
innerPlan2.add(project21) ;
innerPlan2.add(project22) ;
innerPlan2.add(add21) ;
innerPlan2.connect(project21, add21);
innerPlan2.connect(project22, add21);
// List of plans
ArrayList<LogicalPlan> generatePlans = new ArrayList<LogicalPlan>() ;
generatePlans.add(innerPlan1);
generatePlans.add(innerPlan2);
// List of flatten flags
ArrayList<Boolean> flattens = new ArrayList<Boolean>() ;
flattens.add(true) ;
flattens.add(false) ;
// Create LOForEach
LOForEach foreach1 = new LOForEach(plan, genNewOperatorKey(), generatePlans, flattens) ;
// construct the main plan
plan.add(load1) ;
plan.add(foreach1) ;
plan.connect(load1, foreach1);
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
typeValidator.validate(plan, collector) ;
printMessageCollector(collector) ;
printTypeGraph(plan) ;
if (collector.hasError()) {
throw new AssertionError("Expect no error") ;
}
// check outer schema
Schema endResultSchema = foreach1.getSchema() ;
assertEquals(endResultSchema.getField(0).type, DataType.LONG) ;
assertEquals(endResultSchema.getField(1).type, DataType.BYTEARRAY) ;
assertEquals(endResultSchema.getField(2).type, DataType.LONG) ;
}
@Test
public void testCross1() throws Throwable {
printCurrentMethodName();
LogicalPlan plan = new LogicalPlan() ;
LOLoad load1 = genDummyLOLoad(plan) ;
LOLoad load2 = genDummyLOLoad(plan) ;
String[] aliases1 = new String[]{ "a", "b", "c" } ;
byte[] types1 = new byte[] { DataType.INTEGER, DataType.LONG, DataType.BYTEARRAY } ;
Schema schema1 = genFlatSchema(aliases1, types1) ;
String[] aliases2 = new String[]{ "e", "f" } ;
byte[] types2 = new byte[] { DataType.FLOAT, DataType.DOUBLE } ;
Schema schema2 = genFlatSchema(aliases2, types2) ;
// set schemas
load1.setEnforcedSchema(schema1) ;
load2.setEnforcedSchema(schema2) ;
// create union operator
ArrayList<LogicalOperator> inputList = new ArrayList<LogicalOperator>() ;
inputList.add(load1) ;
inputList.add(load2) ;
LOCross cross = new LOCross(plan, genNewOperatorKey()) ;
// wiring
plan.add(load1) ;
plan.add(load2) ;
plan.add(cross) ;
plan.connect(load1, cross);
plan.connect(load2, cross);
// validate
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
typeValidator.validate(plan, collector) ;
printMessageCollector(collector) ;
printTypeGraph(plan) ;
assertEquals(cross.getSchema().size(), 5) ;
assertEquals(cross.getSchema().getField(0).type, DataType.INTEGER);
assertEquals(cross.getSchema().getField(1).type, DataType.LONG);
assertEquals(cross.getSchema().getField(2).type, DataType.BYTEARRAY);
assertEquals(cross.getSchema().getField(3).type, DataType.FLOAT);
assertEquals(cross.getSchema().getField(4).type, DataType.DOUBLE);
}
@Test
public void testLineage1() throws Throwable {
planTester.buildPlan("a = load 'a' as (field1: int, field2: float, field3: chararray );") ;
LogicalPlan plan = planTester.buildPlan("b = foreach a generate field1 + 1.0 ;") ;
// validate
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
typeValidator.validate(plan, collector) ;
printMessageCollector(collector) ;
printTypeGraph(plan) ;
planTester.printPlan(plan, TypeCheckingTestUtil.getCurrentMethodName());
if (collector.hasError()) {
throw new AssertionError("Expect no error") ;
}
LOForEach foreach = (LOForEach)plan.getLeaves().get(0);
LogicalPlan foreachPlan = foreach.getForEachPlans().get(0);
LogicalOperator exOp = foreachPlan.getRoots().get(0);
if(! (exOp instanceof LOProject)) exOp = foreachPlan.getRoots().get(1);
LOCast cast = (LOCast)foreachPlan.getSuccessors(exOp).get(0);
assertTrue(cast.getLoadFuncSpec() == null);
}
@Test
public void testLineage1NoSchema() throws Throwable {
planTester.buildPlan("a = load 'a';") ;
LogicalPlan plan = planTester.buildPlan("b = foreach a generate $1 + 1.0 ;") ;
// validate
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
typeValidator.validate(plan, collector) ;
printMessageCollector(collector) ;
printTypeGraph(plan) ;
planTester.printPlan(plan, TypeCheckingTestUtil.getCurrentMethodName());
if (collector.hasError()) {
throw new AssertionError("Expect no error") ;
}
LOForEach foreach = (LOForEach)plan.getLeaves().get(0);
LogicalPlan foreachPlan = foreach.getForEachPlans().get(0);
LogicalOperator exOp = foreachPlan.getRoots().get(0);
if(! (exOp instanceof LOProject)) exOp = foreachPlan.getRoots().get(1);
LOCast cast = (LOCast)foreachPlan.getSuccessors(exOp).get(0);
assertTrue(cast.getLoadFuncSpec().getClassName().startsWith("org.apache.pig.builtin.PigStorage"));
}
@Test
public void testLineage2() throws Throwable {
planTester.buildPlan("a = load 'a' as (field1, field2: float, field3: chararray );") ;
LogicalPlan plan = planTester.buildPlan("b = foreach a generate field1 + 1.0 ;") ;
// validate
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
typeValidator.validate(plan, collector) ;
printMessageCollector(collector) ;
printTypeGraph(plan) ;
planTester.printPlan(plan, TypeCheckingTestUtil.getCurrentMethodName());
if (collector.hasError()) {
throw new AssertionError("Expect no error") ;
}
LOForEach foreach = (LOForEach)plan.getLeaves().get(0);
LogicalPlan foreachPlan = foreach.getForEachPlans().get(0);
LogicalOperator exOp = foreachPlan.getRoots().get(0);
if(! (exOp instanceof LOProject)) exOp = foreachPlan.getRoots().get(1);
LOCast cast = (LOCast)foreachPlan.getSuccessors(exOp).get(0);
assertTrue(cast.getLoadFuncSpec().getClassName().startsWith("org.apache.pig.builtin.PigStorage"));
}
@Test
public void testGroupLineage() throws Throwable {
planTester.buildPlan("a = load 'a' using BinStorage() as (field1, field2: float, field3: chararray );") ;
planTester.buildPlan("b = group a by field1 ;") ;
planTester.buildPlan("c = foreach b generate flatten(a) ;") ;
LogicalPlan plan = planTester.buildPlan("d = foreach c generate field1 + 1.0 ;") ;
// validate
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
typeValidator.validate(plan, collector) ;
printMessageCollector(collector) ;
printTypeGraph(plan) ;
if (collector.hasError()) {
throw new AssertionError("Expect no error") ;
}
LOForEach foreach = (LOForEach)plan.getLeaves().get(0);
LogicalPlan foreachPlan = foreach.getForEachPlans().get(0);
planTester.printPlan(plan, TypeCheckingTestUtil.getCurrentMethodName());
LogicalOperator exOp = foreachPlan.getRoots().get(0);
if(! (exOp instanceof LOProject)) exOp = foreachPlan.getRoots().get(1);
LOCast cast = (LOCast)foreachPlan.getSuccessors(exOp).get(0);
assertTrue(cast.getLoadFuncSpec().getClassName().startsWith("BinStorage"));
}
@Test
public void testGroupLineageNoSchema() throws Throwable {
planTester.buildPlan("a = load 'a' using BinStorage() ;") ;
planTester.buildPlan("b = group a by $0 ;") ;
planTester.buildPlan("c = foreach b generate flatten(a) ;") ;
LogicalPlan plan = planTester.buildPlan("d = foreach c generate $0 + 1.0 ;") ;
// validate
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
typeValidator.validate(plan, collector) ;
printMessageCollector(collector) ;
printTypeGraph(plan) ;
planTester.printPlan(plan, TypeCheckingTestUtil.getCurrentMethodName());
if (collector.hasError()) {
throw new AssertionError("Expect no error") ;
}
LOForEach foreach = (LOForEach)plan.getLeaves().get(0);
LogicalPlan foreachPlan = foreach.getForEachPlans().get(0);
LogicalOperator exOp = foreachPlan.getRoots().get(0);
if(! (exOp instanceof LOProject)) exOp = foreachPlan.getRoots().get(1);
LOCast cast = (LOCast)foreachPlan.getSuccessors(exOp).get(0);
assertTrue(cast.getLoadFuncSpec().getClassName().startsWith("BinStorage"));
}
@Test
public void testGroupLineage2() throws Throwable {
planTester.buildPlan("a = load 'a' using BinStorage() as (field1, field2: float, field3: chararray );") ;
planTester.buildPlan("b = group a by field1 ;") ;
LogicalPlan plan = planTester.buildPlan("c = foreach b generate group + 1.0 ;") ;
// validate
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
typeValidator.validate(plan, collector) ;
printMessageCollector(collector) ;
printTypeGraph(plan) ;
planTester.printPlan(plan, TypeCheckingTestUtil.getCurrentMethodName());
if (collector.hasError()) {
throw new AssertionError("Expect no error") ;
}
LOForEach foreach = (LOForEach)plan.getLeaves().get(0);
LogicalPlan foreachPlan = foreach.getForEachPlans().get(0);
LogicalOperator exOp = foreachPlan.getRoots().get(0);
if(! (exOp instanceof LOProject)) exOp = foreachPlan.getRoots().get(1);
LOCast cast = (LOCast)foreachPlan.getSuccessors(exOp).get(0);
assertTrue(cast.getLoadFuncSpec().getClassName().startsWith("BinStorage"));
}
@Test
public void testGroupLineage2NoSchema() throws Throwable {
planTester.buildPlan("a = load 'a' using BinStorage() ;") ;
planTester.buildPlan("b = group a by $0 ;") ;
LogicalPlan plan = planTester.buildPlan("c = foreach b generate group + 1.0 ;") ;
// validate
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
typeValidator.validate(plan, collector) ;
printMessageCollector(collector) ;
printTypeGraph(plan) ;
planTester.printPlan(plan, TypeCheckingTestUtil.getCurrentMethodName());
if (collector.hasError()) {
throw new AssertionError("Expect no error") ;
}
LOForEach foreach = (LOForEach)plan.getLeaves().get(0);
LogicalPlan foreachPlan = foreach.getForEachPlans().get(0);
LogicalOperator exOp = foreachPlan.getRoots().get(0);
if(! (exOp instanceof LOProject)) exOp = foreachPlan.getRoots().get(1);
LOCast cast = (LOCast)foreachPlan.getSuccessors(exOp).get(0);
assertTrue(cast.getLoadFuncSpec().getClassName().startsWith("BinStorage"));
}
@Test
public void testGroupLineageStar() throws Throwable {
planTester.buildPlan("a = load 'a' using BinStorage() as (name, age, gpa);") ;
planTester.buildPlan("b = group a by *;") ;
planTester.buildPlan("c = foreach b generate flatten(group);") ;
LogicalPlan plan = planTester.buildPlan("d = foreach c generate $0 + 1;") ;
// validate
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
typeValidator.validate(plan, collector) ;
printMessageCollector(collector) ;
printTypeGraph(plan) ;
planTester.printPlan(plan, TypeCheckingTestUtil.getCurrentMethodName());
if (collector.hasError()) {
throw new AssertionError("Expect no error") ;
}
LOForEach foreach = (LOForEach)plan.getLeaves().get(0);
LogicalPlan foreachPlan = foreach.getForEachPlans().get(0);
LogicalOperator exOp = foreachPlan.getRoots().get(0);
if(! (exOp instanceof LOProject)) exOp = foreachPlan.getRoots().get(1);
LOCast cast = (LOCast)foreachPlan.getSuccessors(exOp).get(0);
assertTrue(cast.getLoadFuncSpec().getClassName().startsWith("BinStorage"));
}
@Test
public void testGroupLineageStarNoSchema() throws Throwable {
planTester.buildPlan("a = load 'a' using BinStorage() ;") ;
planTester.buildPlan("b = group a by *;") ;
planTester.buildPlan("c = foreach b generate flatten(group);") ;
LogicalPlan plan = planTester.buildPlan("d = foreach c generate $0 + 1;") ;
// validate
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
typeValidator.validate(plan, collector) ;
printMessageCollector(collector) ;
printTypeGraph(plan) ;
planTester.printPlan(plan, TypeCheckingTestUtil.getCurrentMethodName());
if (collector.hasError()) {
throw new AssertionError("Expect no error") ;
}
LOForEach foreach = (LOForEach)plan.getLeaves().get(0);
LogicalPlan foreachPlan = foreach.getForEachPlans().get(0);
LogicalOperator exOp = foreachPlan.getRoots().get(0);
if(! (exOp instanceof LOProject)) exOp = foreachPlan.getRoots().get(1);
LOCast cast = (LOCast)foreachPlan.getSuccessors(exOp).get(0);
assertTrue(cast.getLoadFuncSpec().getClassName().startsWith("BinStorage"));
}
@Test
public void testCogroupLineage() throws Throwable {
planTester.buildPlan("a = load 'a' using BinStorage() as (field1, field2: float, field3: chararray );") ;
planTester.buildPlan("b = load 'a' using PigStorage() as (field4, field5, field6: chararray );") ;
planTester.buildPlan("c = cogroup a by field1, b by field4 ;") ;
planTester.buildPlan("d = foreach c generate group, flatten(a), flatten(b) ;") ;
LogicalPlan plan = planTester.buildPlan("e = foreach d generate group, field1 + 1, field4 + 2.0 ;") ;
// validate
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
typeValidator.validate(plan, collector) ;
printMessageCollector(collector) ;
printTypeGraph(plan) ;
planTester.printPlan(plan, TypeCheckingTestUtil.getCurrentMethodName());
if (collector.hasError()) {
throw new AssertionError("Expect no error") ;
}
LOForEach foreach = (LOForEach)plan.getLeaves().get(0);
LogicalPlan foreachPlan = foreach.getForEachPlans().get(1);
LogicalOperator exOp = foreachPlan.getRoots().get(0);
if(! (exOp instanceof LOProject)) exOp = foreachPlan.getRoots().get(1);
LOCast cast = (LOCast)foreachPlan.getSuccessors(exOp).get(0);
assertTrue(cast.getLoadFuncSpec().getClassName().startsWith("BinStorage"));
foreachPlan = foreach.getForEachPlans().get(2);
exOp = foreachPlan.getRoots().get(0);
if(! (exOp instanceof LOProject)) exOp = foreachPlan.getRoots().get(1);
cast = (LOCast)foreachPlan.getSuccessors(exOp).get(0);
assertTrue(cast.getLoadFuncSpec().getClassName().startsWith("PigStorage"));
}
@Test
public void testCogroupMapLookupLineage() throws Throwable {
planTester.buildPlan("a = load 'a' using BinStorage() as (field1, field2: float, field3: chararray );") ;
planTester.buildPlan("b = load 'a' using PigStorage() as (field4, field5, field6: chararray );") ;
planTester.buildPlan("c = cogroup a by field1, b by field4 ;") ;
planTester.buildPlan("d = foreach c generate group, flatten(a), flatten(b) ;") ;
LogicalPlan plan = planTester.buildPlan("e = foreach d generate group, field1#'key' + 1, field4 + 2.0 ;") ;
// validate
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
typeValidator.validate(plan, collector) ;
printMessageCollector(collector) ;
printTypeGraph(plan) ;
planTester.printPlan(plan, TypeCheckingTestUtil.getCurrentMethodName());
if (collector.hasError()) {
throw new AssertionError("Expect no error") ;
}
LOForEach foreach = (LOForEach)plan.getLeaves().get(0);
LogicalPlan foreachPlan = foreach.getForEachPlans().get(1);
LogicalOperator exOp = foreachPlan.getRoots().get(0);
if(! (exOp instanceof LOProject)) exOp = foreachPlan.getRoots().get(1);
LOCast cast1 = (LOCast)foreachPlan.getSuccessors(exOp).get(0);
LOMapLookup map = (LOMapLookup)foreachPlan.getSuccessors(cast1).get(0);
assertTrue(cast1.getLoadFuncSpec().getClassName().startsWith("BinStorage"));
LOCast cast2 = (LOCast)foreachPlan.getSuccessors(map).get(0);
assertTrue(cast2.getLoadFuncSpec().getClassName().startsWith("BinStorage"));
foreachPlan = foreach.getForEachPlans().get(2);
exOp = foreachPlan.getRoots().get(0);
if(! (exOp instanceof LOProject)) exOp = foreachPlan.getRoots().get(1);
LOCast cast = (LOCast)foreachPlan.getSuccessors(exOp).get(0);
assertTrue(cast.getLoadFuncSpec().getClassName().startsWith("PigStorage"));
}
@Test
public void testCogroupStarLineage() throws Throwable {
planTester.buildPlan("a = load 'a' using BinStorage() as (field1, field2: float, field3: chararray );") ;
planTester.buildPlan("b = load 'b' using PigStorage() as (field4, field5, field6: chararray );") ;
planTester.buildPlan("c = cogroup a by *, b by * ;") ;
planTester.buildPlan("d = foreach c generate group, flatten($1), flatten($2);") ;
LogicalPlan plan = planTester.buildPlan("e = foreach d generate group, field1 + 1, field4 + 2.0;") ;
// validate
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
try {
typeValidator.validate(plan, collector) ;
}
catch (PlanValidationException pve) {
//not good
}
printMessageCollector(collector) ;
printTypeGraph(plan) ;
planTester.printPlan(plan, TypeCheckingTestUtil.getCurrentMethodName());
if (collector.hasError()) {
throw new AssertionError("Expect no error") ;
}
LOForEach foreach = (LOForEach)plan.getLeaves().get(0);
LogicalPlan foreachPlan = foreach.getForEachPlans().get(1);
LogicalOperator exOp = foreachPlan.getRoots().get(0);
if(! (exOp instanceof LOProject)) exOp = foreachPlan.getRoots().get(1);
LOCast cast = (LOCast)foreachPlan.getSuccessors(exOp).get(0);
assertTrue(cast.getLoadFuncSpec().getClassName().startsWith("BinStorage"));
foreachPlan = foreach.getForEachPlans().get(2);
exOp = foreachPlan.getRoots().get(0);
if(! (exOp instanceof LOProject)) exOp = foreachPlan.getRoots().get(1);
cast = (LOCast)foreachPlan.getSuccessors(exOp).get(0);
assertTrue(cast.getLoadFuncSpec().getClassName().startsWith("PigStorage"));
}
@Test
public void testCogroupStarLineageFail() throws Throwable {
planTester.buildPlan("a = load 'a' using BinStorage() as (field1, field2: float, field3: chararray );") ;
planTester.buildPlan("b = load 'b' using PigStorage() as (field4, field5, field6: chararray );") ;
planTester.buildPlan("c = cogroup a by *, b by * ;") ;
planTester.buildPlan("d = foreach c generate group, flatten($1), flatten($2);") ;
LogicalPlan plan = planTester.buildPlan("e = foreach d generate group + 1, field1 + 1, field4 + 2.0;") ;
// validate
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
try {
typeValidator.validate(plan, collector) ;
fail("Exception expected") ;
}
catch (PlanValidationException pve) {
//not good
}
printMessageCollector(collector) ;
printTypeGraph(plan) ;
planTester.printPlan(plan, TypeCheckingTestUtil.getCurrentMethodName());
if (!collector.hasError()) {
throw new AssertionError("Expect error") ;
}
}
@Test
public void testCogroupStarLineage1() throws Throwable {
planTester.buildPlan("a = load 'a' using PigStorage() as (field1, field2: float, field3: chararray );") ;
planTester.buildPlan("b = load 'b' using PigStorage() as (field4, field5, field6: chararray );") ;
planTester.buildPlan("c = cogroup a by *, b by * ;") ;
planTester.buildPlan("d = foreach c generate flatten(group), flatten($1), flatten($2);") ;
LogicalPlan plan = planTester.buildPlan("e = foreach d generate $0 + 1, a::field1 + 1, field4 + 2.0;") ;
// validate
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
try {
typeValidator.validate(plan, collector) ;
}
catch (PlanValidationException pve) {
//not good
}
printMessageCollector(collector) ;
printTypeGraph(plan) ;
planTester.printPlan(plan, TypeCheckingTestUtil.getCurrentMethodName());
if (collector.hasError()) {
throw new AssertionError("Expect no error") ;
}
LOForEach foreach = (LOForEach)plan.getLeaves().get(0);
LogicalPlan foreachPlan = foreach.getForEachPlans().get(0);
LogicalOperator exOp = foreachPlan.getRoots().get(0);
if(! (exOp instanceof LOProject)) exOp = foreachPlan.getRoots().get(1);
LOCast cast = (LOCast)foreachPlan.getSuccessors(exOp).get(0);
assertTrue(cast.getLoadFuncSpec().getClassName().startsWith("PigStorage"));
foreachPlan = foreach.getForEachPlans().get(1);
exOp = foreachPlan.getRoots().get(0);
if(! (exOp instanceof LOProject)) exOp = foreachPlan.getRoots().get(1);
cast = (LOCast)foreachPlan.getSuccessors(exOp).get(0);
assertTrue(cast.getLoadFuncSpec().getClassName().startsWith("PigStorage"));
foreachPlan = foreach.getForEachPlans().get(2);
exOp = foreachPlan.getRoots().get(0);
if(! (exOp instanceof LOProject)) exOp = foreachPlan.getRoots().get(1);
cast = (LOCast)foreachPlan.getSuccessors(exOp).get(0);
assertTrue(cast.getLoadFuncSpec().getClassName().startsWith("PigStorage"));
}
@Test
public void testCogroupStarLineageNoSchemaFail() throws Throwable {
planTester.buildPlan("a = load 'a' using BinStorage() ;") ;
planTester.buildPlan("b = load 'b' using PigStorage() ;") ;
boolean exceptionThrown = false;
try {
LogicalPlan lp = planTester.buildPlan("c = cogroup a by *, b by *;");
} catch(AssertionFailedError e) {
assertTrue(e.getMessage().contains("Cogroup/Group by * is only allowed if " +
"the input has a schema"));
exceptionThrown = true;
}
assertTrue(exceptionThrown);
}
@Test
public void testCogroupMultiColumnProjectLineage() throws Throwable {
planTester.buildPlan("a = load 'a' using BinStorage() as (field1, field2: float, field3: chararray );") ;
planTester.buildPlan("b = load 'b' using PigStorage() as (field4, field5, field6: chararray );") ;
planTester.buildPlan("c = cogroup a by field1, b by field4 ;") ;
planTester.buildPlan("d = foreach c generate group, a.(field1, field2), b.(field4);") ;
planTester.buildPlan("e = foreach d generate group, flatten($1), flatten($2);") ;
LogicalPlan plan = planTester.buildPlan("f = foreach e generate group, field1 + 1, field4 + 2.0;") ;
// validate
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
try {
typeValidator.validate(plan, collector) ;
}
catch (PlanValidationException pve) {
//not good
}
printMessageCollector(collector) ;
printTypeGraph(plan) ;
planTester.printPlan(plan, TypeCheckingTestUtil.getCurrentMethodName());
if (collector.hasError()) {
throw new AssertionError("Expect no error") ;
}
LOForEach foreach = (LOForEach)plan.getLeaves().get(0);
LogicalPlan foreachPlan = foreach.getForEachPlans().get(1);
LogicalOperator exOp = foreachPlan.getRoots().get(0);
if(! (exOp instanceof LOProject)) exOp = foreachPlan.getRoots().get(1);
LOCast cast = (LOCast)foreachPlan.getSuccessors(exOp).get(0);
assertTrue(cast.getLoadFuncSpec().getClassName().startsWith("BinStorage"));
foreachPlan = foreach.getForEachPlans().get(2);
exOp = foreachPlan.getRoots().get(0);
if(! (exOp instanceof LOProject)) exOp = foreachPlan.getRoots().get(1);
cast = (LOCast)foreachPlan.getSuccessors(exOp).get(0);
assertTrue(cast.getLoadFuncSpec().getClassName().startsWith("PigStorage"));
}
@Test
public void testCogroupProjectStarLineage() throws Throwable {
planTester.buildPlan("a = load 'a' using BinStorage() as (field1, field2: float, field3: chararray );") ;
planTester.buildPlan("b = load 'b' using PigStorage() as (field4, field5, field6: chararray );") ;
planTester.buildPlan("c = cogroup a by field1, b by field4 ;") ;
planTester.buildPlan("d = foreach c generate * ;") ;
planTester.buildPlan("f = foreach d generate group, flatten(a), flatten(b) ;") ;
LogicalPlan plan = planTester.buildPlan("g = foreach f generate group, field1 + 1, field4 + 2.0 ;") ;
// validate
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
try {
typeValidator.validate(plan, collector) ;
}
catch (PlanValidationException pve) {
//not good
}
printMessageCollector(collector) ;
printTypeGraph(plan) ;
planTester.printPlan(plan, TypeCheckingTestUtil.getCurrentMethodName());
if (collector.hasError()) {
throw new AssertionError("Expect no error") ;
}
LOForEach foreach = (LOForEach)plan.getLeaves().get(0);
LogicalPlan foreachPlan = foreach.getForEachPlans().get(1);
LogicalOperator exOp = foreachPlan.getRoots().get(0);
if(! (exOp instanceof LOProject)) exOp = foreachPlan.getRoots().get(1);
LOCast cast = (LOCast)foreachPlan.getSuccessors(exOp).get(0);
assertTrue(cast.getLoadFuncSpec().getClassName().startsWith("BinStorage"));
foreachPlan = foreach.getForEachPlans().get(2);
exOp = foreachPlan.getRoots().get(0);
if(! (exOp instanceof LOProject)) exOp = foreachPlan.getRoots().get(1);
cast = (LOCast)foreachPlan.getSuccessors(exOp).get(0);
assertTrue(cast.getLoadFuncSpec().getClassName().startsWith("PigStorage"));
}
@Test
public void testCogroupProjectStarLineageNoSchema() throws Throwable {
planTester.buildPlan("a = load 'a' using BinStorage() ;") ;
planTester.buildPlan("b = load 'b' using PigStorage() ;") ;
planTester.buildPlan("c = cogroup a by $0, b by $0 ;") ;
planTester.buildPlan("d = foreach c generate * ;") ;
planTester.buildPlan("f = foreach d generate group, flatten(a), flatten(b) ;") ;
LogicalPlan plan = planTester.buildPlan("g = foreach f generate group, $1 + 1, $2 + 2.0 ;") ;
// validate
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
try {
typeValidator.validate(plan, collector) ;
}
catch (PlanValidationException pve) {
//not good
}
printMessageCollector(collector) ;
printTypeGraph(plan) ;
planTester.printPlan(plan, TypeCheckingTestUtil.getCurrentMethodName());
if (collector.hasError()) {
throw new AssertionError("Expect no error") ;
}
LOForEach foreach = (LOForEach)plan.getLeaves().get(0);
LogicalPlan foreachPlan = foreach.getForEachPlans().get(1);
LogicalOperator exOp = foreachPlan.getRoots().get(0);
if(! (exOp instanceof LOProject)) exOp = foreachPlan.getRoots().get(1);
LOCast cast = (LOCast)foreachPlan.getSuccessors(exOp).get(0);
assertTrue(cast.getLoadFuncSpec().getClassName().startsWith("BinStorage"));
foreachPlan = foreach.getForEachPlans().get(2);
exOp = foreachPlan.getRoots().get(0);
if(! (exOp instanceof LOProject)) exOp = foreachPlan.getRoots().get(1);
cast = (LOCast)foreachPlan.getSuccessors(exOp).get(0);
assertTrue(cast.getLoadFuncSpec().getClassName().startsWith("PigStorage"));
}
@Test
public void testCogroupProjectStarLineageMixSchema() throws Throwable {
planTester.buildPlan("a = load 'a' using BinStorage() as (field1, field2: float, field3: chararray );") ;
planTester.buildPlan("b = load 'b' using PigStorage() ;") ;
planTester.buildPlan("c = cogroup a by field1, b by $0 ;") ;
planTester.buildPlan("d = foreach c generate * ;") ;
planTester.buildPlan("f = foreach d generate group, flatten(a), flatten(b) ;") ;
LogicalPlan plan = planTester.buildPlan("g = foreach f generate group, field1 + 1, $4 + 2.0 ;") ;
// validate
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
try {
typeValidator.validate(plan, collector) ;
}
catch (PlanValidationException pve) {
//not good
}
printMessageCollector(collector) ;
printTypeGraph(plan) ;
planTester.printPlan(plan, TypeCheckingTestUtil.getCurrentMethodName());
if (collector.hasError()) {
throw new AssertionError("Expect no error") ;
}
LOForEach foreach = (LOForEach)plan.getLeaves().get(0);
LogicalPlan foreachPlan = foreach.getForEachPlans().get(1);
LogicalOperator exOp = foreachPlan.getRoots().get(0);
if(! (exOp instanceof LOProject)) exOp = foreachPlan.getRoots().get(1);
LOCast cast = (LOCast)foreachPlan.getSuccessors(exOp).get(0);
assertTrue(cast.getLoadFuncSpec().getClassName().startsWith("BinStorage"));
foreachPlan = foreach.getForEachPlans().get(2);
exOp = foreachPlan.getRoots().get(0);
if(! (exOp instanceof LOProject)) exOp = foreachPlan.getRoots().get(1);
cast = (LOCast)foreachPlan.getSuccessors(exOp).get(0);
assertTrue(cast.getLoadFuncSpec().getClassName().startsWith("PigStorage"));
}
@Test
public void testCogroupLineageFail() throws Throwable {
planTester.buildPlan("a = load 'a' using BinStorage() as (field1, field2: float, field3: chararray );") ;
planTester.buildPlan("b = load 'a' using PigStorage() as (field4, field5, field6: chararray );") ;
planTester.buildPlan("c = cogroup a by field1, b by field4 ;") ;
planTester.buildPlan("d = foreach c generate group, flatten(a), flatten(b) ;") ;
LogicalPlan plan = planTester.buildPlan("e = foreach d generate group + 1, field1 + 1, field4 + 2.0 ;") ;
// validate
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
try {
typeValidator.validate(plan, collector) ;
fail("Exception expected") ;
}
catch (PlanValidationException pve) {
// good
}
printMessageCollector(collector) ;
printTypeGraph(plan) ;
planTester.printPlan(plan, TypeCheckingTestUtil.getCurrentMethodName());
if (!collector.hasError()) {
throw new AssertionError("Expect error") ;
}
}
// The following test is commented out with PIG-505
/*
@Test
public void testCogroupUDFLineageFail() throws Throwable {
planTester.buildPlan("a = load 'a' using BinStorage() as (field1, field2: float, field3: chararray );") ;
planTester.buildPlan("b = load 'a' using PigStorage() as (field4, field5, field6: chararray );") ;
planTester.buildPlan("c = cogroup a by field1, b by field4 ;") ;
planTester.buildPlan("d = foreach c generate flatten(DIFF(a, b)) as diff_a_b ;") ;
LogicalPlan plan = planTester.buildPlan("e = foreach d generate diff_a_b + 1;") ;
// validate
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
try {
typeValidator.validate(plan, collector) ;
fail("Exception expected") ;
}
catch (PlanValidationException pve) {
// good
}
printMessageCollector(collector) ;
printTypeGraph(plan) ;
planTester.printPlan(plan, TypeCheckingTestUtil.getCurrentMethodName());
if (!collector.hasError()) {
throw new AssertionError("Expect error") ;
}
}
*/
@Test
public void testCogroupLineage2NoSchema() throws Throwable {
planTester.buildPlan("a = load 'a' using BinStorage() ;") ;
planTester.buildPlan("b = load 'a' using PigStorage() ;") ;
planTester.buildPlan("c = cogroup a by $0, b by $0 ;") ;
planTester.buildPlan("d = foreach c generate group, flatten(a), flatten(b) ;") ;
LogicalPlan plan = planTester.buildPlan("e = foreach d generate group, $1 + 1, $2 + 2.0 ;") ;
// validate
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
typeValidator.validate(plan, collector) ;
printMessageCollector(collector) ;
printTypeGraph(plan) ;
planTester.printPlan(plan, TypeCheckingTestUtil.getCurrentMethodName());
if (collector.hasError()) {
throw new AssertionError("Expect no error") ;
}
LOForEach foreach = (LOForEach)plan.getLeaves().get(0);
LogicalPlan foreachPlan = foreach.getForEachPlans().get(1);
LogicalOperator exOp = foreachPlan.getRoots().get(0);
if(! (exOp instanceof LOProject)) exOp = foreachPlan.getRoots().get(1);
LOCast cast = (LOCast)foreachPlan.getSuccessors(exOp).get(0);
assertTrue(cast.getLoadFuncSpec().getClassName().startsWith("BinStorage"));
foreachPlan = foreach.getForEachPlans().get(2);
exOp = foreachPlan.getRoots().get(0);
if(! (exOp instanceof LOProject)) exOp = foreachPlan.getRoots().get(1);
cast = (LOCast)foreachPlan.getSuccessors(exOp).get(0);
assertTrue(cast.getLoadFuncSpec().getClassName().startsWith("PigStorage"));
}
@Test
public void testUnionLineage() throws Throwable {
//here the type checker will insert a cast for the union, converting the column field2 into a float
planTester.buildPlan("a = load 'a' using BinStorage() as (field1, field2: float, field3: chararray );") ;
planTester.buildPlan("b = load 'a' using PigStorage() as (field4, field5, field6: chararray );") ;
planTester.buildPlan("c = union a , b ;") ;
LogicalPlan plan = planTester.buildPlan("d = foreach c generate field2 + 2.0 ;") ;
// validate
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
typeValidator.validate(plan, collector) ;
printMessageCollector(collector) ;
printTypeGraph(plan) ;
planTester.printPlan(plan, TypeCheckingTestUtil.getCurrentMethodName());
if (collector.hasError()) {
throw new AssertionError("Expect no error") ;
}
LOForEach foreach = (LOForEach)plan.getLeaves().get(0);
LogicalPlan foreachPlan = foreach.getForEachPlans().get(0);
LogicalOperator exOp = foreachPlan.getRoots().get(0);
if(! (exOp instanceof LOProject)) exOp = foreachPlan.getRoots().get(1);
LOCast cast = (LOCast)foreachPlan.getSuccessors(exOp).get(0);
assertTrue(cast.getLoadFuncSpec() == null);
}
@Test
public void testUnionLineageFail() throws Throwable {
planTester.buildPlan("a = load 'a' using BinStorage() as (field1, field2: float, field3: chararray );") ;
planTester.buildPlan("b = load 'a' using PigStorage() as (field4, field5, field6: chararray );") ;
planTester.buildPlan("c = union a , b ;") ;
LogicalPlan plan = planTester.buildPlan("d = foreach c generate field1 + 2.0 ;") ;
// validate
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
try {
typeValidator.validate(plan, collector) ;
fail("Exception expected") ;
}
catch (PlanValidationException pve) {
// good
}
printMessageCollector(collector) ;
printTypeGraph(plan) ;
planTester.printPlan(plan, TypeCheckingTestUtil.getCurrentMethodName());
if (!collector.hasError()) {
throw new AssertionError("Expect error") ;
}
}
@Test
public void testUnionLineageNoSchema() throws Throwable {
planTester.buildPlan("a = load 'a' using BinStorage() ;") ;
planTester.buildPlan("b = load 'a' using BinStorage() ;") ;
planTester.buildPlan("c = union a , b ;") ;
LogicalPlan plan = planTester.buildPlan("d = foreach c generate $1 + 2.0 ;") ;
// validate
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
try {
typeValidator.validate(plan, collector) ;
}
catch (PlanValidationException pve) {
// good
}
printMessageCollector(collector) ;
printTypeGraph(plan) ;
planTester.printPlan(plan, TypeCheckingTestUtil.getCurrentMethodName());
if (collector.hasError()) {
throw new AssertionError("Expect no error") ;
}
LOForEach foreach = (LOForEach)plan.getLeaves().get(0);
LogicalPlan foreachPlan = foreach.getForEachPlans().get(0);
LogicalOperator exOp = foreachPlan.getRoots().get(0);
if(! (exOp instanceof LOProject)) exOp = foreachPlan.getRoots().get(1);
LOCast cast = (LOCast)foreachPlan.getSuccessors(exOp).get(0);
assertTrue(cast.getLoadFuncSpec().getClassName().startsWith("BinStorage"));
}
@Test
public void testUnionLineageNoSchemaFail() throws Throwable {
planTester.buildPlan("a = load 'a' using BinStorage() ;") ;
planTester.buildPlan("b = load 'a' using PigStorage() ;") ;
planTester.buildPlan("c = union a , b ;") ;
LogicalPlan plan = planTester.buildPlan("d = foreach c generate $1 + 2.0 ;") ;
// validate
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
try {
typeValidator.validate(plan, collector) ;
fail("Exception expected") ;
}
catch (PlanValidationException pve) {
// good
}
printMessageCollector(collector) ;
printTypeGraph(plan) ;
planTester.printPlan(plan, TypeCheckingTestUtil.getCurrentMethodName());
if (!collector.hasError()) {
throw new AssertionError("Expect error") ;
}
}
@Test
public void testUnionLineageDifferentSchema() throws Throwable {
//here the type checker will insert a cast for the union, converting the column field2 into a float
planTester.buildPlan("a = load 'a' using PigStorage() as (field1, field2: float, field3: chararray );") ;
planTester.buildPlan("b = load 'a' using PigStorage() as (field4, field5, field6: chararray, field7 );") ;
planTester.buildPlan("c = union a , b ;") ;
LogicalPlan plan = planTester.buildPlan("d = foreach c generate $3 + 2.0 ;") ;
// validate
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
typeValidator.validate(plan, collector) ;
printMessageCollector(collector) ;
printTypeGraph(plan) ;
planTester.printPlan(plan, TypeCheckingTestUtil.getCurrentMethodName());
if (collector.hasError()) {
throw new AssertionError("Expect no error") ;
}
LOForEach foreach = (LOForEach)plan.getLeaves().get(0);
LogicalPlan foreachPlan = foreach.getForEachPlans().get(0);
LogicalOperator exOp = foreachPlan.getRoots().get(0);
if(! (exOp instanceof LOProject)) exOp = foreachPlan.getRoots().get(1);
LOCast cast = (LOCast)foreachPlan.getSuccessors(exOp).get(0);
assertTrue(cast.getLoadFuncSpec().getClassName().startsWith("PigStorage"));
}
@Test
public void testUnionLineageDifferentSchemaFail() throws Throwable {
planTester.buildPlan("a = load 'a' using BinStorage() as (field1, field2: float, field3: chararray );") ;
planTester.buildPlan("b = load 'a' using PigStorage() as (field4, field5, field6: chararray, field7 );") ;
planTester.buildPlan("c = union a , b ;") ;
LogicalPlan plan = planTester.buildPlan("d = foreach c generate $3 + 2.0 ;") ;
// validate
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
try {
typeValidator.validate(plan, collector) ;
fail("Exception expected") ;
}
catch (PlanValidationException pve) {
// good
}
printMessageCollector(collector) ;
printTypeGraph(plan) ;
planTester.printPlan(plan, TypeCheckingTestUtil.getCurrentMethodName());
if (!collector.hasError()) {
throw new AssertionError("Expect error") ;
}
}
@Test
public void testUnionLineageMixSchema() throws Throwable {
//here the type checker will insert a cast for the union, converting the column field2 into a float
planTester.buildPlan("a = load 'a' using PigStorage() as (field1, field2: float, field3: chararray );") ;
planTester.buildPlan("b = load 'a' using PigStorage() ;") ;
planTester.buildPlan("c = union a , b ;") ;
LogicalPlan plan = planTester.buildPlan("d = foreach c generate $3 + 2.0 ;") ;
// validate
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
typeValidator.validate(plan, collector) ;
printMessageCollector(collector) ;
printTypeGraph(plan) ;
planTester.printPlan(plan, TypeCheckingTestUtil.getCurrentMethodName());
if (collector.hasError()) {
throw new AssertionError("Expect no error") ;
}
LOForEach foreach = (LOForEach)plan.getLeaves().get(0);
LogicalPlan foreachPlan = foreach.getForEachPlans().get(0);
LogicalOperator exOp = foreachPlan.getRoots().get(0);
if(! (exOp instanceof LOProject)) exOp = foreachPlan.getRoots().get(1);
LOCast cast = (LOCast)foreachPlan.getSuccessors(exOp).get(0);
assertTrue(cast.getLoadFuncSpec().getClassName().startsWith("PigStorage"));
}
@Test
public void testUnionLineageMixSchemaFail() throws Throwable {
planTester.buildPlan("a = load 'a' using BinStorage() as (field1, field2: float, field3: chararray );") ;
planTester.buildPlan("b = load 'a' using PigStorage() ;") ;
planTester.buildPlan("c = union a , b ;") ;
LogicalPlan plan = planTester.buildPlan("d = foreach c generate $3 + 2.0 ;") ;
// validate
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
try {
typeValidator.validate(plan, collector) ;
fail("Exception expected") ;
}
catch (PlanValidationException pve) {
// good
}
printMessageCollector(collector) ;
printTypeGraph(plan) ;
planTester.printPlan(plan, TypeCheckingTestUtil.getCurrentMethodName());
if (!collector.hasError()) {
throw new AssertionError("Expect error") ;
}
}
@Test
public void testFilterLineage() throws Throwable {
planTester.buildPlan("a = load 'a' as (field1, field2: float, field3: chararray );") ;
LogicalPlan plan = planTester.buildPlan("b = filter a by field1 > 1.0 ;") ;
// validate
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
typeValidator.validate(plan, collector) ;
printMessageCollector(collector) ;
printTypeGraph(plan) ;
planTester.printPlan(plan, TypeCheckingTestUtil.getCurrentMethodName());
if (collector.hasError()) {
throw new AssertionError("Expect no error") ;
}
LOFilter filter = (LOFilter)plan.getLeaves().get(0);
LogicalPlan filterPlan = filter.getComparisonPlan();
LogicalOperator exOp = filterPlan.getRoots().get(0);
if(! (exOp instanceof LOProject)) exOp = filterPlan.getRoots().get(1);
LOCast cast = (LOCast)filterPlan.getSuccessors(exOp).get(0);
assertTrue(cast.getLoadFuncSpec().getClassName().startsWith("org.apache.pig.builtin.PigStorage"));
}
@Test
public void testFilterLineageNoSchema() throws Throwable {
planTester.buildPlan("a = load 'a' ;") ;
LogicalPlan plan = planTester.buildPlan("b = filter a by $0 > 1.0 ;") ;
// validate
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
typeValidator.validate(plan, collector) ;
printMessageCollector(collector) ;
printTypeGraph(plan) ;
planTester.printPlan(plan, TypeCheckingTestUtil.getCurrentMethodName());
if (collector.hasError()) {
throw new AssertionError("Expect no error") ;
}
LOFilter filter = (LOFilter)plan.getLeaves().get(0);
LogicalPlan filterPlan = filter.getComparisonPlan();
LogicalOperator exOp = filterPlan.getRoots().get(0);
if(! (exOp instanceof LOProject)) exOp = filterPlan.getRoots().get(1);
LOCast cast = (LOCast)filterPlan.getSuccessors(exOp).get(0);
assertTrue(cast.getLoadFuncSpec().getClassName().startsWith("org.apache.pig.builtin.PigStorage"));
}
@Test
public void testFilterLineage1() throws Throwable {
planTester.buildPlan("a = load 'a' as (field1, field2: float, field3: chararray );") ;
planTester.buildPlan("b = filter a by field2 > 1.0 ;") ;
LogicalPlan plan = planTester.buildPlan("c = foreach b generate field1 + 1.0 ;") ;
// validate
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
typeValidator.validate(plan, collector) ;
printMessageCollector(collector) ;
printTypeGraph(plan) ;
planTester.printPlan(plan, TypeCheckingTestUtil.getCurrentMethodName());
if (collector.hasError()) {
throw new AssertionError("Expect no error") ;
}
LOForEach foreach = (LOForEach)plan.getLeaves().get(0);
LogicalPlan foreachPlan = foreach.getForEachPlans().get(0);
LogicalOperator exOp = foreachPlan.getRoots().get(0);
if(! (exOp instanceof LOProject)) exOp = foreachPlan.getRoots().get(1);
LOCast cast = (LOCast)foreachPlan.getSuccessors(exOp).get(0);
assertTrue(cast.getLoadFuncSpec().getClassName().startsWith("org.apache.pig.builtin.PigStorage"));
}
@Test
public void testFilterLineage1NoSchema() throws Throwable {
planTester.buildPlan("a = load 'a' ;") ;
planTester.buildPlan("b = filter a by $0 > 1.0 ;") ;
LogicalPlan plan = planTester.buildPlan("c = foreach b generate $1 + 1.0 ;") ;
// validate
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
typeValidator.validate(plan, collector) ;
printMessageCollector(collector) ;
printTypeGraph(plan) ;
planTester.printPlan(plan, TypeCheckingTestUtil.getCurrentMethodName());
if (collector.hasError()) {
throw new AssertionError("Expect no error") ;
}
LOForEach foreach = (LOForEach)plan.getLeaves().get(0);
LogicalPlan foreachPlan = foreach.getForEachPlans().get(0);
LogicalOperator exOp = foreachPlan.getRoots().get(0);
if(! (exOp instanceof LOProject)) exOp = foreachPlan.getRoots().get(1);
LOCast cast = (LOCast)foreachPlan.getSuccessors(exOp).get(0);
assertTrue(cast.getLoadFuncSpec().getClassName().startsWith("org.apache.pig.builtin.PigStorage"));
}
@Test
public void testCogroupFilterLineage() throws Throwable {
planTester.buildPlan("a = load 'a' using BinStorage() as (field1, field2: float, field3: chararray );") ;
planTester.buildPlan("b = load 'a' using PigStorage() as (field4, field5, field6: chararray );") ;
planTester.buildPlan("c = cogroup a by field1, b by field4 ;") ;
planTester.buildPlan("d = foreach c generate group, flatten(a), flatten(b) ;") ;
planTester.buildPlan("e = filter d by field4 > 5;") ;
LogicalPlan plan = planTester.buildPlan("f = foreach e generate group, field1 + 1, field4 + 2.0 ;") ;
// validate
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
typeValidator.validate(plan, collector) ;
printMessageCollector(collector) ;
printTypeGraph(plan) ;
planTester.printPlan(plan, TypeCheckingTestUtil.getCurrentMethodName());
if (collector.hasError()) {
throw new AssertionError("Expect no error") ;
}
LOForEach foreach = (LOForEach)plan.getLeaves().get(0);
LogicalPlan foreachPlan = foreach.getForEachPlans().get(1);
LogicalOperator exOp = foreachPlan.getRoots().get(0);
if(! (exOp instanceof LOProject)) exOp = foreachPlan.getRoots().get(1);
LOCast cast = (LOCast)foreachPlan.getSuccessors(exOp).get(0);
assertTrue(cast.getLoadFuncSpec().getClassName().startsWith("BinStorage"));
foreachPlan = foreach.getForEachPlans().get(2);
exOp = foreachPlan.getRoots().get(0);
if(! (exOp instanceof LOProject)) exOp = foreachPlan.getRoots().get(1);
cast = (LOCast)foreachPlan.getSuccessors(exOp).get(0);
assertTrue(cast.getLoadFuncSpec().getClassName().startsWith("PigStorage"));
}
@Test
public void testCogroupFilterLineageNoSchema() throws Throwable {
planTester.buildPlan("a = load 'a' using BinStorage() ;") ;
planTester.buildPlan("b = load 'a' using PigStorage() ;") ;
planTester.buildPlan("c = cogroup a by $0, b by $0 ;") ;
planTester.buildPlan("d = foreach c generate group, flatten(a), flatten(b) ;") ;
planTester.buildPlan("e = filter d by $2 > 5;") ;
LogicalPlan plan = planTester.buildPlan("f = foreach e generate group, $1 + 1, $2 + 2.0 ;") ;
// validate
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
typeValidator.validate(plan, collector) ;
printMessageCollector(collector) ;
printTypeGraph(plan) ;
planTester.printPlan(plan, TypeCheckingTestUtil.getCurrentMethodName());
if (collector.hasError()) {
throw new AssertionError("Expect no error") ;
}
LOForEach foreach = (LOForEach)plan.getLeaves().get(0);
LogicalPlan foreachPlan = foreach.getForEachPlans().get(1);
LogicalOperator exOp = foreachPlan.getRoots().get(0);
if(! (exOp instanceof LOProject)) exOp = foreachPlan.getRoots().get(1);
LOCast cast = (LOCast)foreachPlan.getSuccessors(exOp).get(0);
assertTrue(cast.getLoadFuncSpec().getClassName().startsWith("BinStorage"));
foreachPlan = foreach.getForEachPlans().get(2);
exOp = foreachPlan.getRoots().get(0);
if(! (exOp instanceof LOProject)) exOp = foreachPlan.getRoots().get(1);
cast = (LOCast)foreachPlan.getSuccessors(exOp).get(0);
assertTrue(cast.getLoadFuncSpec().getClassName().startsWith("PigStorage"));
}
@Test
public void testSplitLineage() throws Throwable {
planTester.buildPlan("a = load 'a' as (field1, field2: float, field3: chararray );") ;
LogicalPlan plan = planTester.buildPlan("split a into b if field1 > 1.0, c if field1 <= 1.0 ;") ;
// validate
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
typeValidator.validate(plan, collector) ;
printMessageCollector(collector) ;
printTypeGraph(plan) ;
planTester.printPlan(plan, TypeCheckingTestUtil.getCurrentMethodName());
if (collector.hasError()) {
throw new AssertionError("Expect no error") ;
}
LOSplitOutput splitOutputB = (LOSplitOutput)plan.getLeaves().get(0);
LogicalPlan bPlan = splitOutputB.getConditionPlan();
LogicalOperator exOp = bPlan.getRoots().get(0);
if(! (exOp instanceof LOProject)) exOp = bPlan.getRoots().get(1);
LOCast cast = (LOCast)bPlan.getSuccessors(exOp).get(0);
assertTrue(cast.getLoadFuncSpec().getClassName().startsWith("org.apache.pig.builtin.PigStorage"));
LOSplitOutput splitOutputC = (LOSplitOutput)plan.getLeaves().get(0);
LogicalPlan cPlan = splitOutputC.getConditionPlan();
exOp = cPlan.getRoots().get(0);
if(! (exOp instanceof LOProject)) exOp = cPlan.getRoots().get(1);
cast = (LOCast)cPlan.getSuccessors(exOp).get(0);
assertTrue(cast.getLoadFuncSpec().getClassName().startsWith("org.apache.pig.builtin.PigStorage"));
}
@Test
public void testSplitLineageNoSchema() throws Throwable {
planTester.buildPlan("a = load 'a' ;") ;
LogicalPlan plan = planTester.buildPlan("split a into b if $0 > 1.0, c if $1 <= 1.0 ;") ;
// validate
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
typeValidator.validate(plan, collector) ;
printMessageCollector(collector) ;
printTypeGraph(plan) ;
planTester.printPlan(plan, TypeCheckingTestUtil.getCurrentMethodName());
if (collector.hasError()) {
throw new AssertionError("Expect no error") ;
}
LOSplitOutput splitOutputB = (LOSplitOutput)plan.getLeaves().get(0);
LogicalPlan bPlan = splitOutputB.getConditionPlan();
LogicalOperator exOp = bPlan.getRoots().get(0);
if(! (exOp instanceof LOProject)) exOp = bPlan.getRoots().get(1);
LOCast cast = (LOCast)bPlan.getSuccessors(exOp).get(0);
assertTrue(cast.getLoadFuncSpec().getClassName().startsWith("org.apache.pig.builtin.PigStorage"));
LOSplitOutput splitOutputC = (LOSplitOutput)plan.getLeaves().get(0);
LogicalPlan cPlan = splitOutputC.getConditionPlan();
exOp = cPlan.getRoots().get(0);
if(! (exOp instanceof LOProject)) exOp = cPlan.getRoots().get(1);
cast = (LOCast)cPlan.getSuccessors(exOp).get(0);
assertTrue(cast.getLoadFuncSpec().getClassName().startsWith("org.apache.pig.builtin.PigStorage"));
}
@Test
public void testSplitLineage1() throws Throwable {
planTester.buildPlan("a = load 'a' as (field1, field2: float, field3: chararray );") ;
planTester.buildPlan("split a into b if field2 > 1.0, c if field2 <= 1.0 ;") ;
LogicalPlan plan = planTester.buildPlan("c = foreach b generate field1 + 1.0 ;") ;
// validate
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
typeValidator.validate(plan, collector) ;
printMessageCollector(collector) ;
printTypeGraph(plan) ;
planTester.printPlan(plan, TypeCheckingTestUtil.getCurrentMethodName());
if (collector.hasError()) {
throw new AssertionError("Expect no error") ;
}
LOForEach foreach = (LOForEach)plan.getLeaves().get(0);
LogicalPlan foreachPlan = foreach.getForEachPlans().get(0);
LogicalOperator exOp = foreachPlan.getRoots().get(0);
if(! (exOp instanceof LOProject)) exOp = foreachPlan.getRoots().get(1);
LOCast cast = (LOCast)foreachPlan.getSuccessors(exOp).get(0);
assertTrue(cast.getLoadFuncSpec().getClassName().startsWith("org.apache.pig.builtin.PigStorage"));
}
@Test
public void testSplitLineage1NoSchema() throws Throwable {
planTester.buildPlan("a = load 'a' ;") ;
planTester.buildPlan("split a into b if $0 > 1.0, c if $1 <= 1.0 ;") ;
LogicalPlan plan = planTester.buildPlan("c = foreach b generate $1 + 1.0 ;") ;
// validate
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
typeValidator.validate(plan, collector) ;
printMessageCollector(collector) ;
printTypeGraph(plan) ;
planTester.printPlan(plan, TypeCheckingTestUtil.getCurrentMethodName());
if (collector.hasError()) {
throw new AssertionError("Expect no error") ;
}
LOForEach foreach = (LOForEach)plan.getLeaves().get(0);
LogicalPlan foreachPlan = foreach.getForEachPlans().get(0);
LogicalOperator exOp = foreachPlan.getRoots().get(0);
if(! (exOp instanceof LOProject)) exOp = foreachPlan.getRoots().get(1);
LOCast cast = (LOCast)foreachPlan.getSuccessors(exOp).get(0);
assertTrue(cast.getLoadFuncSpec().getClassName().startsWith("org.apache.pig.builtin.PigStorage"));
}
@Test
public void testCogroupSplitLineage() throws Throwable {
planTester.buildPlan("a = load 'a' using BinStorage() as (field1, field2: float, field3: chararray );") ;
planTester.buildPlan("b = load 'a' using PigStorage() as (field4, field5, field6: chararray );") ;
planTester.buildPlan("c = cogroup a by field1, b by field4 ;") ;
planTester.buildPlan("d = foreach c generate group, flatten(a), flatten(b) ;") ;
planTester.buildPlan("split d into e if field4 > 'm', f if field6 > 'm' ;") ;
LogicalPlan plan = planTester.buildPlan("g = foreach e generate group, field1 + 1, field4 + 2.0 ;") ;
// validate
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
typeValidator.validate(plan, collector) ;
printMessageCollector(collector) ;
printTypeGraph(plan) ;
planTester.printPlan(plan, TypeCheckingTestUtil.getCurrentMethodName());
if (collector.hasError()) {
throw new AssertionError("Expect no error") ;
}
LOForEach foreach = (LOForEach)plan.getLeaves().get(0);
LogicalPlan foreachPlan = foreach.getForEachPlans().get(1);
LogicalOperator exOp = foreachPlan.getRoots().get(0);
if(! (exOp instanceof LOProject)) exOp = foreachPlan.getRoots().get(1);
LOCast cast = (LOCast)foreachPlan.getSuccessors(exOp).get(0);
assertTrue(cast.getLoadFuncSpec().getClassName().startsWith("BinStorage"));
foreachPlan = foreach.getForEachPlans().get(2);
exOp = foreachPlan.getRoots().get(0);
if(! (exOp instanceof LOProject)) exOp = foreachPlan.getRoots().get(1);
cast = (LOCast)foreachPlan.getSuccessors(exOp).get(0);
assertTrue(cast.getLoadFuncSpec().getClassName().startsWith("PigStorage"));
}
@Test
public void testCogroupSplitLineageNoSchema() throws Throwable {
planTester.buildPlan("a = load 'a' using BinStorage() ;") ;
planTester.buildPlan("b = load 'a' using PigStorage() ;") ;
planTester.buildPlan("c = cogroup a by $0, b by $0 ;") ;
planTester.buildPlan("d = foreach c generate group, flatten(a), flatten(b) ;") ;
planTester.buildPlan("split d into e if $1 > 'm', f if $1 > 'm' ;") ;
LogicalPlan plan = planTester.buildPlan("g = foreach e generate group, $1 + 1, $2 + 2.0 ;") ;
// validate
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
typeValidator.validate(plan, collector) ;
printMessageCollector(collector) ;
printTypeGraph(plan) ;
planTester.printPlan(plan, TypeCheckingTestUtil.getCurrentMethodName());
if (collector.hasError()) {
throw new AssertionError("Expect no error") ;
}
LOForEach foreach = (LOForEach)plan.getLeaves().get(0);
LogicalPlan foreachPlan = foreach.getForEachPlans().get(1);
LogicalOperator exOp = foreachPlan.getRoots().get(0);
if(! (exOp instanceof LOProject)) exOp = foreachPlan.getRoots().get(1);
LOCast cast = (LOCast)foreachPlan.getSuccessors(exOp).get(0);
assertTrue(cast.getLoadFuncSpec().getClassName().startsWith("BinStorage"));
foreachPlan = foreach.getForEachPlans().get(2);
exOp = foreachPlan.getRoots().get(0);
if(! (exOp instanceof LOProject)) exOp = foreachPlan.getRoots().get(1);
cast = (LOCast)foreachPlan.getSuccessors(exOp).get(0);
assertTrue(cast.getLoadFuncSpec().getClassName().startsWith("PigStorage"));
}
@Test
public void testDistinctLineage() throws Throwable {
planTester.buildPlan("a = load 'a' as (field1, field2: float, field3: chararray );") ;
planTester.buildPlan("b = distinct a;") ;
LogicalPlan plan = planTester.buildPlan("c = foreach b generate field1 + 1.0 ;") ;
// validate
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
typeValidator.validate(plan, collector) ;
printMessageCollector(collector) ;
printTypeGraph(plan) ;
planTester.printPlan(plan, TypeCheckingTestUtil.getCurrentMethodName());
if (collector.hasError()) {
throw new AssertionError("Expect no error") ;
}
LOForEach foreach = (LOForEach)plan.getLeaves().get(0);
LogicalPlan foreachPlan = foreach.getForEachPlans().get(0);
LogicalOperator exOp = foreachPlan.getRoots().get(0);
if(! (exOp instanceof LOProject)) exOp = foreachPlan.getRoots().get(1);
LOCast cast = (LOCast)foreachPlan.getSuccessors(exOp).get(0);
assertTrue(cast.getLoadFuncSpec().getClassName().startsWith("org.apache.pig.builtin.PigStorage"));
}
@Test
public void testDistinctLineageNoSchema() throws Throwable {
planTester.buildPlan("a = load 'a' ;") ;
planTester.buildPlan("b = distinct a;") ;
LogicalPlan plan = planTester.buildPlan("c = foreach b generate $1 + 1.0 ;") ;
// validate
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
typeValidator.validate(plan, collector) ;
printMessageCollector(collector) ;
printTypeGraph(plan) ;
planTester.printPlan(plan, TypeCheckingTestUtil.getCurrentMethodName());
if (collector.hasError()) {
throw new AssertionError("Expect no error") ;
}
LOForEach foreach = (LOForEach)plan.getLeaves().get(0);
LogicalPlan foreachPlan = foreach.getForEachPlans().get(0);
LogicalOperator exOp = foreachPlan.getRoots().get(0);
if(! (exOp instanceof LOProject)) exOp = foreachPlan.getRoots().get(1);
LOCast cast = (LOCast)foreachPlan.getSuccessors(exOp).get(0);
assertTrue(cast.getLoadFuncSpec().getClassName().startsWith("org.apache.pig.builtin.PigStorage"));
}
@Test
public void testCogroupDistinctLineage() throws Throwable {
planTester.buildPlan("a = load 'a' using BinStorage() as (field1, field2: float, field3: chararray );") ;
planTester.buildPlan("b = load 'a' using PigStorage() as (field4, field5, field6: chararray );") ;
planTester.buildPlan("c = cogroup a by field1, b by field4 ;") ;
planTester.buildPlan("d = foreach c generate group, flatten(a), flatten(b) ;") ;
planTester.buildPlan("e = distinct d ;") ;
LogicalPlan plan = planTester.buildPlan("f = foreach e generate group, field1 + 1, field4 + 2.0 ;") ;
// validate
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
typeValidator.validate(plan, collector) ;
printMessageCollector(collector) ;
printTypeGraph(plan) ;
planTester.printPlan(plan, TypeCheckingTestUtil.getCurrentMethodName());
if (collector.hasError()) {
throw new AssertionError("Expect no error") ;
}
LOForEach foreach = (LOForEach)plan.getLeaves().get(0);
LogicalPlan foreachPlan = foreach.getForEachPlans().get(1);
LogicalOperator exOp = foreachPlan.getRoots().get(0);
if(! (exOp instanceof LOProject)) exOp = foreachPlan.getRoots().get(1);
LOCast cast = (LOCast)foreachPlan.getSuccessors(exOp).get(0);
assertTrue(cast.getLoadFuncSpec().getClassName().startsWith("BinStorage"));
foreachPlan = foreach.getForEachPlans().get(2);
exOp = foreachPlan.getRoots().get(0);
if(! (exOp instanceof LOProject)) exOp = foreachPlan.getRoots().get(1);
cast = (LOCast)foreachPlan.getSuccessors(exOp).get(0);
assertTrue(cast.getLoadFuncSpec().getClassName().startsWith("PigStorage"));
}
@Test
public void testCogroupDistinctLineageNoSchema() throws Throwable {
planTester.buildPlan("a = load 'a' using BinStorage() ;") ;
planTester.buildPlan("b = load 'a' using PigStorage() ;") ;
planTester.buildPlan("c = cogroup a by $0, b by $0 ;") ;
planTester.buildPlan("d = foreach c generate group, flatten(a), flatten(b) ;") ;
planTester.buildPlan("e = distinct d ;") ;
LogicalPlan plan = planTester.buildPlan("f = foreach e generate group, $1 + 1, $2 + 2.0 ;") ;
// validate
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
typeValidator.validate(plan, collector) ;
printMessageCollector(collector) ;
printTypeGraph(plan) ;
planTester.printPlan(plan, TypeCheckingTestUtil.getCurrentMethodName());
if (collector.hasError()) {
throw new AssertionError("Expect no error") ;
}
LOForEach foreach = (LOForEach)plan.getLeaves().get(0);
LogicalPlan foreachPlan = foreach.getForEachPlans().get(1);
LogicalOperator exOp = foreachPlan.getRoots().get(0);
if(! (exOp instanceof LOProject)) exOp = foreachPlan.getRoots().get(1);
LOCast cast = (LOCast)foreachPlan.getSuccessors(exOp).get(0);
assertTrue(cast.getLoadFuncSpec().getClassName().startsWith("BinStorage"));
foreachPlan = foreach.getForEachPlans().get(2);
exOp = foreachPlan.getRoots().get(0);
if(! (exOp instanceof LOProject)) exOp = foreachPlan.getRoots().get(1);
cast = (LOCast)foreachPlan.getSuccessors(exOp).get(0);
assertTrue(cast.getLoadFuncSpec().getClassName().startsWith("PigStorage"));
}
@Test
public void testSortLineage() throws Throwable {
planTester.buildPlan("a = load 'a' as (field1, field2: float, field3: chararray );") ;
planTester.buildPlan("b = order a by field1;") ;
LogicalPlan plan = planTester.buildPlan("c = foreach b generate field1 + 1.0 ;") ;
// validate
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
typeValidator.validate(plan, collector) ;
printMessageCollector(collector) ;
printTypeGraph(plan) ;
planTester.printPlan(plan, TypeCheckingTestUtil.getCurrentMethodName());
if (collector.hasError()) {
throw new AssertionError("Expect no error") ;
}
LOForEach foreach = (LOForEach)plan.getLeaves().get(0);
LogicalPlan foreachPlan = foreach.getForEachPlans().get(0);
LogicalOperator exOp = foreachPlan.getRoots().get(0);
if(! (exOp instanceof LOProject)) exOp = foreachPlan.getRoots().get(1);
LOCast cast = (LOCast)foreachPlan.getSuccessors(exOp).get(0);
assertTrue(cast.getLoadFuncSpec().getClassName().startsWith("org.apache.pig.builtin.PigStorage"));
}
@Test
public void testSortLineageNoSchema() throws Throwable {
planTester.buildPlan("a = load 'a' ;") ;
planTester.buildPlan("b = order a by $1;") ;
LogicalPlan plan = planTester.buildPlan("c = foreach b generate $1 + 1.0 ;") ;
// validate
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
typeValidator.validate(plan, collector) ;
printMessageCollector(collector) ;
printTypeGraph(plan) ;
planTester.printPlan(plan, TypeCheckingTestUtil.getCurrentMethodName());
if (collector.hasError()) {
throw new AssertionError("Expect no error") ;
}
LOForEach foreach = (LOForEach)plan.getLeaves().get(0);
LogicalPlan foreachPlan = foreach.getForEachPlans().get(0);
LogicalOperator exOp = foreachPlan.getRoots().get(0);
if(! (exOp instanceof LOProject)) exOp = foreachPlan.getRoots().get(1);
LOCast cast = (LOCast)foreachPlan.getSuccessors(exOp).get(0);
assertTrue(cast.getLoadFuncSpec().getClassName().startsWith("org.apache.pig.builtin.PigStorage"));
}
@Test
public void testCogroupSortLineage() throws Throwable {
planTester.buildPlan("a = load 'a' using BinStorage() as (field1, field2: float, field3: chararray );") ;
planTester.buildPlan("b = load 'a' using PigStorage() as (field4, field5, field6: chararray );") ;
planTester.buildPlan("c = cogroup a by field1, b by field4 ;") ;
planTester.buildPlan("d = foreach c generate group, flatten(a), flatten(b) ;") ;
planTester.buildPlan("e = order d by field4 desc;") ;
LogicalPlan plan = planTester.buildPlan("f = foreach e generate group, field1 + 1, field4 + 2.0 ;") ;
// validate
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
typeValidator.validate(plan, collector) ;
printMessageCollector(collector) ;
printTypeGraph(plan) ;
planTester.printPlan(plan, TypeCheckingTestUtil.getCurrentMethodName());
if (collector.hasError()) {
throw new AssertionError("Expect no error") ;
}
LOForEach foreach = (LOForEach)plan.getLeaves().get(0);
LogicalPlan foreachPlan = foreach.getForEachPlans().get(1);
LogicalOperator exOp = foreachPlan.getRoots().get(0);
if(! (exOp instanceof LOProject)) exOp = foreachPlan.getRoots().get(1);
LOCast cast = (LOCast)foreachPlan.getSuccessors(exOp).get(0);
assertTrue(cast.getLoadFuncSpec().getClassName().startsWith("BinStorage"));
foreachPlan = foreach.getForEachPlans().get(2);
exOp = foreachPlan.getRoots().get(0);
if(! (exOp instanceof LOProject)) exOp = foreachPlan.getRoots().get(1);
cast = (LOCast)foreachPlan.getSuccessors(exOp).get(0);
assertTrue(cast.getLoadFuncSpec().getClassName().startsWith("PigStorage"));
}
@Test
public void testCogroupSortLineageNoSchema() throws Throwable {
planTester.buildPlan("a = load 'a' using BinStorage() ;") ;
planTester.buildPlan("b = load 'a' using PigStorage() ;") ;
planTester.buildPlan("c = cogroup a by $0, b by $0 ;") ;
planTester.buildPlan("d = foreach c generate group, flatten(a), flatten(b) ;") ;
planTester.buildPlan("e = order d by $2 desc;") ;
LogicalPlan plan = planTester.buildPlan("f = foreach e generate group, $1 + 1, $2 + 2.0 ;") ;
// validate
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
typeValidator.validate(plan, collector) ;
printMessageCollector(collector) ;
printTypeGraph(plan) ;
planTester.printPlan(plan, TypeCheckingTestUtil.getCurrentMethodName());
if (collector.hasError()) {
throw new AssertionError("Expect no error") ;
}
LOForEach foreach = (LOForEach)plan.getLeaves().get(0);
LogicalPlan foreachPlan = foreach.getForEachPlans().get(1);
LogicalOperator exOp = foreachPlan.getRoots().get(0);
if(! (exOp instanceof LOProject)) exOp = foreachPlan.getRoots().get(1);
LOCast cast = (LOCast)foreachPlan.getSuccessors(exOp).get(0);
assertTrue(cast.getLoadFuncSpec().getClassName().startsWith("BinStorage"));
foreachPlan = foreach.getForEachPlans().get(2);
exOp = foreachPlan.getRoots().get(0);
if(! (exOp instanceof LOProject)) exOp = foreachPlan.getRoots().get(1);
cast = (LOCast)foreachPlan.getSuccessors(exOp).get(0);
assertTrue(cast.getLoadFuncSpec().getClassName().startsWith("PigStorage"));
}
@Test
public void testCogroupSortStarLineage() throws Throwable {
planTester.buildPlan("a = load 'a' using BinStorage() as (field1, field2: float, field3: chararray );") ;
planTester.buildPlan("b = load 'a' using PigStorage() as (field4, field5, field6: chararray );") ;
planTester.buildPlan("c = cogroup a by field1, b by field4 ;") ;
planTester.buildPlan("d = foreach c generate group, flatten(a), flatten(b) ;") ;
planTester.buildPlan("e = order d by * desc;") ;
LogicalPlan plan = planTester.buildPlan("f = foreach e generate group, field1 + 1, field4 + 2.0 ;") ;
// validate
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
typeValidator.validate(plan, collector) ;
printMessageCollector(collector) ;
printTypeGraph(plan) ;
planTester.printPlan(plan, TypeCheckingTestUtil.getCurrentMethodName());
if (collector.hasError()) {
throw new AssertionError("Expect no error") ;
}
LOForEach foreach = (LOForEach)plan.getLeaves().get(0);
LogicalPlan foreachPlan = foreach.getForEachPlans().get(1);
LogicalOperator exOp = foreachPlan.getRoots().get(0);
if(! (exOp instanceof LOProject)) exOp = foreachPlan.getRoots().get(1);
LOCast cast = (LOCast)foreachPlan.getSuccessors(exOp).get(0);
assertTrue(cast.getLoadFuncSpec().getClassName().startsWith("BinStorage"));
foreachPlan = foreach.getForEachPlans().get(2);
exOp = foreachPlan.getRoots().get(0);
if(! (exOp instanceof LOProject)) exOp = foreachPlan.getRoots().get(1);
cast = (LOCast)foreachPlan.getSuccessors(exOp).get(0);
assertTrue(cast.getLoadFuncSpec().getClassName().startsWith("PigStorage"));
}
@Test
public void testCogroupSortStarLineageNoSchema() throws Throwable {
planTester.buildPlan("a = load 'a' using BinStorage() ;") ;
planTester.buildPlan("b = load 'a' using PigStorage() ;") ;
planTester.buildPlan("c = cogroup a by $0, b by $0 ;") ;
planTester.buildPlan("d = foreach c generate group, flatten(a), flatten(b) ;") ;
planTester.buildPlan("e = order d by * desc;") ;
LogicalPlan plan = planTester.buildPlan("f = foreach e generate group, $1 + 1, $2 + 2.0 ;") ;
// validate
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
typeValidator.validate(plan, collector) ;
printMessageCollector(collector) ;
printTypeGraph(plan) ;
planTester.printPlan(plan, TypeCheckingTestUtil.getCurrentMethodName());
if (collector.hasError()) {
throw new AssertionError("Expect no error") ;
}
LOForEach foreach = (LOForEach)plan.getLeaves().get(0);
LogicalPlan foreachPlan = foreach.getForEachPlans().get(1);
LogicalOperator exOp = foreachPlan.getRoots().get(0);
if(! (exOp instanceof LOProject)) exOp = foreachPlan.getRoots().get(1);
LOCast cast = (LOCast)foreachPlan.getSuccessors(exOp).get(0);
assertTrue(cast.getLoadFuncSpec().getClassName().startsWith("BinStorage"));
foreachPlan = foreach.getForEachPlans().get(2);
exOp = foreachPlan.getRoots().get(0);
if(! (exOp instanceof LOProject)) exOp = foreachPlan.getRoots().get(1);
cast = (LOCast)foreachPlan.getSuccessors(exOp).get(0);
assertTrue(cast.getLoadFuncSpec().getClassName().startsWith("PigStorage"));
}
@Test
public void testCrossLineage() throws Throwable {
planTester.buildPlan("a = load 'a' using BinStorage() as (field1, field2: float, field3: chararray );") ;
planTester.buildPlan("b = load 'a' using PigStorage() as (field4, field5, field6: chararray );") ;
planTester.buildPlan("c = cross a, b ;") ;
LogicalPlan plan = planTester.buildPlan("d = foreach c generate field1 + 1, field4 + 2.0 ;") ;
// validate
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
typeValidator.validate(plan, collector) ;
printMessageCollector(collector) ;
printTypeGraph(plan) ;
planTester.printPlan(plan, TypeCheckingTestUtil.getCurrentMethodName());
if (collector.hasError()) {
throw new AssertionError("Expect no error") ;
}
LOForEach foreach = (LOForEach)plan.getLeaves().get(0);
LogicalPlan foreachPlan = foreach.getForEachPlans().get(0);
LogicalOperator exOp = foreachPlan.getRoots().get(0);
if(! (exOp instanceof LOProject)) exOp = foreachPlan.getRoots().get(1);
LOCast cast = (LOCast)foreachPlan.getSuccessors(exOp).get(0);
assertTrue(cast.getLoadFuncSpec().getClassName().startsWith("BinStorage"));
foreachPlan = foreach.getForEachPlans().get(1);
exOp = foreachPlan.getRoots().get(0);
if(! (exOp instanceof LOProject)) exOp = foreachPlan.getRoots().get(1);
cast = (LOCast)foreachPlan.getSuccessors(exOp).get(0);
assertTrue(cast.getLoadFuncSpec().getClassName().startsWith("PigStorage"));
}
@Test
public void testCrossLineageNoSchema() throws Throwable {
planTester.buildPlan("a = load 'a' using BinStorage() ;") ;
planTester.buildPlan("b = load 'a' using BinStorage() ;") ;
planTester.buildPlan("c = cross a , b ;") ;
LogicalPlan plan = planTester.buildPlan("d = foreach c generate $1 + 2.0 ;") ;
// validate
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
try {
typeValidator.validate(plan, collector) ;
}
catch (PlanValidationException pve) {
// good
}
printMessageCollector(collector) ;
printTypeGraph(plan) ;
planTester.printPlan(plan, TypeCheckingTestUtil.getCurrentMethodName());
if (collector.hasError()) {
throw new AssertionError("Expect no error") ;
}
LOForEach foreach = (LOForEach)plan.getLeaves().get(0);
LogicalPlan foreachPlan = foreach.getForEachPlans().get(0);
LogicalOperator exOp = foreachPlan.getRoots().get(0);
if(! (exOp instanceof LOProject)) exOp = foreachPlan.getRoots().get(1);
LOCast cast = (LOCast)foreachPlan.getSuccessors(exOp).get(0);
assertTrue(cast.getLoadFuncSpec().getClassName().startsWith("BinStorage"));
}
@Test
public void testCrossLineageNoSchemaFail() throws Throwable {
planTester.buildPlan("a = load 'a' using BinStorage() ;") ;
planTester.buildPlan("b = load 'a' using PigStorage() ;") ;
planTester.buildPlan("c = cross a , b ;") ;
LogicalPlan plan = planTester.buildPlan("d = foreach c generate $1 + 2.0 ;") ;
// validate
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
try {
typeValidator.validate(plan, collector) ;
fail("Exception expected") ;
}
catch (PlanValidationException pve) {
// good
}
printMessageCollector(collector) ;
printTypeGraph(plan) ;
planTester.printPlan(plan, TypeCheckingTestUtil.getCurrentMethodName());
if (!collector.hasError()) {
throw new AssertionError("Expect error") ;
}
}
@Test
public void testCrossLineageMixSchema() throws Throwable {
//here the type checker will insert a cast for the union, converting the column field2 into a float
planTester.buildPlan("a = load 'a' using PigStorage() as (field1, field2: float, field3: chararray );") ;
planTester.buildPlan("b = load 'a' using PigStorage() ;") ;
planTester.buildPlan("c = cross a , b ;") ;
LogicalPlan plan = planTester.buildPlan("d = foreach c generate $3 + 2.0 ;") ;
// validate
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
typeValidator.validate(plan, collector) ;
printMessageCollector(collector) ;
printTypeGraph(plan) ;
planTester.printPlan(plan, TypeCheckingTestUtil.getCurrentMethodName());
if (collector.hasError()) {
throw new AssertionError("Expect no error") ;
}
LOForEach foreach = (LOForEach)plan.getLeaves().get(0);
LogicalPlan foreachPlan = foreach.getForEachPlans().get(0);
LogicalOperator exOp = foreachPlan.getRoots().get(0);
if(! (exOp instanceof LOProject)) exOp = foreachPlan.getRoots().get(1);
LOCast cast = (LOCast)foreachPlan.getSuccessors(exOp).get(0);
assertTrue(cast.getLoadFuncSpec().getClassName().startsWith("PigStorage"));
}
@Test
public void testCrossLineageMixSchemaFail() throws Throwable {
planTester.buildPlan("a = load 'a' using BinStorage() as (field1, field2: float, field3: chararray );") ;
planTester.buildPlan("b = load 'a' using PigStorage() ;") ;
planTester.buildPlan("c = cross a , b ;") ;
LogicalPlan plan = planTester.buildPlan("d = foreach c generate $3 + 2.0 ;") ;
// validate
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
try {
typeValidator.validate(plan, collector) ;
fail("Exception expected") ;
}
catch (PlanValidationException pve) {
// good
}
printMessageCollector(collector) ;
printTypeGraph(plan) ;
planTester.printPlan(plan, TypeCheckingTestUtil.getCurrentMethodName());
if (!collector.hasError()) {
throw new AssertionError("Expect error") ;
}
}
@Test
public void testJoinLineage() throws Throwable {
planTester.buildPlan("a = load 'a' using BinStorage() as (field1, field2: float, field3: chararray );") ;
planTester.buildPlan("b = load 'a' using PigStorage() as (field4, field5, field6: chararray );") ;
planTester.buildPlan("c = join a by field1, b by field4 ;") ;
LogicalPlan plan = planTester.buildPlan("d = foreach c generate field1 + 1, field4 + 2.0 ;") ;
// validate
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
typeValidator.validate(plan, collector) ;
printMessageCollector(collector) ;
printTypeGraph(plan) ;
planTester.printPlan(plan, TypeCheckingTestUtil.getCurrentMethodName());
if (collector.hasError()) {
throw new AssertionError("Expect no error") ;
}
LOForEach foreach = (LOForEach)plan.getLeaves().get(0);
LogicalPlan foreachPlan = foreach.getForEachPlans().get(0);
LogicalOperator exOp = foreachPlan.getRoots().get(0);
if(! (exOp instanceof LOProject)) exOp = foreachPlan.getRoots().get(1);
LOCast cast = (LOCast)foreachPlan.getSuccessors(exOp).get(0);
assertTrue(cast.getLoadFuncSpec().getClassName().startsWith("BinStorage"));
foreachPlan = foreach.getForEachPlans().get(1);
exOp = foreachPlan.getRoots().get(0);
if(! (exOp instanceof LOProject)) exOp = foreachPlan.getRoots().get(1);
cast = (LOCast)foreachPlan.getSuccessors(exOp).get(0);
assertTrue(cast.getLoadFuncSpec().getClassName().startsWith("PigStorage"));
}
@Test
public void testJoinLineageNoSchema() throws Throwable {
planTester.buildPlan("a = load 'a' using BinStorage() ;") ;
planTester.buildPlan("b = load 'a' using BinStorage() ;") ;
planTester.buildPlan("c = join a by $0, b by $0 ;") ;
LogicalPlan plan = planTester.buildPlan("d = foreach c generate $1 + 2.0 ;") ;
// validate
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
try {
typeValidator.validate(plan, collector) ;
}
catch (PlanValidationException pve) {
// good
}
printMessageCollector(collector) ;
printTypeGraph(plan) ;
planTester.printPlan(plan, TypeCheckingTestUtil.getCurrentMethodName());
if (collector.hasError()) {
throw new AssertionError("Expect no error") ;
}
LOForEach foreach = (LOForEach)plan.getLeaves().get(0);
LogicalPlan foreachPlan = foreach.getForEachPlans().get(0);
LogicalOperator exOp = foreachPlan.getRoots().get(0);
if(! (exOp instanceof LOProject)) exOp = foreachPlan.getRoots().get(1);
LOCast cast = (LOCast)foreachPlan.getSuccessors(exOp).get(0);
assertTrue(cast.getLoadFuncSpec().getClassName().startsWith("BinStorage"));
}
@Test
public void testJoinLineageNoSchemaFail() throws Throwable {
//this test case should change when we decide on what flattening a tuple or bag
//with null schema results in a foreach flatten and hence a join
planTester.buildPlan("a = load 'a' using BinStorage() ;") ;
planTester.buildPlan("b = load 'a' using PigStorage() ;") ;
planTester.buildPlan("c = join a by $0, b by $0 ;") ;
LogicalPlan plan = planTester.buildPlan("d = foreach c generate $1 + 2.0 ;") ;
// validate
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
try {
typeValidator.validate(plan, collector) ;
}
catch (PlanValidationException pve) {
// good
}
printMessageCollector(collector) ;
printTypeGraph(plan) ;
planTester.printPlan(plan, TypeCheckingTestUtil.getCurrentMethodName());
assertTrue(collector.hasError());
}
@Test
public void testJoinLineageMixSchema() throws Throwable {
planTester.buildPlan("a = load 'a' using PigStorage() as (field1, field2: float, field3: chararray );") ;
planTester.buildPlan("b = load 'a' using PigStorage() ;") ;
planTester.buildPlan("c = join a by field1, b by $0 ;") ;
LogicalPlan plan = planTester.buildPlan("d = foreach c generate $3 + 2.0 ;") ;
// validate
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
typeValidator.validate(plan, collector) ;
printMessageCollector(collector) ;
printTypeGraph(plan) ;
planTester.printPlan(plan, TypeCheckingTestUtil.getCurrentMethodName());
if (collector.hasError()) {
throw new AssertionError("Expect no error") ;
}
LOForEach foreach = (LOForEach)plan.getLeaves().get(0);
LogicalPlan foreachPlan = foreach.getForEachPlans().get(0);
LogicalOperator exOp = foreachPlan.getRoots().get(0);
if(! (exOp instanceof LOProject)) exOp = foreachPlan.getRoots().get(1);
LOCast cast = (LOCast)foreachPlan.getSuccessors(exOp).get(0);
assertTrue(cast.getLoadFuncSpec().getClassName().startsWith("PigStorage"));
}
@Test
public void testJoinLineageMixSchemaFail() throws Throwable {
//this test case should change when we decide on what flattening a tuple or bag
//with null schema results in a foreach flatten and hence a join
planTester.buildPlan("a = load 'a' using BinStorage() as (field1, field2: float, field3: chararray );") ;
planTester.buildPlan("b = load 'a' using PigStorage() ;") ;
planTester.buildPlan("c = join a by field1, b by $0 ;") ;
LogicalPlan plan = planTester.buildPlan("d = foreach c generate $3 + 2.0 ;") ;
// validate
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
try {
typeValidator.validate(plan, collector) ;
}
catch (PlanValidationException pve) {
// good
}
printMessageCollector(collector) ;
printTypeGraph(plan) ;
planTester.printPlan(plan, TypeCheckingTestUtil.getCurrentMethodName());
assertTrue(collector.hasError());
}
@Test
public void testLimitLineage() throws Throwable {
planTester.buildPlan("a = load 'a' as (field1, field2: float, field3: chararray );") ;
planTester.buildPlan("b = limit a 100;") ;
LogicalPlan plan = planTester.buildPlan("c = foreach b generate field1 + 1.0 ;") ;
// validate
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
typeValidator.validate(plan, collector) ;
printMessageCollector(collector) ;
printTypeGraph(plan) ;
planTester.printPlan(plan, TypeCheckingTestUtil.getCurrentMethodName());
if (collector.hasError()) {
throw new AssertionError("Expect no error") ;
}
LOForEach foreach = (LOForEach)plan.getLeaves().get(0);
LogicalPlan foreachPlan = foreach.getForEachPlans().get(0);
LogicalOperator exOp = foreachPlan.getRoots().get(0);
if(! (exOp instanceof LOProject)) exOp = foreachPlan.getRoots().get(1);
LOCast cast = (LOCast)foreachPlan.getSuccessors(exOp).get(0);
assertTrue(cast.getLoadFuncSpec().getClassName().startsWith("org.apache.pig.builtin.PigStorage"));
}
@Test
public void testLimitLineageNoSchema() throws Throwable {
planTester.buildPlan("a = load 'a' ;") ;
planTester.buildPlan("b = limit a 100;") ;
LogicalPlan plan = planTester.buildPlan("c = foreach b generate $1 + 1.0 ;") ;
// validate
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
typeValidator.validate(plan, collector) ;
printMessageCollector(collector) ;
printTypeGraph(plan) ;
planTester.printPlan(plan, TypeCheckingTestUtil.getCurrentMethodName());
if (collector.hasError()) {
throw new AssertionError("Expect no error") ;
}
LOForEach foreach = (LOForEach)plan.getLeaves().get(0);
LogicalPlan foreachPlan = foreach.getForEachPlans().get(0);
LogicalOperator exOp = foreachPlan.getRoots().get(0);
if(! (exOp instanceof LOProject)) exOp = foreachPlan.getRoots().get(1);
LOCast cast = (LOCast)foreachPlan.getSuccessors(exOp).get(0);
assertTrue(cast.getLoadFuncSpec().getClassName().startsWith("org.apache.pig.builtin.PigStorage"));
}
@Test
public void testCogroupLimitLineage() throws Throwable {
planTester.buildPlan("a = load 'a' using BinStorage() as (field1, field2: float, field3: chararray );") ;
planTester.buildPlan("b = load 'a' using PigStorage() as (field4, field5, field6: chararray );") ;
planTester.buildPlan("c = cogroup a by field1, b by field4 ;") ;
planTester.buildPlan("d = foreach c generate group, flatten(a), flatten(b) ;") ;
planTester.buildPlan("e = limit d 100;") ;
LogicalPlan plan = planTester.buildPlan("f = foreach e generate group, field1 + 1, field4 + 2.0 ;") ;
// validate
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
typeValidator.validate(plan, collector) ;
printMessageCollector(collector) ;
printTypeGraph(plan) ;
planTester.printPlan(plan, TypeCheckingTestUtil.getCurrentMethodName());
if (collector.hasError()) {
throw new AssertionError("Expect no error") ;
}
LOForEach foreach = (LOForEach)plan.getLeaves().get(0);
LogicalPlan foreachPlan = foreach.getForEachPlans().get(1);
LogicalOperator exOp = foreachPlan.getRoots().get(0);
if(! (exOp instanceof LOProject)) exOp = foreachPlan.getRoots().get(1);
LOCast cast = (LOCast)foreachPlan.getSuccessors(exOp).get(0);
assertTrue(cast.getLoadFuncSpec().getClassName().startsWith("BinStorage"));
foreachPlan = foreach.getForEachPlans().get(2);
exOp = foreachPlan.getRoots().get(0);
if(! (exOp instanceof LOProject)) exOp = foreachPlan.getRoots().get(1);
cast = (LOCast)foreachPlan.getSuccessors(exOp).get(0);
assertTrue(cast.getLoadFuncSpec().getClassName().startsWith("PigStorage"));
}
@Test
public void testCogroupLimitLineageNoSchema() throws Throwable {
planTester.buildPlan("a = load 'a' using BinStorage() ;") ;
planTester.buildPlan("b = load 'a' using PigStorage() ;") ;
planTester.buildPlan("c = cogroup a by $0, b by $0 ;") ;
planTester.buildPlan("d = foreach c generate group, flatten(a), flatten(b) ;") ;
planTester.buildPlan("e = limit d 100;") ;
LogicalPlan plan = planTester.buildPlan("f = foreach e generate group, $1 + 1, $2 + 2.0 ;") ;
// validate
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
typeValidator.validate(plan, collector) ;
printMessageCollector(collector) ;
printTypeGraph(plan) ;
planTester.printPlan(plan, TypeCheckingTestUtil.getCurrentMethodName());
if (collector.hasError()) {
throw new AssertionError("Expect no error") ;
}
LOForEach foreach = (LOForEach)plan.getLeaves().get(0);
LogicalPlan foreachPlan = foreach.getForEachPlans().get(1);
LogicalOperator exOp = foreachPlan.getRoots().get(0);
if(! (exOp instanceof LOProject)) exOp = foreachPlan.getRoots().get(1);
LOCast cast = (LOCast)foreachPlan.getSuccessors(exOp).get(0);
assertTrue(cast.getLoadFuncSpec().getClassName().startsWith("BinStorage"));
foreachPlan = foreach.getForEachPlans().get(2);
exOp = foreachPlan.getRoots().get(0);
if(! (exOp instanceof LOProject)) exOp = foreachPlan.getRoots().get(1);
cast = (LOCast)foreachPlan.getSuccessors(exOp).get(0);
assertTrue(cast.getLoadFuncSpec().getClassName().startsWith("PigStorage"));
}
@Test
public void testCogroupTopKLineage() throws Throwable {
planTester.buildPlan("a = load 'a' using BinStorage() as (field1, field2: float, field3: chararray );") ;
planTester.buildPlan("b = load 'a' using PigStorage() as (field4, field5, field6: chararray );") ;
planTester.buildPlan("c = cogroup a by field1, b by field4 ;") ;
planTester.buildPlan("d = foreach c generate group, flatten(a), flatten(b) ;") ;
planTester.buildPlan("e = order d by field1 desc;") ;
planTester.buildPlan("f = limit e 100;") ;
LogicalPlan plan = planTester.buildPlan("g = foreach f generate group, field1 + 1, field4 + 2.0 ;") ;
// validate
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
typeValidator.validate(plan, collector) ;
printMessageCollector(collector) ;
printTypeGraph(plan) ;
planTester.printPlan(plan, TypeCheckingTestUtil.getCurrentMethodName());
if (collector.hasError()) {
throw new AssertionError("Expect no error") ;
}
LOForEach foreach = (LOForEach)plan.getLeaves().get(0);
LogicalPlan foreachPlan = foreach.getForEachPlans().get(1);
LogicalOperator exOp = foreachPlan.getRoots().get(0);
if(! (exOp instanceof LOProject)) exOp = foreachPlan.getRoots().get(1);
LOCast cast = (LOCast)foreachPlan.getSuccessors(exOp).get(0);
assertTrue(cast.getLoadFuncSpec().getClassName().startsWith("BinStorage"));
foreachPlan = foreach.getForEachPlans().get(2);
exOp = foreachPlan.getRoots().get(0);
if(! (exOp instanceof LOProject)) exOp = foreachPlan.getRoots().get(1);
cast = (LOCast)foreachPlan.getSuccessors(exOp).get(0);
assertTrue(cast.getLoadFuncSpec().getClassName().startsWith("PigStorage"));
}
@Test
public void testCogroupTopKLineageNoSchema() throws Throwable {
planTester.buildPlan("a = load 'a' using BinStorage() ;") ;
planTester.buildPlan("b = load 'a' using PigStorage() ;") ;
planTester.buildPlan("c = cogroup a by $0, b by $0 ;") ;
planTester.buildPlan("d = foreach c generate group, flatten(a), flatten(b) ;") ;
planTester.buildPlan("e = order d by $2 desc;") ;
planTester.buildPlan("f = limit e 100;") ;
LogicalPlan plan = planTester.buildPlan("g = foreach f generate group, $1 + 1, $2 + 2.0 ;") ;
// validate
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
typeValidator.validate(plan, collector) ;
printMessageCollector(collector) ;
printTypeGraph(plan) ;
planTester.printPlan(plan, TypeCheckingTestUtil.getCurrentMethodName());
if (collector.hasError()) {
throw new AssertionError("Expect no error") ;
}
LOForEach foreach = (LOForEach)plan.getLeaves().get(0);
LogicalPlan foreachPlan = foreach.getForEachPlans().get(1);
LogicalOperator exOp = foreachPlan.getRoots().get(0);
if(! (exOp instanceof LOProject)) exOp = foreachPlan.getRoots().get(1);
LOCast cast = (LOCast)foreachPlan.getSuccessors(exOp).get(0);
assertTrue(cast.getLoadFuncSpec().getClassName().startsWith("BinStorage"));
foreachPlan = foreach.getForEachPlans().get(2);
exOp = foreachPlan.getRoots().get(0);
if(! (exOp instanceof LOProject)) exOp = foreachPlan.getRoots().get(1);
cast = (LOCast)foreachPlan.getSuccessors(exOp).get(0);
assertTrue(cast.getLoadFuncSpec().getClassName().startsWith("PigStorage"));
}
@Test
public void testStreamingLineage1() throws Throwable {
planTester.buildPlan("a = load 'a' using BinStorage() as (field1: int, field2: float, field3: chararray );") ;
planTester.buildPlan("b = stream a through `" + simpleEchoStreamingCommand + "`;");
LogicalPlan plan = planTester.buildPlan("c = foreach b generate $1 + 1.0 ;") ;
// validate
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
typeValidator.validate(plan, collector) ;
printMessageCollector(collector) ;
printTypeGraph(plan) ;
planTester.printPlan(plan, TypeCheckingTestUtil.getCurrentMethodName());
if (collector.hasError()) {
throw new AssertionError("Expect no error") ;
}
LOForEach foreach = (LOForEach)plan.getLeaves().get(0);
LogicalPlan foreachPlan = foreach.getForEachPlans().get(0);
LogicalOperator exOp = foreachPlan.getRoots().get(0);
if(! (exOp instanceof LOProject)) exOp = foreachPlan.getRoots().get(1);
LOCast cast = (LOCast)foreachPlan.getSuccessors(exOp).get(0);
- assertTrue(cast.getLoadFuncSpec().getClassName().startsWith("org.apache.pig.impl.streaming.PigStreaming"));
+ assertTrue(cast.getLoadFuncSpec().getClassName().startsWith("org.apache.pig.builtin.PigStreaming"));
}
@Test
public void testStreamingLineage2() throws Throwable {
planTester.buildPlan("a = load 'a' using BinStorage() as (field1: int, field2: float, field3: chararray );") ;
planTester.buildPlan("b = stream a through `" + simpleEchoStreamingCommand + "` as (f1, f2: float);");
LogicalPlan plan = planTester.buildPlan("c = foreach b generate f1 + 1.0, f2 + 4 ;") ;
// validate
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
typeValidator.validate(plan, collector) ;
printMessageCollector(collector) ;
printTypeGraph(plan) ;
planTester.printPlan(plan, TypeCheckingTestUtil.getCurrentMethodName());
if (collector.hasError()) {
throw new AssertionError("Expect no error") ;
}
LOForEach foreach = (LOForEach)plan.getLeaves().get(0);
LogicalPlan foreachPlan = foreach.getForEachPlans().get(0);
LogicalOperator exOp = foreachPlan.getRoots().get(0);
if(! (exOp instanceof LOProject)) exOp = foreachPlan.getRoots().get(1);
LOCast cast = (LOCast)foreachPlan.getSuccessors(exOp).get(0);
- assertTrue(cast.getLoadFuncSpec().getClassName().startsWith("org.apache.pig.impl.streaming.PigStreaming"));
+ assertTrue(cast.getLoadFuncSpec().getClassName().startsWith("org.apache.pig.builtin.PigStreaming"));
foreachPlan = foreach.getForEachPlans().get(1);
exOp = foreachPlan.getRoots().get(0);
if(! (exOp instanceof LOProject)) exOp = foreachPlan.getRoots().get(1);
assertTrue(foreachPlan.getSuccessors(exOp).get(0) instanceof LOAdd);
}
@Test
public void testCogroupStreamingLineage() throws Throwable {
planTester.buildPlan("a = load 'a' using BinStorage() as (field1, field2: float, field3: chararray );") ;
planTester.buildPlan("b = stream a through `" + simpleEchoStreamingCommand + "` as (field4, field5, field6: chararray);");
planTester.buildPlan("c = cogroup a by field1, b by field4 ;") ;
planTester.buildPlan("d = foreach c generate group, flatten(a), flatten(b) ;") ;
LogicalPlan plan = planTester.buildPlan("e = foreach d generate group, field1 + 1, field4 + 2.0 ;") ;
// validate
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
typeValidator.validate(plan, collector) ;
printMessageCollector(collector) ;
printTypeGraph(plan) ;
planTester.printPlan(plan, TypeCheckingTestUtil.getCurrentMethodName());
if (collector.hasError()) {
throw new AssertionError("Expect no error") ;
}
LOForEach foreach = (LOForEach)plan.getLeaves().get(0);
LogicalPlan foreachPlan = foreach.getForEachPlans().get(1);
LogicalOperator exOp = foreachPlan.getRoots().get(0);
if(! (exOp instanceof LOProject)) exOp = foreachPlan.getRoots().get(1);
LOCast cast = (LOCast)foreachPlan.getSuccessors(exOp).get(0);
assertTrue(cast.getLoadFuncSpec().getClassName().startsWith("BinStorage"));
foreachPlan = foreach.getForEachPlans().get(2);
exOp = foreachPlan.getRoots().get(0);
if(! (exOp instanceof LOProject)) exOp = foreachPlan.getRoots().get(1);
cast = (LOCast)foreachPlan.getSuccessors(exOp).get(0);
- assertTrue(cast.getLoadFuncSpec().getClassName().startsWith("org.apache.pig.impl.streaming.PigStreaming"));
+ assertTrue(cast.getLoadFuncSpec().getClassName().startsWith("org.apache.pig.builtin.PigStreaming"));
}
@Test
public void testCogroupStreamingLineageNoSchema() throws Throwable {
planTester.buildPlan("a = load 'a' using BinStorage() ;") ;
planTester.buildPlan("b = stream a through `" + simpleEchoStreamingCommand + "` ;");
planTester.buildPlan("c = cogroup a by $0, b by $0 ;") ;
planTester.buildPlan("d = foreach c generate group, flatten(a), flatten(b) ;") ;
LogicalPlan plan = planTester.buildPlan("e = foreach d generate group, $1 + 1, $2 + 2.0 ;") ;
// validate
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
typeValidator.validate(plan, collector) ;
printMessageCollector(collector) ;
printTypeGraph(plan) ;
planTester.printPlan(plan, TypeCheckingTestUtil.getCurrentMethodName());
if (collector.hasError()) {
throw new AssertionError("Expect no error") ;
}
LOForEach foreach = (LOForEach)plan.getLeaves().get(0);
LogicalPlan foreachPlan = foreach.getForEachPlans().get(1);
LogicalOperator exOp = foreachPlan.getRoots().get(0);
if(! (exOp instanceof LOProject)) exOp = foreachPlan.getRoots().get(1);
LOCast cast = (LOCast)foreachPlan.getSuccessors(exOp).get(0);
assertTrue(cast.getLoadFuncSpec().getClassName().startsWith("BinStorage"));
foreachPlan = foreach.getForEachPlans().get(2);
exOp = foreachPlan.getRoots().get(0);
if(! (exOp instanceof LOProject)) exOp = foreachPlan.getRoots().get(1);
cast = (LOCast)foreachPlan.getSuccessors(exOp).get(0);
- assertTrue(cast.getLoadFuncSpec().getClassName().startsWith("org.apache.pig.impl.streaming.PigStreaming"));
+ assertTrue(cast.getLoadFuncSpec().getClassName().startsWith("org.apache.pig.builtin.PigStreaming"));
}
@Test
public void testMapLookupLineage() throws Throwable {
planTester.buildPlan("a = load 'a' using BinStorage() as (field1, field2: float, field3: chararray );") ;
planTester.buildPlan("b = foreach a generate field1#'key1' as map1;") ;
LogicalPlan plan = planTester.buildPlan("c = foreach b generate map1#'key2' + 1 ;") ;
// validate
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
typeValidator.validate(plan, collector) ;
printMessageCollector(collector) ;
printTypeGraph(plan) ;
planTester.printPlan(plan, TypeCheckingTestUtil.getCurrentMethodName());
if (collector.hasError()) {
throw new AssertionError("Expect no error") ;
}
LOForEach foreach = (LOForEach)plan.getLeaves().get(0);
LogicalPlan foreachPlan = foreach.getForEachPlans().get(0);
LogicalOperator exOp = foreachPlan.getRoots().get(0);
// the root would be the project and there would be cast
// to map between the project and LOMapLookup
LOCast cast1 = (LOCast)foreachPlan.getSuccessors(exOp).get(0);
assertTrue(cast1.getLoadFuncSpec().getClassName().startsWith("BinStorage"));
LOMapLookup map = (LOMapLookup)foreachPlan.getSuccessors(cast1).get(0);
LOCast cast = (LOCast)foreachPlan.getSuccessors(map).get(0);
assertTrue(cast.getLoadFuncSpec().getClassName().startsWith("BinStorage"));
}
@Test
public void testMapLookupLineageNoSchema() throws Throwable {
planTester.buildPlan("a = load 'a' using BinStorage() ;") ;
planTester.buildPlan("b = foreach a generate $0#'key1';") ;
LogicalPlan plan = planTester.buildPlan("c = foreach b generate $0#'key2' + 1 ;") ;
// validate
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
typeValidator.validate(plan, collector) ;
printMessageCollector(collector) ;
printTypeGraph(plan) ;
planTester.printPlan(plan, TypeCheckingTestUtil.getCurrentMethodName());
if (collector.hasError()) {
throw new AssertionError("Expect no error") ;
}
LOForEach foreach = (LOForEach)plan.getLeaves().get(0);
LogicalPlan foreachPlan = foreach.getForEachPlans().get(0);
LogicalOperator exOp = foreachPlan.getRoots().get(0);
if(! (exOp instanceof LOProject)) exOp = foreachPlan.getRoots().get(1);
// the root would be the project and there would be cast
// to map between the project and LOMapLookup
LOCast cast1 = (LOCast)foreachPlan.getSuccessors(exOp).get(0);
assertTrue(cast1.getLoadFuncSpec().getClassName().startsWith("BinStorage"));
LOMapLookup map = (LOMapLookup)foreachPlan.getSuccessors(cast1).get(0);
LOCast cast = (LOCast)foreachPlan.getSuccessors(map).get(0);
assertTrue(cast.getLoadFuncSpec().getClassName().startsWith("BinStorage"));
}
@Test
public void testMapLookupLineage2() throws Throwable {
planTester.buildPlan("a = load 'a' as (s, m, l);") ;
planTester.buildPlan("b = foreach a generate s#'x' as f1, s#'y' as f2, s#'z' as f3;") ;
planTester.buildPlan("c = group b by f1;") ;
LogicalPlan plan = planTester.buildPlan("d = foreach c {fil = filter b by f2 == 1; generate flatten(group), SUM(fil.f3);};") ;
// validate
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
typeValidator.validate(plan, collector) ;
printMessageCollector(collector) ;
printTypeGraph(plan) ;
planTester.printPlan(plan, TypeCheckingTestUtil.getCurrentMethodName());
if (collector.hasError()) {
throw new AssertionError("Expect no error") ;
}
LOForEach foreach = (LOForEach)plan.getLeaves().get(0);
LogicalPlan foreachPlan = foreach.getForEachPlans().get(1);
LogicalOperator exOp = foreachPlan.getRoots().get(0);
LOFilter filter = (LOFilter)foreachPlan.getSuccessors(exOp).get(0);
LogicalPlan filterPlan = filter.getComparisonPlan();
exOp = filterPlan.getRoots().get(0);
if(! (exOp instanceof LOProject)) exOp = filterPlan.getRoots().get(1);
LOCast cast = (LOCast)filterPlan.getSuccessors(exOp).get(0);
assertTrue(cast.getLoadFuncSpec().getClassName().startsWith("org.apache.pig.builtin.PigStorage"));
}
@Test
public void testMapLookupLineage3() throws Throwable {
planTester.buildPlan("a = load 'a' as (s, m, l);") ;
// planTester.buildPlan("b = foreach a generate s#'src_spaceid' AS vspaceid, flatten(l#'viewinfo') as viewinfo ;") ;
// LogicalPlan plan = planTester.buildPlan("c = foreach b generate (chararray)vspaceid#'foo', (chararray)viewinfo#'pos' as position;") ;
planTester.buildPlan("b = foreach a generate flatten(l#'viewinfo') as viewinfo ;") ;
LogicalPlan plan = planTester.buildPlan("c = foreach b generate (chararray)viewinfo#'pos' as position;") ;
// validate
runTypeCheckingValidator(plan);
checkLoaderInCasts(plan, "org.apache.pig.builtin.PigStorage");
}
/**
* test various scenarios with two level map lookup
*/
@Test
public void testTwolevelMapLookupLineage() throws Exception {
List<String[]> queries = new ArrayList<String[]>();
// CASE 1: LOAD -> FILTER -> FOREACH -> LIMIT -> STORE
queries.add(new String[] {"sds = LOAD '/my/data/location' " +
"AS (simpleFields:map[], mapFields:map[], listMapFields:map[]);",
"queries = FILTER sds BY mapFields#'page_params'#'query' " +
"is NOT NULL;",
"queries_rand = FOREACH queries GENERATE " +
"(CHARARRAY) (mapFields#'page_params'#'query') AS query_string;",
"queries_limit = LIMIT queries_rand 100;",
"STORE queries_limit INTO 'out';"});
// CASE 2: LOAD -> FOREACH -> FILTER -> LIMIT -> STORE
queries.add(new String[]{"sds = LOAD '/my/data/location' " +
"AS (simpleFields:map[], mapFields:map[], listMapFields:map[]);",
"queries_rand = FOREACH sds GENERATE " +
"(CHARARRAY) (mapFields#'page_params'#'query') AS query_string;",
"queries = FILTER queries_rand BY query_string IS NOT null;",
"queries_limit = LIMIT queries 100;",
"STORE queries_limit INTO 'out';"});
// CASE 3: LOAD -> FOREACH -> FOREACH -> FILTER -> LIMIT -> STORE
queries.add(new String[]{"sds = LOAD '/my/data/location' " +
"AS (simpleFields:map[], mapFields:map[], listMapFields:map[]);",
"params = FOREACH sds GENERATE " +
"(map[]) (mapFields#'page_params') AS params;",
"queries = FOREACH params " +
"GENERATE (CHARARRAY) (params#'query') AS query_string;",
"queries_filtered = FILTER queries BY query_string IS NOT null;",
"queries_limit = LIMIT queries_filtered 100;",
"STORE queries_limit INTO 'out';"});
// CASE 4: LOAD -> FOREACH -> FOREACH -> LIMIT -> STORE
queries.add(new String[]{"sds = LOAD '/my/data/location' " +
"AS (simpleFields:map[], mapFields:map[], listMapFields:map[]);",
"params = FOREACH sds GENERATE" +
" (map[]) (mapFields#'page_params') AS params;",
"queries = FOREACH params GENERATE " +
"(CHARARRAY) (params#'query') AS query_string;",
"queries_limit = LIMIT queries 100;",
"STORE queries_limit INTO 'out';"});
// CASE 5: LOAD -> FOREACH -> FOREACH -> FOREACH -> LIMIT -> STORE
queries.add(new String[]{"sds = LOAD '/my/data/location' " +
"AS (simpleFields:map[], mapFields:map[], listMapFields:map[]);",
"params = FOREACH sds GENERATE " +
"(map[]) (mapFields#'page_params') AS params;",
"queries = FOREACH params GENERATE " +
"(CHARARRAY) (params#'query') AS query_string;",
"rand_queries = FOREACH queries GENERATE query_string as query;",
"queries_limit = LIMIT rand_queries 100;",
"STORE rand_queries INTO 'out';"});
for (String[] query: queries) {
LogicalPlan lp = null;
for (String queryLine : query) {
lp = planTester.buildPlan(queryLine);
}
// validate
runTypeCheckingValidator(lp);
checkLoaderInCasts(lp, "org.apache.pig.builtin.PigStorage");
}
}
private void runTypeCheckingValidator(LogicalPlan plan) throws
PlanValidationException {
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
typeValidator.validate(plan, collector) ;
printMessageCollector(collector) ;
printTypeGraph(plan) ;
planTester.printPlan(plan, TypeCheckingTestUtil.getCurrentMethodName());
if (collector.hasError()) {
throw new AssertionError("Expect no error") ;
}
}
private void checkLoaderInCasts(LogicalPlan plan, String loaderClassName)
throws VisitorException {
CastFinder cf = new CastFinder(plan);
cf.visit();
List<LOCast> casts = cf.casts;
for (LOCast cast : casts) {
assertTrue(cast.getLoadFuncSpec().getClassName().startsWith(
loaderClassName));
}
}
class CastFinder extends LOVisitor {
List<LOCast> casts = new ArrayList<LOCast>();
/**
*
*/
public CastFinder(LogicalPlan lp) {
super(lp, new DepthFirstWalker<LogicalOperator, LogicalPlan>(lp));
}
@Override
protected void visit(LOCast cast) throws VisitorException {
casts.add(cast);
}
}
@Test
public void testBincond() throws Throwable {
planTester.buildPlan("a = load 'a' as (name: chararray, age: int, gpa: float);") ;
planTester.buildPlan("b = group a by name;") ;
LogicalPlan plan = planTester.buildPlan("c = foreach b generate (IsEmpty(a) ? " + TestBinCondFieldSchema.class.getName() + "(*): a) ;") ;
// validate
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
typeValidator.validate(plan, collector) ;
printMessageCollector(collector) ;
printTypeGraph(plan) ;
planTester.printPlan(plan, TypeCheckingTestUtil.getCurrentMethodName());
if (collector.hasError()) {
throw new AssertionError("Did not expect an error") ;
}
LOForEach foreach = (LOForEach)plan.getLeaves().get(0);
Schema.FieldSchema charFs = new FieldSchema(null, DataType.CHARARRAY);
Schema.FieldSchema intFs = new FieldSchema(null, DataType.INTEGER);
Schema.FieldSchema floatFs = new FieldSchema(null, DataType.FLOAT);
Schema bagSchema = new Schema();
bagSchema.add(charFs);
bagSchema.add(intFs);
bagSchema.add(floatFs);
Schema.FieldSchema bagFs = null;
try {
bagFs = new Schema.FieldSchema(null, bagSchema, DataType.BAG);
} catch (FrontendException fee) {
fail("Did not expect an error");
}
Schema expectedSchema = new Schema(bagFs);
assertTrue(Schema.equals(foreach.getSchema(), expectedSchema, false, true));
}
@Test
public void testBinCondForOuterJoin() throws Throwable {
planTester.buildPlan("a = LOAD 'student_data' AS (name: chararray, age: int, gpa: float);");
planTester.buildPlan("b = LOAD 'voter_data' AS (name: chararray, age: int, registration: chararray, contributions: float);");
planTester.buildPlan("c = COGROUP a BY name, b BY name;");
LogicalPlan plan = planTester.buildPlan("d = FOREACH c GENERATE group, flatten((not IsEmpty(a) ? a : (bag{tuple(chararray, int, float)}){(null, null, null)})), flatten((not IsEmpty(b) ? b : (bag{tuple(chararray, int, chararray, float)}){(null,null,null, null)}));");
// validate
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
typeValidator.validate(plan, collector) ;
printMessageCollector(collector) ;
printTypeGraph(plan) ;
planTester.printPlan(plan, TypeCheckingTestUtil.getCurrentMethodName());
if (collector.hasError()) {
throw new AssertionError("Expect no error") ;
}
LOForEach foreach = (LOForEach)plan.getLeaves().get(0);
String expectedSchemaString = "mygroup: chararray,A::name: chararray,A::age: int,A::gpa: float,B::name: chararray,B::age: int,B::registration: chararray,B::contributions: float";
Schema expectedSchema = Util.getSchemaFromString(expectedSchemaString);
assertTrue(Schema.equals(foreach.getSchema(), expectedSchema, false, true));
}
@Test
public void testMapLookupCast() throws Exception {
String input[] = { "[k1#hello,k2#bye]",
"[k1#good,k2#morning]" };
File f = Util.createInputFile("test", ".txt", input);
String inputFileName = f.getAbsolutePath();
// load as bytearray and use as map
planTester.buildPlan("a = load 'file://" + inputFileName + "' as (m);");
LogicalPlan lp = planTester.buildPlan("b = foreach a generate m#'k1';");
// validate
CompilationMessageCollector collector = new CompilationMessageCollector() ;
TypeCheckingValidator typeValidator = new TypeCheckingValidator() ;
typeValidator.validate(lp, collector) ;
// check that a LOCast has been introduced
LOForEach foreach = (LOForEach) lp.getLeaves().get(0);
LogicalPlan innerPlan = foreach.getForEachPlans().get(0);
LOMapLookup mapLookup = (LOMapLookup) innerPlan.getLeaves().get(0);
assertEquals(LOCast.class, mapLookup.getMap().getClass());
assertEquals(DataType.MAP, ((LOCast)mapLookup.getMap()).getType());
// load as map and use as map
planTester.buildPlan("a = load 'file://" + inputFileName + "' as (m:[]);");
lp = planTester.buildPlan("b = foreach a generate m#'k1';");
// validate
collector = new CompilationMessageCollector() ;
typeValidator = new TypeCheckingValidator() ;
typeValidator.validate(lp, collector) ;
// check that a LOCast has NOT been introduced
foreach = (LOForEach) lp.getLeaves().get(0);
innerPlan = foreach.getForEachPlans().get(0);
mapLookup = (LOMapLookup) innerPlan.getLeaves().get(0);
assertEquals(LOProject.class, mapLookup.getMap().getClass());
PigServer ps = new PigServer(ExecType.LOCAL);
// load as bytearray and use as map
ps.registerQuery("a = load 'file://" + inputFileName + "' as (m);");
ps.registerQuery("b = foreach a generate m#'k1';");
Iterator<Tuple> it = ps.openIterator("b");
String[] expectedResults = new String[] {"(hello)", "(good)"};
int i = 0;
while(it.hasNext()) {
assertEquals(expectedResults[i++], it.next().toString());
}
// load as map and use as map
ps.registerQuery("a = load 'file://" + inputFileName + "' as (m:[]);");
ps.registerQuery("b = foreach a generate m#'k1';");
it = ps.openIterator("b");
expectedResults = new String[] {"(hello)", "(good)"};
i = 0;
while(it.hasNext()) {
assertEquals(expectedResults[i++], it.next().toString());
}
}
/*
* A test UDF that does not data processing but implements the getOutputSchema for
* checking the type checker
*/
public static class TestBinCondFieldSchema extends EvalFunc<DataBag> {
//no-op exec method
@Override
public DataBag exec(Tuple input) {
return null;
}
@Override
public Schema outputSchema(Schema input) {
Schema.FieldSchema charFs = new FieldSchema(null, DataType.CHARARRAY);
Schema.FieldSchema intFs = new FieldSchema(null, DataType.INTEGER);
Schema.FieldSchema floatFs = new FieldSchema(null, DataType.FLOAT);
Schema bagSchema = new Schema();
bagSchema.add(charFs);
bagSchema.add(intFs);
bagSchema.add(floatFs);
Schema.FieldSchema bagFs;
try {
bagFs = new Schema.FieldSchema(null, bagSchema, DataType.BAG);
} catch (FrontendException fee) {
return null;
}
return new Schema(bagFs);
}
}
////////////////////////// Helper //////////////////////////////////
private void checkForEachCasting(LOForEach foreach, int idx, boolean isCast, byte toType) {
LogicalPlan plan = foreach.getForEachPlans().get(idx) ;
if (isCast) {
List<LogicalOperator> leaveList = plan.getLeaves() ;
assertEquals(leaveList.size(), 1);
assertTrue(leaveList.get(0) instanceof LOCast);
assertTrue(leaveList.get(0).getType() == toType) ;
}
else {
List<LogicalOperator> leaveList = plan.getLeaves() ;
assertEquals(leaveList.size(), 1);
assertTrue(leaveList.get(0) instanceof LOProject);
}
}
}
| false | false | null | null |
diff --git a/eXoApplication/forum/webapp/src/main/java/org/exoplatform/forum/ForumSessionUtils.java b/eXoApplication/forum/webapp/src/main/java/org/exoplatform/forum/ForumSessionUtils.java
index 0113c9e1d..f0e506dde 100644
--- a/eXoApplication/forum/webapp/src/main/java/org/exoplatform/forum/ForumSessionUtils.java
+++ b/eXoApplication/forum/webapp/src/main/java/org/exoplatform/forum/ForumSessionUtils.java
@@ -1,176 +1,176 @@
/***************************************************************************
* Copyright (C) 2003-2007 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.forum;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.List;
import org.exoplatform.commons.utils.PageList;
import org.exoplatform.contact.service.Contact;
import org.exoplatform.contact.service.ContactService;
import org.exoplatform.container.PortalContainer;
import org.exoplatform.download.DownloadService;
import org.exoplatform.download.InputStreamDownloadResource;
import org.exoplatform.portal.webui.util.SessionProviderFactory;
import org.exoplatform.portal.webui.util.Util;
import org.exoplatform.services.jcr.ext.common.SessionProvider;
import org.exoplatform.services.organization.OrganizationService;
import org.exoplatform.services.organization.User;
import org.exoplatform.services.organization.impl.GroupImpl;
public class ForumSessionUtils {
static public String getCurrentUser() throws Exception {
return Util.getPortalRequestContext().getRemoteUser();
}
public static boolean isAnonim() throws Exception {
String userId = getCurrentUser();
if (userId == null)
return true;
return false;
}
public static SessionProvider getSystemProvider() {
return SessionProviderFactory.createSystemProvider();
}
public static String getFileSource(InputStream input, String fileName, DownloadService dservice) throws Exception {
byte[] imageBytes = null;
if (input != null) {
imageBytes = new byte[input.available()];
input.read(imageBytes);
ByteArrayInputStream byteImage = new ByteArrayInputStream(imageBytes);
InputStreamDownloadResource dresource = new InputStreamDownloadResource(
byteImage, "image");
dresource.setDownloadName(fileName);
return dservice.getDownloadLink(dservice.addDownloadResource(dresource));
}
return null;
}
public static String[] getUserGroups() throws Exception {
OrganizationService organizationService = (OrganizationService) PortalContainer
.getComponent(OrganizationService.class);
Object[] objGroupIds = organizationService.getGroupHandler()
.findGroupsOfUser(getCurrentUser()).toArray();
String[] groupIds = new String[objGroupIds.length];
for (int i = 0; i < groupIds.length; i++) {
groupIds[i] = ((GroupImpl) objGroupIds[i]).getId();
}
return groupIds;
}
@SuppressWarnings("unchecked")
public static PageList getPageListUser() throws Exception {
OrganizationService organizationService = (OrganizationService) PortalContainer.getComponent(OrganizationService.class);
return organizationService.getUserHandler().getUserPageList(0);
}
@SuppressWarnings("unchecked")
public static List<User> getAllUser() throws Exception {
OrganizationService organizationService = (OrganizationService) PortalContainer.getComponent(OrganizationService.class);
PageList pageList = organizationService.getUserHandler().getUserPageList(0) ;
List<User>list = pageList.getAll() ;
return list;
}
public static User getUserByUserId(String userId) throws Exception {
OrganizationService organizationService = (OrganizationService) PortalContainer.getComponent(OrganizationService.class);
return organizationService.getUserHandler().findUserByName(userId) ;
}
@SuppressWarnings("unchecked")
public static List<User> getUserByGroupId(String groupId) throws Exception {
OrganizationService organizationService = (OrganizationService) PortalContainer.getComponent(OrganizationService.class);
return organizationService.getUserHandler().findUsersByGroup(groupId).getAll() ;
}
@SuppressWarnings("unchecked")
public static boolean hasUserInGroup(String groupId, String userId) throws Exception {
OrganizationService organizationService = (OrganizationService) PortalContainer.getComponent(OrganizationService.class);
List<User> users = organizationService.getUserHandler().findUsersByGroup(groupId).getAll() ;
for (User user : users) {
if(user.getUserName().equals(userId)) return true ;
}
return false ;
}
@SuppressWarnings("unchecked")
public static boolean hasGroupIdAndMembershipId(String str, OrganizationService organizationService) throws Exception {
if(str.indexOf(":") >= 0) { //membership
String[] array = str.split(":") ;
try {
organizationService.getGroupHandler().findGroupById(array[1]).getId() ;
} catch (Exception e) {
return false ;
}
- if(array[0].charAt(0) == '*' && array[0].length() == 1) {
+ if(array[0].length() == 1 && array[0].charAt(0) == '*') {
return true ;
- } else {
+ } else if(array[0].length() > 0){
if(organizationService.getMembershipTypeHandler().findMembershipType(array[0])== null) return false ;
- }
+ } else return false ;
} else { //group
try {
organizationService.getGroupHandler().findGroupById(str).getId() ;
} catch (Exception e) {
return false ;
}
}
return true ;
}
public static String checkValueUser(String values) throws Exception {
String erroUser = null;
if(values != null && values.trim().length() > 0) {
OrganizationService organizationService = (OrganizationService) PortalContainer.getComponent(OrganizationService.class);
String[] userIds = values.split(",");
boolean isUser = false ;
List<User> users = ForumSessionUtils.getAllUser() ;
for (String str : userIds) {
str = str.trim() ;
if(str.indexOf("/") >= 0) {
if(!hasGroupIdAndMembershipId(str, organizationService)){
if(erroUser == null) erroUser = str ;
else erroUser = erroUser + ", " + str;
}
} else {//user
isUser = false ;
for (User user : users) {
if(user.getUserName().equals(str)) {
isUser = true ;
break;
}
}
if(!isUser) {
if(erroUser == null) erroUser = str ;
else erroUser = erroUser + ", " + str;
}
}
}
}
return erroUser;
}
public static Contact getPersonalContact(String userId) throws Exception {
ContactService contactService = (ContactService) PortalContainer.getComponent(ContactService.class) ;
return contactService.getPersonalContact(userId);
}
}
| false | false | null | null |
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ClassLoaderTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ClassLoaderTest.java
index 9b5b17e1b..43a73ed19 100644
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ClassLoaderTest.java
+++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ClassLoaderTest.java
@@ -1,1263 +1,1264 @@
/*
* 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.harmony.luni.tests.java.lang;
import dalvik.annotation.AndroidOnly;
import dalvik.annotation.BrokenTest;
import dalvik.annotation.KnownFailure;
import dalvik.annotation.TestTargets;
import dalvik.annotation.TestLevel;
import dalvik.annotation.TestTargetNew;
import dalvik.annotation.TestTargetClass;
import junit.framework.TestCase;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.ByteBuffer;
import java.security.CodeSource;
import java.security.Permission;
import java.security.PermissionCollection;
import java.security.Policy;
import java.security.ProtectionDomain;
import java.util.Enumeration;
import java.util.NoSuchElementException;
@TestTargetClass(ClassLoader.class)
public class ClassLoaderTest extends TestCase {
+ private static final String SYSTEM_RESOURCE_PATH = "META-INF/MANIFEST.MF";
public static volatile int flag;
@TestTargetNew(
level = TestLevel.COMPLETE,
notes = "",
method = "ClassLoader",
args = {}
)
public void test_ClassLoader() {
PublicClassLoader pcl = new PublicClassLoader();
SecurityManager sm = new SecurityManager() {
RuntimePermission rp = new RuntimePermission("getProtectionDomain");
public void checkCreateClassLoader() {
throw new SecurityException();
}
public void checkPermission(Permission perm) {
if (perm.equals(rp)) {
throw new SecurityException();
}
}
};
SecurityManager oldSm = System.getSecurityManager();
System.setSecurityManager(sm);
try {
new PublicClassLoader();
fail("SecurityException should be thrown.");
} catch (SecurityException e) {
// expected
} finally {
System.setSecurityManager(oldSm);
}
}
@TestTargetNew(
level = TestLevel.COMPLETE,
notes = "",
method = "ClassLoader",
args = {java.lang.ClassLoader.class}
)
@BrokenTest("Infinite loop in classloader. Actually a known failure.")
public void test_ClassLoaderLClassLoader() {
PublicClassLoader pcl = new PublicClassLoader(
ClassLoader.getSystemClassLoader());
assertEquals(ClassLoader.getSystemClassLoader(), pcl.getParent());
SecurityManager sm = new SecurityManager() {
RuntimePermission rp = new RuntimePermission("getProtectionDomain");
public void checkCreateClassLoader() {
throw new SecurityException();
}
public void checkPermission(Permission perm) {
if (perm.equals(rp)) {
throw new SecurityException();
}
}
};
SecurityManager oldSm = System.getSecurityManager();
System.setSecurityManager(sm);
try {
new PublicClassLoader(ClassLoader.getSystemClassLoader());
fail("SecurityException should be thrown.");
} catch (SecurityException e) {
// expected
} finally {
System.setSecurityManager(oldSm);
}
}
@TestTargetNew(
level = TestLevel.NOT_NECESSARY,
notes = "",
method = "clearAssertionStatus",
args = {}
)
@KnownFailure("Android doesn't support assertions to be activated " +
"through the api")
public void test_clearAssertionStatus() {
String className = getClass().getPackage().getName() + ".TestAssertions";
String className1 = getClass().getPackage().getName() + ".TestAssertions1";
ClassLoader cl = getClass().getClassLoader();
cl.setClassAssertionStatus("TestAssertions", true);
cl.setDefaultAssertionStatus(true);
try {
Class clazz = cl.loadClass(className);
TestAssertions ta = (TestAssertions) clazz.newInstance();
try {
ta.test();
fail("AssertionError should be thrown.");
} catch(AssertionError ae) {
//expected
}
cl.clearAssertionStatus();
clazz = cl.loadClass(className1);
TestAssertions1 ta1 = (TestAssertions1) clazz.newInstance();
try {
ta1.test();
} catch(AssertionError ae) {
fail("AssertionError should not be thrown.");
}
} catch(Exception cnfe) {
fail("Unexpected exception: " + cnfe.toString());
}
}
@TestTargetNew(
level = TestLevel.COMPLETE,
notes = "This method is not supported. " +
"UnsupportedOperationException should be thrown.",
method = "defineClass",
args = {byte[].class, int.class, int.class}
)
@AndroidOnly("define methods re not supported on Android. " +
"UnsupportedOperationException should be thrown.")
public void test_defineClassLbyteArrayLintLint() throws Exception {
try {
Class<?> a = new Ldr().define(Ldr.TEST_CASE_DEFINE_1);
//assertEquals("org.apache.harmony.luni.tests.java.lang.A", a.getName());
fail("UnsupportedOperationException was not thrown.");
} catch(UnsupportedOperationException uoe) {
//expected
}
try {
new Ldr().define(1000, Ldr.TEST_CASE_DEFINE_1);
fail("IndexOutOfBoundsException is not thrown.");
} catch(IndexOutOfBoundsException ioobe) {
fail("UnsupportedOperationException should be thrown.");
} catch(UnsupportedOperationException uoe) {
//expected
}
}
@TestTargetNew(
level = TestLevel.COMPLETE,
notes = "This method is not supported. UnsupportedOperationException should be thrown.",
method = "defineClass",
args = {java.lang.String.class, byte[].class, int.class, int.class, java.security.ProtectionDomain.class}
)
@AndroidOnly("define methods re not supported on Android. " +
"UnsupportedOperationException should be thrown.")
public void test_defineClassLjava_lang_StringLbyteArrayLintLintLProtectionDomain()
throws Exception {
try {
Class<?> a = new Ldr().define(Ldr.TEST_CASE_DEFINE_2);
//assertEquals("org.apache.harmony.luni.tests.java.lang.A", a.getName());
//assertEquals(getClass().getProtectionDomain(), a.getProtectionDomain());
fail("UnsupportedOperationException was not thrown.");
} catch(UnsupportedOperationException uoe) {
//expected
}
try {
new Ldr().define(1000, Ldr.TEST_CASE_DEFINE_2);
fail("IndexOutOfBoundsException is not thrown.");
} catch(IndexOutOfBoundsException ioobe) {
fail("UnsupportedOperationException should be thrown.");
} catch(UnsupportedOperationException uoe) {
//expected
}
/*try {
ErrorLdr loader = new ErrorLdr();
try {
loader.define("WrongFormatClass", Ldr.TEST_CASE_DEFINE_2);
fail("ClassFormatError should be thrown.");
} catch (ClassFormatError le) {
//expected
} catch(UnsupportedOperationException uoe) {
//expected
}
try {
loader.defineWrongName("TestClass", 0);
fail("NoClassDefFoundError should be thrown.");
} catch (NoClassDefFoundError ncdfe) {
//expected
} catch(UnsupportedOperationException uoe) {
//expected
}
try {
Class<?> clazz = loader.defineNullDomain("TestClass", 0);
assertEquals(getClass().getProtectionDomain(),
clazz.getProtectionDomain());
} catch(UnsupportedOperationException uoe) {
//expected
}
} catch(Exception e) {
fail("Unexpected exception was thrown: " + e.toString());
}
*/
}
@TestTargetNew(
level = TestLevel.COMPLETE,
notes = "This method is not supported. UnsupportedOperationException should be thrown.",
method = "defineClass",
args = {java.lang.String.class, java.nio.ByteBuffer.class, java.security.ProtectionDomain.class}
)
@AndroidOnly("define methods re not supported on Android. " +
"UnsupportedOperationException should be thrown.")
public void test_defineClassLjava_lang_StringLByteBufferLProtectionDomain() {
try {
try {
Class<?> a = new Ldr().define(Ldr.TEST_CASE_DEFINE_3);
//assertEquals("org.apache.harmony.luni.tests.java.lang.A", a.getName());
//assertEquals(getClass().getProtectionDomain(), a.getProtectionDomain());
fail("UnsupportedOperationException was not thrown.");
} catch(UnsupportedOperationException uoe) {
//expected
}
try {
new Ldr().define(1000, Ldr.TEST_CASE_DEFINE_3);
fail("IndexOutOfBoundsException is not thrown.");
} catch(IndexOutOfBoundsException ioobe) {
fail("UnsupportedOperationException should be thrown.");
} catch(UnsupportedOperationException uoe) {
//expected
}
} catch(Exception e) {
fail("Unexpected exception was thrown: " + e.toString());
}
}
/**
* Tests that Classloader.defineClass() assigns appropriate
* default domains to the defined classes.
*/
@TestTargetNew(
level = TestLevel.COMPLETE,
notes = "This method is not supported. " +
"UnsupportedOperationException should be thrown.",
method = "defineClass",
args = {java.lang.String.class, byte[].class, int.class, int.class}
)
@AndroidOnly("define methods re not supported on Android. " +
"UnsupportedOperationException should be thrown.")
public void test_defineClass_defaultDomain() throws Exception {
try {
Class<?> a = new Ldr().define(Ldr.TEST_CASE_DEFINE_0);
fail("UnsupportedOperationException was not thrown.");
} catch(UnsupportedOperationException uoe) {
//expected
}
try {
new Ldr().define(1000, Ldr.TEST_CASE_DEFINE_0);
fail("IndexOutOfBoundsException is not thrown.");
} catch(IndexOutOfBoundsException ioobe) {
fail("UnsupportedOperationException should be thrown.");
} catch(UnsupportedOperationException uoe) {
//expected
}
}
static class SyncTestClassLoader extends ClassLoader {
Object lock;
volatile int numFindClassCalled;
SyncTestClassLoader(Object o) {
this.lock = o;
numFindClassCalled = 0;
}
/*
* Byte array of bytecode equivalent to the following source code:
* public class TestClass {
* }
*/
private byte[] classData = new byte[] {
-54, -2, -70, -66, 0, 0, 0, 49, 0, 13,
10, 0, 3, 0, 10, 7, 0, 11, 7, 0,
12, 1, 0, 6, 60, 105, 110, 105, 116, 62,
1, 0, 3, 40, 41, 86, 1, 0, 4, 67,
111, 100, 101, 1, 0, 15, 76, 105, 110, 101,
78, 117, 109, 98, 101, 114, 84, 97, 98, 108,
101, 1, 0, 10, 83, 111, 117, 114, 99, 101,
70, 105, 108, 101, 1, 0, 14, 84, 101, 115,
116, 67, 108, 97, 115, 115, 46, 106, 97, 118,
97, 12, 0, 4, 0, 5, 1, 0, 9, 84,
101, 115, 116, 67, 108, 97, 115, 115, 1, 0,
16, 106, 97, 118, 97, 47, 108, 97, 110, 103,
47, 79, 98, 106, 101, 99, 116, 0, 33, 0,
2, 0, 3, 0, 0, 0, 0, 0, 1, 0,
1, 0, 4, 0, 5, 0, 1, 0, 6, 0,
0, 0, 29, 0, 1, 0, 1, 0, 0, 0,
5, 42, -73, 0, 1, -79, 0, 0, 0, 1,
0, 7, 0, 0, 0, 6, 0, 1, 0, 0,
0, 1, 0, 1, 0, 8, 0, 0, 0, 2,
0, 9 };
protected Class findClass(String name) throws ClassNotFoundException {
try {
while (flag != 2) {
synchronized (lock) {
lock.wait();
}
}
} catch (InterruptedException ie) {}
if (name.equals("TestClass")) {
numFindClassCalled++;
return defineClass(null, classData, 0, classData.length);
} else {
throw new ClassNotFoundException("Class " + name + " not found.");
}
}
}
static class SyncLoadTestThread extends Thread {
volatile boolean started;
ClassLoader cl;
Class cls;
SyncLoadTestThread(ClassLoader cl) {
this.cl = cl;
}
public void run() {
try {
started = true;
cls = Class.forName("TestClass", false, cl);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
/**
* Regression test for HARMONY-1939:
* 2 threads simultaneously run Class.forName() method for the same classname
* and the same classloader. It is expected that both threads succeed but
* class must be defined just once.
*/
@TestTargetNew(
level = TestLevel.PARTIAL,
notes = "Regression test.",
method = "loadClass",
args = {java.lang.String.class}
)
@BrokenTest("Defining classes not supported, unfortunately the test appears"
+ " to succeed, which is not true, so marking it broken.")
public void test_loadClass_concurrentLoad() throws Exception
{
Object lock = new Object();
SyncTestClassLoader cl = new SyncTestClassLoader(lock);
SyncLoadTestThread tt1 = new SyncLoadTestThread(cl);
SyncLoadTestThread tt2 = new SyncLoadTestThread(cl);
flag = 1;
tt1.start();
tt2.start();
while (!tt1.started && !tt2.started) {
Thread.sleep(100);
}
flag = 2;
synchronized (lock) {
lock.notifyAll();
}
tt1.join();
tt2.join();
assertSame("Bad or redefined class", tt1.cls, tt2.cls);
assertEquals("Both threads tried to define class", 1, cl.numFindClassCalled);
}
@TestTargetNew(
level = TestLevel.COMPLETE,
notes = "",
method = "loadClass",
args = {java.lang.String.class}
)
public void test_loadClassLjava_lang_String() {
String [] classNames = {"org.apache.harmony.luni.tests.java.lang.TestClass1",
"org.apache.harmony.luni.tests.java.lang.TestClass3",
"org.apache.harmony.luni.tests.java.lang.A"};
ClassLoader cl = getClass().getClassLoader();
for(String str:classNames) {
try {
Class<?> clazz = cl.loadClass(str);
assertNotNull(clazz);
assertEquals(str, clazz.getName());
if(str.endsWith("A"))
clazz.newInstance();
if(str.endsWith("TestClass1")) {
try {
clazz.newInstance();
fail("ExceptionInInitializerError was not thrown.");
} catch(ExceptionInInitializerError eiine) {
//expected
}
}
if(str.endsWith("TestClass3")) {
try {
clazz.newInstance();
fail("IllegalAccessException was not thrown.");
} catch(IllegalAccessException ie) {
//expected
}
}
} catch (ClassNotFoundException e) {
fail("ClassNotFoundException was thrown." + e.getMessage());
} catch (InstantiationException e) {
fail("InstantiationException was thrown.");
} catch (IllegalAccessException e) {
fail("IllegalAccessException was thrown.");
}
}
try {
Class<?> clazz = cl.loadClass("org.apache.harmony.luni.tests.java.lang.TestClass4");
fail("ClassNotFoundException was not thrown.");
} catch (ClassNotFoundException e) {
//expected
}
try {
Class<?> clazz = cl.loadClass("org.apache.harmony.luni.tests.java.lang.TestClass5");
fail("ClassNotFoundException was not thrown.");
} catch (ClassNotFoundException e) {
//expected
}
}
@TestTargetNew(
level = TestLevel.COMPLETE,
notes = "",
method = "loadClass",
args = {java.lang.String.class, boolean.class}
)
public void test_loadClassLjava_lang_StringLZ() throws
IllegalAccessException, InstantiationException,
ClassNotFoundException {
PackageClassLoader pcl = new PackageClassLoader(
getClass().getClassLoader());
String className = getClass().getPackage().getName() + ".A";
Class<?> clazz = pcl.loadClass(className, false);
assertEquals(className, clazz.getName());
assertNotNull(clazz.newInstance());
clazz = pcl.loadClass(className, true);
assertEquals(className, clazz.getName());
assertNotNull(clazz.newInstance());
try {
clazz = pcl.loadClass("UnknownClass", false);
assertEquals("TestClass", clazz.getName());
fail("ClassNotFoundException was not thrown.");
} catch (ClassNotFoundException e) {
//expected
}
}
/**
* @tests java.lang.ClassLoader#getResource(java.lang.String)
*/
@TestTargetNew(
level = TestLevel.COMPLETE,
notes = "",
method = "getResource",
args = {java.lang.String.class}
)
public void test_getResourceLjava_lang_String() {
// Test for method java.net.URL
// java.lang.ClassLoader.getResource(java.lang.String)
java.net.URL u = getClass().getClassLoader().getResource("hyts_Foo.c");
assertNotNull("Unable to find resource", u);
java.io.InputStream is = null;
try {
is = u.openStream();
assertNotNull("Resource returned is invalid", is);
is.close();
} catch (java.io.IOException e) {
fail("IOException getting stream for resource : " + e.getMessage());
}
assertNull(getClass().getClassLoader()
.getResource("not.found.resource"));
}
/**
* @tests java.lang.ClassLoader#getResourceAsStream(java.lang.String)
*/
@TestTargetNew(
level = TestLevel.COMPLETE,
notes = "",
method = "getResourceAsStream",
args = {java.lang.String.class}
)
public void test_getResourceAsStreamLjava_lang_String() {
// Test for method java.io.InputStream
// java.lang.ClassLoader.getResourceAsStream(java.lang.String)
// Need better test...
java.io.InputStream is = null;
assertNotNull("Failed to find resource: HelloWorld.txt",
(is = getClass().getClassLoader()
.getResourceAsStream("HelloWorld.txt")));
byte [] array = new byte[13];
try {
is.read(array);
} catch(IOException ioe) {
fail("IOException was not thrown.");
} finally {
try {
is.close();
} catch(IOException ioe) {}
}
assertEquals("Hello, World.", new String(array));
try {
is.close();
} catch (java.io.IOException e) {
fail("Exception during getResourceAsStream: " + e.toString());
}
assertNull(getClass().getClassLoader().
getResourceAsStream("unknownResource.txt"));
}
/**
* @tests java.lang.ClassLoader#getSystemClassLoader()
*/
@TestTargetNew(
level = TestLevel.SUFFICIENT,
notes = "",
method = "getSystemClassLoader",
args = {}
)
public void test_getSystemClassLoader() {
// Test for method java.lang.ClassLoader
// java.lang.ClassLoader.getSystemClassLoader()
ClassLoader cl = ClassLoader.getSystemClassLoader();
- java.io.InputStream is = cl.getResourceAsStream("classes.dex");
+ java.io.InputStream is = cl.getResourceAsStream(SYSTEM_RESOURCE_PATH);
assertNotNull("Failed to find resource from system classpath", is);
try {
is.close();
} catch (java.io.IOException e) {
}
SecurityManager sm = new SecurityManager() {
public void checkPermission(Permission perm) {
if(perm.getName().equals("getClassLoader")) {
throw new SecurityException();
}
}
};
SecurityManager oldManager = System.getSecurityManager();
System.setSecurityManager(sm);
try {
ClassLoader.getSystemClassLoader();
} catch(SecurityException se) {
//expected
} finally {
System.setSecurityManager(oldManager);
}
/*
* // java.lang.Error is not thrown on RI, but it's specified.
*
* String keyProp = "java.system.class.loader";
* String oldProp = System.getProperty(keyProp);
* System.setProperty(keyProp, "java.test.UnknownClassLoader");
* boolean isFailed = false;
* try {
* ClassLoader.getSystemClassLoader();
* isFailed = true;
* } catch(java.lang.Error e) {
* //expected
* } finally {
* if(oldProp == null) {
* System.clearProperty(keyProp);
* } else {
* System.setProperty(keyProp, oldProp);
* }
* }
* assertFalse("java.lang.Error was not thrown.", isFailed);
*/
}
/**
* @tests java.lang.ClassLoader#getSystemResource(java.lang.String)
*/
@TestTargetNew(
level = TestLevel.COMPLETE,
notes = "",
method = "getSystemResource",
args = {java.lang.String.class}
)
@AndroidOnly("The RI doesn't have a classes.dex as resource in the "
+ "core-tests.jar. Also on Android this file is the only one "
+ "that is sure to exist.")
public void test_getSystemResourceLjava_lang_String() throws IOException {
// java.lang.ClassLoader.getSystemResource(java.lang.String)
// Need better test...
//String classResource = getClass().getPackage().getName().replace(".", "/") + "/" +
// getClass().getSimpleName() + ".class";
//assertNotNull("Failed to find resource: " + classResource,
// ClassLoader.getSystemResource(classResource));
- URL url = getClass().getClassLoader().getSystemResource("classes.dex");
- assertNotNull("Failed to find resource: classes.dex", url);
+ URL url = getClass().getClassLoader().getSystemResource(SYSTEM_RESOURCE_PATH);
+ assertNotNull(String.format("Failed to find resource: %s", SYSTEM_RESOURCE_PATH), url);
java.io.InputStream is = url.openStream();
assertTrue("System resource not found", is.available() > 0);
assertNull("Doesn't return null for unknown resource.",
getClass().getClassLoader().getSystemResource("NotFound"));
}
@TestTargetNew(
level = TestLevel.COMPLETE,
notes = "",
method = "getSystemResourceAsStream",
args = {java.lang.String.class}
)
@AndroidOnly("The RI doesn't have a classes.dex as resource in the "
+ "core-tests.jar. Also on Android this file is the only one "
+ "that is sure to exist.")
public void test_getSystemResourceAsStreamLjava_lang_String()
throws IOException {
//String classResource = getClass().getPackage().getName().replace(".", "/") + "/" +
// getClass().getSimpleName() + ".class";
//assertNotNull("Failed to find resource: " + classResource,
// ClassLoader.getSystemResourceAsStream(classResource));
java.io.InputStream is = getClass().getClassLoader()
- .getSystemResourceAsStream("classes.dex");
- assertNotNull("Failed to find resource: classes.dex", is);
+ .getSystemResourceAsStream(SYSTEM_RESOURCE_PATH);
+ assertNotNull(String.format("Failed to find resource: %s", SYSTEM_RESOURCE_PATH), is);
assertTrue("System resource not found", is.available() > 0);
assertNull(ClassLoader.getSystemResourceAsStream("NotFoundResource"));
}
@TestTargetNew(
level = TestLevel.COMPLETE,
notes = "",
method = "getSystemResources",
args = {java.lang.String.class}
)
@AndroidOnly("The RI doesn't have a classes.dex as resource in the "
+ "core-tests.jar. Also on Android this file is the only one "
+ "that is sure to exist.")
public void test_getSystemResources() {
- String textResource = "classes.dex";
+ String textResource = SYSTEM_RESOURCE_PATH;
try {
Enumeration<URL> urls = ClassLoader.getSystemResources(textResource);
assertNotNull(urls);
assertTrue(urls.nextElement().getPath().endsWith(textResource));
while (urls.hasMoreElements()) {
assertNotNull(urls.nextElement());
}
try {
urls.nextElement();
fail("NoSuchElementException was not thrown.");
} catch(NoSuchElementException nse) {
//expected
}
} catch(IOException ioe) {
fail("IOException was thrown.");
}
}
@TestTargetNew(
level = TestLevel.COMPLETE,
notes = "",
method = "getPackage",
args = {java.lang.String.class}
)
@KnownFailure("PackageClassLoader.getPackage returns null.")
public void test_getPackageLjava_lang_String() {
PackageClassLoader pcl = new PackageClassLoader(
getClass().getClassLoader());
String [] packageProperties = { "test.package", "title", "1.0",
"Vendor", "Title", "1.1", "implementation vendor"};
URL url = null;
try {
url = new URL("file:");
} catch (MalformedURLException e) {
fail("MalformedURLException was thrown.");
}
pcl.definePackage(packageProperties[0],
packageProperties[1],
packageProperties[2],
packageProperties[3],
packageProperties[4],
packageProperties[5],
packageProperties[6],
url);
assertNotNull(pcl.getPackage(packageProperties[0]));
assertEquals("should define current package", getClass().getPackage(),
pcl.getPackage(getClass().getPackage().getName()));
assertNull(pcl.getPackage("not.found.package"));
}
@TestTargetNew(
level = TestLevel.COMPLETE,
notes = "",
method = "getPackages",
args = {}
)
@KnownFailure("The package canot be found. Seems like the cache is not " +
"shared between the class loaders. But this test seems to " +
"expect exactly that. this tests works on the RI.")
public void test_getPackages() {
PackageClassLoader pcl = new PackageClassLoader(
getClass().getClassLoader());
String [] packageProperties = { "test.package", "title", "1.0",
"Vendor", "Title", "1.1", "implementation vendor"};
URL url = null;
try {
url = new URL("file:");
} catch (MalformedURLException e) {
fail("MalformedURLException was thrown.");
}
pcl.definePackage(packageProperties[0],
packageProperties[1],
packageProperties[2],
packageProperties[3],
packageProperties[4],
packageProperties[5],
packageProperties[6],
url);
Package [] packages = pcl.getPackages();
assertTrue(packages.length != 0);
pcl = new PackageClassLoader(getClass().getClassLoader());
packages = pcl.getPackages();
assertNotNull(packages);
boolean isThisFound = false;
for(Package p:packages) {
if(p.equals(getClass().getPackage())) {
isThisFound = true;
}
}
assertTrue(isThisFound);
}
@TestTargetNew(
level = TestLevel.COMPLETE,
notes = "",
method = "getParent",
args = {}
)
public void test_getParent() {
PublicClassLoader pcl = new PublicClassLoader();
assertNotNull(pcl.getParent());
ClassLoader cl = getClass().getClassLoader().getParent();
assertNotNull(cl);
SecurityManager sm = new SecurityManager() {
final String perName = "getClassLoader";
public void checkPermission(Permission perm) {
if (perm.getName().equals(perName)) {
throw new SecurityException();
}
}
};
SecurityManager oldSm = System.getSecurityManager();
System.setSecurityManager(sm);
try {
getClass().getClassLoader().getParent();
fail("Should throw SecurityException");
} catch (SecurityException e) {
// expected
} finally {
System.setSecurityManager(oldSm);
}
}
@TestTargetNew(
level = TestLevel.COMPLETE,
notes = "",
method = "getResources",
args = {java.lang.String.class}
)
public void test_getResourcesLjava_lang_String() {
Enumeration<java.net.URL> urls = null;
FileInputStream fis = null;
try {
urls = getClass().getClassLoader().getResources("HelloWorld.txt");
URL url = urls.nextElement();
fis = new FileInputStream(url.getFile());
byte [] array = new byte[13];
fis.read(array);
assertEquals("Hello, World.", new String(array));
} catch (IOException e) {
} finally {
try {
fis.close();
} catch(Exception e) {}
}
assertNull(getClass().getClassLoader()
.getResource("not.found.resource"));
}
@TestTargetNew(
level = TestLevel.COMPLETE,
notes = "",
method = "definePackage",
args = {java.lang.String.class, java.lang.String.class,
java.lang.String.class, java.lang.String.class,
java.lang.String.class, java.lang.String.class,
java.lang.String.class, java.net.URL.class }
)
public void test_definePackage() {
PackageClassLoader pcl = new PackageClassLoader(
getClass().getClassLoader());
String [] packageProperties = { "test.package", "title", "1.0",
"Vendor", "Title", "1.1", "implementation vendor"};
URL url = null;
try {
url = new URL("file:");
} catch (MalformedURLException e) {
fail("MalformedURLException was thrown.");
}
pcl.definePackage(packageProperties[0],
packageProperties[1],
packageProperties[2],
packageProperties[3],
packageProperties[4],
packageProperties[5],
packageProperties[6],
url);
Package pack = pcl.getPackage(packageProperties[0]);
assertEquals(packageProperties[1], pack.getSpecificationTitle());
assertEquals(packageProperties[2], pack.getSpecificationVersion());
assertEquals(packageProperties[3], pack.getSpecificationVendor());
assertEquals(packageProperties[4], pack.getImplementationTitle());
assertEquals(packageProperties[5], pack.getImplementationVersion());
assertEquals(packageProperties[6], pack.getImplementationVendor());
assertTrue(pack.isSealed(url));
assertTrue(pack.isSealed());
try {
pcl.definePackage(packageProperties[0],
packageProperties[1],
packageProperties[2],
packageProperties[3],
packageProperties[4],
packageProperties[5],
packageProperties[6],
null);
fail("IllegalArgumentException was not thrown.");
} catch(IllegalArgumentException iae) {
//expected
}
pcl.definePackage("test.package.test", null, null, null, null,
null, null, null);
pack = pcl.getPackage("test.package.test");
assertNull(pack.getSpecificationTitle());
assertNull(pack.getSpecificationVersion());
assertNull(pack.getSpecificationVendor());
assertNull(pack.getImplementationTitle());
assertNull(pack.getImplementationVersion());
assertNull(pack.getImplementationVendor());
assertFalse(pack.isSealed());
}
@TestTargetNew(
level = TestLevel.COMPLETE,
notes = "",
method = "findClass",
args = {java.lang.String.class}
)
@AndroidOnly("findClass method throws ClassNotFoundException exception.")
public void test_findClass(){
try {
PackageClassLoader pcl = new PackageClassLoader(
getClass().getClassLoader());
pcl.findClass(getClass().getPackage().getName() + ".A");
fail("ClassNotFoundException was not thrown.");
} catch(ClassNotFoundException cnfe) {
//expected
}
try {
PackageClassLoader pcl = new PackageClassLoader(
getClass().getClassLoader());
pcl.findClass("TestClass");
fail("ClassNotFoundException was not thrown.");
} catch(ClassNotFoundException cnfe) {
//expected
}
}
@TestTargetNew(
level = TestLevel.COMPLETE,
notes = "",
method = "findLibrary",
args = {java.lang.String.class}
)
@AndroidOnly("findLibrary method is not supported, it returns null.")
public void test_findLibrary() {
PackageClassLoader pcl = new PackageClassLoader(
getClass().getClassLoader());
assertNull(pcl.findLibrary("libjvm.so"));
}
@TestTargetNew(
level = TestLevel.COMPLETE,
notes = "",
method = "findResource",
args = {java.lang.String.class}
)
@AndroidOnly("findResource method is not supported, it returns null.")
public void test_findResourceLjava_lang_String() {
assertNull(new PackageClassLoader(
getClass().getClassLoader()).findResource("hyts_Foo.c"));
}
@TestTargetNew(
level = TestLevel.COMPLETE,
notes = "",
method = "findResources",
args = {java.lang.String.class}
)
@AndroidOnly("findResources method is not supported, it returns " +
"empty Enumeration.")
public void test_findResourcesLjava_lang_String() throws IOException {
assertFalse(new PackageClassLoader(
getClass().getClassLoader()).findResources("hyts_Foo.c").
hasMoreElements());
}
@TestTargetNew(
level = TestLevel.COMPLETE,
notes = "",
method = "findSystemClass",
args = {java.lang.String.class}
)
public void test_findSystemClass() {
PackageClassLoader pcl = new PackageClassLoader(
getClass().getClassLoader());
Class [] classes = { String.class, Integer.class, Object.class,
Object[].class };
for(Class clazz:classes) {
try {
String className = clazz.getName();
assertEquals(clazz, pcl.findSystemClazz(className));
} catch(ClassNotFoundException cnfe) {
fail("ClassNotFoundException was thrown: " + cnfe.getMessage());
}
}
try {
pcl.findSystemClazz("unknownClass");
fail("ClassNotFoundException was not thrown.");
} catch(ClassNotFoundException cnfe) {
//expected
}
}
@TestTargetNew(
level = TestLevel.COMPLETE,
notes = "",
method = "findLoadedClass",
args = {java.lang.String.class }
)
public void test_findLoadedClass() {
PackageClassLoader pcl = new PackageClassLoader(
getClass().getClassLoader());
Class [] classes = { A.class, PublicTestClass.class,
TestAnnotation.class, TestClass1.class };
for(Class clazz:classes) {
String className = clazz.getName();
assertNull(pcl.findLoadedClazz(className));
}
assertNull(pcl.findLoadedClazz("unknownClass"));
}
@TestTargets({
@TestTargetNew(
level = TestLevel.NOT_NECESSARY,
notes = "setClassAssertionStatus is not supported.",
method = "setClassAssertionStatus",
args = {java.lang.String.class, boolean.class}
),
@TestTargetNew(
level = TestLevel.NOT_NECESSARY,
notes = "setDefaultAssertionStatus is not supported.",
method = "setDefaultAssertionStatus",
args = {boolean.class}
),
@TestTargetNew(
level = TestLevel.NOT_NECESSARY,
notes = "setPackageAssertionStatus is not supported.",
method = "setPackageAssertionStatus",
args = {java.lang.String.class, boolean.class}
),
@TestTargetNew(
level = TestLevel.NOT_NECESSARY,
notes = "resolveClass is not supported.",
method = "resolveClass",
args = {java.lang.Class.class}
),
@TestTargetNew(
level = TestLevel.NOT_NECESSARY,
notes = "setSigners is not supported.",
method = "setSigners",
args = {java.lang.Class.class, java.lang.Object[].class}
)
})
public void test_notSupported() {
getClass().getClassLoader().setClassAssertionStatus(getName(), true);
getClass().getClassLoader().setDefaultAssertionStatus(true);
getClass().getClassLoader().setPackageAssertionStatus(
getClass().getPackage().getName(), true);
}
}
class DynamicPolicy extends Policy {
public PermissionCollection pc;
@Override
public PermissionCollection getPermissions(ProtectionDomain pd) {
return pc;
}
@Override
public PermissionCollection getPermissions(CodeSource codesource) {
return pc;
}
@Override
public void refresh() {
}
}
class A {
}
class Ldr extends ClassLoader {
/*
* These bytes are the content of the file
* /org/apache/harmony/luni/tests/java/lang/A.class
*/
byte[] classBytes = new byte[] { -54, -2, -70, -66, 0, 0, 0, 49, 0, 16, 7,
0, 2, 1, 0, 41, 111, 114, 103, 47, 97, 112, 97, 99, 104, 101, 47,
104, 97, 114, 109, 111, 110, 121, 47, 108, 117, 110, 105, 47, 116,
101, 115, 116, 115, 47, 106, 97, 118, 97, 47, 108, 97, 110, 103, 47,
65, 7, 0, 4, 1, 0, 16, 106, 97, 118, 97, 47, 108, 97, 110, 103, 47,
79, 98, 106, 101, 99, 116, 1, 0, 6, 60, 105, 110, 105, 116, 62, 1,
0, 3, 40, 41, 86, 1, 0, 4, 67, 111, 100, 101, 10, 0, 3, 0, 9, 12, 0,
5, 0, 6, 1, 0, 15, 76, 105, 110, 101, 78, 117, 109, 98, 101, 114,
84, 97, 98, 108, 101, 1, 0, 18, 76, 111, 99, 97, 108, 86, 97, 114,
105, 97, 98, 108, 101, 84, 97, 98, 108, 101, 1, 0, 4, 116, 104, 105,
115, 1, 0, 43, 76, 111, 114, 103, 47, 97, 112, 97, 99, 104, 101, 47,
104, 97, 114, 109, 111, 110, 121, 47, 108, 117, 110, 105, 47, 116,
101, 115, 116, 115, 47, 106, 97, 118, 97, 47, 108, 97, 110, 103, 47,
65, 59, 1, 0, 10, 83, 111, 117, 114, 99, 101, 70, 105, 108, 101, 1,
0, 20, 67, 108, 97, 115, 115, 76, 111, 97, 100, 101, 114, 84, 101,
115, 116, 46, 106, 97, 118, 97, 0, 32, 0, 1, 0, 3, 0, 0, 0, 0, 0, 1,
0, 0, 0, 5, 0, 6, 0, 1, 0, 7, 0, 0, 0, 47, 0, 1, 0, 1, 0, 0, 0, 5,
42, -73, 0, 8, -79, 0, 0, 0, 2, 0, 10, 0, 0, 0, 6, 0, 1, 0, 0, 4,
-128, 0, 11, 0, 0, 0, 12, 0, 1, 0, 0, 0, 5, 0, 12, 0, 13, 0, 0, 0,
1, 0, 14, 0, 0, 0, 2, 0, 15 };
public static final int TEST_CASE_DEFINE_0 = 0;
public static final int TEST_CASE_DEFINE_1 = 1;
public static final int TEST_CASE_DEFINE_2 = 2;
public static final int TEST_CASE_DEFINE_3 = 3;
@SuppressWarnings("deprecation")
public Class<?> define(int len, int testCase) throws Exception {
if(len < 0) len = classBytes.length;
Class<?> clazz = null;
String className = "org.apache.harmony.luni.tests.java.lang.A";
switch(testCase) {
case TEST_CASE_DEFINE_0:
clazz = defineClass(className, classBytes, 0, len);
break;
case TEST_CASE_DEFINE_1:
clazz = defineClass(classBytes, 0, len);
break;
case TEST_CASE_DEFINE_2:
clazz = defineClass(className, classBytes, 0, len,
getClass().getProtectionDomain());
break;
case TEST_CASE_DEFINE_3:
ByteBuffer bb = ByteBuffer.wrap(classBytes);
clazz = defineClass(className,
bb, getClass().getProtectionDomain());
break;
}
return clazz;
}
public Class<?> define(int testCase) throws Exception {
return define(-1, testCase);
}
}
class PackageClassLoader extends ClassLoader {
public PackageClassLoader() {
super();
}
public PackageClassLoader(ClassLoader parent) {
super(parent);
}
public Package definePackage(String name,
String specTitle,
String specVersion,
String specVendor,
String implTitle,
String implVersion,
String implVendor,
URL sealBase)
throws IllegalArgumentException {
return super.definePackage(name, specTitle, specVersion,
specVendor, implTitle, implVersion, implVendor, sealBase);
}
public Package getPackage(String name) {
return super.getPackage(name);
}
public Package[] getPackages() {
return super.getPackages();
}
public Class<?> findClass(String name)
throws ClassNotFoundException {
return super.findClass(name);
}
public String findLibrary(String libname) {
return super.findLibrary(libname);
}
public Class<?> loadClass(String name, boolean resolve)
throws ClassNotFoundException {
return super.loadClass(name, resolve);
}
public URL findResource(String name) {
return super.findResource(name);
}
public Enumeration<URL> findResources(String resName)
throws IOException {
return super.findResources(resName);
}
public Class<?> findSystemClazz(String name) throws ClassNotFoundException {
return super.findSystemClass(name);
}
public Class<?> findLoadedClazz(String name) {
return super.findLoadedClass(name);
}
}
| false | false | null | null |
diff --git a/frost-wot/source/frost/MessageObject.java b/frost-wot/source/frost/MessageObject.java
index f860bdc4..a322d93d 100644
--- a/frost-wot/source/frost/MessageObject.java
+++ b/frost-wot/source/frost/MessageObject.java
@@ -1,283 +1,285 @@
/*
MessageObject.java / Frost
Copyright (C) 2001 Jan-Thomas Czornack <[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 2 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, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
package frost;
import java.io.File;
import java.util.Vector;
public class MessageObject {
char[] evilChars = {'/', '\\', '*', '=', '|', '&', '#', '\"', '<', '>'}; // will be converted to _
String board, content, from, subject, date, time, index, publicKey, newContent;
File file;
/**Get*/
public String getNewContent() {
return newContent;
}
//TODO: should return AttachmentObjects (to create)
// newContent is created here and contains whole msg without the found board tags
public Vector getAttachments() {
Vector table = new Vector();
int pos = 0;
int start = content.indexOf("<attached>");
int end = content.indexOf("</attached>");
newContent="";
while (start != -1 && end != -1) {
newContent += content.substring(pos, start).trim();
int spaces = content.indexOf(" * ", start);
String filename = (content.substring(start + "<attached>".length(), spaces)).trim();
String chkKey = (content.substring(spaces + " * ".length(), end)).trim();
Vector rows = new Vector();
rows.add(filename);
rows.add(chkKey);
table.add(rows);
pos = end + "</attached>".length();
start = content.indexOf("<attached>", pos);
end = content.indexOf("</attached>", pos);
}
newContent += content.substring(pos, content.length()).trim();
return table;
}
// TODO: should return AttachedBoards (to create)
// newContent is created here and contains whole msg without the found board tags
public Vector getBoards()
{
// TODO: this code does not care if the <board> or </board> appears somewhere in the content
// if e.g. a <board></board> occurs in message, this throw a NullPointerException
Vector table = new Vector();
int pos = 0;
int start = content.indexOf("<board>");
int end = content.indexOf("</board>", start);
newContent = "";
while (start != -1 && end != -1)
{
try
{
int boardPartLength = end - ( start + "<board>".length() );
// must be at least 14, 1 char boardnamwe, 2 times " * " and keys="N/A"
if (boardPartLength < 14)
{
continue;
}
newContent += content.substring(pos, start).trim();
int spaces = content.indexOf(" * ", start);
int spaces2 = content.indexOf(" * ", spaces + 1);
//System.out.println("* at " + spaces + " " + spaces2);
String boardName = (content.substring(start + "<board>".length(), spaces)).trim();
String pubKey = (content.substring(spaces + " * ".length(), spaces2)).trim();
String privKey = (content.substring(spaces2 + " * ".length(), end)).trim();
Vector rows = new Vector();
rows.add(boardName);
rows.add(pubKey);
rows.add(privKey);
table.add(rows);
}
catch (RuntimeException e) // on wrong format a NullPointerException is thrown
{
System.out.println("Error in format of attached boards, skipping 1 entry.");
}
// maybe try next entry
pos = end + "</board>".length();
start = content.indexOf("<board>", pos);
end = content.indexOf("</board>", pos);
}
newContent += content.substring(pos, content.length()).trim();
return table;
}
public String getPublicKey() {
return publicKey;
}
public String getBoard() {
return board;
}
public String getContent() {
return content;
}
public String getFrom() {
return from;
}
public String getSubject() {
return subject;
}
public String getDate() {
return date;
}
public String getTime() {
return time;
}
public String getIndex() {
return index;
}
public File getFile() {
return file;
}
public String[] getRow() {
String fatFrom = from;
File newMessage = new File(file.getPath() + ".lck");
if (newMessage.isFile()) {
// this is the point where new messages get its bold look,
// this is resetted in TOF.evalSelection to non-bold on first view
fatFrom = new StringBuffer().append("<html><b>").append(from).append("</b></html>").toString();
}
if ( (content.indexOf("<attached>") != -1 && content.indexOf("</attached>") != -1) ||
(content.indexOf("<board>") != -1 && content.indexOf("</board>") != -1) ){
if (fatFrom.startsWith("<html><b>"))
fatFrom = "<html><b><font color=\"blue\">" + from + "</font></b></html>";
else
fatFrom = "<html><font color=\"blue\">" + from + "</font></html>";
}
//String[] row = {index, fatFrom, subject, date + " " + time};
String[] row = {index, fatFrom, subject, date, time};
return row;
}
/**Set*/
public void setBoard(String board) {
this.board = board;
}
public void setContent(String content) {
this.content = content;
}
public void setFrom(String from) {
this.from = from;
}
public void setSubject(String subject) {
this.subject = subject;
}
public void setDate(String date) {
this.date = date;
}
public void setTime(String time) {
this.time = time;
}
public void setFile(File file) {
this.file = file;
}
public void setIndex(String index) {
this.index = index;
}
public boolean isValid() {
if (date.equals(""))
return false;
if (time.equals(""))
return false;
if (subject.equals(""))
return false;
if (board.equals(""))
return false;
if (from.equals(""))
return false;
if (from.length() > 256)
return false;
if (subject.length() > 256)
return false;
if (board.length() > 256)
return false;
if (date.length() > 22)
return false;
+ // FIXME: this could be larger, or not?
+ /*
if (content.length() > 32000)
- return false;
+ return false;*/
return true;
}
/**Set all values*/
public void analyzeFile()
{
try {
String message = new String(FileAccess.readByteArray(file));
if( !message.startsWith("Empty") )
{
Vector lines = FileAccess.readLines(file);
this.board = SettingsFun.getValue(lines, "board");
this.from = SettingsFun.getValue(lines, "from");
this.subject = SettingsFun.getValue(lines, "subject");
this.board = SettingsFun.getValue(lines, "board");
this.date = SettingsFun.getValue(lines, "date");
this.time = SettingsFun.getValue(lines, "time");
this.publicKey = SettingsFun.getValue(lines, "publicKey");
int offset = 17;
int contentStart = message.indexOf("--- message ---\r\n");
if( contentStart == -1 )
{
contentStart = message.indexOf("--- message ---");
offset = 15;
}
if( contentStart != -1 )
this.content = message.substring(contentStart + offset, message.length());
else
this.content = "";
String filename = file.getName();
this.index = (filename.substring(filename.lastIndexOf("-") + 1, filename.lastIndexOf(".txt"))).trim();
for( int i = 0; i < evilChars.length; i++ )
{
this.from = this.from.replace(evilChars[i], '_');
this.subject = this.subject.replace(evilChars[i], '_');
this.date = this.date.replace(evilChars[i], '_');
this.time = this.time.replace(evilChars[i], '_');
}
}
} catch(Exception ex) {
System.out.println("ERROR in MessageObject: could not read file '"+file.getPath()+"'");
ex.printStackTrace();
}
}
/**Constructor*/
public MessageObject(File file)
{
this();
this.file = file;
analyzeFile();
}
/**Constructor*/
public MessageObject() {
this.board = "";
this.from = "";
this.subject = "";
this.board = "";
this.date = "";
this.time = "";
this.content = "";
this.publicKey = "";
}
}
diff --git a/frost-wot/source/frost/threads/MessageDownloadThread.java b/frost-wot/source/frost/threads/MessageDownloadThread.java
index 2e936175..5bbf3704 100644
--- a/frost-wot/source/frost/threads/MessageDownloadThread.java
+++ b/frost-wot/source/frost/threads/MessageDownloadThread.java
@@ -1,341 +1,342 @@
/*
MessageDownloadThread.java / Frost
Copyright (C) 2001 Jan-Thomas Czornack <[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 2 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, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
package frost.threads;
import java.io.File;
import java.util.*;
import frost.*;
import frost.gui.objects.*;
import frost.FcpTools.*;
/**
* Downloads messages
*/
public class MessageDownloadThread extends BoardUpdateThreadObject implements BoardUpdateThread
{
public FrostBoardObject board;
private int downloadHtl;
private String keypool;
private int maxMessageDownload;
private String destination;
private boolean secure;
private String publicKey;
private boolean flagNew;
public int getThreadType()
{
if( flagNew )
{
return BoardUpdateThread.MSG_DNLOAD_TODAY;
}
else
{
return BoardUpdateThread.MSG_DNLOAD_BACK;
}
}
public void run()
{
notifyThreadStarted(this);
try {
String tofType;
if( flagNew )
tofType="TOF Download";
else
tofType="TOF Download Back";
// Wait some random time to speed up the update of the TOF table
// ... and to not to flood the node
int waitTime = (int)(Math.random() * 5000); // wait a max. of 5 seconds between start of threads
mixed.wait(waitTime);
Core.getOut().println("TOFDN: "+tofType + " Thread started for board "+board.toString());
if( isInterrupted() )
{
notifyThreadFinished(this);
return;
}
// switch public / secure board
if( board.isPublicBoard() == false )
{
publicKey = board.getPublicKey();
secure = true;
}
else // public board
{
secure = false;
}
GregorianCalendar cal= new GregorianCalendar();
cal.setTimeZone(TimeZone.getTimeZone("GMT"));
if( this.flagNew )
{
// download only actual date
downloadDate(cal);
}
else
{
// download up to maxMessages days to the past
GregorianCalendar firstDate = new GregorianCalendar();
firstDate.setTimeZone(TimeZone.getTimeZone("GMT"));
firstDate.set(Calendar.YEAR, 2001);
firstDate.set(Calendar.MONTH, 5);
firstDate.set(Calendar.DATE, 11);
int counter=0;
while( !isInterrupted() && cal.after(firstDate) && counter < maxMessageDownload )
{
counter++;
cal.add(Calendar.DATE, -1); // Yesterday
downloadDate(cal);
}
}
Core.getOut().println("TOFDN: "+tofType+" Thread stopped for board "+board.toString());
}
catch(Throwable t)
{
Core.getOut().println(Thread.currentThread().getName()+": Oo. Exception in MessageDownloadThread:");
t.printStackTrace(Core.getOut());
}
notifyThreadFinished(this);
}
/**Returns true if message is duplicate*/
private boolean exists(File file)
{
File[] fileList = (file.getParentFile()).listFiles();
if( fileList != null )
{
for( int i = 0; i < fileList.length; i++ )
{
if( ! fileList[i].equals(file) &&
fileList[i].getName().indexOf(board.getBoardFilename()) != -1 &&
file.getName().indexOf(board.getBoardFilename()) != -1 )
{
String one = FileAccess.readFile(file);
String two = FileAccess.readFile(fileList[i]);
if( one.equals(two) )
return true;
}
}
}
return false;
}
protected void downloadDate(GregorianCalendar calDL)
{
VerifyableMessageObject currentMsg=null;
String dirdate = DateFun.getDateOfCalendar(calDL);
String fileSeparator = System.getProperty("file.separator");
destination = new StringBuffer().append(keypool).append(board.getBoardFilename())
.append(fileSeparator)
.append(dirdate).append(fileSeparator).toString();
File makedir = new File(destination);
if( !makedir.exists() )
{
makedir.mkdirs();
}
File checkLockfile = new File(destination + "locked.lck");
int index = 0;
int failures = 0;
int maxFailures;
if( flagNew )
{
maxFailures = 3; // skip a maximum of 2 empty slots for today
}
else
{
maxFailures = 2; // skip a maximum of 1 empty slot for backload
}
while( failures < maxFailures && (flagNew || !checkLockfile.exists()) )
{
try { //make a wide net so that evil messages don't kill us
String val = new StringBuffer().append(destination)
.append(System.currentTimeMillis())
.append(".txt.msg").toString();
File testMe = new File(val);
val = new StringBuffer().append(destination)
.append(dirdate)
.append("-")
.append(board.getBoardFilename())
.append("-")
.append(index)
.append(".txt").toString();
File testMe2 = new File(val);
if( testMe2.length() > 0 ) // already downloaded
{
index++;
failures = 0;
}
else
{
String downKey = null;
if( secure )
{
downKey = new StringBuffer().append(publicKey)
.append("/")
.append(board.getBoardFilename())
.append("/")
.append(dirdate)
.append("-")
.append(index)
.append(".txt").toString();
}
else
{
downKey = new StringBuffer().append("KSK@frost/message/")
.append(frame1.frostSettings.getValue("messageBase"))
.append("/")
.append(dirdate)
.append("-")
.append(board.getBoardFilename())
.append("-")
.append(index)
.append(".txt").toString();
}
try {
FcpRequest.getFile(downKey, null, testMe, downloadHtl, false);
mixed.wait(111); // wait some time to not to hurt the node on next retry
}
catch(Throwable t)
{
Core.getOut().println(Thread.currentThread().getName()+" :TOFDN - Error in run()/FcpRequest.getFile:");
t.printStackTrace(Core.getOut());
}
// Download successful?
if( testMe.length() > 0 )
{
testMe.renameTo(testMe2);
testMe=testMe2;
// Does a duplicate message exist?
if( !exists(testMe) )
{
//test if encrypted and decrypt
String contents = FileAccess.readFileRaw(testMe);
//Core.getOut().println(contents);
String plaintext;
int encstart = contents.indexOf("==== Frost Signed+Encrypted Message ====");
if( encstart != -1 )
{
Core.getOut().println("TOFDN: Decrypting message ...");
plaintext = frame1.getCrypto().decrypt(contents.substring(encstart,contents.length()),
frame1.getMyId().getPrivKey());
contents = contents.substring(0,encstart) + plaintext;
// Core.getOut().println(contents);
FileAccess.writeFile(contents,testMe);
}
currentMsg = new FrostMessageObject(testMe);
if( currentMsg.getSubject().trim().indexOf("ENCRYPTED MSG FOR") != -1 &&
currentMsg.getSubject().indexOf(frame1.getMyId().getName()) == -1 )
{
Core.getOut().println("TOFDN: Message is encrypted for someone else.");
//testMe.delete();
FileAccess.writeFile("Empty", testMe); // no more checking if for me, no more downloading
index++;
continue;
}
// verify the message
currentMsg.verifyIncoming( calDL );
File sig = new File(testMe.getPath() + ".sig");
// Is this a valid message?
if( currentMsg.isValid() )
{
if( TOF.blocked(currentMsg,board) && testMe.length() > 0 )
{
board.incBlocked();
Core.getOut().println("\nTOFDN: ########### blocked message for board '"+board.toString()+"' #########\n");
}
else
{
frame1.displayNewMessageIcon(true);
String[] header = {SettingsFun.getValue(testMe, "board"),
SettingsFun.getValue(testMe, "from"),
SettingsFun.getValue(testMe, "subject"),
SettingsFun.getValue(testMe, "date") + " " +
SettingsFun.getValue(testMe, "time")};
if( header.length == 4 )
frame1.newMessageHeader = new StringBuffer().append(" ")
.append(header[0]).append(" : ").append(header[1]).append(" - ")
.append(header[2]).append(" (").append(header[3]).append(")").toString();
FileAccess.writeFile("This message is new!", testMe.getPath() + ".lck");
// add new message or notify of arrival
TOF.addNewMessageToTable(testMe, board);
}
}
else
{
FileAccess.writeFile("Empty", testMe);
}
}
else
{ // duplicate message
+ // FIXME: check for real double! this fails for me and an msg file containing "Empty"
Core.getOut().println(Thread.currentThread().getName()+": TOFDN: ****** Duplicate Message : " + testMe.getName() + " *****");
FileAccess.writeFile("Empty", testMe);
}
index++;
failures = 0;
}
else
{
/* if( !flagNew )
{
Core.getOut().println("TOFDN: *** Increased TOF index for board '"+board.toString()+"' ***");
}*/
failures++;
index++;
}
}
if( isInterrupted() )
return;
}catch(Throwable t) {
t.printStackTrace(Core.getOut());
index++;
}
} // end-of: while
}
/**Constructor*/ //
public MessageDownloadThread(boolean fn, FrostBoardObject boa, int dlHtl, String kpool, String maxmsg)
{
super(boa);
this.flagNew = fn;
this.board = boa;
this.downloadHtl = dlHtl;
this.keypool = kpool;
this.maxMessageDownload = Integer.parseInt(maxmsg);
}
}
| false | false | null | null |
diff --git a/org.commonreality/src/org/commonreality/time/impl/net/NetworkedSetableClock.java b/org.commonreality/src/org/commonreality/time/impl/net/NetworkedSetableClock.java
index 5dcf6c5..8b965d8 100644
--- a/org.commonreality/src/org/commonreality/time/impl/net/NetworkedSetableClock.java
+++ b/org.commonreality/src/org/commonreality/time/impl/net/NetworkedSetableClock.java
@@ -1,143 +1,148 @@
/*
* Created on May 10, 2007 Copyright (C) 2001-6, Anthony Harrison [email protected]
* (jactr.org) 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 org.commonreality.time.impl.net;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.commonreality.message.command.time.ITimeCommand;
import org.commonreality.message.request.time.IRequestTime;
import org.commonreality.message.request.time.RequestTime;
import org.commonreality.participant.IParticipant;
import org.commonreality.time.IClock;
import org.commonreality.time.impl.BasicClock;
/**
* @author developer
*/
public class NetworkedSetableClock extends BasicClock implements IClock,
INetworkedClock
{
/**
* logger definition
*/
static private final Log LOGGER = LogFactory
.getLog(NetworkedSetableClock.class);
private ITimeCommand _currentTimeCommand;
private IParticipant _participant;
public NetworkedSetableClock(IParticipant participant)
{
_participant = participant;
setDefaultWaitTime(100);
}
@Override
protected WaitFor createWaitForTime()
{
return new WaitFor() {
@Override
public boolean shouldWait(double currentTime)
{
double targetTime = getWaitForTime();
boolean shouldWait = Double.isInfinite(currentTime)
|| targetTime - currentTime > getEpsilon();
/*
* request time change, send unshifted
*/
double requested = targetTime - getTimeShift();
- if (shouldWait) _participant.send(new RequestTime(_participant.getIdentifier(),
+
+ // always make the request.. regardless of epsilon
+
+ if (targetTime > currentTime)
+ _participant.send(new RequestTime(_participant.getIdentifier(),
requested));
if (LOGGER.isDebugEnabled())
LOGGER.debug("Waiting for " + requested + " @ " +currentTime+" "+ shouldWait);
return shouldWait;
}
};
}
@Override
protected WaitFor createWaitForAny()
{
return new WaitFor() {
@Override
public boolean shouldWait(double currentTime)
{
double targetTime = getWaitForTime();
boolean shouldWait = Double.isInfinite(currentTime)
|| Math.abs(targetTime - currentTime) <= getEpsilon();
/*
* request time change
*/
- if (shouldWait) _participant.send(new RequestTime(_participant.getIdentifier(),
+
+ _participant.send(new RequestTime(_participant.getIdentifier(),
IRequestTime.ANY_CHANGE));
return shouldWait;
}
};
}
// /**
// * @see org.commonreality.time.IClock#waitForChange()
// */
// public double waitForChange() throws InterruptedException
// {
// double now = _clock.getTime();
// while (now == _clock.getTime())
// {
// _participant.send(new RequestTime(_participant.getIdentifier(),
// IRequestTime.ANY_CHANGE));
// _clock.await(750);
// }
// return _clock.getTime();
// }
//
// /**
// * @see org.commonreality.time.IClock#waitForTime(double)
// */
// public double waitForTime(double time) throws InterruptedException
// {
// while (_clock.getTime() < time)
// {
// /*
// * request it unshifted
// */
// _participant.send(new RequestTime(_participant.getIdentifier(), time -
// _clock.getTimeShift()));
// _clock.await(750);
// }
//
// double rtn = _clock.getTime();
//
// if (time < rtn)
// if (LOGGER.isWarnEnabled())
// LOGGER.warn("Time slippage detected, wanted " + time + " got " + rtn);
//
// return rtn;
// }
public void setCurrentTimeCommand(ITimeCommand timeCommand)
{
_currentTimeCommand = timeCommand;
/*
* networked time is unshifted, so we have to shift...
*/
setTime(_currentTimeCommand.getTime() + getTimeShift());
}
}
| false | false | null | null |
diff --git a/src/com/android/launcher2/PagedView.java b/src/com/android/launcher2/PagedView.java
index 11261a57..abb9b0be 100644
--- a/src/com/android/launcher2/PagedView.java
+++ b/src/com/android/launcher2/PagedView.java
@@ -1,1254 +1,1254 @@
/*
* 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.launcher2;
import java.util.ArrayList;
import java.util.HashMap;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.os.Parcel;
import android.os.Parcelable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.ActionMode;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.Checkable;
import android.widget.LinearLayout;
import android.widget.Scroller;
import com.android.launcher.R;
/**
* An abstraction of the original Workspace which supports browsing through a
* sequential list of "pages"
*/
public abstract class PagedView extends ViewGroup {
private static final String TAG = "PagedView";
protected static final int INVALID_PAGE = -1;
// the min drag distance for a fling to register, to prevent random page shifts
private static final int MIN_LENGTH_FOR_FLING = 50;
private static final int PAGE_SNAP_ANIMATION_DURATION = 1000;
protected static final float NANOTIME_DIV = 1000000000.0f;
// the velocity at which a fling gesture will cause us to snap to the next page
protected int mSnapVelocity = 500;
protected float mSmoothingTime;
protected float mTouchX;
protected boolean mFirstLayout = true;
protected int mCurrentPage;
protected int mNextPage = INVALID_PAGE;
protected Scroller mScroller;
private VelocityTracker mVelocityTracker;
private float mDownMotionX;
private float mLastMotionX;
private float mLastMotionY;
private int mLastScreenCenter = -1;
protected final static int TOUCH_STATE_REST = 0;
protected final static int TOUCH_STATE_SCROLLING = 1;
protected final static int TOUCH_STATE_PREV_PAGE = 2;
protected final static int TOUCH_STATE_NEXT_PAGE = 3;
protected final static float ALPHA_QUANTIZE_LEVEL = 0.0001f;
protected int mTouchState = TOUCH_STATE_REST;
protected OnLongClickListener mLongClickListener;
private boolean mAllowLongPress = true;
private int mTouchSlop;
private int mPagingTouchSlop;
private int mMaximumVelocity;
protected int mPageSpacing;
protected int mPageLayoutPaddingTop;
protected int mPageLayoutPaddingBottom;
protected int mPageLayoutPaddingLeft;
protected int mPageLayoutPaddingRight;
protected int mCellCountX;
protected int mCellCountY;
protected static final int INVALID_POINTER = -1;
protected int mActivePointerId = INVALID_POINTER;
private PageSwitchListener mPageSwitchListener;
private ArrayList<Boolean> mDirtyPageContent;
private boolean mDirtyPageAlpha;
// choice modes
protected static final int CHOICE_MODE_NONE = 0;
protected static final int CHOICE_MODE_SINGLE = 1;
// Multiple selection mode is not supported by all Launcher actions atm
protected static final int CHOICE_MODE_MULTIPLE = 2;
protected int mChoiceMode;
private ActionMode mActionMode;
protected PagedViewIconCache mPageViewIconCache;
// If true, syncPages and syncPageItems will be called to refresh pages
protected boolean mContentIsRefreshable = true;
// If true, modify alpha of neighboring pages as user scrolls left/right
protected boolean mFadeInAdjacentScreens = true;
// It true, use a different slop parameter (pagingTouchSlop = 2 * touchSlop) for deciding
// to switch to a new page
protected boolean mUsePagingTouchSlop = true;
// If true, the subclass should directly update mScrollX itself in its computeScroll method
// (SmoothPagedView does this)
protected boolean mDeferScrollUpdate = false;
protected boolean mIsPageMoving = false;
/**
* Simple cache mechanism for PagedViewIcon outlines.
*/
class PagedViewIconCache {
private final HashMap<Object, Bitmap> iconOutlineCache = new HashMap<Object, Bitmap>();
public void clear() {
iconOutlineCache.clear();
}
public void addOutline(Object key, Bitmap b) {
iconOutlineCache.put(key, b);
}
public void removeOutline(Object key) {
if (iconOutlineCache.containsKey(key)) {
iconOutlineCache.remove(key);
}
}
public Bitmap getOutline(Object key) {
return iconOutlineCache.get(key);
}
}
public interface PageSwitchListener {
void onPageSwitch(View newPage, int newPageIndex);
}
public PagedView(Context context) {
this(context, null);
}
public PagedView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public PagedView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
mChoiceMode = CHOICE_MODE_NONE;
TypedArray a = context.obtainStyledAttributes(attrs,
R.styleable.PagedView, defStyle, 0);
mPageSpacing = a.getDimensionPixelSize(R.styleable.PagedView_pageSpacing, 0);
mPageLayoutPaddingTop = a.getDimensionPixelSize(
R.styleable.PagedView_pageLayoutPaddingTop, 10);
mPageLayoutPaddingBottom = a.getDimensionPixelSize(
R.styleable.PagedView_pageLayoutPaddingBottom, 10);
mPageLayoutPaddingLeft = a.getDimensionPixelSize(
R.styleable.PagedView_pageLayoutPaddingLeft, 10);
mPageLayoutPaddingRight = a.getDimensionPixelSize(
R.styleable.PagedView_pageLayoutPaddingRight, 10);
a.recycle();
setHapticFeedbackEnabled(false);
init();
}
/**
* Initializes various states for this workspace.
*/
protected void init() {
mDirtyPageContent = new ArrayList<Boolean>();
mDirtyPageContent.ensureCapacity(32);
mPageViewIconCache = new PagedViewIconCache();
mScroller = new Scroller(getContext());
mCurrentPage = 0;
final ViewConfiguration configuration = ViewConfiguration.get(getContext());
mTouchSlop = configuration.getScaledTouchSlop();
mPagingTouchSlop = configuration.getScaledPagingTouchSlop();
mMaximumVelocity = configuration.getScaledMaximumFlingVelocity();
}
public void setPageSwitchListener(PageSwitchListener pageSwitchListener) {
mPageSwitchListener = pageSwitchListener;
if (mPageSwitchListener != null) {
mPageSwitchListener.onPageSwitch(getPageAt(mCurrentPage), mCurrentPage);
}
}
/**
* Returns the index of the currently displayed page.
*
* @return The index of the currently displayed page.
*/
int getCurrentPage() {
return mCurrentPage;
}
int getPageCount() {
return getChildCount();
}
View getPageAt(int index) {
return getChildAt(index);
}
int getScrollWidth() {
return getWidth();
}
/**
* Sets the current page.
*/
void setCurrentPage(int currentPage) {
if (!mScroller.isFinished()) mScroller.abortAnimation();
if (getChildCount() == 0) return;
mCurrentPage = Math.max(0, Math.min(currentPage, getPageCount() - 1));
int newX = getChildOffset(mCurrentPage) - getRelativeChildOffset(mCurrentPage);
scrollTo(newX, 0);
mScroller.setFinalX(newX);
invalidate();
notifyPageSwitchListener();
}
protected void notifyPageSwitchListener() {
if (mPageSwitchListener != null) {
mPageSwitchListener.onPageSwitch(getPageAt(mCurrentPage), mCurrentPage);
}
}
private void pageBeginMoving() {
mIsPageMoving = true;
onPageBeginMoving();
}
private void pageEndMoving() {
onPageEndMoving();
mIsPageMoving = false;
}
// a method that subclasses can override to add behavior
protected void onPageBeginMoving() {
}
// a method that subclasses can override to add behavior
protected void onPageEndMoving() {
}
/**
* Registers the specified listener on each page contained in this workspace.
*
* @param l The listener used to respond to long clicks.
*/
@Override
public void setOnLongClickListener(OnLongClickListener l) {
mLongClickListener = l;
final int count = getPageCount();
for (int i = 0; i < count; i++) {
getPageAt(i).setOnLongClickListener(l);
}
}
@Override
public void scrollTo(int x, int y) {
super.scrollTo(x, y);
mTouchX = x;
mSmoothingTime = System.nanoTime() / NANOTIME_DIV;
}
// we moved this functionality to a helper function so SmoothPagedView can reuse it
protected boolean computeScrollHelper() {
if (mScroller.computeScrollOffset()) {
mDirtyPageAlpha = true;
scrollTo(mScroller.getCurrX(), mScroller.getCurrY());
invalidate();
return true;
} else if (mNextPage != INVALID_PAGE) {
mDirtyPageAlpha = true;
mCurrentPage = Math.max(0, Math.min(mNextPage, getPageCount() - 1));
mNextPage = INVALID_PAGE;
notifyPageSwitchListener();
pageEndMoving();
return true;
}
return false;
}
@Override
public void computeScroll() {
computeScrollHelper();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
final int widthMode = MeasureSpec.getMode(widthMeasureSpec);
final int widthSize = MeasureSpec.getSize(widthMeasureSpec);
if (widthMode != MeasureSpec.EXACTLY) {
throw new IllegalStateException("Workspace can only be used in EXACTLY mode.");
}
final int heightMode = MeasureSpec.getMode(heightMeasureSpec);
final int heightSize = MeasureSpec.getSize(heightMeasureSpec);
if (heightMode != MeasureSpec.EXACTLY) {
throw new IllegalStateException("Workspace can only be used in EXACTLY mode.");
}
// The children are given the same width and height as the workspace
// unless they were set to WRAP_CONTENT
final int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
// disallowing padding in paged view (just pass 0)
final View child = getChildAt(i);
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
int childWidthMode;
if (lp.width == LayoutParams.WRAP_CONTENT) {
childWidthMode = MeasureSpec.AT_MOST;
} else {
childWidthMode = MeasureSpec.EXACTLY;
}
int childHeightMode;
if (lp.height == LayoutParams.WRAP_CONTENT) {
childHeightMode = MeasureSpec.AT_MOST;
} else {
childHeightMode = MeasureSpec.EXACTLY;
}
final int childWidthMeasureSpec =
MeasureSpec.makeMeasureSpec(widthSize, childWidthMode);
final int childHeightMeasureSpec =
MeasureSpec.makeMeasureSpec(heightSize, childHeightMode);
child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
}
setMeasuredDimension(widthSize, heightSize);
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
if (mFirstLayout && mCurrentPage >= 0 && mCurrentPage < getChildCount()) {
setHorizontalScrollBarEnabled(false);
int newX = getChildOffset(mCurrentPage) - getRelativeChildOffset(mCurrentPage);
scrollTo(newX, 0);
mScroller.setFinalX(newX);
setHorizontalScrollBarEnabled(true);
mFirstLayout = false;
}
final int childCount = getChildCount();
int childLeft = 0;
if (childCount > 0) {
childLeft = getRelativeChildOffset(0);
}
for (int i = 0; i < childCount; i++) {
final View child = getChildAt(i);
if (child.getVisibility() != View.GONE) {
final int childWidth = child.getMeasuredWidth();
final int childHeight = (getMeasuredHeight() - child.getMeasuredHeight()) / 2;
child.layout(childLeft, childHeight,
childLeft + childWidth, childHeight + child.getMeasuredHeight());
childLeft += childWidth + mPageSpacing;
}
}
}
protected void updateAdjacentPagesAlpha() {
if (mFadeInAdjacentScreens) {
if (mDirtyPageAlpha || (mTouchState == TOUCH_STATE_SCROLLING) || !mScroller.isFinished()) {
int halfScreenSize = getMeasuredWidth() / 2;
int screenCenter = mScrollX + halfScreenSize;
final int childCount = getChildCount();
for (int i = 0; i < childCount; ++i) {
View layout = (View) getChildAt(i);
int childWidth = layout.getMeasuredWidth();
int halfChildWidth = (childWidth / 2);
int childCenter = getChildOffset(i) + halfChildWidth;
// On the first layout, we may not have a width nor a proper offset, so for now
// we should just assume full page width (and calculate the offset according to
// that).
if (childWidth <= 0) {
childWidth = getMeasuredWidth();
childCenter = (i * childWidth) + (childWidth / 2);
}
int d = halfChildWidth;
int distanceFromScreenCenter = childCenter - screenCenter;
if (distanceFromScreenCenter > 0) {
if (i > 0) {
d += getChildAt(i - 1).getMeasuredWidth() / 2;
}
} else {
if (i < childCount - 1) {
d += getChildAt(i + 1).getMeasuredWidth() / 2;
}
}
d += mPageSpacing;
// Preventing potential divide-by-zero
d = Math.max(1, d);
float dimAlpha = (float) (Math.abs(distanceFromScreenCenter)) / d;
dimAlpha = Math.max(0.0f, Math.min(1.0f, (dimAlpha * dimAlpha)));
float alpha = 1.0f - dimAlpha;
if (alpha < ALPHA_QUANTIZE_LEVEL) {
alpha = 0.0f;
} else if (alpha > 1.0f - ALPHA_QUANTIZE_LEVEL) {
alpha = 1.0f;
}
if (Float.compare(alpha, layout.getAlpha()) != 0) {
layout.setAlpha(alpha);
}
}
mDirtyPageAlpha = false;
}
}
}
protected void screenScrolled(int screenCenter) {
}
@Override
protected void dispatchDraw(Canvas canvas) {
int halfScreenSize = getMeasuredWidth() / 2;
int screenCenter = mScrollX + halfScreenSize;
if (screenCenter != mLastScreenCenter) {
screenScrolled(screenCenter);
updateAdjacentPagesAlpha();
mLastScreenCenter = screenCenter;
}
// Find out which screens are visible; as an optimization we only call draw on them
// As an optimization, this code assumes that all pages have the same width as the 0th
// page.
final int pageCount = getChildCount();
if (pageCount > 0) {
final int pageWidth = getChildAt(0).getMeasuredWidth();
final int screenWidth = getMeasuredWidth();
int x = getRelativeChildOffset(0) + pageWidth;
int leftScreen = 0;
int rightScreen = 0;
while (x <= mScrollX) {
leftScreen++;
x += pageWidth + mPageSpacing;
// replace above line with this if you don't assume all pages have same width as 0th
// page:
// x += getChildAt(leftScreen).getMeasuredWidth();
}
rightScreen = leftScreen;
while (x < mScrollX + screenWidth) {
rightScreen++;
x += pageWidth + mPageSpacing;
// replace above line with this if you don't assume all pages have same width as 0th
// page:
//if (rightScreen < pageCount) {
// x += getChildAt(rightScreen).getMeasuredWidth();
//}
}
rightScreen = Math.min(getChildCount() - 1, rightScreen);
final long drawingTime = getDrawingTime();
for (int i = leftScreen; i <= rightScreen; i++) {
drawChild(canvas, getChildAt(i), drawingTime);
}
}
}
@Override
public boolean requestChildRectangleOnScreen(View child, Rect rectangle, boolean immediate) {
int page = indexOfChild(child);
if (page != mCurrentPage || !mScroller.isFinished()) {
snapToPage(page);
return true;
}
return false;
}
@Override
protected boolean onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect) {
int focusablePage;
if (mNextPage != INVALID_PAGE) {
focusablePage = mNextPage;
} else {
focusablePage = mCurrentPage;
}
View v = getPageAt(focusablePage);
if (v != null) {
v.requestFocus(direction, previouslyFocusedRect);
}
return false;
}
@Override
public boolean dispatchUnhandledMove(View focused, int direction) {
if (direction == View.FOCUS_LEFT) {
if (getCurrentPage() > 0) {
snapToPage(getCurrentPage() - 1);
return true;
}
} else if (direction == View.FOCUS_RIGHT) {
if (getCurrentPage() < getPageCount() - 1) {
snapToPage(getCurrentPage() + 1);
return true;
}
}
return super.dispatchUnhandledMove(focused, direction);
}
@Override
public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
if (mCurrentPage >= 0 && mCurrentPage < getPageCount()) {
getPageAt(mCurrentPage).addFocusables(views, direction);
}
if (direction == View.FOCUS_LEFT) {
if (mCurrentPage > 0) {
getPageAt(mCurrentPage - 1).addFocusables(views, direction);
}
} else if (direction == View.FOCUS_RIGHT){
if (mCurrentPage < getPageCount() - 1) {
getPageAt(mCurrentPage + 1).addFocusables(views, direction);
}
}
}
/**
* If one of our descendant views decides that it could be focused now, only
* pass that along if it's on the current page.
*
* This happens when live folders requery, and if they're off page, they
* end up calling requestFocus, which pulls it on page.
*/
@Override
public void focusableViewAvailable(View focused) {
View current = getPageAt(mCurrentPage);
View v = focused;
while (true) {
if (v == current) {
super.focusableViewAvailable(focused);
return;
}
if (v == this) {
return;
}
ViewParent parent = v.getParent();
if (parent instanceof View) {
v = (View)v.getParent();
} else {
return;
}
}
}
/**
* {@inheritDoc}
*/
@Override
public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
if (disallowIntercept) {
// We need to make sure to cancel our long press if
// a scrollable widget takes over touch events
final View currentPage = getChildAt(mCurrentPage);
currentPage.cancelLongPress();
}
super.requestDisallowInterceptTouchEvent(disallowIntercept);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
/*
* This method JUST determines whether we want to intercept the motion.
* If we return true, onTouchEvent will be called and we do the actual
* scrolling there.
*/
/*
* Shortcut the most recurring case: the user is in the dragging
* state and he is moving his finger. We want to intercept this
* motion.
*/
final int action = ev.getAction();
if ((action == MotionEvent.ACTION_MOVE) &&
(mTouchState == TOUCH_STATE_SCROLLING)) {
return true;
}
switch (action & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_MOVE: {
/*
* mIsBeingDragged == false, otherwise the shortcut would have caught it. Check
* whether the user has moved far enough from his original down touch.
*/
if (mActivePointerId != INVALID_POINTER) {
determineScrollingStart(ev);
break;
}
// if mActivePointerId is INVALID_POINTER, then we must have missed an ACTION_DOWN
// event. in that case, treat the first occurence of a move event as a ACTION_DOWN
// i.e. fall through to the next case (don't break)
// (We sometimes miss ACTION_DOWN events in Workspace because it ignores all events
// while it's small- this was causing a crash before we checked for INVALID_POINTER)
}
case MotionEvent.ACTION_DOWN: {
final float x = ev.getX();
final float y = ev.getY();
// Remember location of down touch
mDownMotionX = x;
mLastMotionX = x;
mLastMotionY = y;
mActivePointerId = ev.getPointerId(0);
mAllowLongPress = true;
/*
* If being flinged and user touches the screen, initiate drag;
* otherwise don't. mScroller.isFinished should be false when
* being flinged.
*/
final int xDist = (mScroller.getFinalX() - mScroller.getCurrX());
final boolean finishedScrolling = (mScroller.isFinished() || xDist < mTouchSlop);
if (finishedScrolling) {
mTouchState = TOUCH_STATE_REST;
mScroller.abortAnimation();
} else {
mTouchState = TOUCH_STATE_SCROLLING;
}
// check if this can be the beginning of a tap on the side of the pages
// to scroll the current page
if ((mTouchState != TOUCH_STATE_PREV_PAGE) && !handlePagingClicks() &&
(mTouchState != TOUCH_STATE_NEXT_PAGE)) {
if (getChildCount() > 0) {
int width = getMeasuredWidth();
int offset = getRelativeChildOffset(mCurrentPage);
if (x < offset - mPageSpacing) {
mTouchState = TOUCH_STATE_PREV_PAGE;
} else if (x > (width - offset + mPageSpacing)) {
mTouchState = TOUCH_STATE_NEXT_PAGE;
}
}
}
break;
}
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
mTouchState = TOUCH_STATE_REST;
mAllowLongPress = false;
mActivePointerId = INVALID_POINTER;
break;
case MotionEvent.ACTION_POINTER_UP:
onSecondaryPointerUp(ev);
break;
}
/*
* The only time we want to intercept motion events is if we are in the
* drag mode.
*/
return mTouchState != TOUCH_STATE_REST;
}
protected void animateClickFeedback(View v, final Runnable r) {
// animate the view slightly to show click feedback running some logic after it is "pressed"
Animation anim = AnimationUtils.loadAnimation(getContext(),
R.anim.paged_view_click_feedback);
anim.setAnimationListener(new AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {}
@Override
public void onAnimationRepeat(Animation animation) {
r.run();
}
@Override
public void onAnimationEnd(Animation animation) {}
});
v.startAnimation(anim);
}
/*
* Determines if we should change the touch state to start scrolling after the
* user moves their touch point too far.
*/
- private void determineScrollingStart(MotionEvent ev) {
+ protected void determineScrollingStart(MotionEvent ev) {
/*
* Locally do absolute value. mLastMotionX is set to the y value
* of the down event.
*/
final int pointerIndex = ev.findPointerIndex(mActivePointerId);
final float x = ev.getX(pointerIndex);
final float y = ev.getY(pointerIndex);
final int xDiff = (int) Math.abs(x - mLastMotionX);
final int yDiff = (int) Math.abs(y - mLastMotionY);
final int touchSlop = mTouchSlop;
boolean xPaged = xDiff > mPagingTouchSlop;
boolean xMoved = xDiff > touchSlop;
boolean yMoved = yDiff > touchSlop;
if (xMoved || yMoved) {
if (mUsePagingTouchSlop ? xPaged : xMoved) {
// Scroll if the user moved far enough along the X axis
mTouchState = TOUCH_STATE_SCROLLING;
mLastMotionX = x;
mTouchX = mScrollX;
mSmoothingTime = System.nanoTime() / NANOTIME_DIV;
pageBeginMoving();
}
// Either way, cancel any pending longpress
if (mAllowLongPress) {
mAllowLongPress = false;
// Try canceling the long press. It could also have been scheduled
// by a distant descendant, so use the mAllowLongPress flag to block
// everything
final View currentPage = getPageAt(mCurrentPage);
currentPage.cancelLongPress();
}
}
}
protected boolean handlePagingClicks() {
return false;
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
acquireVelocityTrackerAndAddMovement(ev);
final int action = ev.getAction();
switch (action & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
/*
* If being flinged and user touches, stop the fling. isFinished
* will be false if being flinged.
*/
if (!mScroller.isFinished()) {
mScroller.abortAnimation();
}
// Remember where the motion event started
mDownMotionX = mLastMotionX = ev.getX();
mActivePointerId = ev.getPointerId(0);
if (mTouchState == TOUCH_STATE_SCROLLING) {
pageBeginMoving();
}
break;
case MotionEvent.ACTION_MOVE:
if (mTouchState == TOUCH_STATE_SCROLLING) {
// Scroll to follow the motion event
final int pointerIndex = ev.findPointerIndex(mActivePointerId);
final float x = ev.getX(pointerIndex);
final int deltaX = (int) (mLastMotionX - x);
mLastMotionX = x;
int sx = getScrollX();
if (deltaX < 0) {
if (sx > 0) {
mTouchX += Math.max(-mTouchX, deltaX);
mSmoothingTime = System.nanoTime() / NANOTIME_DIV;
if (!mDeferScrollUpdate) {
scrollBy(Math.max(-sx, deltaX), 0);
} else {
// This will trigger a call to computeScroll() on next drawChild() call
invalidate();
}
}
} else if (deltaX > 0) {
final int lastChildIndex = getChildCount() - 1;
final int availableToScroll = getChildOffset(lastChildIndex) -
getRelativeChildOffset(lastChildIndex) - sx;
if (availableToScroll > 0) {
mTouchX += Math.min(availableToScroll, deltaX);
mSmoothingTime = System.nanoTime() / NANOTIME_DIV;
if (!mDeferScrollUpdate) {
scrollBy(Math.min(availableToScroll, deltaX), 0);
} else {
// This will trigger a call to computeScroll() on next drawChild() call
invalidate();
}
}
} else {
awakenScrollBars();
}
} else {
determineScrollingStart(ev);
}
break;
case MotionEvent.ACTION_UP:
if (mTouchState == TOUCH_STATE_SCROLLING) {
final int activePointerId = mActivePointerId;
final int pointerIndex = ev.findPointerIndex(activePointerId);
final float x = ev.getX(pointerIndex);
final VelocityTracker velocityTracker = mVelocityTracker;
velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
int velocityX = (int) velocityTracker.getXVelocity(activePointerId);
boolean isfling = Math.abs(mDownMotionX - x) > MIN_LENGTH_FOR_FLING;
final int snapVelocity = mSnapVelocity;
if (isfling && velocityX > snapVelocity && mCurrentPage > 0) {
snapToPageWithVelocity(mCurrentPage - 1, velocityX);
} else if (isfling && velocityX < -snapVelocity &&
mCurrentPage < getChildCount() - 1) {
snapToPageWithVelocity(mCurrentPage + 1, velocityX);
} else {
snapToDestination();
}
} else if (mTouchState == TOUCH_STATE_PREV_PAGE && !handlePagingClicks()) {
// at this point we have not moved beyond the touch slop
// (otherwise mTouchState would be TOUCH_STATE_SCROLLING), so
// we can just page
int nextPage = Math.max(0, mCurrentPage - 1);
if (nextPage != mCurrentPage) {
snapToPage(nextPage);
} else {
snapToDestination();
}
} else if (mTouchState == TOUCH_STATE_NEXT_PAGE && !handlePagingClicks()) {
// at this point we have not moved beyond the touch slop
// (otherwise mTouchState would be TOUCH_STATE_SCROLLING), so
// we can just page
int nextPage = Math.min(getChildCount() - 1, mCurrentPage + 1);
if (nextPage != mCurrentPage) {
snapToPage(nextPage);
} else {
snapToDestination();
}
}
mTouchState = TOUCH_STATE_REST;
mActivePointerId = INVALID_POINTER;
releaseVelocityTracker();
break;
case MotionEvent.ACTION_CANCEL:
if (mTouchState == TOUCH_STATE_SCROLLING) {
snapToDestination();
}
mTouchState = TOUCH_STATE_REST;
mActivePointerId = INVALID_POINTER;
releaseVelocityTracker();
break;
case MotionEvent.ACTION_POINTER_UP:
onSecondaryPointerUp(ev);
break;
}
return true;
}
private void acquireVelocityTrackerAndAddMovement(MotionEvent ev) {
if (mVelocityTracker == null) {
mVelocityTracker = VelocityTracker.obtain();
}
mVelocityTracker.addMovement(ev);
}
private void releaseVelocityTracker() {
if (mVelocityTracker != null) {
mVelocityTracker.recycle();
mVelocityTracker = null;
}
}
private void onSecondaryPointerUp(MotionEvent ev) {
final int pointerIndex = (ev.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >>
MotionEvent.ACTION_POINTER_INDEX_SHIFT;
final int pointerId = ev.getPointerId(pointerIndex);
if (pointerId == mActivePointerId) {
// This was our active pointer going up. Choose a new
// active pointer and adjust accordingly.
// TODO: Make this decision more intelligent.
final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
mLastMotionX = mDownMotionX = ev.getX(newPointerIndex);
mLastMotionY = ev.getY(newPointerIndex);
mActivePointerId = ev.getPointerId(newPointerIndex);
if (mVelocityTracker != null) {
mVelocityTracker.clear();
}
}
}
@Override
public void requestChildFocus(View child, View focused) {
super.requestChildFocus(child, focused);
int page = indexOfChild(child);
if (page >= 0 && !isInTouchMode()) {
snapToPage(page);
}
}
protected int getChildIndexForRelativeOffset(int relativeOffset) {
final int childCount = getChildCount();
int left;
int right;
for (int i = 0; i < childCount; ++i) {
left = getRelativeChildOffset(i);
right = (left + getChildAt(i).getMeasuredWidth());
if (left <= relativeOffset && relativeOffset <= right) {
return i;
}
}
return -1;
}
protected int getRelativeChildOffset(int index) {
return (getMeasuredWidth() - getChildAt(index).getMeasuredWidth()) / 2;
}
protected int getChildOffset(int index) {
if (getChildCount() == 0)
return 0;
int offset = getRelativeChildOffset(0);
for (int i = 0; i < index; ++i) {
offset += getChildAt(i).getMeasuredWidth() + mPageSpacing;
}
return offset;
}
int getPageNearestToCenterOfScreen() {
int minDistanceFromScreenCenter = getMeasuredWidth();
int minDistanceFromScreenCenterIndex = -1;
int screenCenter = mScrollX + (getMeasuredWidth() / 2);
final int childCount = getChildCount();
for (int i = 0; i < childCount; ++i) {
View layout = (View) getChildAt(i);
int childWidth = layout.getMeasuredWidth();
int halfChildWidth = (childWidth / 2);
int childCenter = getChildOffset(i) + halfChildWidth;
int distanceFromScreenCenter = Math.abs(childCenter - screenCenter);
if (distanceFromScreenCenter < minDistanceFromScreenCenter) {
minDistanceFromScreenCenter = distanceFromScreenCenter;
minDistanceFromScreenCenterIndex = i;
}
}
return minDistanceFromScreenCenterIndex;
}
protected void snapToDestination() {
snapToPage(getPageNearestToCenterOfScreen(), PAGE_SNAP_ANIMATION_DURATION);
}
protected void snapToPageWithVelocity(int whichPage, int velocity) {
// We ignore velocity in this implementation, but children (e.g. SmoothPagedView)
// can use it
snapToPage(whichPage);
}
protected void snapToPage(int whichPage) {
snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION);
}
protected void snapToPage(int whichPage, int duration) {
whichPage = Math.max(0, Math.min(whichPage, getPageCount() - 1));
int newX = getChildOffset(whichPage) - getRelativeChildOffset(whichPage);
final int sX = getScrollX();
final int delta = newX - sX;
snapToPage(whichPage, delta, duration);
}
protected void snapToPage(int whichPage, int delta, int duration) {
mNextPage = whichPage;
View focusedChild = getFocusedChild();
if (focusedChild != null && whichPage != mCurrentPage &&
focusedChild == getChildAt(mCurrentPage)) {
focusedChild.clearFocus();
}
pageBeginMoving();
awakenScrollBars(duration);
if (duration == 0) {
duration = Math.abs(delta);
}
if (!mScroller.isFinished()) mScroller.abortAnimation();
mScroller.startScroll(getScrollX(), 0, delta, 0, duration);
// only load some associated pages
loadAssociatedPages(mNextPage);
notifyPageSwitchListener();
invalidate();
}
@Override
protected Parcelable onSaveInstanceState() {
final SavedState state = new SavedState(super.onSaveInstanceState());
state.currentPage = mCurrentPage;
return state;
}
@Override
protected void onRestoreInstanceState(Parcelable state) {
SavedState savedState = (SavedState) state;
super.onRestoreInstanceState(savedState.getSuperState());
if (savedState.currentPage != -1) {
mCurrentPage = savedState.currentPage;
}
}
public void scrollLeft() {
if (mScroller.isFinished()) {
if (mCurrentPage > 0) snapToPage(mCurrentPage - 1);
} else {
if (mNextPage > 0) snapToPage(mNextPage - 1);
}
}
public void scrollRight() {
if (mScroller.isFinished()) {
if (mCurrentPage < getChildCount() -1) snapToPage(mCurrentPage + 1);
} else {
if (mNextPage < getChildCount() -1) snapToPage(mNextPage + 1);
}
}
public int getPageForView(View v) {
int result = -1;
if (v != null) {
ViewParent vp = v.getParent();
int count = getChildCount();
for (int i = 0; i < count; i++) {
if (vp == getChildAt(i)) {
return i;
}
}
}
return result;
}
/**
* @return True is long presses are still allowed for the current touch
*/
public boolean allowLongPress() {
return mAllowLongPress;
}
/**
* Set true to allow long-press events to be triggered, usually checked by
* {@link Launcher} to accept or block dpad-initiated long-presses.
*/
public void setAllowLongPress(boolean allowLongPress) {
mAllowLongPress = allowLongPress;
}
public static class SavedState extends BaseSavedState {
int currentPage = -1;
SavedState(Parcelable superState) {
super(superState);
}
private SavedState(Parcel in) {
super(in);
currentPage = in.readInt();
}
@Override
public void writeToParcel(Parcel out, int flags) {
super.writeToParcel(out, flags);
out.writeInt(currentPage);
}
public static final Parcelable.Creator<SavedState> CREATOR =
new Parcelable.Creator<SavedState>() {
public SavedState createFromParcel(Parcel in) {
return new SavedState(in);
}
public SavedState[] newArray(int size) {
return new SavedState[size];
}
};
}
public void loadAssociatedPages(int page) {
if (mContentIsRefreshable) {
final int count = getChildCount();
if (page < count) {
int lowerPageBound = getAssociatedLowerPageBound(page);
int upperPageBound = getAssociatedUpperPageBound(page);
for (int i = 0; i < count; ++i) {
final ViewGroup layout = (ViewGroup) getChildAt(i);
final int childCount = layout.getChildCount();
if (lowerPageBound <= i && i <= upperPageBound) {
if (mDirtyPageContent.get(i)) {
syncPageItems(i);
mDirtyPageContent.set(i, false);
}
} else {
if (childCount > 0) {
layout.removeAllViews();
}
mDirtyPageContent.set(i, true);
}
}
}
}
}
protected int getAssociatedLowerPageBound(int page) {
return Math.max(0, page - 1);
}
protected int getAssociatedUpperPageBound(int page) {
final int count = getChildCount();
return Math.min(page + 1, count - 1);
}
protected void startChoiceMode(int mode, ActionMode.Callback callback) {
if (isChoiceMode(CHOICE_MODE_NONE)) {
mChoiceMode = mode;
mActionMode = startActionMode(callback);
}
}
public void endChoiceMode() {
if (!isChoiceMode(CHOICE_MODE_NONE)) {
mChoiceMode = CHOICE_MODE_NONE;
resetCheckedGrandchildren();
if (mActionMode != null) mActionMode.finish();
mActionMode = null;
}
}
protected boolean isChoiceMode(int mode) {
return mChoiceMode == mode;
}
protected ArrayList<Checkable> getCheckedGrandchildren() {
ArrayList<Checkable> checked = new ArrayList<Checkable>();
final int childCount = getChildCount();
for (int i = 0; i < childCount; ++i) {
final ViewGroup layout = (ViewGroup) getChildAt(i);
final int grandChildCount = layout.getChildCount();
for (int j = 0; j < grandChildCount; ++j) {
final View v = layout.getChildAt(j);
if (v instanceof Checkable && ((Checkable) v).isChecked()) {
checked.add((Checkable) v);
}
}
}
return checked;
}
/**
* If in CHOICE_MODE_SINGLE and an item is checked, returns that item.
* Otherwise, returns null.
*/
protected Checkable getSingleCheckedGrandchild() {
if (mChoiceMode == CHOICE_MODE_SINGLE) {
final int childCount = getChildCount();
for (int i = 0; i < childCount; ++i) {
final ViewGroup layout = (ViewGroup) getChildAt(i);
final int grandChildCount = layout.getChildCount();
for (int j = 0; j < grandChildCount; ++j) {
final View v = layout.getChildAt(j);
if (v instanceof Checkable && ((Checkable) v).isChecked()) {
return (Checkable) v;
}
}
}
}
return null;
}
public Object getChosenItem() {
View checkedView = (View) getSingleCheckedGrandchild();
if (checkedView != null) {
return checkedView.getTag();
}
return null;
}
protected void resetCheckedGrandchildren() {
// loop through children, and set all of their children to _not_ be checked
final ArrayList<Checkable> checked = getCheckedGrandchildren();
for (int i = 0; i < checked.size(); ++i) {
final Checkable c = checked.get(i);
c.setChecked(false);
}
}
/**
* This method is called ONLY to synchronize the number of pages that the paged view has.
* To actually fill the pages with information, implement syncPageItems() below. It is
* guaranteed that syncPageItems() will be called for a particular page before it is shown,
* and therefore, individual page items do not need to be updated in this method.
*/
public abstract void syncPages();
/**
* This method is called to synchronize the items that are on a particular page. If views on
* the page can be reused, then they should be updated within this method.
*/
public abstract void syncPageItems(int page);
public void invalidatePageData() {
if (mContentIsRefreshable) {
// Update all the pages
syncPages();
// Mark each of the pages as dirty
final int count = getChildCount();
mDirtyPageContent.clear();
for (int i = 0; i < count; ++i) {
mDirtyPageContent.add(true);
}
// Load any pages that are necessary for the current window of views
loadAssociatedPages(mCurrentPage);
mDirtyPageAlpha = true;
updateAdjacentPagesAlpha();
requestLayout();
}
}
}
diff --git a/src/com/android/launcher2/Workspace.java b/src/com/android/launcher2/Workspace.java
index 051ac65f..8f5a1155 100644
--- a/src/com/android/launcher2/Workspace.java
+++ b/src/com/android/launcher2/Workspace.java
@@ -1,1836 +1,1841 @@
/*
* 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.launcher2;
import android.animation.AnimatorListenerAdapter;
import com.android.launcher.R;
import android.animation.Animator;
import android.animation.Animator.AnimatorListener;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
import android.app.WallpaperManager;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProviderInfo;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ProviderInfo;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.graphics.Region.Op;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.IBinder;
import android.os.Parcelable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.HashSet;
/**
* The workspace is a wide area with a wallpaper and a finite number of pages.
* Each page contains a number of icons, folders or widgets the user can
* interact with. A workspace is meant to be used with a fixed width only.
*/
public class Workspace extends SmoothPagedView
implements DropTarget, DragSource, DragScroller, View.OnTouchListener {
@SuppressWarnings({"UnusedDeclaration"})
private static final String TAG = "Launcher.Workspace";
// This is how much the workspace shrinks when we enter all apps or
// customization mode
private static final float SHRINK_FACTOR = 0.16f;
// Y rotation to apply to the workspace screens
private static final float WORKSPACE_ROTATION = 12.5f;
// These are extra scale factors to apply to the mini home screens
// so as to achieve the desired transform
private static final float EXTRA_SCALE_FACTOR_0 = 0.97f;
private static final float EXTRA_SCALE_FACTOR_1 = 1.0f;
private static final float EXTRA_SCALE_FACTOR_2 = 1.08f;
private static final int BACKGROUND_FADE_OUT_DELAY = 300;
private static final int BACKGROUND_FADE_OUT_DURATION = 300;
private static final int BACKGROUND_FADE_IN_DURATION = 100;
// These animators are used to fade the background
private ObjectAnimator mBackgroundFadeInAnimation;
private ObjectAnimator mBackgroundFadeOutAnimation;
private float mBackgroundAlpha = 0;
private final WallpaperManager mWallpaperManager;
private int mDefaultPage;
private boolean mWaitingToShrinkToBottom = false;
private boolean mPageMoving = false;
/**
* CellInfo for the cell that is currently being dragged
*/
private CellLayout.CellInfo mDragInfo;
/**
* Target drop area calculated during last acceptDrop call.
*/
private int[] mTargetCell = null;
/**
* The CellLayout that is currently being dragged over
*/
private CellLayout mDragTargetLayout = null;
private Launcher mLauncher;
private IconCache mIconCache;
private DragController mDragController;
// These are temporary variables to prevent having to allocate a new object just to
// return an (x, y) value from helper functions. Do NOT use them to maintain other state.
private int[] mTempCell = new int[2];
private int[] mTempEstimate = new int[2];
private float[] mTempOriginXY = new float[2];
private float[] mTempDragCoordinates = new float[2];
private float[] mTempTouchCoordinates = new float[2];
private float[] mTempCellLayoutCenterCoordinates = new float[2];
private float[] mTempDragBottomRightCoordinates = new float[2];
private Matrix mTempInverseMatrix = new Matrix();
private static final int DEFAULT_CELL_COUNT_X = 4;
private static final int DEFAULT_CELL_COUNT_Y = 4;
private Drawable mPreviousIndicator;
private Drawable mNextIndicator;
// State variable that indicates whether the pages are small (ie when you're
// in all apps or customize mode)
private boolean mIsSmall = false;
private boolean mIsInUnshrinkAnimation = false;
private AnimatorListener mUnshrinkAnimationListener;
private enum ShrinkPosition {
SHRINK_TO_TOP, SHRINK_TO_MIDDLE, SHRINK_TO_BOTTOM_HIDDEN, SHRINK_TO_BOTTOM_VISIBLE };
private ShrinkPosition mShrunkenState;
private boolean mInScrollArea = false;
private HolographicOutlineHelper mOutlineHelper = new HolographicOutlineHelper();
private Bitmap mDragOutline = null;
private Rect mTempRect = new Rect();
private int[] mTempXY = new int[2];
/**
* Used to inflate the Workspace from XML.
*
* @param context The application's context.
* @param attrs The attributes set containing the Workspace's customization values.
*/
public Workspace(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
/**
* Used to inflate the Workspace from XML.
*
* @param context The application's context.
* @param attrs The attributes set containing the Workspace's customization values.
* @param defStyle Unused.
*/
public Workspace(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
mContentIsRefreshable = false;
if (!LauncherApplication.isScreenXLarge()) {
mFadeInAdjacentScreens = false;
}
mWallpaperManager = WallpaperManager.getInstance(context);
TypedArray a = context.obtainStyledAttributes(attrs,
R.styleable.Workspace, defStyle, 0);
int cellCountX = a.getInt(R.styleable.Workspace_cellCountX, DEFAULT_CELL_COUNT_X);
int cellCountY = a.getInt(R.styleable.Workspace_cellCountY, DEFAULT_CELL_COUNT_Y);
mDefaultPage = a.getInt(R.styleable.Workspace_defaultScreen, 1);
a.recycle();
LauncherModel.updateWorkspaceLayoutCells(cellCountX, cellCountY);
setHapticFeedbackEnabled(false);
initWorkspace();
}
/**
* Initializes various states for this workspace.
*/
protected void initWorkspace() {
Context context = getContext();
mCurrentPage = mDefaultPage;
Launcher.setScreen(mCurrentPage);
LauncherApplication app = (LauncherApplication)context.getApplicationContext();
mIconCache = app.getIconCache();
mUnshrinkAnimationListener = new AnimatorListenerAdapter() {
public void onAnimationStart(Animator animation) {
mIsInUnshrinkAnimation = true;
}
public void onAnimationEnd(Animator animation) {
mIsInUnshrinkAnimation = false;
}
};
mSnapVelocity = 600;
}
@Override
protected int getScrollMode() {
if (LauncherApplication.isScreenXLarge()) {
return SmoothPagedView.QUINTIC_MODE;
} else {
return SmoothPagedView.OVERSHOOT_MODE;
}
}
@Override
public void addView(View child, int index, LayoutParams params) {
if (!(child instanceof CellLayout)) {
throw new IllegalArgumentException("A Workspace can only have CellLayout children.");
}
((CellLayout) child).setOnInterceptTouchListener(this);
super.addView(child, index, params);
}
@Override
public void addView(View child) {
if (!(child instanceof CellLayout)) {
throw new IllegalArgumentException("A Workspace can only have CellLayout children.");
}
((CellLayout) child).setOnInterceptTouchListener(this);
super.addView(child);
}
@Override
public void addView(View child, int index) {
if (!(child instanceof CellLayout)) {
throw new IllegalArgumentException("A Workspace can only have CellLayout children.");
}
((CellLayout) child).setOnInterceptTouchListener(this);
super.addView(child, index);
}
@Override
public void addView(View child, int width, int height) {
if (!(child instanceof CellLayout)) {
throw new IllegalArgumentException("A Workspace can only have CellLayout children.");
}
((CellLayout) child).setOnInterceptTouchListener(this);
super.addView(child, width, height);
}
@Override
public void addView(View child, LayoutParams params) {
if (!(child instanceof CellLayout)) {
throw new IllegalArgumentException("A Workspace can only have CellLayout children.");
}
((CellLayout) child).setOnInterceptTouchListener(this);
super.addView(child, params);
}
/**
* @return The open folder on the current screen, or null if there is none
*/
Folder getOpenFolder() {
CellLayout currentPage = (CellLayout) getChildAt(mCurrentPage);
int count = currentPage.getChildCount();
for (int i = 0; i < count; i++) {
View child = currentPage.getChildAt(i);
if (child instanceof Folder) {
Folder folder = (Folder) child;
if (folder.getInfo().opened)
return folder;
}
}
return null;
}
ArrayList<Folder> getOpenFolders() {
final int screenCount = getChildCount();
ArrayList<Folder> folders = new ArrayList<Folder>(screenCount);
for (int screen = 0; screen < screenCount; screen++) {
CellLayout currentPage = (CellLayout) getChildAt(screen);
int count = currentPage.getChildCount();
for (int i = 0; i < count; i++) {
View child = currentPage.getChildAt(i);
if (child instanceof Folder) {
Folder folder = (Folder) child;
if (folder.getInfo().opened)
folders.add(folder);
break;
}
}
}
return folders;
}
boolean isDefaultPageShowing() {
return mCurrentPage == mDefaultPage;
}
/**
* Sets the current screen.
*
* @param currentPage
*/
@Override
void setCurrentPage(int currentPage) {
super.setCurrentPage(currentPage);
updateWallpaperOffset(mScrollX);
}
/**
* Adds the specified child in the specified screen. The position and dimension of
* the child are defined by x, y, spanX and spanY.
*
* @param child The child to add in one of the workspace's screens.
* @param screen The screen in which to add the child.
* @param x The X position of the child in the screen's grid.
* @param y The Y position of the child in the screen's grid.
* @param spanX The number of cells spanned horizontally by the child.
* @param spanY The number of cells spanned vertically by the child.
*/
void addInScreen(View child, int screen, int x, int y, int spanX, int spanY) {
addInScreen(child, screen, x, y, spanX, spanY, false);
}
void addInFullScreen(View child, int screen) {
addInScreen(child, screen, 0, 0, -1, -1);
}
/**
* Adds the specified child in the specified screen. The position and dimension of
* the child are defined by x, y, spanX and spanY.
*
* @param child The child to add in one of the workspace's screens.
* @param screen The screen in which to add the child.
* @param x The X position of the child in the screen's grid.
* @param y The Y position of the child in the screen's grid.
* @param spanX The number of cells spanned horizontally by the child.
* @param spanY The number of cells spanned vertically by the child.
* @param insert When true, the child is inserted at the beginning of the children list.
*/
void addInScreen(View child, int screen, int x, int y, int spanX, int spanY, boolean insert) {
if (screen < 0 || screen >= getChildCount()) {
Log.e(TAG, "The screen must be >= 0 and < " + getChildCount()
+ " (was " + screen + "); skipping child");
return;
}
final CellLayout group = (CellLayout) getChildAt(screen);
CellLayout.LayoutParams lp = (CellLayout.LayoutParams) child.getLayoutParams();
if (lp == null) {
lp = new CellLayout.LayoutParams(x, y, spanX, spanY);
} else {
lp.cellX = x;
lp.cellY = y;
lp.cellHSpan = spanX;
lp.cellVSpan = spanY;
}
// Get the canonical child id to uniquely represent this view in this screen
int childId = LauncherModel.getCellLayoutChildId(-1, screen, x, y, spanX, spanY);
if (!group.addViewToCellLayout(child, insert ? 0 : -1, childId, lp)) {
// TODO: This branch occurs when the workspace is adding views
// outside of the defined grid
// maybe we should be deleting these items from the LauncherModel?
Log.w(TAG, "Failed to add to item at (" + lp.cellX + "," + lp.cellY + ") to CellLayout");
}
if (!(child instanceof Folder)) {
child.setHapticFeedbackEnabled(false);
child.setOnLongClickListener(mLongClickListener);
}
if (child instanceof DropTarget) {
mDragController.addDropTarget((DropTarget) child);
}
}
public boolean onTouch(View v, MotionEvent event) {
// this is an intercepted event being forwarded from a cell layout
if (mIsSmall || mIsInUnshrinkAnimation) {
mLauncher.onWorkspaceClick((CellLayout) v);
return true;
} else if (!mPageMoving) {
if (v == getChildAt(mCurrentPage - 1)) {
snapToPage(mCurrentPage - 1);
return true;
} else if (v == getChildAt(mCurrentPage + 1)) {
snapToPage(mCurrentPage + 1);
return true;
}
}
return false;
}
@Override
public boolean dispatchUnhandledMove(View focused, int direction) {
if (mIsSmall || mIsInUnshrinkAnimation) {
// when the home screens are shrunken, shouldn't allow side-scrolling
return false;
}
return super.dispatchUnhandledMove(focused, direction);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
if (mIsSmall || mIsInUnshrinkAnimation) {
// when the home screens are shrunken, shouldn't allow side-scrolling
return false;
}
return super.onInterceptTouchEvent(ev);
}
+ @Override
+ protected void determineScrollingStart(MotionEvent ev) {
+ if (!mIsSmall && !mIsInUnshrinkAnimation) super.determineScrollingStart(ev);
+ }
+
protected void onPageBeginMoving() {
if (mNextPage != INVALID_PAGE) {
// we're snapping to a particular screen
enableChildrenCache(mCurrentPage, mNextPage);
} else {
// this is when user is actively dragging a particular screen, they might
// swipe it either left or right (but we won't advance by more than one screen)
enableChildrenCache(mCurrentPage - 1, mCurrentPage + 1);
}
showOutlines();
mPageMoving = true;
}
protected void onPageEndMoving() {
clearChildrenCache();
// Hide the outlines, as long as we're not dragging
if (!mDragController.dragging()) {
hideOutlines();
}
mPageMoving = false;
}
@Override
protected void notifyPageSwitchListener() {
super.notifyPageSwitchListener();
if (mPreviousIndicator != null) {
// if we know the next page, we show the indication for it right away; it looks
// weird if the indicators are lagging
int page = mNextPage;
if (page == INVALID_PAGE) {
page = mCurrentPage;
}
mPreviousIndicator.setLevel(page);
mNextIndicator.setLevel(page);
}
Launcher.setScreen(mCurrentPage);
};
private void updateWallpaperOffset() {
updateWallpaperOffset(getChildAt(getChildCount() - 1).getRight() - (mRight - mLeft));
}
private void updateWallpaperOffset(int scrollRange) {
final boolean isStaticWallpaper = (mWallpaperManager != null) &&
(mWallpaperManager.getWallpaperInfo() == null);
if (LauncherApplication.isScreenXLarge() && !isStaticWallpaper) {
IBinder token = getWindowToken();
if (token != null) {
mWallpaperManager.setWallpaperOffsetSteps(1.0f / (getChildCount() - 1), 0 );
mWallpaperManager.setWallpaperOffsets(getWindowToken(),
Math.max(0.f, Math.min(mScrollX/(float)scrollRange, 1.f)), 0);
}
}
}
public void showOutlines() {
if (!mIsSmall && !mIsInUnshrinkAnimation) {
if (mBackgroundFadeOutAnimation != null) mBackgroundFadeOutAnimation.cancel();
if (mBackgroundFadeInAnimation != null) mBackgroundFadeInAnimation.cancel();
mBackgroundFadeInAnimation = ObjectAnimator.ofFloat(this, "backgroundAlpha", 1.0f);
mBackgroundFadeInAnimation.setDuration(BACKGROUND_FADE_IN_DURATION);
mBackgroundFadeInAnimation.start();
}
}
public void hideOutlines() {
if (!mIsSmall && !mIsInUnshrinkAnimation) {
if (mBackgroundFadeInAnimation != null) mBackgroundFadeInAnimation.cancel();
if (mBackgroundFadeOutAnimation != null) mBackgroundFadeOutAnimation.cancel();
mBackgroundFadeOutAnimation = ObjectAnimator.ofFloat(this, "backgroundAlpha", 0.0f);
mBackgroundFadeOutAnimation.setDuration(BACKGROUND_FADE_OUT_DURATION);
mBackgroundFadeOutAnimation.setStartDelay(BACKGROUND_FADE_OUT_DELAY);
mBackgroundFadeOutAnimation.start();
}
}
public void setBackgroundAlpha(float alpha) {
mBackgroundAlpha = alpha;
for (int i = 0; i < getChildCount(); i++) {
CellLayout cl = (CellLayout) getChildAt(i);
cl.setBackgroundAlpha(alpha);
}
}
public float getBackgroundAlpha() {
return mBackgroundAlpha;
}
@Override
protected void screenScrolled(int screenCenter) {
final int halfScreenSize = getMeasuredWidth() / 2;
for (int i = 0; i < getChildCount(); i++) {
View v = getChildAt(i);
if (v != null) {
int totalDistance = v.getMeasuredWidth() + mPageSpacing;
int delta = screenCenter - (getChildOffset(i) -
getRelativeChildOffset(i) + halfScreenSize);
float scrollProgress = delta/(totalDistance*1.0f);
scrollProgress = Math.min(scrollProgress, 1.0f);
scrollProgress = Math.max(scrollProgress, -1.0f);
float rotation = WORKSPACE_ROTATION * scrollProgress;
v.setRotationY(rotation);
}
}
}
protected void onAttachedToWindow() {
super.onAttachedToWindow();
computeScroll();
mDragController.setWindowToken(getWindowToken());
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
// if shrinkToBottom() is called on initialization, it has to be deferred
// until after the first call to onLayout so that it has the correct width
if (mWaitingToShrinkToBottom) {
shrinkToBottom(false);
mWaitingToShrinkToBottom = false;
}
if (LauncherApplication.isInPlaceRotationEnabled()) {
// When the device is rotated, the scroll position of the current screen
// needs to be refreshed
setCurrentPage(getCurrentPage());
}
}
@Override
protected void dispatchDraw(Canvas canvas) {
if (mIsSmall || mIsInUnshrinkAnimation) {
// Draw all the workspaces if we're small
final int pageCount = getChildCount();
final long drawingTime = getDrawingTime();
for (int i = 0; i < pageCount; i++) {
final View page = (View) getChildAt(i);
drawChild(canvas, page, drawingTime);
}
} else {
super.dispatchDraw(canvas);
}
}
@Override
protected boolean onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect) {
if (!mLauncher.isAllAppsVisible()) {
final Folder openFolder = getOpenFolder();
if (openFolder != null) {
return openFolder.requestFocus(direction, previouslyFocusedRect);
} else {
return super.onRequestFocusInDescendants(direction, previouslyFocusedRect);
}
}
return false;
}
@Override
public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
if (!mLauncher.isAllAppsVisible()) {
final Folder openFolder = getOpenFolder();
if (openFolder != null) {
openFolder.addFocusables(views, direction);
} else {
super.addFocusables(views, direction, focusableMode);
}
}
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
// (In XLarge mode, the workspace is shrunken below all apps, and responds to taps
// ie when you click on a mini-screen, it zooms back to that screen)
if (!LauncherApplication.isScreenXLarge() && mLauncher.isAllAppsVisible()) {
return false;
}
}
return super.dispatchTouchEvent(ev);
}
void enableChildrenCache(int fromPage, int toPage) {
if (fromPage > toPage) {
final int temp = fromPage;
fromPage = toPage;
toPage = temp;
}
final int screenCount = getChildCount();
fromPage = Math.max(fromPage, 0);
toPage = Math.min(toPage, screenCount - 1);
for (int i = fromPage; i <= toPage; i++) {
final CellLayout layout = (CellLayout) getChildAt(i);
layout.setChildrenDrawnWithCacheEnabled(true);
layout.setChildrenDrawingCacheEnabled(true);
}
}
void clearChildrenCache() {
final int screenCount = getChildCount();
for (int i = 0; i < screenCount; i++) {
final CellLayout layout = (CellLayout) getChildAt(i);
layout.setChildrenDrawnWithCacheEnabled(false);
}
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
if (mLauncher.isAllAppsVisible()) {
// Cancel any scrolling that is in progress.
if (!mScroller.isFinished()) {
mScroller.abortAnimation();
}
setCurrentPage(mCurrentPage);
return false; // We don't want the events. Let them fall through to the all apps view.
}
return super.onTouchEvent(ev);
}
public boolean isSmall() {
return mIsSmall;
}
void shrinkToTop(boolean animated) {
shrink(ShrinkPosition.SHRINK_TO_TOP, animated);
}
void shrinkToMiddle() {
shrink(ShrinkPosition.SHRINK_TO_MIDDLE, true);
}
void shrinkToBottom() {
shrinkToBottom(true);
}
void shrinkToBottom(boolean animated) {
if (mFirstLayout) {
// (mFirstLayout == "first layout has not happened yet")
// if we get a call to shrink() as part of our initialization (for example, if
// Launcher is started in All Apps mode) then we need to wait for a layout call
// to get our width so we can layout the mini-screen views correctly
mWaitingToShrinkToBottom = true;
} else {
shrink(ShrinkPosition.SHRINK_TO_BOTTOM_HIDDEN, animated);
}
}
private float getYScaleForScreen(int screen) {
int x = Math.abs(screen - 2);
// TODO: This should be generalized for use with arbitrary rotation angles.
switch(x) {
case 0: return EXTRA_SCALE_FACTOR_0;
case 1: return EXTRA_SCALE_FACTOR_1;
case 2: return EXTRA_SCALE_FACTOR_2;
}
return 1.0f;
}
// we use this to shrink the workspace for the all apps view and the customize view
private void shrink(ShrinkPosition shrinkPosition, boolean animated) {
mIsSmall = true;
mShrunkenState = shrinkPosition;
// Stop any scrolling, move to the current page right away
setCurrentPage(mCurrentPage);
updateWhichPagesAcceptDrops(mShrunkenState);
// we intercept and reject all touch events when we're small, so be sure to reset the state
mTouchState = TOUCH_STATE_REST;
mActivePointerId = INVALID_POINTER;
final Resources res = getResources();
final int screenWidth = getWidth();
final int screenHeight = getHeight();
// Making the assumption that all pages have the same width as the 0th
final int pageWidth = getChildAt(0).getMeasuredWidth();
final int pageHeight = getChildAt(0).getMeasuredHeight();
final int scaledPageWidth = (int) (SHRINK_FACTOR * pageWidth);
final int scaledPageHeight = (int) (SHRINK_FACTOR * pageHeight);
final float extraScaledSpacing = res.getDimension(R.dimen.smallScreenExtraSpacing);
final int screenCount = getChildCount();
float totalWidth = screenCount * scaledPageWidth + (screenCount - 1) * extraScaledSpacing;
float newY = getResources().getDimension(R.dimen.smallScreenVerticalMargin);
float finalAlpha = 1.0f;
float extraShrinkFactor = 1.0f;
if (shrinkPosition == ShrinkPosition.SHRINK_TO_BOTTOM_VISIBLE) {
newY = screenHeight - newY - scaledPageHeight;
} else if (shrinkPosition == ShrinkPosition.SHRINK_TO_BOTTOM_HIDDEN) {
// We shrink and disappear to nothing in the case of all apps
// (which is when we shrink to the bottom)
newY = screenHeight - newY - scaledPageHeight;
finalAlpha = 0.0f;
extraShrinkFactor = 0.1f;
} else if (shrinkPosition == ShrinkPosition.SHRINK_TO_MIDDLE) {
newY = screenHeight / 2 - scaledPageHeight / 2;
finalAlpha = 1.0f;
} else if (shrinkPosition == ShrinkPosition.SHRINK_TO_TOP) {
newY = screenHeight / 10;
}
// We animate all the screens to the centered position in workspace
// At the same time, the screens become greyed/dimmed
// newX is initialized to the left-most position of the centered screens
float newX = mScroller.getFinalX() + screenWidth / 2 - totalWidth / 2;
// We are going to scale about the center of the view, so we need to adjust the positions
// of the views accordingly
newX -= (pageWidth - scaledPageWidth) / 2.0f;
newY -= (pageHeight - scaledPageHeight) / 2.0f;
for (int i = 0; i < screenCount; i++) {
CellLayout cl = (CellLayout) getChildAt(i);
float rotation = (-i + 2) * WORKSPACE_ROTATION;
float rotationScaleX = (float) (1.0f / Math.cos(Math.PI * rotation / 180.0f));
float rotationScaleY = getYScaleForScreen(i);
if (animated) {
final int duration = res.getInteger(R.integer.config_workspaceShrinkTime);
ObjectAnimator anim = ObjectAnimator.ofPropertyValuesHolder(cl,
PropertyValuesHolder.ofFloat("x", newX),
PropertyValuesHolder.ofFloat("y", newY),
PropertyValuesHolder.ofFloat("scaleX",
SHRINK_FACTOR * rotationScaleX * extraShrinkFactor),
PropertyValuesHolder.ofFloat("scaleY",
SHRINK_FACTOR * rotationScaleY * extraShrinkFactor),
PropertyValuesHolder.ofFloat("backgroundAlpha", finalAlpha),
PropertyValuesHolder.ofFloat("alpha", finalAlpha),
PropertyValuesHolder.ofFloat("rotationY", rotation));
anim.setDuration(duration);
anim.start();
} else {
cl.setX((int)newX);
cl.setY((int)newY);
cl.setScaleX(SHRINK_FACTOR * rotationScaleX);
cl.setScaleY(SHRINK_FACTOR * rotationScaleY);
cl.setBackgroundAlpha(1.0f);
cl.setAlpha(finalAlpha);
cl.setRotationY(rotation);
}
// increment newX for the next screen
newX += scaledPageWidth + extraScaledSpacing;
}
setChildrenDrawnWithCacheEnabled(true);
}
private void updateWhichPagesAcceptDrops(ShrinkPosition state) {
updateWhichPagesAcceptDropsHelper(state, false, 1, 1);
}
private void updateWhichPagesAcceptDropsDuringDrag(ShrinkPosition state, int spanX, int spanY) {
updateWhichPagesAcceptDropsHelper(state, true, spanX, spanY);
}
private void updateWhichPagesAcceptDropsHelper(
ShrinkPosition state, boolean isDragHappening, int spanX, int spanY) {
final int screenCount = getChildCount();
for (int i = 0; i < screenCount; i++) {
CellLayout cl = (CellLayout) getChildAt(i);
switch (state) {
case SHRINK_TO_TOP:
if (!isDragHappening) {
boolean showDropHighlight = i == mCurrentPage;
cl.setAcceptsDrops(showDropHighlight);
break;
}
// otherwise, fall through below and mark non-full screens as accepting drops
case SHRINK_TO_BOTTOM_HIDDEN:
case SHRINK_TO_BOTTOM_VISIBLE:
if (!isDragHappening) {
// even if a drag isn't happening, we don't want to show a screen as
// accepting drops if it doesn't have at least one free cell
spanX = 1;
spanY = 1;
}
// the page accepts drops if we can find at least one empty spot
cl.setAcceptsDrops(cl.findCellForSpan(null, spanX, spanY));
break;
default:
throw new RuntimeException(
"updateWhichPagesAcceptDropsHelper passed an unhandled ShrinkPosition");
}
}
}
/*
*
* We call these methods (onDragStartedWithItemSpans/onDragStartedWithItemMinSize) whenever we
* start a drag in Launcher, regardless of whether the drag has ever entered the Workspace
*
* These methods mark the appropriate pages as accepting drops (which alters their visual
* appearance) and, if the pages are hidden, makes them visible.
*
*/
public void onDragStartedWithItemSpans(int spanX, int spanY) {
updateWhichPagesAcceptDropsDuringDrag(mShrunkenState, spanX, spanY);
if (mShrunkenState == ShrinkPosition.SHRINK_TO_BOTTOM_HIDDEN) {
shrink(ShrinkPosition.SHRINK_TO_BOTTOM_VISIBLE, true);
}
}
public void onDragStartedWithItemMinSize(int minWidth, int minHeight) {
int[] spanXY = CellLayout.rectToCell(getResources(), minWidth, minHeight, null);
onDragStartedWithItemSpans(spanXY[0], spanXY[1]);
}
// we call this method whenever a drag and drop in Launcher finishes, even if Workspace was
// never dragged over
public void onDragStopped() {
updateWhichPagesAcceptDrops(mShrunkenState);
if (mShrunkenState == ShrinkPosition.SHRINK_TO_BOTTOM_VISIBLE) {
shrink(ShrinkPosition.SHRINK_TO_BOTTOM_HIDDEN, true);
}
}
// We call this when we trigger an unshrink by clicking on the CellLayout cl
public void unshrink(CellLayout clThatWasClicked) {
int newCurrentPage = mCurrentPage;
final int screenCount = getChildCount();
for (int i = 0; i < screenCount; i++) {
if (getChildAt(i) == clThatWasClicked) {
newCurrentPage = i;
}
}
unshrink(newCurrentPage);
}
@Override
protected boolean handlePagingClicks() {
return true;
}
private void unshrink(int newCurrentPage) {
if (mIsSmall) {
int newX = getChildOffset(newCurrentPage) - getRelativeChildOffset(newCurrentPage);
int delta = newX - mScrollX;
final int screenCount = getChildCount();
for (int i = 0; i < screenCount; i++) {
CellLayout cl = (CellLayout) getChildAt(i);
cl.setX(cl.getX() + delta);
}
setCurrentPage(newCurrentPage);
unshrink();
}
}
void unshrink() {
unshrink(true);
}
void unshrink(boolean animated) {
if (mIsSmall) {
mIsSmall = false;
AnimatorSet s = new AnimatorSet();
final int screenCount = getChildCount();
final int duration = getResources().getInteger(R.integer.config_workspaceUnshrinkTime);
for (int i = 0; i < screenCount; i++) {
final CellLayout cl = (CellLayout)getChildAt(i);
float finalAlphaValue = (i == mCurrentPage) ? 1.0f : 0.0f;
float rotation = 0.0f;
if (i < mCurrentPage) {
rotation = WORKSPACE_ROTATION;
} else if (i > mCurrentPage) {
rotation = -WORKSPACE_ROTATION;
}
if (animated) {
s.playTogether(
ObjectAnimator.ofFloat(cl, "translationX", 0.0f).setDuration(duration),
ObjectAnimator.ofFloat(cl, "translationY", 0.0f).setDuration(duration),
ObjectAnimator.ofFloat(cl, "scaleX", 1.0f).setDuration(duration),
ObjectAnimator.ofFloat(cl, "scaleY", 1.0f).setDuration(duration),
ObjectAnimator.ofFloat(cl, "backgroundAlpha", 0.0f).setDuration(duration),
ObjectAnimator.ofFloat(cl, "alpha", finalAlphaValue).setDuration(duration),
ObjectAnimator.ofFloat(cl, "rotationY", rotation).setDuration(duration));
} else {
cl.setTranslationX(0.0f);
cl.setTranslationY(0.0f);
cl.setScaleX(1.0f);
cl.setScaleY(1.0f);
cl.setBackgroundAlpha(0.0f);
cl.setAlpha(finalAlphaValue);
cl.setRotationY(rotation);
}
}
if (animated) {
// If we call this when we're not animated, onAnimationEnd is never called on
// the listener; make sure we only use the listener when we're actually animating
s.addListener(mUnshrinkAnimationListener);
s.start();
}
}
}
/**
* Draw the View v into the given Canvas.
*
* @param v the view to draw
* @param destCanvas the canvas to draw on
* @param padding the horizontal and vertical padding to use when drawing
*/
private void drawDragView(View v, Canvas destCanvas, int padding) {
final Rect clipRect = mTempRect;
v.getDrawingRect(clipRect);
// For a TextView, adjust the clip rect so that we don't include the text label
if (v instanceof TextView) {
final int iconHeight = ((TextView)v).getCompoundPaddingTop() - v.getPaddingTop();
clipRect.bottom = clipRect.top + iconHeight;
}
// Draw the View into the bitmap.
// The translate of scrollX and scrollY is necessary when drawing TextViews, because
// they set scrollX and scrollY to large values to achieve centered text
destCanvas.save();
destCanvas.translate(-v.getScrollX() + padding / 2, -v.getScrollY() + padding / 2);
destCanvas.clipRect(clipRect, Op.REPLACE);
v.draw(destCanvas);
destCanvas.restore();
}
/**
* Returns a new bitmap to be used as the object outline, e.g. to visualize the drop location.
* Responsibility for the bitmap is transferred to the caller.
*/
private Bitmap createDragOutline(View v, Canvas canvas, int padding) {
final int outlineColor = getResources().getColor(R.color.drag_outline_color);
final Bitmap b = Bitmap.createBitmap(
v.getWidth() + padding, v.getHeight() + padding, Bitmap.Config.ARGB_8888);
canvas.setBitmap(b);
drawDragView(v, canvas, padding);
mOutlineHelper.applyExpensiveOuterOutline(b, canvas, outlineColor, true);
return b;
}
/**
* Returns a new bitmap to show when the given View is being dragged around.
* Responsibility for the bitmap is transferred to the caller.
*/
private Bitmap createDragBitmap(View v, Canvas canvas, int padding) {
final int outlineColor = getResources().getColor(R.color.drag_outline_color);
final Bitmap b = Bitmap.createBitmap(
mDragOutline.getWidth(), mDragOutline.getHeight(), Bitmap.Config.ARGB_8888);
canvas.setBitmap(b);
canvas.drawBitmap(mDragOutline, 0, 0, null);
drawDragView(v, canvas, padding);
mOutlineHelper.applyGlow(b, canvas, outlineColor);
return b;
}
void startDrag(CellLayout.CellInfo cellInfo) {
View child = cellInfo.cell;
final int blurPadding = 40;
// Make sure the drag was started by a long press as opposed to a long click.
if (!child.isInTouchMode()) {
return;
}
mDragInfo = cellInfo;
mDragInfo.screen = mCurrentPage;
CellLayout current = getCurrentDropLayout();
current.onDragChild(child);
child.clearFocus();
child.setPressed(false);
final Canvas canvas = new Canvas();
// The outline is used to visualize where the item will land if dropped
mDragOutline = createDragOutline(child, canvas, blurPadding);
// The drag bitmap follows the touch point around on the screen
final Bitmap b = createDragBitmap(child, canvas, blurPadding);
final int bmpWidth = b.getWidth();
final int bmpHeight = b.getHeight();
child.getLocationOnScreen(mTempXY);
final int screenX = (int) mTempXY[0] + (child.getWidth() - bmpWidth) / 2;
final int screenY = (int) mTempXY[1] + (child.getHeight() - bmpHeight) / 2;
mDragController.startDrag(b, screenX, screenY, 0, 0, bmpWidth, bmpHeight, this,
child.getTag(), DragController.DRAG_ACTION_MOVE, null);
b.recycle();
child.setVisibility(View.GONE);
}
void addApplicationShortcut(ShortcutInfo info, int screen, int cellX, int cellY,
boolean insertAtFirst, int intersectX, int intersectY) {
final CellLayout cellLayout = (CellLayout) getChildAt(screen);
View view = mLauncher.createShortcut(R.layout.application, cellLayout, (ShortcutInfo) info);
final int[] cellXY = new int[2];
cellLayout.findCellForSpanThatIntersects(cellXY, 1, 1, intersectX, intersectY);
addInScreen(view, screen, cellXY[0], cellXY[1], 1, 1, insertAtFirst);
LauncherModel.addOrMoveItemInDatabase(mLauncher, info,
LauncherSettings.Favorites.CONTAINER_DESKTOP, screen,
cellXY[0], cellXY[1]);
}
public void onDrop(DragSource source, int x, int y, int xOffset, int yOffset,
DragView dragView, Object dragInfo) {
if (mDragTargetLayout == null) {
// cancel the drag if we're not over a screen at time of drop
// TODO: maybe add a nice fade here?
return;
}
int originX = x - xOffset;
int originY = y - yOffset;
if (mIsSmall || mIsInUnshrinkAnimation) {
// get originX and originY in the local coordinate system of the screen
mTempOriginXY[0] = originX;
mTempOriginXY[1] = originY;
mapPointFromSelfToChild(mDragTargetLayout, mTempOriginXY);
originX = (int)mTempOriginXY[0];
originY = (int)mTempOriginXY[1];
}
if (source != this) {
onDropExternal(originX, originY, dragInfo, mDragTargetLayout);
} else {
// Move internally
if (mDragInfo != null) {
final View cell = mDragInfo.cell;
mTargetCell = findNearestVacantArea(originX, originY,
mDragInfo.spanX, mDragInfo.spanY, cell, mDragTargetLayout,
mTargetCell);
int screen = indexOfChild(mDragTargetLayout);
if (screen != mDragInfo.screen) {
final CellLayout originalCellLayout = (CellLayout) getChildAt(mDragInfo.screen);
originalCellLayout.removeView(cell);
addInScreen(cell, screen, mTargetCell[0], mTargetCell[1],
mDragInfo.spanX, mDragInfo.spanY);
}
mDragTargetLayout.onDropChild(cell);
// update the item's position after drop
final ItemInfo info = (ItemInfo) cell.getTag();
CellLayout.LayoutParams lp = (CellLayout.LayoutParams) cell.getLayoutParams();
mDragTargetLayout.onMove(cell, mTargetCell[0], mTargetCell[1]);
lp.cellX = mTargetCell[0];
lp.cellY = mTargetCell[1];
cell.setId(LauncherModel.getCellLayoutChildId(-1, mDragInfo.screen,
mTargetCell[0], mTargetCell[1], mDragInfo.spanX, mDragInfo.spanY));
LauncherModel.moveItemInDatabase(mLauncher, info,
LauncherSettings.Favorites.CONTAINER_DESKTOP, screen,
lp.cellX, lp.cellY);
}
}
}
public void onDragEnter(DragSource source, int x, int y, int xOffset,
int yOffset, DragView dragView, Object dragInfo) {
mDragTargetLayout = null; // Reset the drag state
if (!mIsSmall) {
mDragTargetLayout = getCurrentDropLayout();
mDragTargetLayout.onDragEnter(dragView);
showOutlines();
}
}
public DropTarget getDropTargetDelegate(DragSource source, int x, int y, int xOffset, int yOffset,
DragView dragView, Object dragInfo) {
if (mIsSmall || mIsInUnshrinkAnimation) {
// If we're shrunken, don't let anyone drag on folders/etc that are on the mini-screens
return null;
}
// We may need to delegate the drag to a child view. If a 1x1 item
// would land in a cell occupied by a DragTarget (e.g. a Folder),
// then drag events should be handled by that child.
ItemInfo item = (ItemInfo)dragInfo;
CellLayout currentLayout = getCurrentDropLayout();
int dragPointX, dragPointY;
if (item.spanX == 1 && item.spanY == 1) {
// For a 1x1, calculate the drop cell exactly as in onDragOver
dragPointX = x - xOffset;
dragPointY = y - yOffset;
} else {
// Otherwise, use the exact drag coordinates
dragPointX = x;
dragPointY = y;
}
dragPointX += mScrollX - currentLayout.getLeft();
dragPointY += mScrollY - currentLayout.getTop();
// If we are dragging over a cell that contains a DropTarget that will
// accept the drop, delegate to that DropTarget.
final int[] cellXY = mTempCell;
currentLayout.estimateDropCell(dragPointX, dragPointY, item.spanX, item.spanY, cellXY);
View child = currentLayout.getChildAt(cellXY[0], cellXY[1]);
if (child instanceof DropTarget) {
DropTarget target = (DropTarget)child;
if (target.acceptDrop(source, x, y, xOffset, yOffset, dragView, dragInfo)) {
return target;
}
}
return null;
}
/*
*
* Convert the 2D coordinate xy from the parent View's coordinate space to this CellLayout's
* coordinate space. The argument xy is modified with the return result.
*
*/
void mapPointFromSelfToChild(View v, float[] xy) {
mapPointFromSelfToChild(v, xy, null);
}
/*
*
* Convert the 2D coordinate xy from the parent View's coordinate space to this CellLayout's
* coordinate space. The argument xy is modified with the return result.
*
* if cachedInverseMatrix is not null, this method will just use that matrix instead of
* computing it itself; we use this to avoid redundant matrix inversions in
* findMatchingPageForDragOver
*
*/
void mapPointFromSelfToChild(View v, float[] xy, Matrix cachedInverseMatrix) {
if (cachedInverseMatrix == null) {
v.getMatrix().invert(mTempInverseMatrix);
cachedInverseMatrix = mTempInverseMatrix;
}
xy[0] = xy[0] + mScrollX - v.getLeft();
xy[1] = xy[1] + mScrollY - v.getTop();
cachedInverseMatrix.mapPoints(xy);
}
/*
*
* Convert the 2D coordinate xy from this CellLayout's coordinate space to
* the parent View's coordinate space. The argument xy is modified with the return result.
*
*/
void mapPointFromChildToSelf(View v, float[] xy) {
v.getMatrix().mapPoints(xy);
xy[0] -= (mScrollX - v.getLeft());
xy[1] -= (mScrollY - v.getTop());
}
static private float squaredDistance(float[] point1, float[] point2) {
float distanceX = point1[0] - point2[0];
float distanceY = point2[1] - point2[1];
return distanceX * distanceX + distanceY * distanceY;
}
/*
*
* Returns true if the passed CellLayout cl overlaps with dragView
*
*/
boolean overlaps(CellLayout cl, DragView dragView,
int dragViewX, int dragViewY, Matrix cachedInverseMatrix) {
// Transform the coordinates of the item being dragged to the CellLayout's coordinates
final float[] draggedItemTopLeft = mTempDragCoordinates;
draggedItemTopLeft[0] = dragViewX + dragView.getScaledDragRegionXOffset();
draggedItemTopLeft[1] = dragViewY + dragView.getScaledDragRegionYOffset();
final float[] draggedItemBottomRight = mTempDragBottomRightCoordinates;
draggedItemBottomRight[0] = draggedItemTopLeft[0] + dragView.getScaledDragRegionWidth();
draggedItemBottomRight[1] = draggedItemTopLeft[1] + dragView.getScaledDragRegionHeight();
// Transform the dragged item's top left coordinates
// to the CellLayout's local coordinates
mapPointFromSelfToChild(cl, draggedItemTopLeft, cachedInverseMatrix);
float overlapRegionLeft = Math.max(0f, draggedItemTopLeft[0]);
float overlapRegionTop = Math.max(0f, draggedItemTopLeft[1]);
if (overlapRegionLeft <= cl.getWidth() && overlapRegionTop >= 0) {
// Transform the dragged item's bottom right coordinates
// to the CellLayout's local coordinates
mapPointFromSelfToChild(cl, draggedItemBottomRight, cachedInverseMatrix);
float overlapRegionRight = Math.min(cl.getWidth(), draggedItemBottomRight[0]);
float overlapRegionBottom = Math.min(cl.getHeight(), draggedItemBottomRight[1]);
if (overlapRegionRight >= 0 && overlapRegionBottom <= cl.getHeight()) {
float overlap = (overlapRegionRight - overlapRegionLeft) *
(overlapRegionBottom - overlapRegionTop);
if (overlap > 0) {
return true;
}
}
}
return false;
}
/*
*
* This method returns the CellLayout that is currently being dragged to. In order to drag
* to a CellLayout, either the touch point must be directly over the CellLayout, or as a second
* strategy, we see if the dragView is overlapping any CellLayout and choose the closest one
*
* Return null if no CellLayout is currently being dragged over
*
*/
private CellLayout findMatchingPageForDragOver(
DragView dragView, int originX, int originY, int offsetX, int offsetY) {
// We loop through all the screens (ie CellLayouts) and see which ones overlap
// with the item being dragged and then choose the one that's closest to the touch point
final int screenCount = getChildCount();
CellLayout bestMatchingScreen = null;
float smallestDistSoFar = Float.MAX_VALUE;
for (int i = 0; i < screenCount; i++) {
CellLayout cl = (CellLayout)getChildAt(i);
final float[] touchXy = mTempTouchCoordinates;
touchXy[0] = originX + offsetX;
touchXy[1] = originY + offsetY;
// Transform the touch coordinates to the CellLayout's local coordinates
// If the touch point is within the bounds of the cell layout, we can return immediately
cl.getMatrix().invert(mTempInverseMatrix);
mapPointFromSelfToChild(cl, touchXy, mTempInverseMatrix);
if (touchXy[0] >= 0 && touchXy[0] <= cl.getWidth() &&
touchXy[1] >= 0 && touchXy[1] <= cl.getHeight()) {
return cl;
}
if (overlaps(cl, dragView, originX, originY, mTempInverseMatrix)) {
// Get the center of the cell layout in screen coordinates
final float[] cellLayoutCenter = mTempCellLayoutCenterCoordinates;
cellLayoutCenter[0] = cl.getWidth()/2;
cellLayoutCenter[1] = cl.getHeight()/2;
mapPointFromChildToSelf(cl, cellLayoutCenter);
touchXy[0] = originX + offsetX;
touchXy[1] = originY + offsetY;
// Calculate the distance between the center of the CellLayout
// and the touch point
float dist = squaredDistance(touchXy, cellLayoutCenter);
if (dist < smallestDistSoFar) {
smallestDistSoFar = dist;
bestMatchingScreen = cl;
}
}
}
return bestMatchingScreen;
}
public void onDragOver(DragSource source, int x, int y, int xOffset, int yOffset,
DragView dragView, Object dragInfo) {
// When touch is inside the scroll area, skip dragOver actions for the current screen
if (!mInScrollArea) {
CellLayout layout;
int originX = x - xOffset;
int originY = y - yOffset;
if (mIsSmall || mIsInUnshrinkAnimation) {
layout = findMatchingPageForDragOver(
dragView, originX, originY, xOffset, yOffset);
if (layout != mDragTargetLayout) {
if (mDragTargetLayout != null) {
mDragTargetLayout.setHover(false);
}
mDragTargetLayout = layout;
if (mDragTargetLayout != null) {
mDragTargetLayout.setHover(true);
}
}
} else {
layout = getCurrentDropLayout();
final ItemInfo item = (ItemInfo)dragInfo;
if (dragInfo instanceof LauncherAppWidgetInfo) {
LauncherAppWidgetInfo widgetInfo = (LauncherAppWidgetInfo)dragInfo;
if (widgetInfo.spanX == -1) {
// Calculate the grid spans needed to fit this widget
int[] spans = layout.rectToCell(
widgetInfo.minWidth, widgetInfo.minHeight, null);
item.spanX = spans[0];
item.spanY = spans[1];
}
}
if (source instanceof AllAppsPagedView) {
// This is a hack to fix the point used to determine which cell an icon from
// the all apps screen is over
if (item != null && item.spanX == 1 && layout != null) {
int dragRegionLeft = (dragView.getWidth() - layout.getCellWidth()) / 2;
originX += dragRegionLeft - dragView.getDragRegionLeft();
if (dragView.getDragRegionWidth() != layout.getCellWidth()) {
dragView.setDragRegion(dragView.getDragRegionLeft(),
dragView.getDragRegionTop(),
layout.getCellWidth(),
dragView.getDragRegionHeight());
}
}
}
if (layout != mDragTargetLayout) {
if (mDragTargetLayout != null) {
mDragTargetLayout.onDragExit();
}
layout.onDragEnter(dragView);
mDragTargetLayout = layout;
}
// only visualize the drop locations for moving icons within the home screen on
// tablet on phone, we also visualize icons dragged in from All Apps
if ((!LauncherApplication.isScreenXLarge() || source == this)
&& mDragTargetLayout != null) {
final View child = (mDragInfo == null) ? null : mDragInfo.cell;
int localOriginX = originX - (mDragTargetLayout.getLeft() - mScrollX);
int localOriginY = originY - (mDragTargetLayout.getTop() - mScrollY);
mDragTargetLayout.visualizeDropLocation(child, mDragOutline,
localOriginX, localOriginY, item.spanX, item.spanY);
}
}
}
}
public void onDragExit(DragSource source, int x, int y, int xOffset,
int yOffset, DragView dragView, Object dragInfo) {
if (mDragTargetLayout != null) {
mDragTargetLayout.onDragExit();
}
if (!mIsPageMoving) {
hideOutlines();
}
clearAllHovers();
}
private void onDropExternal(int x, int y, Object dragInfo,
CellLayout cellLayout) {
onDropExternal(x, y, dragInfo, cellLayout, false);
}
/**
* Add the item specified by dragInfo to the given layout.
* This is basically the equivalent of onDropExternal, except it's not initiated
* by drag and drop.
* @return true if successful
*/
public boolean addExternalItemToScreen(Object dragInfo, View layout) {
CellLayout cl = (CellLayout) layout;
ItemInfo info = (ItemInfo) dragInfo;
if (cl.findCellForSpan(mTempEstimate, info.spanX, info.spanY)) {
onDropExternal(0, 0, dragInfo, cl, false);
return true;
}
mLauncher.showOutOfSpaceMessage();
return false;
}
// Drag from somewhere else
// NOTE: This can also be called when we are outside of a drag event, when we want
// to add an item to one of the workspace screens.
private void onDropExternal(int x, int y, Object dragInfo,
CellLayout cellLayout, boolean insertAtFirst) {
int screen = indexOfChild(cellLayout);
if (dragInfo instanceof PendingAddItemInfo) {
PendingAddItemInfo info = (PendingAddItemInfo) dragInfo;
// When dragging and dropping from customization tray, we deal with creating
// widgets/shortcuts/folders in a slightly different way
int[] touchXY = new int[2];
touchXY[0] = x;
touchXY[1] = y;
switch (info.itemType) {
case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
mLauncher.addAppWidgetFromDrop(info.componentName, screen, touchXY);
break;
case LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER:
mLauncher.addLiveFolderFromDrop(info.componentName, screen, touchXY);
break;
case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
mLauncher.processShortcutFromDrop(info.componentName, screen, touchXY);
break;
default:
throw new IllegalStateException("Unknown item type: " + info.itemType);
}
cellLayout.onDragExit();
return;
}
// This is for other drag/drop cases, like dragging from All Apps
ItemInfo info = (ItemInfo) dragInfo;
View view = null;
switch (info.itemType) {
case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
if (info.container == NO_ID && info instanceof ApplicationInfo) {
// Came from all apps -- make a copy
info = new ShortcutInfo((ApplicationInfo) info);
}
view = mLauncher.createShortcut(R.layout.application, cellLayout,
(ShortcutInfo) info);
break;
case LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER:
view = FolderIcon.fromXml(R.layout.folder_icon, mLauncher,
cellLayout, ((UserFolderInfo) info));
break;
default:
throw new IllegalStateException("Unknown item type: " + info.itemType);
}
// If the view is null, it has already been added.
if (view == null) {
cellLayout.onDragExit();
} else {
mTargetCell = findNearestVacantArea(x, y, 1, 1, null, cellLayout, mTargetCell);
addInScreen(view, indexOfChild(cellLayout), mTargetCell[0],
mTargetCell[1], info.spanX, info.spanY, insertAtFirst);
cellLayout.onDropChild(view);
CellLayout.LayoutParams lp = (CellLayout.LayoutParams) view.getLayoutParams();
LauncherModel.addOrMoveItemInDatabase(mLauncher, info,
LauncherSettings.Favorites.CONTAINER_DESKTOP, screen,
lp.cellX, lp.cellY);
}
}
/**
* Return the current {@link CellLayout}, correctly picking the destination
* screen while a scroll is in progress.
*/
private CellLayout getCurrentDropLayout() {
// if we're currently small, use findMatchingPageForDragOver instead
if (mIsSmall) return null;
int index = mScroller.isFinished() ? mCurrentPage : mNextPage;
return (CellLayout) getChildAt(index);
}
/**
* Return the current CellInfo describing our current drag; this method exists
* so that Launcher can sync this object with the correct info when the activity is created/
* destroyed
*
*/
public CellLayout.CellInfo getDragInfo() {
return mDragInfo;
}
/**
* {@inheritDoc}
*/
public boolean acceptDrop(DragSource source, int x, int y,
int xOffset, int yOffset, DragView dragView, Object dragInfo) {
if (mDragTargetLayout == null) {
// cancel the drag if we're not over a screen at time of drop
return false;
}
final CellLayout.CellInfo dragCellInfo = mDragInfo;
final int spanX = dragCellInfo == null ? 1 : dragCellInfo.spanX;
final int spanY = dragCellInfo == null ? 1 : dragCellInfo.spanY;
final View ignoreView = dragCellInfo == null ? null : dragCellInfo.cell;
if (mDragTargetLayout.findCellForSpanIgnoring(null, spanX, spanY, ignoreView)) {
return true;
} else {
mLauncher.showOutOfSpaceMessage();
return false;
}
}
/**
* Calculate the nearest cell where the given object would be dropped.
*/
private int[] findNearestVacantArea(int pixelX, int pixelY,
int spanX, int spanY, View ignoreView, CellLayout layout, int[] recycle) {
int localPixelX = pixelX - (layout.getLeft() - mScrollX);
int localPixelY = pixelY - (layout.getTop() - mScrollY);
// Find the best target drop location
return layout.findNearestVacantArea(
localPixelX, localPixelY, spanX, spanY, ignoreView, recycle);
}
/**
* Estimate the size that a child with the given dimensions will take in the current screen.
*/
void estimateChildSize(int minWidth, int minHeight, int[] result) {
((CellLayout)getChildAt(mCurrentPage)).estimateChildSize(minWidth, minHeight, result);
}
void setLauncher(Launcher launcher) {
mLauncher = launcher;
}
public void setDragController(DragController dragController) {
mDragController = dragController;
}
public void onDropCompleted(View target, boolean success) {
if (success) {
if (target != this && mDragInfo != null) {
final CellLayout cellLayout = (CellLayout) getChildAt(mDragInfo.screen);
cellLayout.removeView(mDragInfo.cell);
if (mDragInfo.cell instanceof DropTarget) {
mDragController.removeDropTarget((DropTarget)mDragInfo.cell);
}
// final Object tag = mDragInfo.cell.getTag();
}
} else {
if (mDragInfo != null) {
final CellLayout cellLayout = (CellLayout) getChildAt(mDragInfo.screen);
cellLayout.onDropAborted(mDragInfo.cell);
}
}
if (mDragInfo != null) {
mDragInfo.cell.setVisibility(View.VISIBLE);
}
mDragOutline = null;
mDragInfo = null;
}
public boolean isDropEnabled() {
return true;
}
@Override
protected void onRestoreInstanceState(Parcelable state) {
super.onRestoreInstanceState(state);
Launcher.setScreen(mCurrentPage);
}
@Override
public void scrollLeft() {
if (!mIsSmall && !mIsInUnshrinkAnimation) {
super.scrollLeft();
}
}
@Override
public void scrollRight() {
if (!mIsSmall && !mIsInUnshrinkAnimation) {
super.scrollRight();
}
}
@Override
public void onEnterScrollArea(int direction) {
if (!mIsSmall && !mIsInUnshrinkAnimation) {
mInScrollArea = true;
final int screen = getCurrentPage() + ((direction == DragController.SCROLL_LEFT) ? -1 : 1);
if (0 <= screen && screen < getChildCount()) {
((CellLayout) getChildAt(screen)).setHover(true);
}
if (mDragTargetLayout != null) {
mDragTargetLayout.onDragExit();
mDragTargetLayout = null;
}
}
}
private void clearAllHovers() {
final int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
((CellLayout) getChildAt(i)).setHover(false);
}
}
@Override
public void onExitScrollArea() {
if (mInScrollArea) {
mInScrollArea = false;
clearAllHovers();
}
}
public Folder getFolderForTag(Object tag) {
final int screenCount = getChildCount();
for (int screen = 0; screen < screenCount; screen++) {
CellLayout currentScreen = ((CellLayout) getChildAt(screen));
int count = currentScreen.getChildCount();
for (int i = 0; i < count; i++) {
View child = currentScreen.getChildAt(i);
CellLayout.LayoutParams lp = (CellLayout.LayoutParams) child.getLayoutParams();
if (lp.cellHSpan == 4 && lp.cellVSpan == 4 && child instanceof Folder) {
Folder f = (Folder) child;
if (f.getInfo() == tag && f.getInfo().opened) {
return f;
}
}
}
}
return null;
}
public View getViewForTag(Object tag) {
int screenCount = getChildCount();
for (int screen = 0; screen < screenCount; screen++) {
CellLayout currentScreen = ((CellLayout) getChildAt(screen));
int count = currentScreen.getChildCount();
for (int i = 0; i < count; i++) {
View child = currentScreen.getChildAt(i);
if (child.getTag() == tag) {
return child;
}
}
}
return null;
}
void removeItems(final ArrayList<ApplicationInfo> apps) {
final int screenCount = getChildCount();
final PackageManager manager = getContext().getPackageManager();
final AppWidgetManager widgets = AppWidgetManager.getInstance(getContext());
final HashSet<String> packageNames = new HashSet<String>();
final int appCount = apps.size();
for (int i = 0; i < appCount; i++) {
packageNames.add(apps.get(i).componentName.getPackageName());
}
for (int i = 0; i < screenCount; i++) {
final CellLayout layout = (CellLayout) getChildAt(i);
// Avoid ANRs by treating each screen separately
post(new Runnable() {
public void run() {
final ArrayList<View> childrenToRemove = new ArrayList<View>();
childrenToRemove.clear();
int childCount = layout.getChildCount();
for (int j = 0; j < childCount; j++) {
final View view = layout.getChildAt(j);
Object tag = view.getTag();
if (tag instanceof ShortcutInfo) {
final ShortcutInfo info = (ShortcutInfo) tag;
final Intent intent = info.intent;
final ComponentName name = intent.getComponent();
if (Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) {
for (String packageName: packageNames) {
if (packageName.equals(name.getPackageName())) {
LauncherModel.deleteItemFromDatabase(mLauncher, info);
childrenToRemove.add(view);
}
}
}
} else if (tag instanceof UserFolderInfo) {
final UserFolderInfo info = (UserFolderInfo) tag;
final ArrayList<ShortcutInfo> contents = info.contents;
final ArrayList<ShortcutInfo> toRemove = new ArrayList<ShortcutInfo>(1);
final int contentsCount = contents.size();
boolean removedFromFolder = false;
for (int k = 0; k < contentsCount; k++) {
final ShortcutInfo appInfo = contents.get(k);
final Intent intent = appInfo.intent;
final ComponentName name = intent.getComponent();
if (Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) {
for (String packageName: packageNames) {
if (packageName.equals(name.getPackageName())) {
toRemove.add(appInfo);
LauncherModel.deleteItemFromDatabase(mLauncher, appInfo);
removedFromFolder = true;
}
}
}
}
contents.removeAll(toRemove);
if (removedFromFolder) {
final Folder folder = getOpenFolder();
if (folder != null)
folder.notifyDataSetChanged();
}
} else if (tag instanceof LiveFolderInfo) {
final LiveFolderInfo info = (LiveFolderInfo) tag;
final Uri uri = info.uri;
final ProviderInfo providerInfo = manager.resolveContentProvider(
uri.getAuthority(), 0);
if (providerInfo != null) {
for (String packageName: packageNames) {
if (packageName.equals(providerInfo.packageName)) {
LauncherModel.deleteItemFromDatabase(mLauncher, info);
childrenToRemove.add(view);
}
}
}
} else if (tag instanceof LauncherAppWidgetInfo) {
final LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) tag;
final AppWidgetProviderInfo provider =
widgets.getAppWidgetInfo(info.appWidgetId);
if (provider != null) {
for (String packageName: packageNames) {
if (packageName.equals(provider.provider.getPackageName())) {
LauncherModel.deleteItemFromDatabase(mLauncher, info);
childrenToRemove.add(view);
}
}
}
}
}
childCount = childrenToRemove.size();
for (int j = 0; j < childCount; j++) {
View child = childrenToRemove.get(j);
layout.removeViewInLayout(child);
if (child instanceof DropTarget) {
mDragController.removeDropTarget((DropTarget)child);
}
}
if (childCount > 0) {
layout.requestLayout();
layout.invalidate();
}
}
});
}
}
void updateShortcuts(ArrayList<ApplicationInfo> apps) {
final int screenCount = getChildCount();
for (int i = 0; i < screenCount; i++) {
final CellLayout layout = (CellLayout) getChildAt(i);
int childCount = layout.getChildCount();
for (int j = 0; j < childCount; j++) {
final View view = layout.getChildAt(j);
Object tag = view.getTag();
if (tag instanceof ShortcutInfo) {
ShortcutInfo info = (ShortcutInfo)tag;
// We need to check for ACTION_MAIN otherwise getComponent() might
// return null for some shortcuts (for instance, for shortcuts to
// web pages.)
final Intent intent = info.intent;
final ComponentName name = intent.getComponent();
if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION &&
Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) {
final int appCount = apps.size();
for (int k = 0; k < appCount; k++) {
ApplicationInfo app = apps.get(k);
if (app.componentName.equals(name)) {
info.setIcon(mIconCache.getIcon(info.intent));
((TextView)view).setCompoundDrawablesWithIntrinsicBounds(null,
new FastBitmapDrawable(info.getIcon(mIconCache)),
null, null);
}
}
}
}
}
}
}
void moveToDefaultScreen(boolean animate) {
if (mIsSmall || mIsInUnshrinkAnimation) {
mLauncher.showWorkspace(animate, (CellLayout)getChildAt(mDefaultPage));
} else if (animate) {
snapToPage(mDefaultPage);
} else {
setCurrentPage(mDefaultPage);
}
getChildAt(mDefaultPage).requestFocus();
}
void setIndicators(Drawable previous, Drawable next) {
mPreviousIndicator = previous;
mNextIndicator = next;
previous.setLevel(mCurrentPage);
next.setLevel(mCurrentPage);
}
@Override
public void syncPages() {
}
@Override
public void syncPageItems(int page) {
}
}
| false | false | null | null |
diff --git a/plugins/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/olap/data/impl/aggregation/filter/AggrMeasureFilterHelper.java b/plugins/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/olap/data/impl/aggregation/filter/AggrMeasureFilterHelper.java
index d596a1b13..34c2b06d9 100644
--- a/plugins/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/olap/data/impl/aggregation/filter/AggrMeasureFilterHelper.java
+++ b/plugins/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/olap/data/impl/aggregation/filter/AggrMeasureFilterHelper.java
@@ -1,472 +1,476 @@
/*******************************************************************************
* Copyright (c) 2004, 2007 Actuate Corporation.
* 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:
* Actuate Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.birt.data.engine.olap.data.impl.aggregation.filter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.eclipse.birt.data.engine.api.IBaseExpression;
import org.eclipse.birt.data.engine.api.IConditionalExpression;
import org.eclipse.birt.data.engine.api.IScriptExpression;
import org.eclipse.birt.data.engine.core.DataException;
import org.eclipse.birt.data.engine.core.security.PropertySecurity;
import org.eclipse.birt.data.engine.expression.ExpressionCompilerUtil;
import org.eclipse.birt.data.engine.olap.data.api.DimLevel;
import org.eclipse.birt.data.engine.olap.data.api.IAggregationResultSet;
import org.eclipse.birt.data.engine.olap.data.api.ILevel;
import org.eclipse.birt.data.engine.olap.data.api.cube.ICube;
import org.eclipse.birt.data.engine.olap.data.api.cube.IDimension;
import org.eclipse.birt.data.engine.olap.data.impl.AggregationFunctionDefinition;
import org.eclipse.birt.data.engine.olap.data.impl.DrilledAggregationDefinition;
import org.eclipse.birt.data.engine.olap.data.impl.dimension.Dimension;
import org.eclipse.birt.data.engine.olap.data.impl.dimension.Level;
import org.eclipse.birt.data.engine.olap.data.util.BufferedPrimitiveDiskArray;
import org.eclipse.birt.data.engine.olap.data.util.IDiskArray;
import org.eclipse.birt.data.engine.olap.data.util.SetUtil;
import org.eclipse.birt.data.engine.olap.util.OlapExpressionCompiler;
import org.eclipse.birt.data.engine.olap.util.filter.CubePosFilter;
import org.eclipse.birt.data.engine.olap.util.filter.IAggrMeasureFilterEvalHelper;
import org.eclipse.birt.data.engine.olap.util.filter.InvalidCubePosFilter;
import org.eclipse.birt.data.engine.olap.util.filter.ValidCubePosFilter;
import org.eclipse.birt.data.engine.script.FilterPassController;
import org.eclipse.birt.data.engine.script.NEvaluator;
import org.eclipse.birt.data.engine.script.ScriptConstants;
/**
*
*/
public class AggrMeasureFilterHelper
{
private Map dimMap = null;
private IAggregationResultSet[] resultSet;
/**
*
* @param cube
* @param resultSet
*/
public AggrMeasureFilterHelper( ICube cube,
IAggregationResultSet[] resultSet )
{
dimMap = new HashMap( );
IDimension[] dimension = cube.getDimesions( );
for ( int i = 0; i < dimension.length; i++ )
{
dimMap.put( dimension[i].getName( ), dimension[i] );
}
this.resultSet = resultSet;
}
private List<String> getAggregationName( )
{
List<String> aggregationName = new ArrayList<String>();
for( int i = 0; i < resultSet.length; i++ )
{
AggregationFunctionDefinition[] functions = resultSet[i].getAggregationDefinition().getAggregationFunctions();
if( functions == null )
continue;
for( int j = 0; j < functions.length; j++ )
{
aggregationName.add( functions[j].getName( ) );
}
}
return aggregationName;
}
/**
*
* @param resultSet
* @throws DataException
* @throws IOException
*/
public List getCubePosFilters( List jsMeasureEvalFilterHelper )
throws DataException, IOException
{
String[] aggregationNames = populateAggregationNames( getAggregationName( ), jsMeasureEvalFilterHelper );
List cubePosFilterList = new ArrayList( );
for ( int i = 0; i < resultSet.length; i++ )
{
if ( hasDefinition( resultSet[i], aggregationNames ) )
{
//
if( resultSet[i].getAllLevels( ) == null || resultSet[i].getAllLevels( ).length == 0 )
{
if ( resultSet[i].length( ) == 0 )
return null;
AggregationRowAccessor rowAccessor = new AggregationRowAccessor( resultSet[i], null );
for ( int j = 0; j < jsMeasureEvalFilterHelper.size( ); j++ )
{
if ( resultSet[i].getAggregationIndex( aggregationNames[j] ) >= 0 )
{
IAggrMeasureFilterEvalHelper filterHelper = (IAggrMeasureFilterEvalHelper) jsMeasureEvalFilterHelper.get( j );
- if ( !filterHelper.evaluateFilter( rowAccessor ) )
+ if ( !isTopBottomNConditionalExpression( filterHelper.getExpression( ) ) )
{
- return null;
+ //For grand total, the top/bottom filter is meaningless. Simply ignore.
+ if ( !filterHelper.evaluateFilter( rowAccessor ) )
+ {
+ return null;
+ }
}
}
}
continue;
}
Map levelMap = populateLevelMap( resultSet[i] );
final int dimSize = levelMap.size( );
List[] levelListArray = new List[dimSize];
levelMap.values( ).toArray( levelListArray );
String[] dimensionNames = new String[dimSize];
levelMap.keySet( ).toArray( dimensionNames );
IDiskArray rowIndexArray = collectValidRowIndexArray( resultSet[i],
jsMeasureEvalFilterHelper,
aggregationNames );
CubePosFilter cubePosFilter = null;;
if ( rowIndexArray.size( ) <= resultSet[i].length( ) / 2 )
{// use valid position filter
cubePosFilter = getValidPosFilter( resultSet[i],
rowIndexArray,
dimensionNames,
levelListArray );
}
else
{// use invalid position filter
cubePosFilter = getInvalidPosFilter( resultSet[i],
rowIndexArray,
dimensionNames,
levelListArray );
}
cubePosFilterList.add( cubePosFilter );
}
}
return cubePosFilterList;
}
/**
* to indicate whether the specified <code>resultSet</code> has
* aggregation definition for any one of the <code>aggregationNames</code>.
* //TODO Currently we do not support the filter on drilled aggregate result.
* @param resultSet
* @param aggregationNames
* @return
* @throws IOException
*/
private boolean hasDefinition( IAggregationResultSet resultSet,
String[] aggregationNames ) throws IOException
{
for ( int j = 0; j < aggregationNames.length; j++ )
{
if ( resultSet.getAggregationIndex( aggregationNames[j] ) >= 0
&& !( resultSet.getAggregationDefinition( ) instanceof DrilledAggregationDefinition ) )
{
return true;
}
}
return false;
}
/**
*
* @param jsMeasureEvalFilterHelper
* @return
* @throws DataException
*/
private String[] populateAggregationNames( List<String> allAggrNames, List jsMeasureEvalFilterHelper ) throws DataException
{
String[] aggregationNames = new String[jsMeasureEvalFilterHelper.size( )];
for ( int i = 0; i < aggregationNames.length; i++ )
{
IAggrMeasureFilterEvalHelper filterHelper = (IAggrMeasureFilterEvalHelper) jsMeasureEvalFilterHelper.get( i );
List bindingName = ExpressionCompilerUtil.extractColumnExpression( filterHelper.getExpression( ),
ScriptConstants.DATA_BINDING_SCRIPTABLE );
aggregationNames[i] = (String) getIntersection( allAggrNames, bindingName );
if( aggregationNames[i] == null )
aggregationNames[i] = OlapExpressionCompiler.getReferencedScriptObject( filterHelper.getExpression( ),
ScriptConstants.DATA_SET_BINDING_SCRIPTABLE );
}
return aggregationNames;
}
private Object getIntersection( List list1, List list2 )
{
for( int i = 0; i < list1.size( ); i++ )
{
for( int j = 0; j < list2.size( ); j++ )
{
if( list1.get(i).equals(list2.get(j) ) )
return list1.get(i);
}
}
return null;
}
/**
*
* @param resultSet
* @param rowIndexArray
* @param dimensionNames
* @param levelListArray
* @return
* @throws IOException
* @throws DataException
*/
private CubePosFilter getInvalidPosFilter( IAggregationResultSet resultSet,
IDiskArray rowIndexArray, String[] dimensionNames,
List[] levelListArray ) throws IOException, DataException
{
CubePosFilter cubePosFilter = new InvalidCubePosFilter( dimensionNames );
int rowIndex = 0;
for ( int i = 0; i < resultSet.length( ); i++ )
{
if ( rowIndex < rowIndexArray.size( ) )
{
Integer index = (Integer) rowIndexArray.get( rowIndex );
if ( i == index.intValue( ) )
{// ignore the valid positions
rowIndex++;
continue;
}
}
resultSet.seek( i );
IDiskArray[] dimPositions = new IDiskArray[dimensionNames.length];
for ( int j = 0; j < levelListArray.length; j++ )
{
for ( int k = 0; k < levelListArray[j].size( ); k++ )
{
DimLevel level = (DimLevel) levelListArray[j].get( k );
int levelIndex = resultSet.getLevelIndex( level );
Object[] value = resultSet.getLevelKeyValue( levelIndex );
IDiskArray positions = find( dimensionNames[j],
level,
value );
if ( dimPositions[j] == null )
{
dimPositions[j] = positions;
}
else
{
dimPositions[j] = SetUtil.getIntersection( dimPositions[j],
positions );
}
}
}
cubePosFilter.addDimPositions( dimPositions );
for ( int n = 0; n < dimPositions.length; n++ )
{
dimPositions[n].close( );
}
}
return cubePosFilter;
}
/**
*
* @param resultSet
* @param rowIndexArray
* @param dimensionNames
* @param levelListArray
* @return
* @throws IOException
* @throws DataException
*/
private CubePosFilter getValidPosFilter( IAggregationResultSet resultSet,
IDiskArray rowIndexArray, String[] dimensionNames,
List[] levelListArray ) throws IOException, DataException
{
CubePosFilter cubePosFilter = new ValidCubePosFilter( dimensionNames );
for ( int i = 0; i < rowIndexArray.size( ); i++ )
{
Integer rowIndex = (Integer) rowIndexArray.get( i );
resultSet.seek( rowIndex.intValue( ) );
IDiskArray[] dimPositions = new IDiskArray[dimensionNames.length];
for ( int j = 0; j < levelListArray.length; j++ )
{
for ( int k = 0; k < levelListArray[j].size( ); k++ )
{
DimLevel level = (DimLevel) levelListArray[j].get( k );
int levelIndex = resultSet.getLevelIndex( level );
Object[] value = resultSet.getLevelKeyValue( levelIndex );
IDiskArray positions = find( dimensionNames[j],
level,
value );
if ( dimPositions[j] == null )
{
dimPositions[j] = positions;
}
else
{
dimPositions[j] = SetUtil.getIntersection( dimPositions[j],
positions );
}
}
}
cubePosFilter.addDimPositions( dimPositions );
for ( int n = 0; n < dimPositions.length; n++ )
{
dimPositions[n].close( );
}
}
return cubePosFilter;
}
/**
* collect the filtered result
*
* @param resultSet
* @param filterHelpers
* @param aggregationNames
* @return
* @throws DataException
* @throws IOException
*/
private IDiskArray collectValidRowIndexArray(
IAggregationResultSet resultSet, List filterHelpers,
String[] aggregationNames ) throws DataException, IOException
{
IDiskArray result = new BufferedPrimitiveDiskArray( );
AggregationRowAccessor rowAccessor = new AggregationRowAccessor( resultSet, null );
List<IAggrMeasureFilterEvalHelper> firstRoundFilterHelper = new ArrayList<IAggrMeasureFilterEvalHelper>();
FilterPassController filterPassController = new FilterPassController();
for ( int j = 0; j < filterHelpers.size( ); j++ )
{
if ( resultSet.getAggregationIndex( aggregationNames[j] ) >= 0 )
{
IAggrMeasureFilterEvalHelper filterHelper = (IAggrMeasureFilterEvalHelper) filterHelpers.get( j );
if( isTopBottomNConditionalExpression( filterHelper.getExpression()))
{
IConditionalExpression expr = (IConditionalExpression)filterHelper.getExpression( );
firstRoundFilterHelper.add( filterHelper );
expr.setHandle( NEvaluator.newInstance( PropertySecurity.getSystemProperty( "java.io.tmpdir" ),
expr.getOperator( ),
expr.getExpression( ),
(IScriptExpression)expr.getOperand1( ),
filterPassController ) );
}
}
}
filterPassController.setPassLevel( FilterPassController.FIRST_PASS );
filterPassController.setRowCount( resultSet.length());
if ( firstRoundFilterHelper.size( ) > 0 )
{
for ( int i = 0; i < resultSet.length( ); i++ )
{
resultSet.seek( i );
for ( int j = 0; j < firstRoundFilterHelper.size( ); j++ )
{
firstRoundFilterHelper.get( j )
.evaluateFilter( rowAccessor );
}
}
}
filterPassController.setPassLevel( FilterPassController.SECOND_PASS );
for ( int i = 0; i < resultSet.length( ); i++ )
{
resultSet.seek( i );
boolean isFilterByAll = true;
for ( int j = 0; j < filterHelpers.size( ); j++ )
{
if ( resultSet.getAggregationIndex( aggregationNames[j] ) >= 0 )
{
IAggrMeasureFilterEvalHelper filterHelper = (IAggrMeasureFilterEvalHelper) filterHelpers.get( j );
if ( !filterHelper.evaluateFilter( rowAccessor ) )
{
isFilterByAll = false;
break;
}
}
}
if ( isFilterByAll )
{
result.add( Integer.valueOf( i ) );
}
}
return result;
}
private boolean isTopBottomNConditionalExpression( IBaseExpression expr )
{
if( expr == null || ! (expr instanceof IConditionalExpression ))
{
return false;
}
switch (( (IConditionalExpression)expr).getOperator())
{
case IConditionalExpression.OP_TOP_N :
case IConditionalExpression.OP_BOTTOM_N :
case IConditionalExpression.OP_TOP_PERCENT :
case IConditionalExpression.OP_BOTTOM_PERCENT :
return true;
default:
return false;
}
}
/**
*
* @param resultSet
* @return
*/
private Map populateLevelMap( IAggregationResultSet resultSet )
{
final DimLevel[] dimLevels = resultSet.getAllLevels( );
Map levelMap = new HashMap( );
for ( int j = 0; j < dimLevels.length; j++ )
{
final String dimensionName = dimLevels[j].getDimensionName( );
List list = (List) levelMap.get( dimensionName );
if ( list == null )
{
list = new ArrayList( );
levelMap.put( dimensionName, list );
}
list.add( dimLevels[j] );
}
return levelMap;
}
/**
*
* @param dimensionName
* @param level
* @param keyValue
* @return
* @throws DataException
* @throws IOException
*/
private IDiskArray find( String dimensionName, DimLevel level,
Object[] keyValue ) throws DataException, IOException
{
Dimension dimension = (Dimension) dimMap.get( dimensionName );
ILevel[] levels = dimension.getHierarchy( ).getLevels( );
int i = 0;
for ( ; i < levels.length; i++ )
{
if ( level.getLevelName( ).equals( levels[i].getName( ) ) )
{
break;
}
}
if ( i < levels.length )
{
return dimension.findPosition( (Level) levels[i], keyValue );
}
throw new DataException( "Can't find level {0} in the dimension!", level );//$NON-NLS-1$
}
}
| false | false | null | null |
diff --git a/src/powercrystals/minefactoryreloaded/setup/recipe/GregTech.java b/src/powercrystals/minefactoryreloaded/setup/recipe/GregTech.java
index c63a8b49..759a151c 100644
--- a/src/powercrystals/minefactoryreloaded/setup/recipe/GregTech.java
+++ b/src/powercrystals/minefactoryreloaded/setup/recipe/GregTech.java
@@ -1,1179 +1,1181 @@
package powercrystals.minefactoryreloaded.setup.recipe;
import ic2.api.item.Items;
import net.minecraft.block.Block;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraftforge.oredict.ShapedOreRecipe;
import powercrystals.minefactoryreloaded.MineFactoryReloadedCore;
import powercrystals.minefactoryreloaded.setup.MFRConfig;
import powercrystals.minefactoryreloaded.setup.Machine;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.registry.GameRegistry;
public class GregTech extends Vanilla
{
@Override
protected void registerMachines()
{
if(!Loader.isModLoaded("GregTech_Addon") || !Loader.isModLoaded("IC2"))
{
return;
}
try
{
ItemStack generator = Items.getItem("generator");
ItemStack compressor = Items.getItem("compressor");
ItemStack luminator = Items.getItem("luminator");
ItemStack mfsUnit = Items.getItem("mfsUnit");
ItemStack reactorChamber = Items.getItem("reactorChamber");
ItemStack reinforcedGlass = Items.getItem("reinforcedGlass");
if(Machine.Planter.getIsRecipeEnabled())
{
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(MineFactoryReloadedCore.machineBlocks.get(0), 1, 0), new Object[]
{
"PTP",
"SFS",
"OCO",
'P', "sheetPlastic",
'T', Item.flowerPot,
'S', Block.pistonBase,
'F', "craftingRawMachineTier00",
'O', "plateCopper",
'C', "craftingCircuitTier02",
} ));
}
if(Machine.Fisher.getIsRecipeEnabled())
{
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(MineFactoryReloadedCore.machineBlocks.get(0), 1, 1), new Object[]
{
"PTP",
"SFS",
"OCO",
'P', "sheetPlastic",
'T', Item.fishingRod,
'S', Item.bucketEmpty,
'F', "craftingRawMachineTier01",
'O', "plateSteel",
'C', "craftingCircuitTier04"
} ));
}
if(Machine.Harvester.getIsRecipeEnabled())
{
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(MineFactoryReloadedCore.machineBlocks.get(0), 1, 2), new Object[]
{
"PTP",
"SFS",
"OCO",
'P', "sheetPlastic",
'T', Item.axeIron,
'S', Item.shears,
'F', "craftingRawMachineTier00",
'O', "plateGold",
'C', "craftingCircuitTier02"
} ));
}
if(Machine.Rancher.getIsRecipeEnabled())
{
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(MineFactoryReloadedCore.machineBlocks.get(0), 1, 3), new Object[]
{
"PTP",
"SFS",
"OCO",
'P', "sheetPlastic",
'T', "craftingPump",
'S', Item.shears,
'F', "craftingRawMachineTier01",
'O', "plateTin",
'C', "craftingCircuitTier04"
} ));
}
if(Machine.Fertilizer.getIsRecipeEnabled())
{
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(MineFactoryReloadedCore.machineBlocks.get(0), 1, 4), new Object[]
{
"PTP",
"SFS",
"OCO",
'P', "sheetPlastic",
'T', Item.glassBottle,
'S', Item.leather,
'F', "craftingRawMachineTier01",
'O', "plateSilver",
'C', "craftingCircuitTier04"
} ));
}
if(Machine.Vet.getIsRecipeEnabled())
{
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(MineFactoryReloadedCore.machineBlocks.get(0), 1, 5), new Object[]
{
"PTP",
"TFT",
"OCO",
'P', "sheetPlastic",
'T', MineFactoryReloadedCore.syringeEmptyItem,
'F', "craftingRawMachineTier01",
'O', "plateZinc",
'C', "craftingCircuitTier04"
} ));
}
if(Machine.ItemCollector.getIsRecipeEnabled())
{
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(MineFactoryReloadedCore.machineBlocks.get(0), 1, 6), new Object[]
{
"PVP",
" F ",
"PCP",
'P', "sheetPlastic",
'F', "craftingRawMachineTier01",
'C', Block.chest,
'V', "craftingConveyor"
} ));
}
if(Machine.BlockBreaker.getIsRecipeEnabled())
{
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(MineFactoryReloadedCore.machineBlocks.get(0), 1, 7), new Object[]
{
"PTP",
"SFS",
"OCO",
'P', "sheetPlastic",
'T', "craftingItemValve",
'S', Item.pickaxeIron,
'F', "craftingRawMachineTier02",
'O', "plateAluminium",
'C', "craftingCircuitTier04"
} ));
}
if(Machine.WeatherCollector.getIsRecipeEnabled())
{
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(MineFactoryReloadedCore.machineBlocks.get(0), 1, 8), new Object[]
{
"PTP",
"TFT",
"OCO",
'P', "sheetPlastic",
'T', Item.bucketEmpty,
'F', "craftingRawMachineTier02",
'O', "plateBrass",
'C', "craftingCircuitTier04"
} ));
}
if(Machine.SludgeBoiler.getIsRecipeEnabled())
{
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(MineFactoryReloadedCore.machineBlocks.get(0), 1, 9), new Object[]
{
"PTP",
"SFS",
"OCO",
'P', "sheetPlastic",
'T', Item.bucketEmpty,
'S', Block.furnaceIdle,
'F', "craftingRawMachineTier02",
'O', "plateRefinedIron",
'C', "craftingCircuitTier04"
} ));
}
if(Machine.Sewer.getIsRecipeEnabled())
{
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(MineFactoryReloadedCore.machineBlocks.get(0), 1, 10), new Object[]
{
"PTP",
"SFS",
"SSS",
'P', "sheetPlastic",
'T', Item.bucketEmpty,
'S', Block.brick,
'F', "craftingRawMachineTier01",
} ));
}
if(Machine.Composter.getIsRecipeEnabled())
{
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(MineFactoryReloadedCore.machineBlocks.get(0), 1, 11), new Object[]
{
"PTP",
"SFS",
"OCO",
'P', "sheetPlastic",
'T', Block.furnaceIdle,
'S', Block.pistonBase,
'F', "craftingRawMachineTier01",
'O', Block.brick,
'C', "craftingCircuitTier04"
} ));
}
if(Machine.Breeder.getIsRecipeEnabled())
{
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(MineFactoryReloadedCore.machineBlocks.get(0), 1, 12), new Object[]
{
"PTP",
"SFS",
"OCO",
'P', "sheetPlastic",
'T', Item.appleGold,
'S', Item.goldenCarrot,
'F', "craftingRawMachineTier02",
'O', new ItemStack(Item.dyePowder, 1, 5),
'C', "craftingCircuitTier04"
} ));
}
if(Machine.Grinder.getIsRecipeEnabled())
{
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(MineFactoryReloadedCore.machineBlocks.get(0), 1, 13), new Object[]
{
"PTP",
"SFS",
"OCO",
'P', "sheetPlastic",
'S', "craftingMachineParts",
'T', "craftingGrinder",
'F', "craftingRawMachineTier02",
'O', Item.book,
'C', "craftingCircuitTier04"
} ));
}
if(Machine.AutoEnchanter.getIsRecipeEnabled())
{
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(MineFactoryReloadedCore.machineBlocks.get(0), 1, 14), new Object[]
{
"PTP",
"SFS",
"OCO",
'P', "sheetPlastic",
'T', "plateAlloyIridium",
'S', Item.book,
'F', "craftingRawMachineTier04",
'O', "craftingCircuitTier06",
'C', Block.obsidian
} ));
}
if(Machine.Chronotyper.getIsRecipeEnabled())
{
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(MineFactoryReloadedCore.machineBlocks.get(0), 1, 15), new Object[]
{
"PTP",
"TFT",
"OCO",
'P', "sheetPlastic",
'T', "gemEmerald",
'F', "craftingRawMachineTier02",
'O', new ItemStack(Item.dyePowder, 1, 5),
'C', "craftingCircuitTier06"
} ));
}
if(Machine.Ejector.getIsRecipeEnabled())
{
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(MineFactoryReloadedCore.machineBlocks.get(1), 1, 0), new Object[]
{
"PTP",
" F ",
"OOO",
'P', "sheetPlastic",
'T', "craftingRedstoneReceiver",
'F', "craftingRawMachineTier02",
'O', "dustRedstone"
} ));
}
if(Machine.ItemRouter.getIsRecipeEnabled())
{
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(MineFactoryReloadedCore.machineBlocks.get(1), 1, 1), new Object[]
{
"PTP",
"SFS",
"PSP",
'P', "sheetPlastic",
'T', Block.chest,
'S', Item.redstoneRepeater,
'F', "craftingRawMachineTier02"
} ));
}
if(Machine.LiquidRouter.getIsRecipeEnabled())
{
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(MineFactoryReloadedCore.machineBlocks.get(1), 1, 2), new Object[]
{
"PTP",
"SFS",
"PSP",
'P', "sheetPlastic",
'T', "craftingPump",
'S', Item.redstoneRepeater,
'F', "craftingRawMachineTier02"
} ));
}
if(Machine.DeepStorageUnit.getIsRecipeEnabled())
{
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(MineFactoryReloadedCore.machineBlocks.get(1), 1, 3), new Object[]
{
"PDP",
"CFC",
"PEP",
'P', "sheetPlastic",
'C', "craftingCircuitTier07",
'E', Item.eyeOfEnder,
'D', "craftingCircuitTier08",
'F', "craftingRawMachineTier04"
} ));
if(MFRConfig.enableCheapDSU.getBoolean(false))
{
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(MineFactoryReloadedCore.machineBlocks.get(1), 1, 3), new Object[]
{
"PCP",
"CFC",
"PCP",
'P', "sheetPlastic",
'C', Block.chest,
'F', "craftingRawMachineTier01"
} ));
}
}
if(Machine.LiquiCrafter.getIsRecipeEnabled())
{
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(MineFactoryReloadedCore.machineBlocks.get(1), 1, 4), new Object[]
{
"PTP",
"SFS",
"OCO",
'P', "sheetPlastic",
'T', Block.workbench,
'S', "craftingPump",
'F', "craftingRawMachineTier01",
'O', Item.book,
'C', "craftingLiquidMeter"
} ));
}
if(Machine.LavaFabricator.getIsRecipeEnabled())
{
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(MineFactoryReloadedCore.machineBlocks.get(1), 1, 5), new Object[]
{
"PTP",
"SFS",
"OCO",
'P', "sheetPlastic",
'T', "plateSteel",
'S', Item.magmaCream,
'F', "craftingRawMachineTier03",
'O', Item.blazeRod,
'C', "craftingCircuitTier04"
} ));
}
if(Machine.OilFabricator.getIsRecipeEnabled())
{
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(MineFactoryReloadedCore.machineBlocks.get(1), 1, 6), new Object[]
{
"PTP",
"OFO",
"OCO",
'P', "sheetPlastic",
'T', Block.tnt,
'F', "craftingRawMachineTier03",
'O', Block.obsidian,
'C', "craftingCircuitTier04"
} ));
}
if(Machine.AutoJukebox.getIsRecipeEnabled())
{
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(MineFactoryReloadedCore.machineBlocks.get(1), 1, 7), new Object[]
{
"PJP",
" F ",
" P ",
'P', "sheetPlastic",
'J', Block.jukebox,
'F', "craftingRawMachineTier01"
} ));
}
if(Machine.Unifier.getIsRecipeEnabled())
{
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(MineFactoryReloadedCore.machineBlocks.get(1), 1, 8), new Object[]
{
"PTP",
"SFL",
"OCO",
'P', "sheetPlastic",
'T', "plateCopper",
'S', "plateSilver",
'L', "plateGold",
'F', "craftingRawMachineTier01",
'O', Item.comparator,
'C', Item.book
} ));
}
if(Machine.AutoSpawner.getIsRecipeEnabled())
{
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(MineFactoryReloadedCore.machineBlocks.get(1), 1, 9), new Object[]
{
"PTP",
"SFS",
"OCO",
'P', "sheetPlastic",
'T', "plateAlloyIridium",
'S', Item.magmaCream,
'F', "craftingRawMachineTier02",
'O', "gemRuby",
'C', "craftingCircuitTier05"
} ));
}
if(Machine.BioReactor.getIsRecipeEnabled())
{
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(MineFactoryReloadedCore.machineBlocks.get(1), 1, 10), new Object[]
{
"PTP",
"SFS",
"OCO",
'P', "sheetPlastic",
'T', Item.fermentedSpiderEye,
'S', Item.slimeBall,
'F', "craftingRawMachineTier03",
'O', "craftingItemValve",
'C', "craftingPump"
} ));
}
if(Machine.BioFuelGenerator.getIsRecipeEnabled())
{
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(MineFactoryReloadedCore.machineBlocks.get(1), 1, 11), new Object[]
{
"PCP",
"SFS",
"OCO",
'P', "sheetPlastic",
'S', "plateRefinedIron",
'F', generator,
'O', Item.blazeRod,
'C', "craftingCircuitTier04"
} ));
}
if(Machine.AutoDisenchanter.getIsRecipeEnabled())
{
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(MineFactoryReloadedCore.machineBlocks.get(1), 1, 12), new Object[]
{
"PTP",
"SFS",
"OCO",
'P', "sheetPlastic",
'T', "plateAlloyIridium",
'S', Item.book,
'F', "craftingRawMachineTier03",
'O', "craftingCircuitTier06",
'C', Block.netherBrick
} ));
}
if(Machine.Slaughterhouse.getIsRecipeEnabled())
{
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(MineFactoryReloadedCore.machineBlocks.get(1), 1, 13), new Object[]
{
"GIG",
"SFS",
"XCX",
'G', "sheetPlastic",
'S', "craftingPump",
'X', "craftingGrinder",
'I', "craftingDiamond",
'F', "craftingRawMachineTier02",
'C', "craftingCircuitTier04"
} ));
}
if(Machine.MeatPacker.getIsRecipeEnabled())
{
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(MineFactoryReloadedCore.machineBlocks.get(1), 1, 14), new Object[]
{
"GSG",
"BFB",
"TCT",
'G', "sheetPlastic",
'B', "craftingHeatingCoilTier01",
'S', "craftingPump",
'F', compressor,
'C', "craftingMachineParts",
'T', "craftingPump"
} ));
}
if(Machine.EnchantmentRouter.getIsRecipeEnabled())
{
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(MineFactoryReloadedCore.machineBlocks.get(1), 1, 15), new Object[]
{
"PBP",
"SFS",
"PSP",
'P', "sheetPlastic",
'B', Item.book,
'S', Item.redstoneRepeater,
'F', "craftingRawMachineTier02"
} ));
}
if(Machine.LaserDrill.getIsRecipeEnabled())
{
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(MineFactoryReloadedCore.machineBlocks.get(2), 1, 0), new Object[]
{
"GFG",
"CRC",
"DLD",
'G', "sheetPlastic",
'D', "gemDiamond",
'L', reinforcedGlass,
'R', reactorChamber,
'F', "craftingRawMachineTier04",
'C', "craftingSuperconductor"
} ));
}
if(Machine.LaserDrillPrecharger.getIsRecipeEnabled())
{
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(MineFactoryReloadedCore.machineBlocks.get(2), 1, 1), new Object[]
{
"GSG",
"RFL",
"DCD",
'G', "sheetPlastic",
'D', "gemDiamond",
'S', MineFactoryReloadedCore.pinkSlimeballItem,
'L', luminator,
'F', mfsUnit,
'C', "craftingCircuitTier07",
'R', "craftingSuperconductor"
} ));
}
if(Machine.AutoAnvil.getIsRecipeEnabled())
{
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(MineFactoryReloadedCore.machineBlocks.get(2), 1, 2), new Object[]
{
"GIG",
"SFS",
"ACA",
'G', "sheetPlastic",
'A', Block.anvil,
'S', "plateSteel",
'F', "craftingRawMachineTier04",
'C', "craftingCircuitTier07",
'I', "plateAlloyIridium"
} ));
}
if(Machine.BlockSmasher.getIsRecipeEnabled())
{
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(MineFactoryReloadedCore.machineBlocks.get(2), 1, 3), new Object[]
{
"GPG",
"HFH",
"BCB",
'G', "sheetPlastic",
'P', Block.pistonBase,
'H', MineFactoryReloadedCore.factoryHammerItem,
'B', "craftingItemValve",
'F', "craftingRawMachineTier03",
'C', "craftingCircuitTier06"
} ));
}
if(Machine.RedNote.getIsRecipeEnabled())
{
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(MineFactoryReloadedCore.machineBlocks.get(2), 1, 4), new Object[]
{
"GNG",
"CFC",
"GNG",
'G', "sheetPlastic",
'C', MineFactoryReloadedCore.rednetCableBlock,
'N', Block.music,
'F', "craftingRawMachineTier01"
} ));
}
if(Machine.AutoBrewer.getIsRecipeEnabled())
{
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(MineFactoryReloadedCore.machineBlocks.get(2), 1, 5), new Object[]
{
"GBG",
"CFC",
"RCR",
'G', "sheetPlastic",
'C', "craftingPump",
'B', Item.brewingStand,
'R', "craftingItemValve",
'F', "craftingRawMachineTier02",
'C', "craftingCircuitTier05"
} ));
}
if(Machine.FruitPicker.getIsRecipeEnabled())
{
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(MineFactoryReloadedCore.machineBlocks.get(2), 1, 6), new Object[]
{
"GXG",
"SFS",
"SCS",
'G', "sheetPlastic",
'X', Item.axeGold,
'S', Item.shears,
'F', "craftingRawMachineTier03",
'C', "craftingCircuitTier04"
} ));
}
}
catch (Exception x)
{
x.printStackTrace();
}
}
@Override
protected void registerMachineUpgrades()
{
if(!Loader.isModLoaded("GregTech_Addon") || !Loader.isModLoaded("IC2"))
{
return;
}
try
{
+ ItemStack insulatedGoldCableItem = Items.getItem("insulatedGoldCableItem");
+
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(MineFactoryReloadedCore.upgradeItem, 1, 0), new Object[]
{
"III",
"PPP",
"RGR",
'I', "dyeBlue",
'P', "dustPlastic",
- 'R', "copperWire",
+ 'R', insulatedGoldCableItem,
'G', "craftingCircuitTier02",
} ));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(MineFactoryReloadedCore.upgradeItem, 1, 1), new Object[]
{
"III",
"PPP",
"RGR",
'I', Item.ingotIron,
'P', "dustPlastic",
- 'R', "copperWire",
+ 'R', insulatedGoldCableItem,
'G', "craftingCircuitTier02",
} ));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(MineFactoryReloadedCore.upgradeItem, 1, 2), new Object[]
{
"III",
"PPP",
"RGR",
'I', "ingotTin",
'P', "dustPlastic",
- 'R', "copperWire",
+ 'R', insulatedGoldCableItem,
'G', "craftingCircuitTier02",
} ));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(MineFactoryReloadedCore.upgradeItem, 1, 3), new Object[]
{
"III",
"PPP",
"RGR",
'I', "ingotCopper",
'P', "dustPlastic",
- 'R', "copperWire",
+ 'R', insulatedGoldCableItem,
'G', "craftingCircuitTier04",
} ));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(MineFactoryReloadedCore.upgradeItem, 1, 4), new Object[]
{
"III",
"PPP",
"RGR",
'I', "ingotBronze",
'P', "dustPlastic",
- 'R', "copperWire",
+ 'R', insulatedGoldCableItem,
'G', "craftingCircuitTier04",
} ));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(MineFactoryReloadedCore.upgradeItem, 1, 5), new Object[]
{
"III",
"PPP",
"RGR",
'I', "ingotSilver",
'P', "dustPlastic",
- 'R', "copperWire",
+ 'R', insulatedGoldCableItem,
'G', "craftingCircuitTier04",
} ));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(MineFactoryReloadedCore.upgradeItem, 1, 6), new Object[]
{
"III",
"PPP",
"RGR",
'I', "ingotGold",
'P', "dustPlastic",
- 'R', "copperWire",
+ 'R', insulatedGoldCableItem,
'G', "craftingCircuitTier04",
} ));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(MineFactoryReloadedCore.upgradeItem, 1, 7), new Object[]
{
"III",
"PPP",
"RGR",
'I', Item.netherQuartz,
'P', "dustPlastic",
- 'R', "copperWire",
+ 'R', insulatedGoldCableItem,
'G', "craftingCircuitTier06",
} ));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(MineFactoryReloadedCore.upgradeItem, 1, 8), new Object[]
{
"III",
"PPP",
"RGR",
'I', "gemDiamond",
'P', "dustPlastic",
- 'R', "copperWire",
+ 'R', insulatedGoldCableItem,
'G', "craftingCircuitTier06",
} ));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(MineFactoryReloadedCore.upgradeItem, 1, 9), new Object[]
{
"III",
"PPP",
"RGR",
'I', "ingotPlatinum",
'P', "dustPlastic",
- 'R', "copperWire",
+ 'R', insulatedGoldCableItem,
'G', "craftingCircuitTier06",
} ));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(MineFactoryReloadedCore.upgradeItem, 1, 10), new Object[]
{
"III",
"PPP",
"RGR",
'I', Item.emerald,
'P', "dustPlastic",
- 'R', "copperWire",
+ 'R', insulatedGoldCableItem,
'G', "craftingCircuitTier06",
} ));
}
catch (Exception x)
{
x.printStackTrace();
}
}
@Override
protected void registerConveyors()
{
if(!Loader.isModLoaded("GregTech_Addon") || !Loader.isModLoaded("IC2"))
{
return;
}
try
{
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(MineFactoryReloadedCore.conveyorBlock, 16, 16), new Object[]
{
"UUU",
"RIR",
'U', "itemRubber",
'R', "dustRedstone",
'I', "plateIron",
} ));
for(int i = 0; i < 16; i++)
{
GameRegistry.addShapelessRecipe(new ItemStack(MineFactoryReloadedCore.conveyorBlock, 1, i), new ItemStack(MineFactoryReloadedCore.conveyorBlock, 1, 16), new ItemStack(MineFactoryReloadedCore.ceramicDyeItem, 1, i));
}
}
catch (Exception x)
{
x.printStackTrace();
}
}
@Override
protected void registerSyringes()
{
if(!Loader.isModLoaded("GregTech_Addon") || !Loader.isModLoaded("IC2"))
{
return;
}
try
{
ItemStack cell = Items.getItem("cell");
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(MineFactoryReloadedCore.syringeEmptyItem, 1), new Object[]
{
"PRP",
"PCP",
" I ",
'P', "sheetPlastic",
'R', "itemRubber",
'I', Item.ingotIron,
'C', cell
} ));
GameRegistry.addShapelessRecipe(new ItemStack(MineFactoryReloadedCore.syringeHealthItem), new Object[] { MineFactoryReloadedCore.syringeEmptyItem, Item.appleRed });
GameRegistry.addShapelessRecipe(new ItemStack(MineFactoryReloadedCore.syringeGrowthItem), new Object[] { MineFactoryReloadedCore.syringeEmptyItem, Item.goldenCarrot });
GameRegistry.addRecipe(new ItemStack(MineFactoryReloadedCore.syringeZombieItem, 1), new Object[]
{
"FFF",
"FSF",
"FFF",
'F', Item.rottenFlesh,
'S', MineFactoryReloadedCore.syringeEmptyItem,
} );
GameRegistry.addRecipe(new ItemStack(MineFactoryReloadedCore.syringeSlimeItem, 1), new Object[]
{
" ",
" S ",
"BLB",
'B', Item.slimeBall,
'L', new ItemStack(Item.dyePowder, 1, 4),
'S', MineFactoryReloadedCore.syringeEmptyItem,
} );
GameRegistry.addShapelessRecipe(new ItemStack(MineFactoryReloadedCore.syringeCureItem), new Object[] { MineFactoryReloadedCore.syringeEmptyItem, Item.appleGold });
}
catch (Exception x)
{
x.printStackTrace();
}
}
@Override
protected void registerMiscItems()
{
if(!Loader.isModLoaded("GregTech_Addon") || !Loader.isModLoaded("IC2"))
{
return;
}
try
{
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(MineFactoryReloadedCore.plasticSheetItem, 4), new Object[]
{
"##",
"##",
'#', "dustPlastic",
} ));
GameRegistry.addRecipe(new ItemStack(MineFactoryReloadedCore.fertilizerItem, 16), new Object[]
{
"WBW",
"STS",
"WBW",
'W', Item.wheat,
'B', new ItemStack(Item.dyePowder, 1, 15),
'S', Item.silk,
'T', Item.stick,
} );
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(MineFactoryReloadedCore.safariNetItem, 1), new Object[]
{
" E ",
"CGC",
" E ",
'E', Item.enderPearl,
'G', Item.ghastTear,
'C', "craftingCircuitTier04"
} ));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(MineFactoryReloadedCore.safariNetSingleItem, 1), new Object[]
{
"SLS",
"CBC",
"S S",
'S', Item.silk,
'L', Item.leather,
'B', Item.slimeBall,
'C', "craftingCircuitTier02"
} ));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(MineFactoryReloadedCore.safariNetJailerItem, 1), new Object[]
{
" P ",
"ISI",
" P ",
'S', MineFactoryReloadedCore.safariNetSingleItem,
'I', Block.fenceIron,
'P', "plateIron"
} ));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(MineFactoryReloadedCore.safariNetLauncherItem, 1), new Object[]
{
"PGP",
"LGL",
"IRI",
'P', "sheetPlastic",
'L', Item.lightStoneDust,
'G', Item.gunpowder,
'I', "plateIron",
'R', "craftingItemValve"
} ));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(MineFactoryReloadedCore.factoryHammerItem, 1), new Object[]
{
"PPP",
" S ",
" S ",
'P', "sheetPlastic",
'S', Item.stick,
} ));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(MineFactoryReloadedCore.blankRecordItem, 1), new Object[]
{
"RRR",
"RPR",
"RRR",
- 'R', "plasticDust",
+ 'R', "dustPlastic",
'P', Item.paper,
} ));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(MineFactoryReloadedCore.spyglassItem), new Object[]
{
"GLG",
"PLP",
" S ",
'G', "ingotGold",
'L', Block.glass,
'P', "sheetPlastic",
'S', Item.stick
} ));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(MineFactoryReloadedCore.portaSpawnerItem), new Object[]
{
"GLG",
"DND",
"GLG",
'G', "plateChrome",
'L', "plateAlloyIridium",
'D', "gemDiamond",
'N', Item.netherStar
} ));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(MineFactoryReloadedCore.strawItem), new Object[]
{
"PP",
"P ",
"P ",
'P', "sheetPlastic",
} ));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(MineFactoryReloadedCore.xpExtractorItem), new Object[]
{
"PLP",
"PLP",
"RPR",
'R', "itemRubber",
'L', Block.glass,
'P', "sheetPlastic",
} ));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(MineFactoryReloadedCore.rulerItem), new Object[]
{
"P",
"A",
"P",
'P', "sheetPlastic",
'A', Item.paper,
} ));
GameRegistry.addRecipe(new ItemStack(MineFactoryReloadedCore.vineScaffoldBlock, 8), new Object[]
{
"VV",
"VV",
"VV",
'V', Block.vine,
} );
}
catch (Exception x)
{
x.printStackTrace();
}
}
@Override
protected void registerRails()
{
if(!Loader.isModLoaded("GregTech_Addon") || !Loader.isModLoaded("IC2"))
{
return;
}
try
{
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(MineFactoryReloadedCore.railPickupCargoBlock, 1), new Object[]
{
" C ",
"SDS",
"SSS",
'C', "craftingConveyor",
'S', "sheetPlastic",
'D', Block.railDetector
} ));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(MineFactoryReloadedCore.railDropoffCargoBlock, 1), new Object[]
{
"SSS",
"SDS",
" C ",
'C', "craftingConveyor",
'S', "sheetPlastic",
'D', Block.railDetector
} ));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(MineFactoryReloadedCore.railPickupPassengerBlock, 1), new Object[]
{
" L ",
"SDS",
"SSS",
'L', Block.blockLapis,
'S', "sheetPlastic",
'D', Block.railDetector
} ));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(MineFactoryReloadedCore.railDropoffPassengerBlock, 1), new Object[]
{
"SSS",
"SDS",
" L ",
'L', Block.blockLapis,
'S', "sheetPlastic",
'D', Block.railDetector
} ));
}
catch (Exception x)
{
x.printStackTrace();
}
}
@Override
protected void registerRedNet()
{
if(!Loader.isModLoaded("GregTech_Addon") || !Loader.isModLoaded("IC2"))
{
return;
}
try
{
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(MineFactoryReloadedCore.rednetCableBlock, 8), new Object[]
{
"PPP",
"RRR",
"PPP",
'R', "dustRedstone",
'P', "sheetPlastic",
} ));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(MineFactoryReloadedCore.factoryDecorativeBrickBlock, 1, 11), new Object[]
{
"PRP",
"RGR",
"PIP",
'R', "dustRedstone",
'P', "sheetPlastic",
'G', Block.glass,
'I', "plateIron",
} ));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(MineFactoryReloadedCore.rednetLogicBlock), new Object[]
{
"RDR",
"LGL",
"PHP",
'H', new ItemStack(MineFactoryReloadedCore.factoryDecorativeBrickBlock, 1, 11),
'P', "sheetPlastic",
'G', "plateGold",
'L', "craftingCircuitTier04",
'D', "gemDiamond",
'R', "dustRedstone",
} ));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(MineFactoryReloadedCore.logicCardItem, 1, 0), new Object[]
{
"RPR",
"PGP",
"RPR",
'P', "sheetPlastic",
'G', "ingotGold",
'R', "dustRedstone",
} ));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(MineFactoryReloadedCore.logicCardItem, 1, 1), new Object[]
{
"GPG",
"PCP",
"RGR",
'C', new ItemStack(MineFactoryReloadedCore.logicCardItem, 1, 0),
'P', "sheetPlastic",
'G', "plateGold",
'R', "dustRedstone",
} ));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(MineFactoryReloadedCore.logicCardItem, 1, 2), new Object[]
{
"DPD",
"RCR",
"GDG",
'C', new ItemStack(MineFactoryReloadedCore.logicCardItem, 1, 1),
'P', "sheetPlastic",
'G', "plateSteel",
'D', "gemDiamond",
'R', "dustRedstone",
} ));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(MineFactoryReloadedCore.rednetMeterItem, 1, 0), new Object[]
{
" G",
"PR",
"PP",
'P', "sheetPlastic",
'G', "nuggetGold",
'R', "dustRedstone",
} ));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(MineFactoryReloadedCore.rednetMemoryCardItem, 1, 0), new Object[]
{
"GGG",
"PRP",
"PPP",
'P', "sheetPlastic",
'G', "nuggetGold",
'R', "dustRedstone",
} ));
GameRegistry.addShapelessRecipe(new ItemStack(MineFactoryReloadedCore.rednetMemoryCardItem, 1, 0), new ItemStack(MineFactoryReloadedCore.rednetMemoryCardItem, 1, 0));
}
catch (Exception x)
{
x.printStackTrace();
}
}
}
\ No newline at end of file
| false | false | null | null |
diff --git a/loci/formats/in/QTReader.java b/loci/formats/in/QTReader.java
index dfaf5feb5..7a341724a 100644
--- a/loci/formats/in/QTReader.java
+++ b/loci/formats/in/QTReader.java
@@ -1,698 +1,698 @@
//
// QTReader.java
//
/*
LOCI Bio-Formats package for reading and converting biological file formats.
Copyright (C) 2005-@year@ Melissa Linkert, Curtis Rueden, Chris Allan,
Eric Kjellman and Brian Loranger.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Library General Public License as published by
the Free Software Foundation; either version 2 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 Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package loci.formats.in;
import java.io.*;
import java.util.Vector;
import java.util.zip.*;
import loci.formats.*;
import loci.formats.codec.*;
import loci.formats.meta.FilterMetadata;
import loci.formats.meta.MetadataStore;
/**
* QTReader is the file format reader for QuickTime movie files.
* It does not require any external libraries to be installed.
*
* Video codecs currently supported: raw, rle, jpeg, mjpb, rpza.
* Additional video codecs will be added as time permits.
*
* <dl><dt><b>Source code:</b></dt>
* <dd><a href="https://skyking.microscopy.wisc.edu/trac/java/browser/trunk/loci/formats/in/QTReader.java">Trac</a>,
* <a href="https://skyking.microscopy.wisc.edu/svn/java/trunk/loci/formats/in/QTReader.java">SVN</a></dd></dl>
*
* @author Melissa Linkert linkert at wisc.edu
*/
public class QTReader extends FormatReader {
// -- Constants --
/** List of identifiers for each container atom. */
private static final String[] CONTAINER_TYPES = {
"moov", "trak", "udta", "tref", "imap", "mdia", "minf", "stbl", "edts",
"mdra", "rmra", "imag", "vnrp", "dinf"
};
// -- Fields --
/** Offset to start of pixel data. */
private long pixelOffset;
/** Total number of bytes of pixel data. */
private long pixelBytes;
/** Pixel depth. */
private int bitsPerPixel;
/** Raw plane size, in bytes. */
private int rawSize;
/** Offsets to each plane's pixel data. */
private Vector offsets;
/** Pixel data for the previous image plane. */
private byte[] prevPixels;
/** Previous plane number. */
private int prevPlane;
/** Flag indicating whether we can safely use prevPixels. */
private boolean canUsePrevious;
/** Video codec used by this movie. */
private String codec;
/** Some movies use two video codecs -- this is the second codec. */
private String altCodec;
/** Number of frames that use the alternate codec. */
private int altPlanes;
/** An instance of the old QuickTime reader, in case this one fails. */
private LegacyQTReader legacy;
/** Flag indicating whether to use legacy reader by default. */
private boolean useLegacy;
/** Amount to subtract from each offset. */
private int scale;
/** Number of bytes in each plane. */
private Vector chunkSizes;
/** Set to true if the scanlines in a plane are interlaced (mjpb only). */
private boolean interlaced;
/** Flag indicating whether the resource and data fork are separated. */
private boolean spork;
private boolean flip;
// -- Constructor --
/** Constructs a new QuickTime reader. */
public QTReader() { super("QuickTime", "mov"); }
// -- QTReader API methods --
/** Sets whether to use the legacy reader (QTJava) by default. */
public void setLegacy(boolean legacy) { useLegacy = legacy; }
// -- IFormatReader API methods --
/* @see loci.formats.IFormatReader#isThisType(byte[]) */
public boolean isThisType(byte[] block) {
// use a crappy hack for now
String s = new String(block);
for (int i=0; i<CONTAINER_TYPES.length; i++) {
if (s.indexOf(CONTAINER_TYPES[i]) >= 0) return true;
}
return s.indexOf("wide") >= 0 ||
s.indexOf("mdat") >= 0 || s.indexOf("ftypqt") >= 0;
}
/* @see loci.formats.IFormatReader#setMetadataStore(MetadataStore) */
public void setMetadataStore(MetadataStore store) {
FormatTools.assertId(currentId, false, 1);
super.setMetadataStore(store);
if (useLegacy) legacy.setMetadataStore(store);
}
/**
* @see loci.formats.IFormatReader#openBytes(int, byte[], int, int, int, int)
*/
public byte[] openBytes(int no, byte[] buf, int x, int y, int w, int h)
throws FormatException, IOException
{
FormatTools.assertId(currentId, true, 1);
FormatTools.checkPlaneNumber(this, no);
FormatTools.checkBufferSize(this, buf.length, w, h);
String code = codec;
if (no >= getImageCount() - altPlanes) code = altCodec;
boolean doLegacy = useLegacy;
if (!doLegacy && !code.equals("raw ") && !code.equals("rle ") &&
!code.equals("jpeg") && !code.equals("mjpb") && !code.equals("rpza"))
{
if (debug) {
debug("Unsupported codec (" + code + "); using QTJava reader");
}
doLegacy = true;
}
if (doLegacy) {
if (legacy == null) legacy = createLegacyReader();
legacy.setId(currentId);
return legacy.openBytes(no, buf, x, y, w, h);
}
int offset = ((Integer) offsets.get(no)).intValue();
int nextOffset = (int) pixelBytes;
scale = ((Integer) offsets.get(0)).intValue();
offset -= scale;
if (no < offsets.size() - 1) {
nextOffset = ((Integer) offsets.get(no + 1)).intValue();
nextOffset -= scale;
}
if ((nextOffset - offset) < 0) {
int temp = offset;
offset = nextOffset;
nextOffset = temp;
}
byte[] pixs = new byte[nextOffset - offset];
in.seek(pixelOffset + offset);
in.read(pixs);
canUsePrevious = (prevPixels != null) && (prevPlane == no - 1) &&
!code.equals(altCodec);
byte[] t = uncompress(pixs, code);
if (code.equals("rpza")) {
for (int i=0; i<t.length; i++) {
t[i] = (byte) (255 - t[i]);
}
prevPlane = no;
return buf;
}
// on rare occassions, we need to trim the data
if (canUsePrevious && (prevPixels.length < t.length)) {
byte[] temp = t;
t = new byte[prevPixels.length];
System.arraycopy(temp, 0, t, 0, t.length);
}
prevPixels = t;
prevPlane = no;
// determine whether we need to strip out any padding bytes
int pad = (4 - (core.sizeX[0] % 4)) % 4;
if (codec.equals("mjpb")) pad = 0;
int size = core.sizeX[0] * core.sizeY[0];
if (size * (bitsPerPixel / 8) == prevPixels.length) pad = 0;
if (pad > 0) {
t = new byte[prevPixels.length - core.sizeY[0]*pad];
for (int row=0; row<core.sizeY[0]; row++) {
System.arraycopy(prevPixels, row*(core.sizeX[0]+pad), t,
row*core.sizeX[0], core.sizeX[0]);
}
}
int bpp = FormatTools.getBytesPerPixel(core.pixelType[0]);
int srcRowLen = core.sizeX[0] * bpp * core.sizeC[0];
int destRowLen = w * bpp * core.sizeC[0];
for (int row=0; row<h; row++) {
if (bitsPerPixel == 32) {
for (int col=0; col<w; col++) {
System.arraycopy(t, row*core.sizeX[0]*bpp*4 + (x + col)*bpp*4 + 1,
buf, row*destRowLen + col*bpp*3, 3);
}
}
else {
System.arraycopy(t, row*srcRowLen + x*bpp*core.sizeC[0], buf,
row*destRowLen, destRowLen);
}
}
if ((bitsPerPixel == 40 || bitsPerPixel == 8) && !code.equals("mjpb")) {
// invert the pixels
for (int i=0; i<buf.length; i++) {
buf[i] = (byte) (255 - buf[i]);
}
}
return buf;
}
// -- IFormatHandler API methods --
/* @see loci.formats.IFormatHandler#isThisType(String, boolean) */
public boolean isThisType(String name, boolean open) {
if (super.isThisType(name, open)) return true; // check extension
if (open) {
byte[] b;
try {
in = new RandomAccessStream(name);
long len = in.length();
if (len > 20) len = 20;
b = new byte[(int) len];
in.readFully(b);
}
catch (IOException exc) {
if (debug) trace(exc);
return false;
}
return isThisType(b);
}
else { // not allowed to check the file contents
return name.indexOf(".") < 0; // file appears to have no extension
}
}
/* @see loci.formats.IFormatHandler#close() */
public void close() throws IOException {
super.close();
if (legacy != null) {
legacy.close();
legacy = null;
}
offsets = null;
prevPixels = null;
codec = altCodec = null;
pixelOffset = pixelBytes = bitsPerPixel = rawSize = 0;
prevPlane = altPlanes = 0;
canUsePrevious = useLegacy = false;
}
// -- Internal FormatReader API methods --
/* @see loci.formats.FormatReader#initFile(String) */
protected void initFile(String id) throws FormatException, IOException {
if (debug) debug("QTReader.initFile(" + id + ")");
super.initFile(id);
in = new RandomAccessStream(id);
spork = true;
offsets = new Vector();
chunkSizes = new Vector();
status("Parsing tags");
Exception exc = null;
try { parse(0, 0, in.length()); }
catch (FormatException e) { exc = e; }
catch (IOException e) { exc = e; }
if (exc != null) {
if (debug) trace(exc);
useLegacy = true;
legacy = createLegacyReader();
legacy.setId(id, true);
core = legacy.getCoreMetadata();
return;
}
core.imageCount[0] = offsets.size();
if (chunkSizes.size() < core.imageCount[0] && chunkSizes.size() > 0) {
core.imageCount[0] = chunkSizes.size();
}
status("Populating metadata");
int bytesPerPixel = (bitsPerPixel / 8) % 4;
core.pixelType[0] =
bytesPerPixel == 2 ? FormatTools.UINT16 : FormatTools.UINT8;
core.sizeZ[0] = 1;
core.currentOrder[0] = "XYCZT";
core.littleEndian[0] = false;
core.metadataComplete[0] = true;
core.indexed[0] = false;
core.falseColor[0] = false;
// this handles the case where the data and resource forks have been
// separated
if (spork) {
// first we want to check if there is a resource fork present
// the resource fork will generally have the same name as the data fork,
// but will have either the prefix "._" or the suffix ".qtr"
// (or <filename>/rsrc on a Mac)
String base = null;
if (id.indexOf(".") != -1) {
base = id.substring(0, id.lastIndexOf("."));
}
else base = id;
Location f = new Location(base + ".qtr");
if (debug) debug("Searching for research fork:");
if (f.exists()) {
if (debug) debug("\t Found: " + f);
in = new RandomAccessStream(f.getAbsolutePath());
stripHeader();
parse(0, 0, in.length());
core.imageCount[0] = offsets.size();
}
else {
if (debug) debug("\tAbsent: " + f);
f = new Location(id.substring(0,
id.lastIndexOf(File.separator) + 1) + "._" +
id.substring(base.lastIndexOf(File.separator) + 1));
if (f.exists()) {
if (debug) debug("\t Found: " + f);
in = new RandomAccessStream(f.getAbsolutePath());
stripHeader();
parse(0, in.getFilePointer(), in.length());
core.imageCount[0] = offsets.size();
}
else {
if (debug) debug("\tAbsent: " + f);
f = new Location(id + "/..namedfork/rsrc");
if (f.exists()) {
if (debug) debug("\t Found: " + f);
in = new RandomAccessStream(f.getAbsolutePath());
stripHeader();
- parse(0, 0, in.length());
+ parse(0, in.getFilePointer(), in.length());
core.imageCount[0] = offsets.size();
}
else {
if (debug) debug("\tAbsent: " + f);
throw new FormatException("QuickTime resource fork not found. " +
" To avoid this issue, please flatten your QuickTime movies " +
"before importing with Bio-Formats.");
}
}
}
}
in = new RandomAccessStream(currentId);
core.rgb[0] = bitsPerPixel < 40;
core.sizeC[0] = core.rgb[0] ? 3 : 1;
core.interleaved[0] = bitsPerPixel == 32;
core.sizeT[0] = core.imageCount[0];
// The metadata store we're working with.
MetadataStore store =
new FilterMetadata(getMetadataStore(), isMetadataFiltered());
store.setImageName("", 0);
store.setImageCreationDate(
DataTools.convertDate(System.currentTimeMillis(), DataTools.UNIX), 0);
MetadataTools.populatePixels(store, this);
}
// -- Helper methods --
/** Parse all of the atoms in the file. */
private void parse(int depth, long offset, long length)
throws FormatException, IOException
{
while (offset < length) {
in.seek(offset);
// first 4 bytes are the atom size
long atomSize = in.readInt() & 0xffffffff;
// read the atom type
String atomType = in.readString(4);
// if atomSize is 1, then there is an 8 byte extended size
if (atomSize == 1) {
atomSize = in.readLong();
}
if (atomSize < 0) {
LogTools.println("QTReader: invalid atom size: " + atomSize);
}
if (debug) {
debug("Seeking to " + offset +
"; atomType=" + atomType + "; atomSize=" + atomSize);
}
// if this is a container atom, parse the children
if (isContainer(atomType)) {
parse(depth++, in.getFilePointer(), offset + atomSize);
}
else {
if (atomSize == 0) atomSize = in.length();
long oldpos = in.getFilePointer();
if (atomType.equals("mdat")) {
// we've found the pixel data
pixelOffset = in.getFilePointer();
pixelBytes = atomSize;
if (pixelBytes > (in.length() - pixelOffset)) {
pixelBytes = in.length() - pixelOffset;
}
}
else if (atomType.equals("tkhd")) {
// we've found the dimensions
in.skipBytes(38);
int[][] matrix = new int[3][3];
for (int i=0; i<matrix.length; i++) {
for (int j=0; j<matrix[0].length; j++) {
matrix[i][j] = in.readInt();
}
}
// The contents of the matrix we just read determine whether or not
// we should flip the width and height. We can check the first two
// rows of the matrix - they should correspond to the first two rows
// of an identity matrix.
// TODO : adapt to use the value of flip
flip = matrix[0][0] == 0 && matrix[1][0] != 0;
if (core.sizeX[0] == 0) core.sizeX[0] = in.readInt();
if (core.sizeY[0] == 0) core.sizeY[0] = in.readInt();
}
else if (atomType.equals("cmov")) {
in.skipBytes(8);
if ("zlib".equals(in.readString(4))) {
atomSize = in.readInt();
in.skipBytes(4);
int uncompressedSize = in.readInt();
byte[] b = new byte[(int) (atomSize - 12)];
in.read(b);
Inflater inf = new Inflater();
inf.setInput(b, 0, b.length);
byte[] output = new byte[uncompressedSize];
try {
inf.inflate(output);
}
catch (DataFormatException exc) {
if (debug) trace(exc);
throw new FormatException("Compressed header not supported.");
}
inf.end();
RandomAccessStream oldIn = in;
in = new RandomAccessStream(output);
parse(0, 0, output.length);
in.close();
in = oldIn;
}
else throw new FormatException("Compressed header not supported.");
}
else if (atomType.equals("stco")) {
// we've found the plane offsets
if (offsets.size() > 0) break;
spork = false;
in.skipBytes(4);
int numPlanes = in.readInt();
if (numPlanes != core.imageCount[0]) {
in.seek(in.getFilePointer() - 4);
int off = in.readInt();
offsets.add(new Integer(off));
for (int i=1; i<core.imageCount[0]; i++) {
if ((chunkSizes.size() > 0) && (i < chunkSizes.size())) {
rawSize = ((Integer) chunkSizes.get(i)).intValue();
}
else i = core.imageCount[0];
off += rawSize;
offsets.add(new Integer(off));
}
}
else {
for (int i=0; i<numPlanes; i++) {
offsets.add(new Integer(in.readInt()));
}
}
}
else if (atomType.equals("stsd")) {
// found video codec and pixel depth information
in.skipBytes(4);
int numEntries = in.readInt();
in.skipBytes(4);
for (int i=0; i<numEntries; i++) {
if (i == 0) {
codec = in.readString(4);
if (!codec.equals("raw ") && !codec.equals("rle ") &&
!codec.equals("rpza") && !codec.equals("mjpb") &&
!codec.equals("jpeg"))
{
throw new FormatException("Unsupported codec: " + codec);
}
in.skipBytes(16);
if (in.readShort() == 0) {
in.skipBytes(56);
bitsPerPixel = in.readShort();
if (codec.equals("rpza")) bitsPerPixel = 8;
in.skipBytes(10);
interlaced = in.read() == 2;
addMeta("Codec", codec);
addMeta("Bits per pixel", new Integer(bitsPerPixel));
in.skipBytes(9);
}
}
else {
altCodec = in.readString(4);
addMeta("Second codec", altCodec);
}
}
}
else if (atomType.equals("stsz")) {
// found the number of planes
in.skipBytes(4);
rawSize = in.readInt();
core.imageCount[0] = in.readInt();
if (rawSize == 0) {
in.seek(in.getFilePointer() - 4);
for (int b=0; b<core.imageCount[0]; b++) {
chunkSizes.add(new Integer(in.readInt()));
}
}
}
else if (atomType.equals("stsc")) {
in.skipBytes(4);
int numChunks = in.readInt();
if (altCodec != null) {
int prevChunk = 0;
for (int i=0; i<numChunks; i++) {
int chunk = in.readInt();
int planesPerChunk = in.readInt();
int id = in.readInt();
if (id == 2) altPlanes += planesPerChunk * (chunk - prevChunk);
prevChunk = chunk;
}
}
}
else if (atomType.equals("stts")) {
in.skipBytes(10);
int fps = in.readInt();
addMeta("Frames per second", new Integer(fps));
}
if (oldpos + atomSize < in.length()) {
in.seek(oldpos + atomSize);
}
else break;
}
if (atomSize == 0) offset = in.length();
else offset += atomSize;
// if a 'udta' atom, skip ahead 4 bytes
if (atomType.equals("udta")) offset += 4;
if (debug) print(depth, atomSize, atomType);
}
}
/** Checks if the given String is a container atom type. */
private boolean isContainer(String type) {
for (int i=0; i<CONTAINER_TYPES.length; i++) {
if (type.equals(CONTAINER_TYPES[i])) return true;
}
return false;
}
/** Debugging method; prints information on an atom. */
private void print(int depth, long size, String type) {
StringBuffer sb = new StringBuffer();
for (int i=0; i<depth; i++) sb.append(" ");
sb.append(type + " : [" + size + "]");
debug(sb.toString());
}
/** Uncompresses an image plane according to the the codec identifier. */
private byte[] uncompress(byte[] pixs, String code)
throws FormatException, IOException
{
if (code.equals("raw ")) return pixs;
else if (code.equals("rle ")) {
Object[] options = new Object[2];
options[0] = new int[] {core.sizeX[0], core.sizeY[0],
bitsPerPixel < 40 ? bitsPerPixel / 8 : (bitsPerPixel - 32) / 8};
options[1] = canUsePrevious ? prevPixels : null;
return new QTRLECodec().decompress(pixs, options);
}
else if (code.equals("rpza")) {
int[] options = new int[2];
options[0] = core.sizeX[0];
options[1] = core.sizeY[0];
return new RPZACodec().decompress(pixs, options);
}
else if (code.equals("mjpb")) {
int[] options = new int[4];
options[0] = core.sizeX[0];
options[1] = core.sizeY[0];
options[2] = bitsPerPixel;
options[3] = interlaced ? 1 : 0;
return new MJPBCodec().decompress(pixs, options);
}
else if (code.equals("jpeg")) {
return new JPEGCodec().decompress(pixs,
new Boolean(core.littleEndian[0]));
}
else throw new FormatException("Unsupported codec : " + code);
}
/** Cut off header bytes from a resource fork file. */
private void stripHeader() throws IOException {
// seek to 4 bytes before first occurence of 'moov'
String test = null;
boolean found = false;
while (!found && in.getFilePointer() < (in.length() - 4)) {
test = in.readString(4);
if (test.equals("moov")) {
found = true;
in.seek(in.getFilePointer() - 8);
}
else in.seek(in.getFilePointer() - 3);
}
}
/** Creates a legacy QT reader. */
private LegacyQTReader createLegacyReader() {
// use the same id mappings that this reader does
return new LegacyQTReader();
}
}
| true | false | null | null |
diff --git a/advanced/dynamic-ftp/src/test/java/org/springframework/integration/samples/ftp/FtpOutboundChannelAdapterSample.java b/advanced/dynamic-ftp/src/test/java/org/springframework/integration/samples/ftp/FtpOutboundChannelAdapterSample.java
index c856686b..969a78aa 100644
--- a/advanced/dynamic-ftp/src/test/java/org/springframework/integration/samples/ftp/FtpOutboundChannelAdapterSample.java
+++ b/advanced/dynamic-ftp/src/test/java/org/springframework/integration/samples/ftp/FtpOutboundChannelAdapterSample.java
@@ -1,70 +1,70 @@
/*
- * Copyright 2002-2010 the original author or authors.
+ * Copyright 2002-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.samples.ftp;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.net.UnknownHostException;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.integration.Message;
import org.springframework.integration.MessageChannel;
import org.springframework.integration.MessageHandlingException;
import org.springframework.integration.support.MessageBuilder;
/**
* @author Gary Russell
*
*/
public class FtpOutboundChannelAdapterSample {
@Test
public void runDemo() throws Exception{
ApplicationContext ctx =
new ClassPathXmlApplicationContext("META-INF/spring/integration/DynamicFtpOutboundChannelAdapterSample-context.xml");
MessageChannel channel = ctx.getBean("toDynRouter", MessageChannel.class);
File file = File.createTempFile("temp", "txt");
Message<File> message = MessageBuilder.withPayload(file)
.setHeader("customer", "cust1")
.build();
try {
channel.send(message);
} catch (MessageHandlingException e) {
assertTrue(e.getCause().getCause() instanceof UnknownHostException);
assertEquals("host.for.cust1", e.getCause().getCause().getMessage());
}
// send another so we can see in the log we don't create the ac again.
try {
channel.send(message);
} catch (MessageHandlingException e) {
assertTrue(e.getCause().getCause() instanceof UnknownHostException);
assertEquals("host.for.cust1", e.getCause().getCause().getMessage());
}
// send to a different customer; again, check the log to see a new ac is built
message = MessageBuilder.withPayload(file)
.setHeader("customer", "cust2").build();
try {
channel.send(message);
} catch (MessageHandlingException e) {
assertTrue(e.getCause().getCause() instanceof UnknownHostException);
assertEquals("host.for.cust2", e.getCause().getCause().getMessage());
}
}
}
| true | false | null | null |
diff --git a/src/org/apache/xalan/xsltc/compiler/Step.java b/src/org/apache/xalan/xsltc/compiler/Step.java
index 0d50548f..c6820b09 100644
--- a/src/org/apache/xalan/xsltc/compiler/Step.java
+++ b/src/org/apache/xalan/xsltc/compiler/Step.java
@@ -1,445 +1,446 @@
/*
* Copyright 2001-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.
*/
/*
* $Id$
*/
package org.apache.xalan.xsltc.compiler;
import java.util.Vector;
import org.apache.bcel.generic.CHECKCAST;
import org.apache.bcel.generic.ConstantPoolGen;
import org.apache.bcel.generic.ICONST;
import org.apache.bcel.generic.INVOKEINTERFACE;
import org.apache.bcel.generic.INVOKESPECIAL;
import org.apache.bcel.generic.InstructionList;
import org.apache.bcel.generic.NEW;
import org.apache.bcel.generic.PUSH;
import org.apache.xalan.xsltc.DOM;
import org.apache.xalan.xsltc.compiler.util.ClassGenerator;
import org.apache.xalan.xsltc.compiler.util.MethodGenerator;
import org.apache.xalan.xsltc.compiler.util.Type;
import org.apache.xalan.xsltc.compiler.util.TypeCheckError;
import org.apache.xalan.xsltc.dom.Axis;
import org.apache.xml.dtm.DTM;
/**
* @author Jacek Ambroziak
* @author Santiago Pericas-Geertsen
* @author Morten Jorgensen
*/
final class Step extends RelativeLocationPath {
/**
* This step's axis as defined in class Axis.
*/
private int _axis;
/**
* A vector of predicates (filters) defined on this step - may be null
*/
private Vector _predicates;
/**
* Some simple predicates can be handled by this class (and not by the
* Predicate class) and will be removed from the above vector as they are
* handled. We use this boolean to remember if we did have any predicates.
*/
private boolean _hadPredicates = false;
/**
* Type of the node test.
*/
private int _nodeType;
public Step(int axis, int nodeType, Vector predicates) {
_axis = axis;
_nodeType = nodeType;
_predicates = predicates;
}
/**
* Set the parser for this element and all child predicates
*/
public void setParser(Parser parser) {
super.setParser(parser);
if (_predicates != null) {
final int n = _predicates.size();
for (int i = 0; i < n; i++) {
final Predicate exp = (Predicate)_predicates.elementAt(i);
exp.setParser(parser);
exp.setParent(this);
}
}
}
/**
* Define the axis (defined in Axis class) for this step
*/
public int getAxis() {
return _axis;
}
/**
* Get the axis (defined in Axis class) for this step
*/
public void setAxis(int axis) {
_axis = axis;
}
/**
* Returns the node-type for this step
*/
public int getNodeType() {
return _nodeType;
}
/**
* Returns the vector containing all predicates for this step.
*/
public Vector getPredicates() {
return _predicates;
}
/**
* Returns the vector containing all predicates for this step.
*/
public void addPredicates(Vector predicates) {
if (_predicates == null) {
_predicates = predicates;
}
else {
_predicates.addAll(predicates);
}
}
/**
* Returns 'true' if this step has a parent pattern.
* This method will return 'false' if this step occurs on its own under
* an element like <xsl:for-each> or <xsl:apply-templates>.
*/
private boolean hasParentPattern() {
final SyntaxTreeNode parent = getParent();
return (parent instanceof ParentPattern ||
parent instanceof ParentLocationPath ||
parent instanceof UnionPathExpr ||
parent instanceof FilterParentPath);
}
/**
* Returns 'true' if this step has any predicates
*/
private boolean hasPredicates() {
return _predicates != null && _predicates.size() > 0;
}
/**
* Returns 'true' if this step is used within a predicate
*/
private boolean isPredicate() {
SyntaxTreeNode parent = this;
while (parent != null) {
parent = parent.getParent();
if (parent instanceof Predicate) return true;
}
return false;
}
/**
* True if this step is the abbreviated step '.'
*/
public boolean isAbbreviatedDot() {
return _nodeType == NodeTest.ANODE && _axis == Axis.SELF;
}
/**
* True if this step is the abbreviated step '..'
*/
public boolean isAbbreviatedDDot() {
return _nodeType == NodeTest.ANODE && _axis == Axis.PARENT;
}
/**
* Type check this step. The abbreviated steps '.' and '@attr' are
* assigned type node if they have no predicates. All other steps
* have type node-set.
*/
public Type typeCheck(SymbolTable stable) throws TypeCheckError {
// Save this value for later - important for testing for special
// combinations of steps and patterns than can be optimised
_hadPredicates = hasPredicates();
// Special case for '.'
// in the case where '.' has a context such as book/.
// or .[false()] we can not optimize the nodeset to a single node.
if (isAbbreviatedDot()) {
_type = (hasParentPattern() || hasPredicates() ) ?
Type.NodeSet : Type.Node;
}
else {
_type = Type.NodeSet;
}
// Type check all predicates (expressions applied to the step)
if (_predicates != null) {
final int n = _predicates.size();
for (int i = 0; i < n; i++) {
final Expression pred = (Expression)_predicates.elementAt(i);
pred.typeCheck(stable);
}
}
// Return either Type.Node or Type.NodeSet
return _type;
}
/**
* Translate a step by pushing the appropriate iterator onto the stack.
* The abbreviated steps '.' and '@attr' do not create new iterators
* if they are not part of a LocationPath and have no filters.
* In these cases a node index instead of an iterator is pushed
* onto the stack.
*/
public void translate(ClassGenerator classGen, MethodGenerator methodGen) {
final ConstantPoolGen cpg = classGen.getConstantPool();
final InstructionList il = methodGen.getInstructionList();
if (hasPredicates()) {
translatePredicates(classGen, methodGen);
- }
- else {
- // If it is an attribute but not '@*', '@attr' or '@node()' and
- // has no parent
- if (_axis == Axis.ATTRIBUTE && _nodeType != NodeTest.ATTRIBUTE &&
- _nodeType != NodeTest.ANODE && !hasParentPattern())
+ } else {
+ int star = 0;
+ String name = null;
+ final XSLTC xsltc = getParser().getXSLTC();
+
+ if (_nodeType >= DTM.NTYPES) {
+ final Vector ni = xsltc.getNamesIndex();
+
+ name = (String)ni.elementAt(_nodeType-DTM.NTYPES);
+ star = name.lastIndexOf('*');
+ }
+
+ // If it is an attribute, but not '@*', '@pre:*' or '@node()',
+ // and has no parent
+ if (_axis == Axis.ATTRIBUTE && _nodeType != NodeTest.ATTRIBUTE
+ && _nodeType != NodeTest.ANODE && !hasParentPattern()
+ && star == 0)
{
int iter = cpg.addInterfaceMethodref(DOM_INTF,
"getTypedAxisIterator",
"(II)"+NODE_ITERATOR_SIG);
il.append(methodGen.loadDOM());
il.append(new PUSH(cpg, Axis.ATTRIBUTE));
il.append(new PUSH(cpg, _nodeType));
il.append(new INVOKEINTERFACE(iter, 3));
return;
}
// Special case for '.'
if (isAbbreviatedDot()) {
if (_type == Type.Node) {
// Put context node on stack if using Type.Node
il.append(methodGen.loadContextNode());
}
else {
// Wrap the context node in a singleton iterator if not.
int init = cpg.addMethodref(SINGLETON_ITERATOR,
"<init>", "("+NODE_SIG+")V");
il.append(new NEW(cpg.addClass(SINGLETON_ITERATOR)));
il.append(DUP);
il.append(methodGen.loadContextNode());
il.append(new INVOKESPECIAL(init));
}
return;
}
// Special case for /foo/*/bar
SyntaxTreeNode parent = getParent();
if ((parent instanceof ParentLocationPath) &&
(parent.getParent() instanceof ParentLocationPath)) {
if ((_nodeType == NodeTest.ELEMENT) && (!_hadPredicates)) {
_nodeType = NodeTest.ANODE;
}
}
// "ELEMENT" or "*" or "@*" or ".." or "@attr" with a parent.
switch (_nodeType) {
case NodeTest.ATTRIBUTE:
_axis = Axis.ATTRIBUTE;
case NodeTest.ANODE:
// DOM.getAxisIterator(int axis);
int git = cpg.addInterfaceMethodref(DOM_INTF,
"getAxisIterator",
"(I)"+NODE_ITERATOR_SIG);
il.append(methodGen.loadDOM());
il.append(new PUSH(cpg, _axis));
il.append(new INVOKEINTERFACE(git, 2));
break;
default:
- final XSLTC xsltc = getParser().getXSLTC();
- final Vector ni = xsltc.getNamesIndex();
- String name = null;
- int star = 0;
-
- if (_nodeType >= DTM.NTYPES) {
- name = (String)ni.elementAt(_nodeType-DTM.NTYPES);
- star = name.lastIndexOf('*');
- }
-
if (star > 1) {
final String namespace;
if (_axis == Axis.ATTRIBUTE)
namespace = name.substring(0,star-2);
else
namespace = name.substring(0,star-1);
final int nsType = xsltc.registerNamespace(namespace);
final int ns = cpg.addInterfaceMethodref(DOM_INTF,
"getNamespaceAxisIterator",
"(II)"+NODE_ITERATOR_SIG);
il.append(methodGen.loadDOM());
il.append(new PUSH(cpg, _axis));
il.append(new PUSH(cpg, nsType));
il.append(new INVOKEINTERFACE(ns, 3));
break;
}
case NodeTest.ELEMENT:
// DOM.getTypedAxisIterator(int axis, int type);
final int ty = cpg.addInterfaceMethodref(DOM_INTF,
"getTypedAxisIterator",
"(II)"+NODE_ITERATOR_SIG);
// Get the typed iterator we're after
il.append(methodGen.loadDOM());
il.append(new PUSH(cpg, _axis));
il.append(new PUSH(cpg, _nodeType));
il.append(new INVOKEINTERFACE(ty, 3));
break;
}
}
}
/**
* Translate a sequence of predicates. Each predicate is translated
* by constructing an instance of <code>CurrentNodeListIterator</code>
* which is initialized from another iterator (recursive call),
* a filter and a closure (call to translate on the predicate) and "this".
*/
public void translatePredicates(ClassGenerator classGen,
MethodGenerator methodGen) {
final ConstantPoolGen cpg = classGen.getConstantPool();
final InstructionList il = methodGen.getInstructionList();
int idx = 0;
if (_predicates.size() == 0) {
translate(classGen, methodGen);
}
else {
final Predicate predicate = (Predicate)_predicates.lastElement();
_predicates.remove(predicate);
// Special case for predicates that can use the NodeValueIterator
// instead of an auxiliary class. Certain path/predicates pairs
// are translated into a base path, on top of which we place a
// node value iterator that tests for the desired value:
// foo[@attr = 'str'] -> foo/@attr + test(value='str')
// foo[bar = 'str'] -> foo/bar + test(value='str')
// foo/bar[. = 'str'] -> foo/bar + test(value='str')
if (predicate.isNodeValueTest()) {
Step step = predicate.getStep();
il.append(methodGen.loadDOM());
// If the predicate's Step is simply '.' we translate this Step
// and place the node test on top of the resulting iterator
if (step.isAbbreviatedDot()) {
translate(classGen, methodGen);
il.append(new ICONST(DOM.RETURN_CURRENT));
}
// Otherwise we create a parent location path with this Step and
// the predicates Step, and place the node test on top of that
else {
ParentLocationPath path = new ParentLocationPath(this,step);
try {
path.typeCheck(getParser().getSymbolTable());
}
catch (TypeCheckError e) { }
path.translate(classGen, methodGen);
il.append(new ICONST(DOM.RETURN_PARENT));
}
predicate.translate(classGen, methodGen);
idx = cpg.addInterfaceMethodref(DOM_INTF,
GET_NODE_VALUE_ITERATOR,
GET_NODE_VALUE_ITERATOR_SIG);
il.append(new INVOKEINTERFACE(idx, 5));
}
// Handle '//*[n]' expression
else if (predicate.isNthDescendant()) {
il.append(methodGen.loadDOM());
// il.append(new ICONST(NodeTest.ELEMENT));
il.append(new ICONST(predicate.getPosType()));
predicate.translate(classGen, methodGen);
il.append(new ICONST(0));
idx = cpg.addInterfaceMethodref(DOM_INTF,
"getNthDescendant",
"(IIZ)"+NODE_ITERATOR_SIG);
il.append(new INVOKEINTERFACE(idx, 4));
}
// Handle 'elem[n]' expression
else if (predicate.isNthPositionFilter()) {
idx = cpg.addMethodref(NTH_ITERATOR_CLASS,
"<init>",
"("+NODE_ITERATOR_SIG+"I)V");
il.append(new NEW(cpg.addClass(NTH_ITERATOR_CLASS)));
il.append(DUP);
translatePredicates(classGen, methodGen); // recursive call
predicate.translate(classGen, methodGen);
il.append(new INVOKESPECIAL(idx));
}
else {
idx = cpg.addMethodref(CURRENT_NODE_LIST_ITERATOR,
"<init>",
"("
+ NODE_ITERATOR_SIG
+ CURRENT_NODE_LIST_FILTER_SIG
+ NODE_SIG
+ TRANSLET_SIG
+ ")V");
// create new CurrentNodeListIterator
il.append(new NEW(cpg.addClass(CURRENT_NODE_LIST_ITERATOR)));
il.append(DUP);
translatePredicates(classGen, methodGen); // recursive call
predicate.translateFilter(classGen, methodGen);
il.append(methodGen.loadCurrentNode());
il.append(classGen.loadTranslet());
if (classGen.isExternal()) {
final String className = classGen.getClassName();
il.append(new CHECKCAST(cpg.addClass(className)));
}
il.append(new INVOKESPECIAL(idx));
}
}
}
/**
* Returns a string representation of this step.
*/
public String toString() {
final StringBuffer buffer = new StringBuffer("step(\"");
buffer.append(Axis.names[_axis]).append("\", ").append(_nodeType);
if (_predicates != null) {
final int n = _predicates.size();
for (int i = 0; i < n; i++) {
final Predicate pred = (Predicate)_predicates.elementAt(i);
buffer.append(", ").append(pred.toString());
}
}
return buffer.append(')').toString();
}
}
| false | false | null | null |
diff --git a/plugins/org.eclipse.jem.beaninfo/beaninfo/org/eclipse/jem/internal/beaninfo/core/BeanInfoCacheController.java b/plugins/org.eclipse.jem.beaninfo/beaninfo/org/eclipse/jem/internal/beaninfo/core/BeanInfoCacheController.java
index 6bd29a23e..652313cc9 100644
--- a/plugins/org.eclipse.jem.beaninfo/beaninfo/org/eclipse/jem/internal/beaninfo/core/BeanInfoCacheController.java
+++ b/plugins/org.eclipse.jem.beaninfo/beaninfo/org/eclipse/jem/internal/beaninfo/core/BeanInfoCacheController.java
@@ -1,1602 +1,1602 @@
/*******************************************************************************
* Copyright (c) 2005 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 - initial API and implementation
*******************************************************************************/
/*
* $RCSfile: BeanInfoCacheController.java,v $
- * $Revision: 1.16 $ $Date: 2005/09/13 20:30:46 $
+ * $Revision: 1.17 $ $Date: 2005/11/29 15:13:59 $
*/
package org.eclipse.jem.internal.beaninfo.core;
import java.io.*;
import java.util.*;
import java.util.logging.Level;
import org.eclipse.core.resources.*;
import org.eclipse.core.runtime.*;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.emf.common.notify.*;
import org.eclipse.emf.common.notify.impl.AdapterImpl;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.change.ChangeDescription;
import org.eclipse.emf.ecore.change.impl.EObjectToChangesMapEntryImpl;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.eclipse.emf.ecore.xmi.XMLResource;
import org.eclipse.jdt.core.*;
import org.eclipse.jem.internal.beaninfo.adapters.*;
import org.eclipse.jem.internal.java.beaninfo.IIntrospectionAdapter;
import org.eclipse.jem.java.JavaClass;
import org.eclipse.jem.util.emf.workbench.ProjectResourceSet;
import org.eclipse.jem.util.logger.proxy.Logger;
import org.eclipse.jem.util.plugin.JEMUtilPlugin;
import org.eclipse.jem.util.plugin.JEMUtilPlugin.CleanResourceChangeListener;
/**
* Controller of the BeanInfo cache. There is one per workspace (it is a static).
*
* The cache is stored on a per IPackageFragmentRoot basis. Each package fragment root will be:
*
* <pre>
*
* root{999}/classname.xmi
*
* </pre>
*
* "root{999}" will be a unigue name (root appended with a number}, one for each package fragment root. The "classname.xmi" will be the BeanInfo cache
* for a class in the root. A root can't have more than one class with the same name, so there shouldn't be any collisions.
* <p>
* Now roots can either be in a project, or they can be an external jar (which can be shared between projects).
* <p>
* Now all roots for a project will be stored in the project's working location
* {@link org.eclipse.core.resources.IProject#getWorkingLocation(java.lang.String)}under the ".cache" directory. It will be this format in each
* project location (under the org.eclipse.jem.beaninfo directory):
*
* <pre>
*
* .index
* root{999}/...
*
* </pre>
*
* The ".index" file will be stored/loaded through an ObjectStream. It will be a {@link BeanInfoCacheController.Index}. It is the index to all of the
* root's in the directory.
* <p>
* All of the external jar roots will be stored in the org.eclipse.jem.beaninfo plugin's state location
* {@link org.eclipse.core.runtime.Platform#getStateLocation(org.osgi.framework.Bundle)}under the ".cache" directory. The format of this directory
* will be the same as for each project. And the roots will be for each unique shared external jar (such as the differnt jre's rt.jars).
* <p>
* Note: There are so many places where synchronization is needed, so it is decided to synchronize only on BeanInfoCacheController.INSTANCE. It would
* be too easy to get a dead-lock because the order of synchronizations can't be easily controlled. Since each piece of sync control is very short
* (except for save of the indices, but that is ok because we don't want them changing while saving) it shouldn't block a lot. There is one place we
* violate this and that is we do a sync on ClassEntry instance when working with the pending. This is necessary because we don't want the cache write
* job to hold up everything while writing, so we sync on the entry being written instead. There we must be very careful that we never to
* BeanInfoCacheControler.INSTANCE sync and then a ClassEntry sync because we could deadlock. The CE access under the covers may do a CE sync and then
* a BeanInfoCacheController.INSTANCE sync.
*
* @since 1.1.0
*/
public class BeanInfoCacheController {
/**
* Singleton cache controller.
*
* @since 1.1.0
*/
public static final BeanInfoCacheController INSTANCE = new BeanInfoCacheController();
private BeanInfoCacheController() {
// Start up save participent. This only is used for saving indexes and shutdown. Currently the saved state delta
// is of no interest. If a project is deleted while we were not up, then the project index would be gone, so
// our data will automatically be gone for the project.
// If a class was deleted while the project's beaninfo was not active, the cache will still contain it. If the class ever came back it
// would be stale and so recreated. If it never comes back, until a clean is done, it would just hang around.
// The problem with delete is it is hard to determine that the file is actually a class of interest. The javamodel
// handles that for us but we won't have a javamodel to handle this on start up to tell us the file was a class of interest. So
// we'll take the hit of possible cache for non-existant classes. A clean will take care of this.
saveParticipant = new SaveParticipant();
try {
ResourcesPlugin.getWorkspace().addSaveParticipant(BeaninfoPlugin.getPlugin(), saveParticipant);
} catch (CoreException e) {
BeaninfoPlugin.getPlugin().getLogger().log(e.getStatus());
}
// Create a cleanup listener to handle clean requests and project deletes. We need to know about project deletes while
// active because we may have a project index in memory and that needs to be thrown away.
JEMUtilPlugin.addCleanResourceChangeListener(new CleanResourceChangeListener() {
protected void cleanProject(IProject project) {
// Get rid of the project index and the data for the project.
synchronized (BeanInfoCacheController.this) {
try {
Index projectIndex = (Index) project.getSessionProperty(PROJECT_INDEX_KEY);
if (projectIndex != null) {
project.setSessionProperty(PROJECT_INDEX_KEY, null);
projectIndex.markDead();
cleanDirectory(getCacheDir(project).toFile(), true);
}
BeaninfoNature nature = BeaninfoPlugin.getPlugin().getNature(project);
if (nature != null) {
BeaninfoAdapterFactory adapterFactory = (BeaninfoAdapterFactory) EcoreUtil.getAdapterFactory(nature.getResourceSet().getAdapterFactories(), IIntrospectionAdapter.ADAPTER_KEY);
if (adapterFactory != null) {
adapterFactory.markAllStale(true); // Also clear the overrides.
}
}
} catch (CoreException e) {
// Shouldn't occur.
}
}
}
protected void cleanAll() {
synchronized(BeanInfoCacheController.this) {
// Get MAIN_INDEX, mark it dead, and then delete everything under it.
if (MAIN_INDEX != null) {
MAIN_INDEX.markDead();
MAIN_INDEX = null;
cleanDirectory(getCacheDir(null).toFile(), true);
}
}
super.cleanAll();
}
public void resourceChanged(IResourceChangeEvent event) {
// We don't need to handle PRE_CLOSE because SaveParticipent project save will handle closing.
switch (event.getType()) {
case IResourceChangeEvent.PRE_DELETE:
// Don't need to clear the cache directory because Eclipse will get rid of it.
synchronized (BeanInfoCacheController.this) {
try {
Index projectIndex = (Index) event.getResource().getSessionProperty(PROJECT_INDEX_KEY);
if (projectIndex != null) {
// No need to remove from the project because the project is going away and will clean itself up.
projectIndex.markDead();
}
} catch (CoreException e) {
// Shouldn't occur.
}
}
// Flow into PRE_CLOSE to release the nature.
case IResourceChangeEvent.PRE_CLOSE:
// About to close or delete, so release the nature, if any.
IProject project = (IProject) event.getResource();
BeaninfoNature nature = BeaninfoPlugin.getPlugin().getNature(project);
if (nature != null) {
nature.cleanup(false, true);
}
break;
default:
super.resourceChanged(event);
break;
}
}
}, IResourceChangeEvent.PRE_DELETE | IResourceChangeEvent.PRE_CLOSE);
}
protected SaveParticipant saveParticipant;
/**
* An index structure for the Main and Project indexes. Access to the index contents and methods should synchronize on the index itself.
* <p>
* Getting to the index instance should only be through the <code>getMainIndex()</code> and <code>getProjectIndex(IProject)</code> accessors
* so that synchronization and serialization is controlled.
*
* @since 1.1.0
*/
protected static class Index implements Serializable {
private static final long serialVersionUID = 1106864425423L;
/*
* Is this a dirty index, i.e. it has been changed and needs to be saved.
*/
transient private boolean dirty;
private static final int DEAD = -1; // Used in highRootNumber to indicate the index is dead.
/**
* The highest root number used. It is incremented everytime one is needed. It doesn't ever decrease to recover removed roots.
*
* @since 1.1.0
*/
public int highRootNumber;
/**
* Map of root names to the root Index. The key is a {@link IPath}. The path will be relative to the workspace if a project root, or an
* absolute local path to the archive if it is an external archive. It is the IPath to package fragment root (either a folder or a jar file).
* <p>
* The value will be a {@link BeanInfoCacheController.RootIndex}. This is the index for the contents of that root.
*
* @since 1.1.0
*/
transient public Map rootToRootIndex;
/**
* @param dirty
* The dirty to set.
*
* @since 1.1.0
*/
public void setDirty(boolean dirty) {
synchronized (BeanInfoCacheController.INSTANCE) {
this.dirty = dirty;
}
}
/**
* @return Returns the dirty.
*
* @since 1.1.0
*/
public boolean isDirty() {
synchronized (BeanInfoCacheController.INSTANCE) {
return dirty;
}
}
/**
* Answer if this index is dead. It is dead if a clean has occurred. This is needed because there could be some ClassEntry's still
* around (such as in the pending write queue) that are for cleaned roots. This is used to test if it has been cleaned.
* @return
*
* @since 1.1.0
*/
public boolean isDead() {
return highRootNumber == DEAD;
}
/**
* Mark the index as dead.
*
*
* @since 1.1.0
*/
void markDead() {
highRootNumber = DEAD;
}
private void writeObject(ObjectOutputStream os) throws IOException {
os.defaultWriteObject();
// Now write out the root to root index map. We are not serializing the Map directly using normal Map serialization because
// the key of the map is an IPath (which is a Path under the covers) and Path is not serializable.
os.writeInt(rootToRootIndex.size());
for (Iterator mapItr = rootToRootIndex.entrySet().iterator(); mapItr.hasNext();) {
Map.Entry entry = (Map.Entry) mapItr.next();
os.writeUTF(((IPath) entry.getKey()).toString());
os.writeObject(entry.getValue());
}
}
private void readObject(ObjectInputStream is) throws IOException, ClassNotFoundException {
is.defaultReadObject();
int size = is.readInt();
rootToRootIndex = new HashMap(size < 100 ? 100 : size);
while (size-- > 0) {
rootToRootIndex.put(new Path(is.readUTF()), is.readObject());
}
}
}
/**
* An index for a root. It has an entry for each class in this root. The class cache entry describes the cache, whether it is stale, what the
* current mod stamp is, etc.
*
* @since 1.1.0
*/
public static abstract class RootIndex implements Serializable {
private static final long serialVersionUID = 1106868674867L;
transient private IPath cachePath; // Absolute local filesystem IPath to the root cache directory. Computed at runtime because it may change
// if workspace relocated.
protected Map classNameToClassEntry; // Map of class names to class entries.
private String rootName; // Name of the root directory in the cache (e.g. "root1").
protected Index index; // Index containing this root index.
protected RootIndex() {
}
public RootIndex(String rootName, Index index) {
this.rootName = rootName;
classNameToClassEntry = new HashMap(100); // When created brand new, put in a map. Otherwise object stream will create the map.
this.index = index;
}
/**
* Get the index that points to this root.
* @return
*
* @since 1.1.0
*/
Index getIndex() {
return index;
}
/**
* Return the root directory name
*
* @return rootname
*
* @since 1.1.0
*/
public String getRootName() {
return rootName;
}
/**
* Set this RootIndex (and the containing Index) as being dirty and in need of saving.
*
*
* @since 1.1.0
*/
public void setDirty() {
index.setDirty(true);
}
/*
* Setup for index. It will initialize the path. Once set it won't set it again. This will be called repeatedly by the cache controller
* because there is no way to know if it was lazily created or was brought in from file. When brought in from file the path is not set because
* it should be relocatable and we don't want absolute paths out on the disk caches, and we don't want to waste time creating the path at load
* time because it may not be needed for a while. So it will be lazily created. <p> If the project is set, then the path will be relative to
* the project's working location. If project is <code> null </code> then it will be relative to the BeanInfo plugin's state location. <p>
* This is <package-protected> because only the creator (BeanInfoCacheController class) should set this up.
*
* @param project
*
* @since 1.1.0
*/
void setupIndex(IProject project) {
if (getCachePath() == null)
cachePath = getCacheDir(project).append(rootName);
}
/**
* @return Returns the path of the cache directory for the root.
*
* @since 1.1.0
*/
public IPath getCachePath() {
return cachePath;
}
/**
* Return whether this is a root for a archive or a folder.
*
* @return <code>true</code> if archive for a root. <code>false</code> if archive for a folder.
*
* @since 1.1.0
*/
public abstract boolean isArchiveRoot();
}
/**
* A root index that is for an archive, either internal or external. It contains the archive's modification stamp. Each class cache entry will
* have this same modification stamp. If the archive is changed then all of the class cache entries will be removed because they are all possibly
* stale. No way to know which may be stale and which not.
*
* @since 1.1.0
*/
public static class ArchiveRootIndex extends RootIndex {
private static final long serialVersionUID = 110686867456L;
private long archiveModificationStamp;
/*
* For serializer to call.
*/
protected ArchiveRootIndex() {
}
public ArchiveRootIndex(String rootName, long archiveModificationStamp, Index index) {
super(rootName, index);
this.archiveModificationStamp = archiveModificationStamp;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jem.internal.beaninfo.core.BeanInfoCacheController.RootIndex#isArchiveRoot()
*/
public boolean isArchiveRoot() {
return true;
}
/*
* Set the modification stamp. <p> <package-protected> because only the cache controller should change it.
*
* @param archiveModificationStamp The archiveModificationStamp to set.
*
* @see BeanInfoCacheController#MODIFICATION_STAMP_STALE
* @since 1.1.0
*/
void setArchiveModificationStamp(long archiveModificationStamp) {
this.archiveModificationStamp = archiveModificationStamp;
setDirty();
}
/**
* Returns the modification stamp.
*
* @return Returns the archiveModificationStamp.
* @see BeanInfoCacheController#MODIFICATION_STAMP_STALE
* @since 1.1.0
*/
public long getArchiveModificationStamp() {
return archiveModificationStamp;
}
}
/**
* This is a root index for a folder (which will be in the workspace). Each class cache entry can have a different modification stamp with a
* folder root index.
*
* @since 1.1.0
*/
public static class FolderRootIndex extends RootIndex {
private static final long serialVersionUID = 1106868674834L;
/*
* For serialization.
*/
protected FolderRootIndex() {
}
/**
* @param rootName
*
* @since 1.1.0
*/
public FolderRootIndex(String rootName, Index index) {
super(rootName, index);
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jem.internal.beaninfo.core.BeanInfoCacheController.RootIndex#isArchiveRoot()
*/
public boolean isArchiveRoot() {
return false;
}
}
/**
* An individual class entry from the cache. It has an entry for each class in the root. The class cache entry describes the cache, whether it is
* stale, what the current mod stamp is, etc.
* <p>
* There is a method to call to see if deleted. This should only be called if entry is being held on to because
* <code>getClassEntry(JavaClass)</code> will never return a deleted entry. There is a method to get the modification stamp of the current cache
* entry. This is the time stamp of the cooresponding class resource (or archive file) that the cache file was created from. If the value is
* <code>IResource.NULL_STAMP</code>, then the cache file is known to be stale. Otherwise if the value is less than a modification stamp of a
* super class then the cache file is stale.
*
* @see ClassEntry#isDeleted()
* @see ClassEntry#getModificationStamp()
* @see BeanInfoCacheController#getClassEntry(JavaClass)
* @since 1.1.0
*/
public static class ClassEntry implements Serializable {
private static final long serialVersionUID = 1106868674666L;
public static final long DELETED_MODIFICATION_STAMP = Long.MIN_VALUE; // This flag won't be seen externally. It is used to indicate the entry
// has been deleted for those that have been holding a CE.
/**
* Check against the super modification stamp and the interface stamps to see if they were set
* by undefined super class or interface at cache creation time.
*
* @since 1.1.0
*/
public static final long SUPER_UNDEFINED_MODIFICATION_STAMP = Long.MIN_VALUE+1;
private long modificationStamp;
private long superModificationStamp; // Stamp of superclass, if any, at time of cache creation.
private String[] interfaceNames; // Interfaces names (null if no interfaces)
private long[] interfaceModicationStamps; // Modification stamps of interfaces, if any. (null if no interfaces).
private transient Resource pendingResource; // Resource is waiting to be saved, but the timestamps are for this pending resource so that we know what it will be ahead of time. At this point the class will be introspected.
private RootIndex rootIndex; // The root index this class entry is in, so that any changes can mark the entry as dirty.
private String className; // The classname for this entry.
private boolean saveOperations; // Flag for saving operations. Once this is set, it will continue to save operations in the cache in addition to everything else.
private long configurationModificationStamp; // Modification stamp of the Eclipse configuration. Used to determine if the cache of override files is out of date due to a config change.
private boolean overrideCacheExists; // Flag that there is an override cache to load. This is orthogonal to the config mod stamp because it simply means that on the current configuration there is no override cache.
private transient Resource pendingOverrideResource; // Override resource is waiting to be saved.
protected ClassEntry() {
}
ClassEntry(RootIndex rootIndex, String className) {
this.setRootIndex(rootIndex);
this.className = className;
modificationStamp = IResource.NULL_STAMP;
rootIndex.classNameToClassEntry.put(className, this);
}
/**
*
* @return
*
* @since 1.1.0
*/
public String getClassName() {
return className;
}
/**
* Return whether the entry has been deleted. This will never be seen in an entry that is still in an index. It is used for entries that have
* been removed from the index. It is for classes (such as the BeanInfoClassAdapter) which are holding onto a copy of entry to let them know.
* <p>
* Holders of entries should call isDeleted if they don't need to further check the mod stamp. Else they should call getModificationStamp and
* check of deleted, stale, or mod stamp. That would save extra synchronizations. If entry is deleted then it should throw the entry away.
*
* @return <code>true</code> if the entry has been deleted, <code>false</code> if still valid.
*
* @see ClassEntry#getModificationStamp()
* @see ClassEntry#isStale()
* @see ClassEntry#DELETED_MODIFICATION_STAMP
* @since 1.1.0
*/
public boolean isDeleted() {
return getModificationStamp() == DELETED_MODIFICATION_STAMP;
}
/**
* Mark the entry as deleted. It will also be removed from root index in that case.
* <p>
* Note: It is public only so that BeanInfoClassAdapter can access it. It should not be called by anyone else outside of BeanInfo.
*/
public synchronized void markDeleted() {
if (!isDeleted()) {
getRootIndex().classNameToClassEntry.remove(className);
setModificationStamp(DELETED_MODIFICATION_STAMP); // Also marks index as dirty.
}
}
/**
* Return whether the entry is stale or not. This orthoganal to isDeleted. isDeleted will not be true if isStale and isStale will not be true
* if isDeleted. Normally you should use getModificationStamp and check the value for IResource.NULL_STAMP and other values to bring it down
* to only one synchronized call to CE, but if only needing to know if stale, you can use this.
*
* @return
*
* @since 1.1.0
* @see IResource#NULL_STAMP
* @see ClassEntry#getModificationStamp()
* @see ClassEntry#isDeleted()
*/
public boolean isStale() {
return getModificationStamp() == IResource.NULL_STAMP;
}
/**
* Return the modification stamp. For those holding onto an entry, and they need to know more than if just deleted, then they should just the
* return value from getModificationStamp. Else they should use isDeleted or isStale.
*
* @return modification stamp, or {@link IResource#NULL_STAMP}if stale or not yet created, or {@link ClassEntry#DELETED_MODIFICATION_STAMP}
* if deleted.
*
* @see ClassEntry#isDeleted()
* @see ClassEntry#isStale()
* @since 1.1.0
*/
public synchronized long getModificationStamp() {
return modificationStamp;
}
/**
* Return the super modification stamp.
* @return
*
* @since 1.1.0
*/
public synchronized long getSuperModificationStamp() {
return superModificationStamp;
}
/**
* Return the interface names or <code>null</code> if no interface names.
* @return
*
* @since 1.1.0
*/
public synchronized String[] getInterfaceNames() {
return interfaceNames;
}
/**
* Return the interface modification stamps or <code>null</code> if no interfaces.
* @return
*
* @since 1.1.0
*/
public synchronized long[] getInterfaceModificationStamps() {
return interfaceModicationStamps;
}
/*
* Set the modification stamp. <p> <package-protected> because only the cache controller should set it. @param modificationStamp
*
* @since 1.1.0
*/
void setModificationStamp(long modificationStamp) {
if (this.modificationStamp != modificationStamp) {
this.modificationStamp = modificationStamp;
getRootIndex().setDirty();
}
}
/**
* Answer whether operations are also stored in the cache for this class. By default they are not. Once turned on they
* will always be stored for this class until the class is deleted.
*
* @return <code>true</code> if operations are cached, <code>false</code> if they are not cached.
*
* @since 1.1.0
*/
public synchronized boolean isOperationsStored() {
return saveOperations;
}
/*
* Set the operations stored flag.
* @param storeOperations
*
* @see BeanInfoCacheController.ClassEntry#isOperationsStored()
* @since 1.1.0
*/
void setOperationsStored(boolean storeOperations) {
saveOperations = storeOperations;
}
/**
* Get the configuration modification stamp of the last saved override cache.
*
* @return
*
* @since 1.1.0
*/
public synchronized long getConfigurationModificationStamp() {
return configurationModificationStamp;
}
/*
* Set the configuration modification stamp.
* <p> <package-protected> because only the cache controller should access it.
*
* @param configurationModificationStamp
*
* @since 1.1.0
*/
void setConfigurationModificationStamp(long configurationModificationStamp) {
this.configurationModificationStamp = configurationModificationStamp;
getRootIndex().setDirty();
}
/**
* Answer whether there is an override cache available.
* @return
*
* @since 1.1.0
*/
public synchronized boolean overrideCacheExists() {
return overrideCacheExists;
}
/*
* Set the override cache exists flag.
* <p> <package-protected> because only the cache controller should access it.
* @param overrideCacheExists
*
* @since 1.1.0
*/
void setOverrideCacheExists(boolean overrideCacheExists) {
this.overrideCacheExists = overrideCacheExists;
}
/**
* Get the pending resource or <code>null</code> if not pending.
*
* @return the pending resource or <code>null</code> if not pending.
*
* @since 1.1.0
*/
public synchronized Resource getPendingResource() {
return pendingResource;
}
/*
* Set the entry. The sequence get,do something,set must be grouped within a synchronized(ClassEntry).
* <p> <package-protected> because only the cache controller should access it.
* @param cacheResource The cacheResource to set.
*
* @since 1.1.0
*/
void setPendingResource(Resource pendingResource) {
this.pendingResource = pendingResource;
}
/**
* Get the pending override resource or <code>null</code> if not pending.
*
* @return the pending override resource or <code>null</code> if not pending.
*
* @since 1.1.0
*/
public synchronized Resource getPendingOverrideResource() {
return pendingOverrideResource;
}
/*
* Set the entry. The sequence get,do something,set must be grouped within a synchronized(ClassEntry).
* <p> <package-protected> because only the cache controller should access it.
* @param cacheResource The cacheResource to set.
*
* @since 1.1.0
*/
void setPendingOverrideResource(Resource pendingOverrideResource) {
this.pendingOverrideResource = pendingOverrideResource;
}
/*
* <package-protected> because only the cache controller should access it. @param rootIndex The rootIndex to set.
*
* @since 1.1.0
*/
void setRootIndex(RootIndex rootIndex) {
this.rootIndex = rootIndex;
}
/*
* <package-protected> because only the cache controller should access it. @return Returns the rootIndex.
*
* @since 1.1.0
*/
RootIndex getRootIndex() {
return rootIndex;
}
/*
* <package-protected> because only the cache controller should access it.
*
* @since 1.1.0
*/
void setSuperModificationStamp(long superModificationStamp) {
this.superModificationStamp = superModificationStamp;
}
/*
* <package-protected> because only the cache controller should access it.
*
* @since 1.1.0
*/
void setInterfaceNames(String[] interfaceNames) {
this.interfaceNames = interfaceNames;
}
/*
* <package-protected> because only the cache controller should access it.
*
* @since 1.1.0
*/
void setInterfaceModificationStamps(long[] interfaceModificationStamps) {
this.interfaceModicationStamps = interfaceModificationStamps;
}
}
/*
* Main index for the external jars. This variable should not be referenced directly except through the getMainIndex() accessor. That controls
* synchronization and restoration as needed.
*/
private static Index MAIN_INDEX;
/*
* Key into the Project's session data for the project index. The Project index is stored in the project's session data. That
* way when the project is closed or deleted it will go away.
*
* The project indexes will be read in as needed on a per-project basis. This variable should not be
* referenced directly except through the getProjectIndex(IProject) accessor. That controls synchronization and restoration as needed.
* Only during cleanup and such where we don't want to create one if it doesn't exist you must use sync(this). Be careful to keep
* the sync small.
*/
private static final QualifiedName PROJECT_INDEX_KEY = new QualifiedName(BeaninfoPlugin.PI_BEANINFO_PLUGINID, "project_index"); //$NON-NLS-1$
/*
* Suffix for class cache files.
*/
private static final String CLASS_CACHE_SUFFIX = ".xmi"; //$NON-NLS-1$
/*
* Suffic for class override cache files.
*/
private static final String OVERRIDE_CACHE_SUFFIX = ".override.xmi"; //$NON-NLS-1$
/**
* Return the current class entry for the JavaClass, or <code>null</code> if no current entry.
*
* @param jclass
* @return class entry or <code>null</code> if no current entry.
*
* @since 1.1.0
*/
public ClassEntry getClassEntry(JavaClass jclass) {
IType type = (IType) jclass.getReflectionType();
RootIndex rootIndex = getRootIndex(type);
String className = jclass.getQualifiedNameForReflection();
return getClassEntry(rootIndex, className, false);
}
/**
* Enumeration for newCache: Signals that this cache is the Reflection Cache with no operations in it.
* @since 1.1.0
*/
public final static int REFLECTION_CACHE = 1;
/**
* Enumeration for newCache: Signals that this cache is the Reflection Cache with operations in it.
* @since 1.1.0
*/
public final static int REFLECTION_OPERATIONS_CACHE = 2;
/**
* Enumeration for newCache: Signals that this cache is the Overrides cache.
* @since 1.1.0
*/
public final static int OVERRIDES_CACHE = 3;
/**
* A new cache entry for the given class has been created. Need to write it out.
*
* @param jclass
* the JavaClass the cache is for.
* @param cache
* the ChangeDescription to put out if cacheType is Reflection types, a List if override cache type.
* @param cacheType
* {@link BeanInfoCacheController.ClassEntry#REFLECTION_CACHE} for the enum values.
* @return new class entry (or old one if same one). Should always replace one being held by this one. <code>null</code> if cache could not be
* updated for some reason.
* @since 1.1.0
*/
public ClassEntry newCache(JavaClass jclass, Object cache, int cacheType) {
if (BeaninfoPlugin.getPlugin().getLogger().isLoggingLevel(Level.FINER)) {
Logger logger = BeaninfoPlugin.getPlugin().getLogger();
String type = cacheType!=OVERRIDES_CACHE?"Class":"Overrides"; //$NON-NLS-1$ //$NON-NLS-2$
if (cacheType == OVERRIDES_CACHE && cache == null)
type+=" empty"; //$NON-NLS-1$
logger.log("Creating cache for class "+jclass.getQualifiedNameForReflection()+" cache type="+type, Level.FINER); //$NON-NLS-1$ //$NON-NLS-2$
}
ChangeDescription cd = null;
if (cacheType != OVERRIDES_CACHE) {
// First go through the cd and remove any empty changes. This is because we created the feature change before we knew what went into
// it, and at times nothing goes into it.
cd = (ChangeDescription) cache;
for (Iterator iter = cd.getObjectChanges().iterator(); iter.hasNext();) {
EObjectToChangesMapEntryImpl fcEntry = (EObjectToChangesMapEntryImpl) iter.next();
if (((List) fcEntry.getValue()).isEmpty())
iter.remove(); // Empty changes, remove it.
}
}
IType type = (IType) jclass.getReflectionType();
RootIndex rootIndex = getRootIndex(type);
String className = jclass.getQualifiedNameForReflection();
ClassEntry ce = getClassEntry(rootIndex, className, true); // Create it if not existing.
// Sync on ce so that only can create a cache for a class at a time and so that writing (if occurring at the same time for the class) can be
// held up.
// this is a violation of the agreement to only sync on THIS, but it is necessary or else the write job would lock everything out while it is
// writing. This way it only locks out one class, if the class is at the same time.
// We shouldn't have deadlock because here we lock ce and then THIS (maybe). The write job will lock ce, and then lock THIS. Everywhere else
// we must
// also do lock ce then THIS. Mustn't do other way around or possibility of deadlock. Be careful that any synchronized methods in this class
// do
// not lock an existing ce.
ResourceSet cacheRset = null;
synchronized (ce) {
Resource cres;
if (cacheType != OVERRIDES_CACHE) {
cres = ce.getPendingResource();
if (cres != null) {
// We have a pending, so clear and reuse the resource.
cres.getContents().clear();
} else {
// Not currently writing or waiting to write, so create a new resource.
cres = jclass.eResource().getResourceSet().createResource(
URI.createFileURI(rootIndex.getCachePath().append(className + CLASS_CACHE_SUFFIX).toString()));
}
cacheRset = cres.getResourceSet();
ce.setOperationsStored(cacheType == REFLECTION_OPERATIONS_CACHE);
ce.setPendingResource(cres);
cres.getContents().add(cd);
// Archives use same mod as archive (retrieve from rootindex), while non-archive use the underlying resource's mod stamp.
if (rootIndex.isArchiveRoot())
ce.setModificationStamp(((ArchiveRootIndex) rootIndex).getArchiveModificationStamp());
else {
try {
ce.setModificationStamp(type.getUnderlyingResource().getModificationStamp());
} catch (JavaModelException e) {
BeaninfoPlugin.getPlugin().getLogger().log(e);
ce.markDeleted(); // Mark as deleted in case this was an existing that someone is holding.
return null; // Couldn't do it, throw cache entry away. This actually should never occur.
}
}
// Need to get the supers info.
List supers = jclass.getESuperTypes();
if (!supers.isEmpty()) {
// We assume that they all have been introspected. This was done back in main introspection. If they are introspected they will have a class entry.
BeaninfoClassAdapter bca = BeaninfoClassAdapter.getBeaninfoClassAdapter((EObject) supers.get(0));
ClassEntry superCE = bca.getClassEntry();
if (superCE != null)
ce.setSuperModificationStamp(superCE.getModificationStamp());
else
ce.setSuperModificationStamp(ClassEntry.SUPER_UNDEFINED_MODIFICATION_STAMP); // No classentry means undefined. So put something in so that when it becomes defined we will know.
if(supers.size() == 1) {
ce.setInterfaceNames(null);
ce.setInterfaceModificationStamps(null);
} else {
String[] interNames = new String[supers.size()-1];
long[] interMods = new long[interNames.length];
- for (int i = 1, indx = 0; i < interNames.length; i++, indx++) {
+ for (int i = 1, indx = 0; indx < interNames.length; i++, indx++) {
JavaClass javaClass = (JavaClass) supers.get(i);
bca = BeaninfoClassAdapter.getBeaninfoClassAdapter(javaClass);
bca.introspectIfNecessary(); // Force introspection to get a valid super mod stamp.
superCE = bca.getClassEntry();
interNames[indx] = javaClass.getQualifiedNameForReflection();
if (superCE != null)
interMods[indx] = superCE.getModificationStamp();
else
interMods[indx] = ClassEntry.SUPER_UNDEFINED_MODIFICATION_STAMP; // No classentry means undefined. So put something in so that when it becomes defined we will know.
}
ce.setInterfaceNames(interNames);
ce.setInterfaceModificationStamps(interMods);
}
} else {
ce.setSuperModificationStamp(IResource.NULL_STAMP);
ce.setInterfaceNames(null);
ce.setInterfaceModificationStamps(null);
}
} else {
// We are an override cache.
if (cache != null) {
cres = ce.getPendingOverrideResource();
if (cres != null) {
// We have a pending, so clear and reuse the resource.
cres.getContents().clear();
} else {
// Not currently writing or waiting to write, so create a new resource.
cres = jclass.eResource().getResourceSet().createResource(
URI.createFileURI(rootIndex.getCachePath().append(className + OVERRIDE_CACHE_SUFFIX).toString()));
}
cacheRset = cres.getResourceSet();
cres.getContents().addAll((List) cache);
ce.setPendingOverrideResource(cres);
ce.setOverrideCacheExists(true);
} else {
ce.setPendingOverrideResource(null);
ce.setOverrideCacheExists(false);
}
ce.setConfigurationModificationStamp(Platform.getPlatformAdmin().getState(false).getTimeStamp());
}
}
queueClassEntry(ce, cacheRset); // Now queue it up.
return ce;
}
/**
* Get the cache resource for the given java class.
* <p>
* NOTE: It is the responsibility of the caller to ALWAYS remove the Resource from its resource set when done with it.
*
* @param jclass
* @param ce the class entry for the jclass
* @param reflectCache <code>true</code> if this the reflection/introspection cache or <code>false</code> if this is the override cache.
* @return the loaded cache resource, or <code>null</code> if not there (for some reason) or an error trying to load it.
*
* @since 1.1.0
*/
public Resource getCache(JavaClass jclass, ClassEntry ce, boolean reflectCache) {
String className = jclass.getQualifiedNameForReflection();
if (BeaninfoPlugin.getPlugin().getLogger().isLoggingLevel(Level.FINER)) {
Logger logger = BeaninfoPlugin.getPlugin().getLogger();
String type = reflectCache?"Class":"Overrides"; //$NON-NLS-1$ //$NON-NLS-2$
logger.log("Loading cache for class "+className+" cache type="+type, Level.FINER); //$NON-NLS-1$ //$NON-NLS-2$
}
if (reflectCache) {
boolean waitForJob = false;
synchronized (ce) {
if (ce.getPendingResource() != null) {
// We have one pending. So wait until write cache job is done, and then load it in.
// Note: Can't just copy the pending resource because it has references to JavaClasses
// and these could be in a different project (since this could be a workspace wide class).
// We would get the wrong java classes then when we apply it.
waitForJob = true;
if (BeaninfoPlugin.getPlugin().getLogger().isLoggingLevel(Level.FINER))
BeaninfoPlugin.getPlugin().getLogger().log("Using pending class cache.", Level.FINER); //$NON-NLS-1$
}
}
if (waitForJob)
waitForCacheSaveJob();
try {
return jclass.eResource().getResourceSet().getResource(
URI.createFileURI(ce.getRootIndex().getCachePath().append(
className + CLASS_CACHE_SUFFIX).toString()), true);
} catch (Exception e) {
// Something happened and couldn't load it.
// TODO - need to remove the Level.INFO arg when the beaninfo cache is working dynamically
BeaninfoPlugin.getPlugin().getLogger().log(e, Level.INFO);
return null;
}
} else {
boolean waitForJob = false;
synchronized (ce) {
if (ce.getPendingOverrideResource() != null) {
// We have one pending. So wait until write cache job is done, and then load it in.
// Note: Can't just copy the pending resource because it has references to JavaClasses
// and these could be in a different project (since this could be a workspace wide class).
// We would get the wrong java classes then when we apply it.
waitForJob = true;
if (BeaninfoPlugin.getPlugin().getLogger().isLoggingLevel(Level.FINER))
BeaninfoPlugin.getPlugin().getLogger().log("Using pending override cache.", Level.FINER); //$NON-NLS-1$
}
}
if (waitForJob)
waitForCacheSaveJob();
try {
return jclass.eResource().getResourceSet().getResource(
URI.createFileURI(ce.getRootIndex().getCachePath().append(
className + OVERRIDE_CACHE_SUFFIX).toString()), true);
} catch (Exception e) {
// Something happened and couldn't load it.
// TODO - need to remove the Level.INFO arg when the beaninfo cache is working dynamically
BeaninfoPlugin.getPlugin().getLogger().log(e, Level.INFO);
return null;
}
}
}
private synchronized ClassEntry getClassEntry(RootIndex rootIndex, String className, boolean createEntry) {
ClassEntry ce = (ClassEntry) rootIndex.classNameToClassEntry.get(className);
if (createEntry && ce == null) {
// Need to create one.
ce = new ClassEntry(rootIndex, className);
// Don't actually mark the rootIndex dirty until the cache for it is actually saved out.
}
return ce;
}
private static final String ROOT_PREFIX = "root"; //$NON-NLS-1$
/*
* Get the root index for the appropriate cache for the given java class.
*/
private RootIndex getRootIndex(IType type) {
IPackageFragmentRoot root = (IPackageFragmentRoot) type.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
if (!root.isExternal()) {
// So it is in a project. Get the project index.
return getRootIndex(root, root.getJavaProject().getProject());
} else {
// It is an external jar (archive), so needs to come from main index, no project.
return getRootIndex(root, null);
}
}
/*
* Get the root index for the given root. A Project index if project is not null.
*/
private synchronized RootIndex getRootIndex(IPackageFragmentRoot root, IProject project) {
Index index = project != null ? getProjectIndex(project) : getMainIndex();
IPath rootPath = root.getPath();
RootIndex rootIndex = (RootIndex) index.rootToRootIndex.get(rootPath);
if (rootIndex == null) {
// Need to do a new root path.
String rootName = ROOT_PREFIX + (++index.highRootNumber);
rootIndex = root.isArchive() ? createArchiveRootIndex(root, rootName, index) : new FolderRootIndex(rootName, index);
index.rootToRootIndex.put(rootPath, rootIndex);
// Don't set index dirty until we actually save a class cache file. Until then it only needs to be in memory.
}
rootIndex.setupIndex(project); // Set it up, or may already be set, so it will do nothing in that case.
return rootIndex;
}
/*
* Create an archive root with the given root number and root.
*/
private RootIndex createArchiveRootIndex(IPackageFragmentRoot rootArchive, String rootName, Index index) {
long modStamp = IResource.NULL_STAMP;
if (rootArchive.isExternal()) {
modStamp = rootArchive.getPath().toFile().lastModified();
} else {
try {
modStamp = rootArchive.getUnderlyingResource().getModificationStamp();
} catch (JavaModelException e) {
BeaninfoPlugin.getPlugin().getLogger().log(e);
}
}
return new ArchiveRootIndex(rootName, modStamp, index);
}
private static final String INDEXFILENAME = ".index"; //$NON-NLS-1$
private static final String CACHEDIR = ".cache"; // Cache directory (so as not to conflict with any future BeanInfo Plugin specific data files. //$NON-NLS-1$
/*
* Get the cache directory for the project (or if project is null, the main plugin cache directory).
*/
// TODO: make this one private
public static IPath getCacheDir(IProject project) {
if (project != null)
return project.getWorkingLocation(BeaninfoPlugin.getPlugin().getBundle().getSymbolicName()).append(CACHEDIR);
else
return BeaninfoPlugin.getPlugin().getStateLocation().append(CACHEDIR);
}
/*
* Get the project index. Synchronized so that we can create it if necessary and not get race conditions.
*/
private synchronized Index getProjectIndex(IProject project) {
try {
Index index = (Index) project.getSessionProperty(PROJECT_INDEX_KEY);
if (index == null) {
// Read the index in.
File indexDirFile = getCacheDir(project).append(INDEXFILENAME).toFile();
if (indexDirFile.canRead()) {
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream(new BufferedInputStream(new FileInputStream(indexDirFile)));
index = (Index) ois.readObject();
} catch (InvalidClassException e) {
// This is ok. It simply means the cache index is at a downlevel format and needs to be reconstructed.
} catch (IOException e) {
BeaninfoPlugin.getPlugin().getLogger().log(e);
} catch (ClassNotFoundException e) {
BeaninfoPlugin.getPlugin().getLogger().log(e);
} finally {
if (ois != null)
try {
ois.close();
} catch (IOException e) {
BeaninfoPlugin.getPlugin().getLogger().log(e);
}
}
}
if (index == null) {
// Doesn't yet exist or it couldn't be read for some reason, or it was downlevel cache in which case we just throw it away and create
// new).
index = new Index();
index.highRootNumber = 0;
index.rootToRootIndex = new HashMap();
}
project.setSessionProperty(PROJECT_INDEX_KEY, index); // We either created a new one, or we were able to load it.
}
return index;
} catch (CoreException e) {
// Shouldn't occur,
return null;
}
}
/*
* Get the main index. Synchronized so that we can create it if necessary and not get race conditions.
*/
private synchronized Index getMainIndex() {
if (MAIN_INDEX == null) {
// Read the index in.
File indexDirFile = getCacheDir(null).append(INDEXFILENAME).toFile();
if (indexDirFile.canRead()) {
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream(new BufferedInputStream(new FileInputStream(indexDirFile)));
MAIN_INDEX = (Index) ois.readObject();
} catch (InvalidClassException e) {
// This is ok. It just means that the cache index is at a downlevel format and needs to be reconstructed.
} catch (IOException e) {
BeaninfoPlugin.getPlugin().getLogger().log(e);
} catch (ClassNotFoundException e) {
BeaninfoPlugin.getPlugin().getLogger().log(e);
} finally {
if (ois != null)
try {
ois.close();
} catch (IOException e) {
BeaninfoPlugin.getPlugin().getLogger().log(e);
}
}
}
if (MAIN_INDEX == null) {
// Doesn't yet exist or it couldn't be read for some reason, or it was downlevel cache in which case we just throw it away and create
// new).
MAIN_INDEX = new Index();
MAIN_INDEX.highRootNumber = 0;
MAIN_INDEX.rootToRootIndex = new HashMap();
}
}
return MAIN_INDEX;
}
// -------------- Save Participant code -----------------
protected class SaveParticipant implements ISaveParticipant {
/*
* (non-Javadoc)
*
* @see org.eclipse.core.resources.ISaveParticipant#doneSaving(org.eclipse.core.resources.ISaveContext)
*/
public void doneSaving(ISaveContext context) {
}
/*
* (non-Javadoc)
*
* @see org.eclipse.core.resources.ISaveParticipant#prepareToSave(org.eclipse.core.resources.ISaveContext)
*/
public void prepareToSave(ISaveContext context) throws CoreException {
}
/*
* (non-Javadoc)
*
* @see org.eclipse.core.resources.ISaveParticipant#rollback(org.eclipse.core.resources.ISaveContext)
*/
public void rollback(ISaveContext context) {
}
/*
* (non-Javadoc)
*
* @see org.eclipse.core.resources.ISaveParticipant#saving(org.eclipse.core.resources.ISaveContext)
*/
public void saving(ISaveContext context) throws CoreException {
boolean fullsave = false;
switch (context.getKind()) {
case ISaveContext.PROJECT_SAVE:
IProject project = context.getProject();
synchronized (BeanInfoCacheController.INSTANCE) {
// Write the index. The cache save job will eventually run and at that point write out the pending cache files too.
// They don't need to be written before the project save is complete.
Index projectIndex = (Index) project.getSessionProperty(PROJECT_INDEX_KEY);
if (projectIndex != null && projectIndex.isDirty())
if (reconcileIndexDirectory(project, projectIndex))
writeIndex(project, projectIndex);
else {
// It was empty, just get rid of the index. The directories have already been cleared.
projectIndex.markDead();
project.setSessionProperty(PROJECT_INDEX_KEY, null);
}
}
break;
case ISaveContext.FULL_SAVE:
fullsave = true;
waitForCacheSaveJob();
// Now flow into the snapshot save to complete the fullsave.
case ISaveContext.SNAPSHOT:
// For a snapshot, just the dirty indexes, no clean up. If fullsave, cleanup the indexes, but only save the dirty.
synchronized (BeanInfoCacheController.INSTANCE) {
if (MAIN_INDEX != null) {
if (fullsave) {
if (reconcileIndexDirectory(null, MAIN_INDEX)) {
if (MAIN_INDEX.isDirty())
writeIndex(null, MAIN_INDEX);
} else {
// It was empty, just get rid of the index. The directories have already been cleared.
MAIN_INDEX.markDead();
MAIN_INDEX = null;
}
} else if (MAIN_INDEX.isDirty())
writeIndex(null, MAIN_INDEX);
}
// Now do the project indexes. We have to walk all open projects to see which have an index. Since we are
// doing a major save, the hit will ok
IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects();
for (int i=0; i<projects.length; i++) {
project = projects[i];
if (project.isOpen()) {
Index index = (Index) project.getSessionProperty(PROJECT_INDEX_KEY);
if (index != null) {
if (fullsave) {
if (reconcileIndexDirectory(project, index)) {
if (index.isDirty())
writeIndex(project, index);
} else {
// It was empty, just get rid of the index from memory. It has already been deleted from disk.
index.markDead();
project.setSessionProperty(PROJECT_INDEX_KEY, null);
}
} else if (index.isDirty())
writeIndex(project, index);
}
}
}
}
}
}
/*
* Write an index. Project if not null indicates a project index.
*/
private void writeIndex(IProject project, Index index) {
ObjectOutputStream oos = null;
try {
File indexDirFile = getCacheDir(project).toFile();
indexDirFile.mkdirs();
File indexFile = new File(indexDirFile, INDEXFILENAME);
oos = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(indexFile)));
oos.writeObject(index);
index.setDirty(false);
} catch (IOException e) {
BeaninfoPlugin.getPlugin().getLogger().log(e);
} finally {
if (oos != null)
try {
oos.close();
} catch (IOException e) {
BeaninfoPlugin.getPlugin().getLogger().log(e);
}
}
}
/*
* Reconcile the index directory of unused (empty) root directories. If after reconciling the index is empty, then it will delete the index file too. @return
* true if index not empty, false if index was empty and was erased too.
*/
private boolean reconcileIndexDirectory(IProject project, Index index) {
// clean out unused rootIndexes
File indexDir = getCacheDir(project).toFile();
if (indexDir.canWrite()) {
// Create a set of all root names for quick look up.
if (index.rootToRootIndex.isEmpty()) {
// It is empty, clear everything, including index file.
cleanDirectory(indexDir, false);
return false;
} else {
// Need a set of the valid rootnames for quick lookup of names in the directory list.
// And while accumulating this list, clean out the root indexes cache too (i.e. the class cache files).
final Set validFiles = new HashSet(index.rootToRootIndex.size());
validFiles.add(INDEXFILENAME);
for (Iterator itr = index.rootToRootIndex.values().iterator(); itr.hasNext();) {
RootIndex rootIndex = (RootIndex) itr.next();
if (reconcileClassCacheDirectory(rootIndex, project)) {
// The class cache has been reconciled, and there are still some classes left, so keep the root index.
validFiles.add(rootIndex.getRootName());
} else {
itr.remove(); // The root index is empty, so get rid of it. Since not a valid name, it will be deleted in next step.
index.setDirty(true); // Also set it dirty in case it wasn't because we need to write out the container Index since it was
// changed.
}
}
// Get list of files and delete those that are not a valid name (used root name, or index file)
String[] fileNames = indexDir.list();
for (int i = 0; i < fileNames.length; i++) {
if (!validFiles.contains(fileNames[i])) {
File file = new File(indexDir, fileNames[i]);
if (file.isDirectory())
cleanDirectory(file, true);
else
file.delete();
}
}
return true;
}
} else
return true; // Can't write, so treat as leave alone.
}
/*
* Reconcile the class cache directory for the root index. Return true if reconciled good but not empty. Return false if the class cache
* directory is now empty. In this case we should actually get rid of the entire root index. This makes sure that the directory matches
* the contents of the index by removing any file not found in the index.
*/
private boolean reconcileClassCacheDirectory(RootIndex rootIndex, IProject project) {
if (rootIndex.classNameToClassEntry.isEmpty())
return false; // There are no classes, so get rid the entire root index.
else {
final Set validFiles = rootIndex.classNameToClassEntry.keySet(); // The keys (classnames) are the filenames (without extension)
// that
// should be kept.
File indexDir = getCacheDir(project).append(rootIndex.getRootName()).toFile();
// Get list of files that are not a valid name (used classname)
String[] fileNames = indexDir.list();
if (fileNames != null) {
for (int i = 0; i < fileNames.length; i++) {
String fileName = fileNames[i];
if (fileName.endsWith(OVERRIDE_CACHE_SUFFIX)) {
// Ends with out class cache extension, see if valid classname.
String classname = fileName.substring(0, fileName.length() - OVERRIDE_CACHE_SUFFIX.length());
ClassEntry ce = (ClassEntry) rootIndex.classNameToClassEntry.get(classname);
if (ce != null && ce.overrideCacheExists())
continue; // It is one of ours. Keep it.
} else if (fileName.endsWith(CLASS_CACHE_SUFFIX)) {
// Ends with out class cache extension, see if valid classname.
if (validFiles.contains(fileName.substring(0, fileName.length() - CLASS_CACHE_SUFFIX.length()))) // Strip down to just
// class and see if
// one of ours.
continue; // It is one of ours. Keep it.
}
// Not valid, get rid of it.
File file = new File(indexDir, fileName);
if (file.isDirectory())
cleanDirectory(file, true);
else
file.delete();
}
}
return true;
}
}
}
private static void cleanDirectory(File dir, boolean eraseDir) {
if (dir.canWrite()) {
File[] files = dir.listFiles();
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory())
cleanDirectory(files[i], true);
else
files[i].delete();
}
if (eraseDir)
dir.delete();
}
}
//-------------- Save Class Cache Entry Job -------------------
// This is write queue for class caches. It is a FIFO queue. It is sychronized so that adds/removes are controlled.
// Entries are ClassEntry's. The class entry has the resource that needs to be written out. It will be set to null
// by the job when it is written. The job will have a ClassEntry locked while it is retrieving and resetting the resource
// field in the entry.
//
// The process is the new cache will lock, create resource, set resource into the CE and release lock. Then add the CE to the queue
// and schedule the job (in case job is not running).
//
// The job will lock the CE, get resource from the CE, write it out, set it back to null, release the CE). If the resource is null,
// then it was already processed (this could happen if the job didn't get a chance to save it before another entry was posted
// and this is the second request and it was actually processed by the first request).
// IE:
// 1) resource created, queue entry added
// 2) 2nd req, job not processed yet, resource recreated and put back into CE, new queue entry.
// 3) job pulls from queue, locks ce, grabs resource, writes out the resource, sets back to null, release ce.
// 4) job pulls from queue. This time the resoure is null so it skips it.
//
// Need to lock Ce during entire create and write because the resource set is not reentrant so can't be writing it while creating it.
private List cacheWriteQueue = null;
void waitForCacheSaveJob() {
// For a full save we want to get the class cache files written too, so we need to manipulate the job to get it to finish ASAP.
if (cacheWriteJob != null) {
if (BeaninfoPlugin.getPlugin().getLogger().isLoggingLevel(Level.FINER))
BeaninfoPlugin.getPlugin().getLogger().log("Forcing a cache save job to start early.", Level.FINER); //$NON-NLS-1$
switch (cacheWriteJob.getState()) {
case Job.SLEEPING:
// It could be waiting a long time, so we need to wake it up at a high priority to get it running ASAP.
cacheWriteJob.setPriority(Job.INTERACTIVE); // Need to get it going right away
cacheWriteJob.wakeUp();
// Now drop into the wait.
default:
// Now wait for it (if not running this will return right away).
try {
cacheWriteJob.join();
} catch (InterruptedException e) {
}
}
}
}
static final Map SAVE_CACHE_OPTIONS;
static {
SAVE_CACHE_OPTIONS = new HashMap(3);
SAVE_CACHE_OPTIONS.put(XMLResource.OPTION_SAVE_TYPE_INFORMATION, Boolean.TRUE);
SAVE_CACHE_OPTIONS.put(XMLResource.OPTION_USE_ENCODED_ATTRIBUTE_STYLE, Boolean.TRUE);
SAVE_CACHE_OPTIONS.put(XMLResource.OPTION_ENCODING, "UTF-8"); //$NON-NLS-1$
}
protected Job cacheWriteJob = null;
protected Adapter projectReleaseAdapter = new AdapterImpl() {
/* (non-Javadoc)
* @see org.eclipse.emf.common.notify.impl.AdapterImpl#isAdapterForType(java.lang.Object)
*/
public boolean isAdapterForType(Object type) {
return type == BeanInfoCacheController.this; // We're making the BeanInfoCacheController.this be the adapter type.
}
/* (non-Javadoc)
* @see org.eclipse.emf.common.notify.impl.AdapterImpl#notifyChanged(org.eclipse.emf.common.notify.Notification)
*/
public void notifyChanged(Notification msg) {
if (msg.getEventType() == ProjectResourceSet.SPECIAL_NOTIFICATION_TYPE && msg.getFeatureID(BeanInfoCacheController.class) == ProjectResourceSet.PROJECTRESOURCESET_ABOUT_TO_RELEASE_ID) {
// This is an about to be closed. If we have an active write job, bring it up to top priority and wait for it to finish.
// This will make sure any resources in the project are written. There may not be any waiting, but this is doing a close
// project, which is slow already relatively speaking, that waiting for the cache write job to finish is not bad.
waitForCacheSaveJob();
}
}
};
private void queueClassEntry(ClassEntry ce, ResourceSet rset) {
if (cacheWriteQueue == null) {
cacheWriteQueue = Collections.synchronizedList(new LinkedList());
cacheWriteJob = new Job(BeaninfoCoreMessages.BeanInfoCacheController_Job_WriteBeaninfoCache_Title) {
protected IStatus run(IProgressMonitor monitor) {
monitor.beginTask("", cacheWriteQueue.size() + 10); // This is actually can change during the run, so we add 10 for the heck of it. //$NON-NLS-1$
if (BeaninfoPlugin.getPlugin().getLogger().isLoggingLevel(Level.FINER))
BeaninfoPlugin.getPlugin().getLogger().log("Starting write BeanInfo Cache files.", Level.FINER); //$NON-NLS-1$
while (!monitor.isCanceled() && !cacheWriteQueue.isEmpty()) {
ClassEntry ce = (ClassEntry) cacheWriteQueue.remove(0); // Get first one.
boolean dead = false;
synchronized (BeanInfoCacheController.this) {
if (ce.getRootIndex().getIndex().isDead()) {
dead = true; // The index is dead, so don't write it. We still need to go through and get the pending resource out of its resource set so that it goes away.
}
}
synchronized (ce) {
Resource cres = ce.getPendingResource();
if (cres != null) {
try {
if (!dead)
cres.save(SAVE_CACHE_OPTIONS);
} catch (IOException e) {
BeaninfoPlugin.getPlugin().getLogger().log(e);
} finally {
// Remove the resource from resource set, clear out the pending.
cres.getResourceSet().getResources().remove(cres);
ce.setPendingResource(null);
}
}
cres = ce.getPendingOverrideResource();
if (cres != null) {
try {
if (!dead)
cres.save(SAVE_CACHE_OPTIONS);
} catch (IOException e) {
BeaninfoPlugin.getPlugin().getLogger().log(e);
} finally {
// Remove the resource from resource set, clear out the pending.
cres.getResourceSet().getResources().remove(cres);
ce.setPendingOverrideResource(null);
}
}
monitor.worked(1);
}
}
monitor.done();
if (BeaninfoPlugin.getPlugin().getLogger().isLoggingLevel(Level.FINER))
BeaninfoPlugin.getPlugin().getLogger().log("Finished write BeanInfo Cache files.", Level.FINER); //$NON-NLS-1$
return Status.OK_STATUS;
}
};
cacheWriteJob.setPriority(Job.SHORT);
cacheWriteJob.setSystem(true);
}
if (rset != null && EcoreUtil.getExistingAdapter(rset, this) == null) {
// If it is a project resource set, then add ourselves as listeners so we know when released.
if (rset instanceof ProjectResourceSet)
rset.eAdapters().add(projectReleaseAdapter);
}
cacheWriteQueue.add(ce);
cacheWriteJob.schedule(60 * 1000L); // Put off for 1 minute to let other stuff go on. Not important that it happens immediately.
}
}
\ No newline at end of file
| false | false | null | null |
diff --git a/Twist/src/com/secondhand/opengl/StarsVertexBuffer.java b/Twist/src/com/secondhand/opengl/StarsVertexBuffer.java
index e330ab27..b33d13ab 100644
--- a/Twist/src/com/secondhand/opengl/StarsVertexBuffer.java
+++ b/Twist/src/com/secondhand/opengl/StarsVertexBuffer.java
@@ -1,84 +1,77 @@
package com.secondhand.opengl;
import java.util.List;
import java.util.Random;
import org.anddev.andengine.opengl.util.FastFloatBuffer;
import org.anddev.andengine.opengl.vertex.VertexBuffer;
import com.badlogic.gdx.math.Vector2;
public class StarsVertexBuffer extends VertexBuffer {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
-
- private List<Vector2> mVertices;
private int mStars;
// ===========================================================
// Constructors
// ===========================================================
-
- public List<Vector2> getVertices() {
- return this.mVertices;
- }
-
public StarsVertexBuffer(final int stars, final int pDrawType, final boolean pManaged) {
super(stars * 2, pDrawType, pManaged);
this.mStars = stars;
}
// ===========================================================
// Getter & Setter
// ===========================================================
public int getStars() {
return this.mStars;
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public synchronized void update(final float width, final float height) {
final int[] vertices = this.mBufferData;
Random rng = new Random();
int count = 0;
for (int i = 0; i < this.getStars(); ++i) {
float x = (float) (rng.nextInt(Integer.MAX_VALUE) % (int)width);
float y = (float) (rng.nextInt(Integer.MAX_VALUE) % (int)height);
vertices[count++] = Float.floatToRawIntBits(x);
vertices[count++] = Float.floatToRawIntBits(y);
}
final FastFloatBuffer buffer = this.getFloatBuffer();
buffer.position(0);
buffer.put(vertices);
buffer.position(0);
super.setHardwareBufferNeedsUpdate();
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| false | false | null | null |
diff --git a/winstone/src/net/gnehzr/tnoodle/server/TNoodleServer.java b/winstone/src/net/gnehzr/tnoodle/server/TNoodleServer.java
index 25894a4a..5941796e 100755
--- a/winstone/src/net/gnehzr/tnoodle/server/TNoodleServer.java
+++ b/winstone/src/net/gnehzr/tnoodle/server/TNoodleServer.java
@@ -1,292 +1,305 @@
package net.gnehzr.tnoodle.server;
import java.awt.Desktop;
import java.awt.Image;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.BindException;
import java.net.InetAddress;
import java.net.InterfaceAddress;
import java.net.MalformedURLException;
import java.net.NetworkInterface;
import java.net.ServerSocket;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.NamingException;
import javax.swing.ImageIcon;
import joptsimple.OptionParser;
import joptsimple.OptionSet;
import joptsimple.OptionSpec;
import net.gnehzr.tnoodle.utils.Launcher;
import net.gnehzr.tnoodle.utils.TNoodleLogging;
import net.gnehzr.tnoodle.utils.Utils;
import winstone.TNoodleWinstoneLauncher;
public class TNoodleServer {
+ private static final Logger l = Logger.getLogger(TNoodleServer.class.getName());
+
public static String NAME = Utils.getProjectName();
public static String VERSION = Utils.getVersion();
private static final int MIN_HEAP_SIZE_MEGS = 512;
private static final String ICONS_FOLDER = "icons";
private static final String ICON_WRAPPER = "tnoodle_logo_1024_gray.png";
private static final String ICON_WORKER = "tnoodle_logo_1024.png";
private static final String DB_NAME = "tnoodledb";
private static final String DB_USERNAME = "root";
private static final String DB_PASSWORD = "password";
public TNoodleServer(int httpPort, boolean bindAggressively, boolean browse) throws IOException, ClassNotFoundException, NamingException {
// at startup
Map<String, String> serverArgs = new HashMap<String, String>();
serverArgs.put("webappsDir", Utils.getWebappsDir().getAbsolutePath());
serverArgs.put("httpPort", "" + httpPort);
serverArgs.put("ajp13Port", "-1");
- File db = new File(Utils.getResourceDirectory(), DB_NAME);
- serverArgs.put("useJNDI", "true");
- serverArgs.put("jndi.resource.jdbc/connPool", "javax.sql.DataSource");
- serverArgs.put("jndi.param.jdbc/connPool.url", String.format("jdbc:h2:%s;MODE=MySQL;USER=%s;PASSWORD=%s;MVCC=TRUE", db.getAbsoluteFile(), DB_USERNAME, DB_PASSWORD));
- serverArgs.put("jndi.param.jdbc/connPool.driverClassName", "org.h2.Driver");
- serverArgs.put("jndi.param.jdbc/connPool.username", DB_USERNAME);
- serverArgs.put("jndi.param.jdbc/connPool.password", DB_PASSWORD);
+ String dbDriver = "org.h2.Driver";
+ boolean initializeDb;
+ try {
+ Class.forName(dbDriver);
+ initializeDb = true;
+ } catch(ClassNotFoundException e) {
+ initializeDb = false;
+ l.info("Could not find class " + dbDriver + ", so we're not creating an entry in JNDI for a db.");
+ }
+ if(initializeDb) {
+ File db = new File(Utils.getResourceDirectory(), DB_NAME);
+ serverArgs.put("useJNDI", "true");
+ serverArgs.put("jndi.resource.jdbc/connPool", "javax.sql.DataSource");
+ serverArgs.put("jndi.param.jdbc/connPool.url", String.format("jdbc:h2:%s;MODE=MySQL;USER=%s;PASSWORD=%s;MVCC=TRUE", db.getAbsoluteFile(), DB_USERNAME, DB_PASSWORD));
+ serverArgs.put("jndi.param.jdbc/connPool.driverClassName", dbDriver);
+ serverArgs.put("jndi.param.jdbc/connPool.username", DB_USERNAME);
+ serverArgs.put("jndi.param.jdbc/connPool.password", DB_PASSWORD);
+ }
// By default, winstone looks in ./lib, which I don't like, as it means
// we'll behave differently when run from different directories.
serverArgs.put("commonLibFolder", "");
ServerSocket ss = aggressivelyBindSocket(httpPort, bindAggressively);
Utils.azzert(ss != null);
final Logger winstoneLogger = Logger.getLogger(winstone.Logger.class.getName());
winstone.Logger.init(winstone.Logger.MAX, new OutputStream() {
private StringBuilder msg = new StringBuilder();
@Override
public void write(int b) throws IOException {
char ch = (char) b;
if(ch == '\n') {
winstoneLogger.log(Level.FINER, msg.toString());
msg.setLength(0);
} else {
msg.append(ch);
}
}
}, false);
TNoodleWinstoneLauncher.create(serverArgs, ss);
System.out.println(NAME + "-" + VERSION + " started");
ArrayList<String> hostnames = new ArrayList<String>();
try {
hostnames.add(InetAddress.getLocalHost().getHostAddress());
} catch(UnknownHostException e) {
for(Enumeration<NetworkInterface> intfs = NetworkInterface.getNetworkInterfaces(); intfs.hasMoreElements();) {
NetworkInterface intf = intfs.nextElement();
for(InterfaceAddress addr : intf.getInterfaceAddresses()) {
hostnames.add(addr.getAddress().getHostAddress());
}
}
}
if(hostnames.isEmpty()) {
System.out.println("Couldn't find any hostnames for this machine");
} else {
if(hostnames.size() > 1 && browse) {
browse = false;
System.out.println("Couldn't determine which url to browse to");
}
for(String hostname : hostnames) {
String url = "http://" + hostname + ":" + httpPort;
// TODO - maybe it would make sense to open this url asap, that
// way the user's browser starts parsing tnt even as the server
// is starting up. The only problem with this is that we'd open
// the browser even if the server fails to start.
if(browse) {
if(Desktop.isDesktopSupported()) {
Desktop d = Desktop.getDesktop();
if(d.isSupported(Desktop.Action.BROWSE)) {
try {
URI uri = new URI(url);
System.out.println("Opening " + uri + " in browser. Pass -n to disable this!");
d.browse(uri);
return;
} catch(URISyntaxException e) {
e.printStackTrace();
}
}
}
System.out.println("Sorry, it appears the Desktop api is not supported on your platform");
}
System.out.println("Visit " + url + " for a readme and demo.");
}
}
}
private ServerSocket aggressivelyBindSocket(int port, boolean bindAggressively) throws IOException {
ServerSocket server = null;
final int MAX_TRIES = 10;
for(int i = 0; i < MAX_TRIES && server == null; i++) {
if(i > 0) {
System.out.println("Attempt " + (i+1) + "/" + MAX_TRIES + " to bind to port " + port);
}
try {
server = new ServerSocket(port, AggressiveHttpListener.getBacklogCount());
} catch(BindException e) {
// If this port is in use, we assume it's an instance of
// TNoodleServer, and ask it to commit honorable suicide.
// After that, we can start up. If it was a TNoodleServer,
// it hopefully will have freed up the port we want.
System.out.println("Detected server running on port " + port + ", maybe it's an old " + NAME + "?");
if(!bindAggressively) {
System.out.println("noupgrade option set. You'll have to free up port " + port + " manually, or clear this option.");
break;
}
try {
URL url = new URL("http://localhost:" + port + "/kill/now");
System.out.println("Sending request to " + url + " to hopefully kill it.");
URLConnection conn = url.openConnection();
InputStream in = conn.getInputStream();
in.close();
Thread.sleep(1000);
} catch(MalformedURLException ee) {
ee.printStackTrace();
} catch(IOException ee) {
ee.printStackTrace();
} catch(InterruptedException ee) {
ee.printStackTrace();
}
}
}
if(server == null) {
System.out.println("Failed to bind to port " + port + ". Giving up");
System.exit(1);
}
return server;
}
// Preferred way to detect OSX according to https://developer.apple.com/library/mac/#technotes/tn2002/tn2110.html
public static boolean isOSX() {
String osName = System.getProperty("os.name");
return osName.contains("OS X");
}
/*
* Sets the dock icon in OSX. Could be made to have uses in other operating systems.
*/
private static void setApplicationIcon() {
// Let's wrap everything in a big try-catch, just in case OS-specific stuff goes wonky.
try {
// Find out which icon to use.
final Launcher.PROCESS_TYPE processType = Launcher.getProcessType();
final String iconFileName;
switch (processType) {
case WORKER:
iconFileName = ICON_WORKER;
break;
default:
iconFileName = ICON_WRAPPER;
break;
}
// Get the file name of the icon.
final String fullFileName = Utils.getResourceDirectory() + "/" + ICONS_FOLDER + "/" + iconFileName;
final Image image = new ImageIcon(fullFileName).getImage();
// OSX-specific code to set the dock icon.
if (isOSX()) {
final com.apple.eawt.Application application = com.apple.eawt.Application.getApplication();
application.setDockIconImage(image);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException {
Utils.doFirstRunStuff();
TNoodleLogging.initializeLogging();
setApplicationIcon();
Launcher.wrapMain(args, MIN_HEAP_SIZE_MEGS);
setApplicationIcon();
OptionParser parser = new OptionParser();
OptionSpec<Integer> httpPortOpt = parser.
acceptsAll(Arrays.asList("p", "http"), "The port to run the http server on").
withRequiredArg().
ofType(Integer.class).
defaultsTo(8080);
OptionSpec<?> noBrowserOpt = parser.acceptsAll(Arrays.asList("n", "nobrowser"), "Don't open the browser when starting the server");
OptionSpec<?> noUpgradeOpt = parser.acceptsAll(Arrays.asList("u", "noupgrade"), "If an instance of " + NAME + " is running on the desired port(s), do not attempt to kill it and start up");
OptionSpec<File> injectJsOpt = parser.acceptsAll(Arrays.asList("i", "inject"), "File containing code to inject into the bottom of the <head>...</head> section of all html served").withRequiredArg().ofType(File.class);
OptionSpec<?> help = parser.acceptsAll(Arrays.asList("h", "help", "?"), "Show this help");
String levels = Utils.join(TNoodleLogging.getLevels(), ",");
OptionSpec<String> consoleLogLevel = parser.
acceptsAll(Arrays.asList("cl", "consoleLevel"), "The minimum level a log must be to be printed to the console. Options: " + levels).
withRequiredArg().
ofType(String.class).
defaultsTo(Level.WARNING.getName());
OptionSpec<String> fileLogLevel = parser.
acceptsAll(Arrays.asList("fl", "fileLevel"), "The minimum level a log must be to be printed to " + TNoodleLogging.getLogFile() + ". Options: " + levels).
withRequiredArg().
ofType(String.class).
defaultsTo(Level.INFO.getName());
try {
OptionSet options = parser.parse(args);
if(!options.has(help)) {
boolean bindAggressively = !options.has(noUpgradeOpt);
Level cl = Level.parse(options.valueOf(consoleLogLevel));
TNoodleLogging.setConsoleLogLevel(cl);
Level fl = Level.parse(options.valueOf(fileLogLevel));
TNoodleLogging.setFileLogLevel(fl);
if(options.has(injectJsOpt)) {
File injectCodeFile = options.valueOf(injectJsOpt);
if(!injectCodeFile.exists() || !injectCodeFile.canRead()) {
System.err.println("Cannot find or read " + injectCodeFile);
System.exit(1);
}
DataInputStream in = new DataInputStream(new FileInputStream(injectCodeFile));
byte[] b = new byte[(int) injectCodeFile.length()];
in.readFully(b);
in.close();
HtmlInjectFilter.setHeadInjectCode(new String(b));
}
int httpPort = options.valueOf(httpPortOpt);
boolean openBrowser = !options.has(noBrowserOpt);
new TNoodleServer(httpPort, bindAggressively, openBrowser);
return;
}
} catch(Exception e) {
e.printStackTrace();
}
parser.printHelpOn(System.out);
System.exit(1); // non zero exit status
}
}
| false | false | null | null |
diff --git a/src/main/java/org/dancres/paxos/impl/faildet/HeartbeaterImpl.java b/src/main/java/org/dancres/paxos/impl/faildet/HeartbeaterImpl.java
index 7a83a11..df7d67b 100644
--- a/src/main/java/org/dancres/paxos/impl/faildet/HeartbeaterImpl.java
+++ b/src/main/java/org/dancres/paxos/impl/faildet/HeartbeaterImpl.java
@@ -1,49 +1,54 @@
package org.dancres.paxos.impl.faildet;
import org.dancres.paxos.impl.Heartbeater;
import org.dancres.paxos.impl.Transport;
/**
* Broadcasts <code>Heartbeat</code> messages at an appropriate rate for <code>FailureDetectorImpl</code>'s in
* other nodes. Heartbeats optionally carry metadata which an application could use e.g. to find the contact details
* for the server that is the new leader after a paxos view change as indicated by receiving
* <code>Event.Reason.OTHER_LEADER</code>.
*
* @author dan
*/
class HeartbeaterImpl extends Thread implements Heartbeater {
private final Transport _transport;
private final byte[] _metaData;
private final long _pulseRate;
private boolean _stopping = false;
HeartbeaterImpl(Transport aTransport, byte[] metaData, long aPulseRate) {
_transport = aTransport;
_metaData = metaData;
_pulseRate = aPulseRate;
}
public void halt() {
synchronized(this) {
_stopping = true;
}
}
private boolean isStopping() {
synchronized(this) {
return _stopping;
}
}
public void run() {
while (! isStopping()) {
- _transport.send(_transport.getPickler().newPacket(new Heartbeat(_metaData)),
+
+ try {
+ _transport.send(_transport.getPickler().newPacket(new Heartbeat(_metaData)),
_transport.getBroadcastAddress());
+ } catch (Throwable aT) {
+ // Doesn't matter
+ }
try {
Thread.sleep(_pulseRate);
} catch (InterruptedException e) {}
}
}
}
| false | false | null | null |
diff --git a/src/GUI.java b/src/GUI.java
index b9650f3..8297cfa 100644
--- a/src/GUI.java
+++ b/src/GUI.java
@@ -1,815 +1,815 @@
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import javax.imageio.ImageIO;
import javax.swing.ButtonGroup;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButtonMenuItem;
public class GUI {
public JFrame frame;
private final int FRAME_WIDTH = 1280;
private final int FRAME_HEIGHT = 900;
private final int BUT_HEIGHT = 100;
private final int BUT_WIDTH = 100;
public JPanel panel;
public JPanel gemPileStuff;
public JPanel playerStuff;
public Game game;
public Color trans = new Color(255, 255, 255, 0);
private int quickBuyVal;
private int quickBuyNum;
public boolean buyPhase = false;
public boolean chooseCharPhase = false;
public int playerNum;
public int selectedChar = 0;
public String lang = "English";
public JPanel charChoices = new JPanel();
public ArrayList<Integer> charsSoFar = new ArrayList<Integer>();
public GUI() {
this.game = new Game(1);
this.game.setLocale("English");
this.frame = new JFrame(this.game.names.getString("Title"));
this.frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
this.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.frame.setResizable(false);
this.frame.setVisible(true);
this.frame.setResizable(false);
this.panel = new JBackgroundPanel();
this.frame.setContentPane(this.panel);
updateFrame();
// StartGUI();
titleScreen();
}
public GUI(int i, ArrayList<Integer> chtrs) {
this.playerNum = i;
this.charsSoFar = chtrs;
this.game = new Game(1);
this.frame = new JFrame(this.game.names.getString("Title"));
this.frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
this.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.frame.setResizable(false);
this.frame.setVisible(true);
this.frame.setResizable(false);
this.panel = new JBackgroundPanel();
this.frame.setContentPane(this.panel);
updateFrame();
this.startGameWithPlaysAndChars();
}
public void StartGUI() {
Icon icon = new ImageIcon();
Object[] options = { 2, 3, 4 };
Integer n = JOptionPane
.showOptionDialog(
this.frame,
"How many players will be playing?\nCombien de joueurs vont jouer?",
"New Game", JOptionPane.OK_OPTION,
JOptionPane.QUESTION_MESSAGE, icon, options, options[0]);
Object[] options2 = { "English", "French" };
this.lang = (String) JOptionPane.showInputDialog(this.frame,
"Choose Default Language\nChoisir la Langue par D�faut",
"Language", JOptionPane.OK_OPTION, icon, options2, options2[0]);
this.game.setLocale(this.lang);
this.frame.setTitle(this.game.names.getString("Title"));
this.playerNum = n + 2;
setUpCharChoicePanel();
chooseCharsScreen();
}
private void setUpCharChoicePanel() {
class ChangeCharListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
changeSelectedChar((JButton) e.getSource());
}
}
this.charChoices = new JPanel();
this.charChoices.setPreferredSize(new Dimension(FRAME_WIDTH, 200));
this.charChoices.setBackground(this.trans);
for (int i = 0; i < this.game.Characters.length; i++) {
JButton character = new JBackgroundButton();
character.setName("" + i);
character.add(new JLabel((String) this.game.Characters[i]));
character.setPreferredSize(new Dimension(BUT_WIDTH, BUT_HEIGHT));
character.addActionListener(new ChangeCharListener());
this.charChoices.add(character);
}
}
public void titleScreen() {
JPanel titleStuff = new JPanel();
titleStuff.setBackground(this.trans);
titleStuff.setPreferredSize(new Dimension(FRAME_WIDTH,
FRAME_HEIGHT));
JLabel picLabel = new JLabel(new ImageIcon("titlescreen.png"));
picLabel.setBackground(this.trans);
titleStuff.add(picLabel);
JButton startGameUp = new JButton("Start Game");
class StartListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
StartGUI();
}
}
startGameUp.addActionListener(new StartListener());
titleStuff.add(startGameUp);
if (this.panel.getComponentCount() != 0) {
this.panel.removeAll();
}
titleStuff.setName("Title");
this.panel.add(titleStuff);
updateFrame();
}
public void chooseCharsScreen() {
this.chooseCharPhase = true;
addMenuBar();
JPanel chardsStuff = new JPanel();
chardsStuff.setBackground(this.trans);
chardsStuff.setPreferredSize(new Dimension(FRAME_WIDTH,
FRAME_HEIGHT / 3));
JPanel hand = new JPanel();
hand.setPreferredSize(new Dimension(FRAME_WIDTH, 500));
hand.setBackground(this.trans);
for (int i = 0; i < 3; i++) {
Card card = this.game.getPlayerCards(this.selectedChar).get(i);
JLabel picLabel = new JLabel(new ImageIcon(
this.game.names.getString("Path") + card.imagePath));
picLabel.setBackground(this.trans);
hand.add(picLabel);
}
JButton selectBut = new JButton(this.game.names.getString("Select"));
class SelectListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
selectChar((JButton) e.getSource());
}
}
selectBut.addActionListener(new SelectListener());
JPanel screen = new JPanel();
screen.setBackground(this.trans);
screen.add(hand);
JPanel mostPhases = new JPanel();
mostPhases.setBackground(this.trans);
mostPhases.setPreferredSize(new Dimension(FRAME_WIDTH, FRAME_HEIGHT));
mostPhases.add(screen);
mostPhases.add(selectBut);
mostPhases.add(this.charChoices);
if (this.panel.getComponentCount() != 0) {
this.panel.removeAll();
}
mostPhases.setName("Choosing");
this.panel.add(mostPhases);
updateFrame();
}
public void startGameWithPlaysAndChars() {
this.game = new Game(this.playerNum);
this.game.setLocale(this.lang);
chooseCharacters(this.playerNum, this.charsSoFar);
firstSetUp();
newTurn();
}
public void changeGameLanguage(String lang) {
this.game.setLocale(lang);
JOptionPane.setDefaultLocale(this.game.currentLocale);
this.frame.setTitle(this.game.names.getString("Title"));
if (this.chooseCharPhase) {
this.chooseCharsScreen();
return;
}
if (buyPhase) {
newTurn();
setUp();
} else {
setUp();
newTurn();
}
if (this.game.getNumber > 0) {
quickBuy(this.game.underVal, this.game.getNumber);
updateFrame();
}
}
private void changeSelectedChar(JButton chars) {
this.selectedChar = Integer.parseInt(chars.getName());
chooseCharsScreen();
}
public class JBackgroundPanel extends JPanel {
private BufferedImage img;
public JBackgroundPanel() {
// load the background image
try {
img = ImageIO.read(new File("./backgroundpanels.png"));
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
// paint the background image and scale it to fill the entire space
g.drawImage(img, 0, 0, getWidth(), getHeight(), this);
}
}
public class JBackgroundButton extends JButton {
private BufferedImage img;
public JBackgroundButton() {
// load the background image
try {
img = ImageIO.read(new File("./cardbg.png"));
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
// paint the background image and scale it to fill the entire space
g.drawImage(img, 0, 0, getWidth(), getHeight(), this);
}
}
public void firstSetUp() {
JPanel shopPhase = new JPanel();
shopPhase.setName("Shopping");
JPanel shopCards = new JPanel();
class CardShopListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
cardShopInfo((JButton) e.getSource());
}
}
shopPhase.setBackground(this.trans);
shopPhase.setPreferredSize(new Dimension(FRAME_WIDTH, FRAME_HEIGHT));
shopCards.setBackground(this.trans);
shopCards.setPreferredSize(new Dimension(FRAME_WIDTH,
14 * FRAME_HEIGHT / 16));
for (int i = 0; i < this.game.bank.size(); i++) {
JButton card = new JBackgroundButton();
card.setName("" + i);
card.add(new JLabel(this.game.bank.get(i).getName(this.game)));
card.setPreferredSize(new Dimension(BUT_WIDTH, BUT_HEIGHT));
card.addActionListener(new CardShopListener());
shopCards.add(card);
}
class EndShopListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
endShopPhase();
}
}
JButton endPhase = new JButton(this.game.names.getString("EndPhase"));
endPhase.addActionListener(new EndShopListener());
shopPhase.add(shopCards);
shopPhase.add(endPhase);
if (this.panel.getComponentCount() != 0) {
this.panel.removeAll();
}
this.panel.add(shopPhase);
}
public void setUp() {
firstSetUp();
updateFrame();
}
public void newTurn() {
addMenuBar();
class CardListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
cardInfo((JButton) e.getSource());
}
}
this.playerStuff = new JPanel();
this.playerStuff.setBackground(this.trans);
this.playerStuff.setPreferredSize(new Dimension(FRAME_WIDTH,
FRAME_HEIGHT / 3));
JPanel hand = new JPanel();
hand.setBackground(this.trans);
hand.setPreferredSize(new Dimension(FRAME_WIDTH, 2 * FRAME_HEIGHT / 8));
for (int i = 0; i < this.game.players.get(this.game.turn).hand.size(); i++) {
JButton card = new JBackgroundButton();
card.add(new JLabel(this.game.getCurrentPlayer().hand.get(i)
.getName(this.game)));
card.setName("" + i);
card.addActionListener(new CardListener());
card.setPreferredSize(new Dimension(BUT_WIDTH, BUT_HEIGHT));
hand.add(card);
}
JButton endPhase = new JButton(this.game.names.getString("EndPhase"));
class EndListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
newShopPhase();
}
}
endPhase.addActionListener(new EndListener());
this.playerStuff.add(hand);
this.playerStuff.add(endPhase);
this.gemPileStuff = new JPanel();
for (int i = 0; i < this.game.playerNum; i++) {
JLabel name = new JLabel(this.game.names.getString("Player") + " "
+ (i + 1));
JPanel gemPileMargins = new JPanel();
JPanel gemPile = new JPanel();
gemPileMargins.setPreferredSize(new Dimension(FRAME_WIDTH
/ (this.game.playerNum + 1), 400));
gemPileMargins.setBackground(this.trans);
gemPile.setPreferredSize(new Dimension(100, 400));
gemPile.setBackground(this.trans);
addGemPile(i, gemPile);
gemPileMargins.add(gemPile);
if (this.game.turn == i) {
name.setForeground(Color.YELLOW);
} else {
name.setForeground(Color.WHITE);
}
JPanel player = new JPanel();
player.setPreferredSize(new Dimension(FRAME_WIDTH
/ (this.game.playerNum + 1), FRAME_HEIGHT / 2));
player.setBackground(this.trans);
player.add(name);
player.add(gemPileMargins);
this.gemPileStuff.add(player);
}
this.gemPileStuff.setBackground(this.trans);
this.gemPileStuff.setPreferredSize(new Dimension(FRAME_WIDTH,
3 * FRAME_HEIGHT / 5));
JPanel mostPhases = new JPanel();
mostPhases.setBackground(this.trans);
mostPhases.setPreferredSize(new Dimension(FRAME_WIDTH, FRAME_HEIGHT));
mostPhases.add(this.gemPileStuff);
mostPhases.add(this.playerStuff);
if (this.panel.getComponentCount() != 0) {
this.panel.removeAll();
}
mostPhases.setName("Playing");
this.panel.add(mostPhases);
updateFrame();
}
public void endQuickBuy() {
this.game.clearMiniBuy();
newTurn();
}
public void selectChar(JButton source) {
JButton selected = findSelectedChar();
this.charChoices.remove(selected);
this.charsSoFar.add(Integer.parseInt(selected.getName()));
if (this.charsSoFar.size() == this.playerNum) {
this.chooseCharPhase = false;
startGameWithPlaysAndChars();
} else {
JButton charsThing = (JButton) this.charChoices.getComponent(0);
this.selectedChar = Integer.parseInt(charsThing.getName());
chooseCharsScreen();
}
}
public JButton findSelectedChar(){
Component[] things = this.charChoices.getComponents();
for (int i = 0; i < things.length; i++){
if (Integer.parseInt(things[i].getName()) == this.selectedChar){
return (JButton) things[i];
}
}
return null;
}
public void endShopPhase() {
if (this.game.boughtSomething) {
this.buyPhase = false;
this.game.getCurrentPlayer().endTurn();
this.game.newTurn();
newTurn();
}
}
public void newShopPhase() {
this.buyPhase = true;
this.game.totalMoney();
if (this.panel.getComponentCount() != 0) {
this.panel.removeAll();
}
setUp();
}
private void useCard(Card clicked) {
ChoiceGroup choices = clicked.getChoice(this.game);
Icon icon = new ImageIcon();
Choice current = choices.getNextChoice();
boolean completeSoFar = cycleChoices(choices, current, clicked,
this.game.turn);
if (completeSoFar && clicked.opposing) {
// if targets opponent(s)
boolean reacted = reactToPlay(clicked, choices);
// Nobody reacted to card
if (!reacted) {
clicked.use(choices.getChoiceList(), this.game);
}
// No target
} else if (completeSoFar) {
clicked.use(choices.getChoiceList(), this.game);
- }
-
- if (this.game.getNumber > 0) {
- this.game.useCard(clicked);
- quickBuy(this.game.underVal, this.game.getNumber);
- } else {
- this.game.useCard(clicked);
- newTurn();
+
+ if (this.game.getNumber > 0) {
+ this.game.useCard(clicked);
+ quickBuy(this.game.underVal, this.game.getNumber);
+ } else {
+ this.game.useCard(clicked);
+ newTurn();
+ }
}
}
private void updateFrame() {
this.frame.validate();
this.frame.setVisible(true);
this.frame.repaint();
}
private void quickBuy(int val, int num) {
this.panel = new JBackgroundPanel();
this.frame.setContentPane(this.panel);
updateFrame();
this.quickBuyVal = val;
this.quickBuyNum = num;
JPanel quickBuy = new JPanel();
JPanel quickCards = new JPanel();
if (num > 0) {
class CardShopListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
cardGetInfo((JButton) e.getSource());
}
}
quickBuy.setBackground(this.trans);
quickBuy.setPreferredSize(new Dimension(FRAME_WIDTH, FRAME_HEIGHT));
quickCards.setBackground(this.trans);
quickCards.setPreferredSize(new Dimension(FRAME_WIDTH,
14 * FRAME_HEIGHT / 16));
for (int i = 0; i < this.game.bank.size(); i++) {
if (this.game.bank.get(i).cost <= val) {
JButton card = new JBackgroundButton();
card.setName("" + i);
card.add(new JLabel(this.game.bank.get(i)
.getName(this.game)));
card.setPreferredSize(new Dimension(BUT_WIDTH, BUT_HEIGHT));
card.addActionListener(new CardShopListener());
quickCards.add(card);
}
}
class EndShopListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
endQuickBuy();
}
}
JButton endPhase = new JButton(
this.game.names.getString("EndPhase"));
endPhase.addActionListener(new EndShopListener());
quickBuy.add(quickCards);
quickBuy.add(endPhase);
if (this.panel.getComponentCount() != 0) {
this.panel.removeAll();
}
this.panel.add(quickBuy);
updateFrame();
} else {
this.game.clearMiniBuy();
newTurn();
}
}
public void cardInfo(JButton card) {
String numString = card.getName();
int num = Integer.parseInt(numString);
Card clicked = this.game.getCurrentPlayer().hand.get(num);
Object[] options = { this.game.names.getString("Use") };
int decision = cardMakeInfo(
this.game.getCurrentPlayer().canUseCard(clicked), "", clicked,
options);
if (decision == 0) {
newTurn();
useCard(clicked);
}
updateFrame();
}
public int cardMakeInfo(Boolean condition, String description, Card card,
Object[] options) {
Card clicked = card;
Icon icon = new ImageIcon();
if (clicked.imagePath != null) {
icon = new ImageIcon(this.game.names.getString("Path")
+ clicked.imagePath);
}
if (condition) {
Integer n = JOptionPane.showOptionDialog(this.frame, description,
clicked.getName(this.game), JOptionPane.OK_OPTION,
JOptionPane.QUESTION_MESSAGE, icon, options, options[0]);
if (n == 0) {
updateFrame();
return n;
} else {
updateFrame();
return -1;
}
} else {
Object[] noOptions = {};
JOptionPane.showOptionDialog(this.frame, description,
clicked.getName(this.game), JOptionPane.DEFAULT_OPTION,
JOptionPane.INFORMATION_MESSAGE, icon, noOptions, null);
updateFrame();
return -1;
}
}
public void cardShopInfo(JButton card) {
String numString = card.getName();
int num = Integer.parseInt(numString);
Card clicked = this.game.bank.get(num);
Object[] options = { this.game.names.getString("Buy") };
int decision = cardMakeInfo(this.game.canBuy(clicked),
this.game.names.getString("Amount") + " " + clicked.amount,
clicked, options);
if (decision == 0) {
this.game.playerBuyCard(this.game.getCurrentPlayer(), clicked);
}
updateFrame();
}
public void cardGetInfo(JButton card) {
String numString = card.getName();
int num = Integer.parseInt(numString);
Card clicked = this.game.bank.get(num);
Object[] options = { this.game.names.getString("Get") };
int decision = cardMakeInfo(true, this.game.names.getString("Amount")
+ " " + clicked.amount, clicked, options);
if (decision == 0) {
this.game.playerGetCard(this.game.getCurrentPlayer(), clicked);
quickBuy(this.quickBuyVal, this.quickBuyNum - 1);
}
updateFrame();
}
public boolean cardReactInfo(Card card) {
Card clicked = card;
Object[] options = { this.game.names.getString("React"),
this.game.names.getString("Dont") };
int decision = cardMakeInfo(true, "", clicked, options);
if (decision == 0) {
return true;
} else {
return false;
}
}
public void addGemPile(int i, JPanel pane) {
for (int j = 0; j < 4; j++) {
JLabel gem = new JLabel("" + (j + 1) + " "
+ this.game.names.getString("Gems") + ": "
+ this.game.players.get(i).gemPile[j]);
pane.add(gem);
}
JLabel totalVal = new JLabel(this.game.names.getString("Total") + ": "
+ this.game.players.get(i).totalGemValue());
pane.add(totalVal);
}
public boolean cycleChoices(ChoiceGroup choices, Choice current,
Card clicked, int player) {
Icon icon = new ImageIcon();
while (current != null) {
while (current.nextChoice()) {
Object[] options = current.getOptions().toArray();
String n = (String) JOptionPane.showInputDialog(
this.frame,
current.getInstructions(),
this.game.names.getString("Player") + " "
+ (player + 1) + ": "
+ clicked.getName(this.game),
JOptionPane.OK_OPTION, icon, options, options[0]);
if (n != null) {
current.addChoice(n);
} else {
return false;
}
current = choices.getNextChoice();
if (current == null) {
return true;
}
}
current = choices.getNextChoice();
}
return true;
}
public void makeLangOptions(String[] langs, String[] counts, String[] keys,
JMenu menu) {
ButtonGroup group = new ButtonGroup();
class ChangeLanguage implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
changeGameLanguage(((JRadioButtonMenuItem) e.getSource())
.getName());
}
}
for (int i = 0; i < langs.length; i++) {
JRadioButtonMenuItem rbMenuItem = new JRadioButtonMenuItem(
this.game.names.getString(langs[i]));
if (this.game.currentLocale.getCountry().equals(counts[i])) {
rbMenuItem.setSelected(true);
}
rbMenuItem.setName(keys[i]);
rbMenuItem.addActionListener(new ChangeLanguage());
group.add(rbMenuItem);
menu.add(rbMenuItem);
}
}
public ArrayList<ArrayList<Card>> getDefensiveCards(
ArrayList<Player> targets, Card clicked) {
ArrayList<ArrayList<Card>> playersReacts = new ArrayList<ArrayList<Card>>();
// cycles through targets
for (int i = 0; i < targets.size(); i++) {
ArrayList<Card> defends = new ArrayList<Card>();
ArrayList<Card> hand = targets.get(i).hand;
// cycles through hand
for (int j = 0; j < hand.size(); j++) {
Card card = hand.get(j);
// only runs if card is defensive
if (card.defense) {
if (((ReactionCard) card).canReactTo(clicked)) {
defends.add(card);
}
}
}
playersReacts.add(defends);
}
return playersReacts;
}
public boolean reactToPlay(Card clicked, ChoiceGroup choices) {
clicked.prepare(choices.getChoiceList(), this.game);
ArrayList<Player> targets = clicked.targets;
ArrayList<ArrayList<Card>> defends = getDefensiveCards(targets, clicked);
// cycles through targets
for (int i = 0; i < targets.size(); i++) {
ArrayList<Card> playersDefs = defends.get(i);
// cycles through hand
for (int j = 0; j < playersDefs.size(); j++) {
Card card = playersDefs.get(j);
// only runs if card is defensive
ReactionCard react = (ReactionCard) card;
boolean wantReact = cardReactInfo(card);
if (wantReact) {
ChoiceGroup reactChoices = react.getReactChoices(this.game);
Choice currents = reactChoices.getNextChoice();
boolean completeSoFarReact = cycleChoices(reactChoices,
currents, react,
this.game.players.indexOf(targets.get(i)));
// Uses card if you filled things out
if (completeSoFarReact) {
react.react(clicked, targets.get(i),
reactChoices.getChoiceList(), this.game);
return true;
}
}
}
}
return false;
}
public void chooseCharacters(int num, ArrayList<Integer> chtrs) {
for (int i = 0; i < num; i++) {
int m = chtrs.get(i);
this.game.setCharacter(i, m);
}
}
public void addMenuBar() {
// Create the menu bar.
JMenuBar menuBar = new JMenuBar();
// Build the first menu.
JMenu menu = new JMenu(this.game.names.getString("LangOption"));
menu.getAccessibleContext().setAccessibleDescription(
"The only menu in this program that has menu items");
menuBar.add(menu);
String[] langs = { "English", "French" };
String[] country = { "US", "FR" };
String[] keys = { "english", "french" };
makeLangOptions(langs, country, keys, menu);
frame.setJMenuBar(menuBar);
}
}
| true | false | null | null |
diff --git a/java/src/org/broadinstitute/sting/utils/sam/GATKSAMRecord.java b/java/src/org/broadinstitute/sting/utils/sam/GATKSAMRecord.java
index c4536d176..f3d9edab9 100755
--- a/java/src/org/broadinstitute/sting/utils/sam/GATKSAMRecord.java
+++ b/java/src/org/broadinstitute/sting/utils/sam/GATKSAMRecord.java
@@ -1,457 +1,457 @@
package org.broadinstitute.sting.utils.sam;
import java.lang.reflect.Method;
import java.util.*;
import net.sf.samtools.*;
import org.broadinstitute.sting.utils.exceptions.ReviewedStingException;
import org.broadinstitute.sting.utils.exceptions.UserException;
/**
* @author ebanks
* GATKSAMRecord
*
* this class extends the samtools SAMRecord class and caches important
* (and oft-accessed) data that's not already cached by the SAMRecord class
*
* IMPORTANT NOTE: Because ReadGroups are not set through the SAMRecord,
* if they are ever modified externally then one must also invoke the
* setReadGroup() method here to ensure that the cache is kept up-to-date.
*
* 13 Oct 2010 - mhanna - this class is fundamentally flawed: it uses a decorator
* pattern to wrap a heavyweight object, which can lead
* to heinous side effects if the wrapping is not carefully
* done. Hopefully SAMRecord will become an interface and
* this will eventually be fixed.
*/
public class GATKSAMRecord extends SAMRecord {
// the underlying SAMRecord which we are wrapping
private final SAMRecord mRecord;
// the SAMRecord data we're caching
private String mReadString = null;
private SAMReadGroupRecord mReadGroup = null;
private boolean mNegativeStrandFlag;
private boolean mUnmappedFlag;
private Boolean mSecondOfPairFlag = null;
// because some values can be null, we don't want to duplicate effort
private boolean retrievedReadGroup = false;
// These temporary attributes were added here to make life easier for
// certain algorithms by providing a way to label or attach arbitrary data to
// individual GATKSAMRecords.
// These attributes exist in memory only, and are never written to disk.
private Map<Object, Object> temporaryAttributes;
public GATKSAMRecord(SAMRecord record, boolean useOriginalBaseQualities, byte defaultBaseQualities) {
super(null); // it doesn't matter - this isn't used
if ( record == null )
throw new IllegalArgumentException("The SAMRecord argument cannot be null");
mRecord = record;
mNegativeStrandFlag = mRecord.getReadNegativeStrandFlag();
mUnmappedFlag = mRecord.getReadUnmappedFlag();
// because attribute methods are declared to be final (and we can't overload them),
// we need to actually set all of the attributes here
List<SAMTagAndValue> attributes = record.getAttributes();
for ( SAMTagAndValue attribute : attributes )
setAttribute(attribute.tag, attribute.value);
// if we are using default quals, check if we need them, and add if necessary.
// 1. we need if reads are lacking or have incomplete quality scores
// 2. we add if defaultBaseQualities has a positive value
if (defaultBaseQualities >= 0) {
byte reads [] = record.getReadBases();
byte quals [] = record.getBaseQualities();
if (quals == null || quals.length < reads.length) {
byte new_quals [] = new byte [reads.length];
for (int i=0; i<reads.length; i++)
new_quals[i] = defaultBaseQualities;
record.setBaseQualities(new_quals);
}
}
// if we are using original quals, set them now if they are present in the record
if ( useOriginalBaseQualities ) {
byte[] originalQuals = mRecord.getOriginalBaseQualities();
if ( originalQuals != null )
mRecord.setBaseQualities(originalQuals);
}
// sanity check that the lengths of the base and quality strings are equal
if ( getBaseQualities().length != getReadLength() )
- throw new UserException.MalformedBAM(this, String.format("Error: the number of base qualities does not match the number of bases in %s. Use -DBQ x to set a default base quality score to all reads so GATK can proceed.", mRecord.getReadName()));
+ throw new UserException.MalformedBAM(this, String.format("Error: the number of base qualities does not match the number of bases in %s.", mRecord.getReadName()));
}
///////////////////////////////////////////////////////////////////////////////
// *** The following methods are overloaded to cache the appropriate data ***//
///////////////////////////////////////////////////////////////////////////////
public String getReadString() {
if ( mReadString == null )
mReadString = mRecord.getReadString();
return mReadString;
}
public void setReadString(String s) {
mRecord.setReadString(s);
mReadString = s;
}
public SAMReadGroupRecord getReadGroup() {
if ( !retrievedReadGroup ) {
SAMReadGroupRecord tempReadGroup = mRecord.getReadGroup();
mReadGroup = (tempReadGroup == null ? tempReadGroup : new GATKSAMReadGroupRecord(tempReadGroup));
retrievedReadGroup = true;
}
return mReadGroup;
}
public void setReadGroup(SAMReadGroupRecord record) {
mReadGroup = record;
}
public boolean getReadUnmappedFlag() {
return mUnmappedFlag;
}
public void setReadUnmappedFlag(boolean b) {
mRecord.setReadUnmappedFlag(b);
mUnmappedFlag = b;
}
public boolean getReadNegativeStrandFlag() {
return mNegativeStrandFlag;
}
public void setReadNegativeStrandFlag(boolean b) {
mRecord.setReadNegativeStrandFlag(b);
mNegativeStrandFlag = b;
}
public boolean getSecondOfPairFlag() {
if( mSecondOfPairFlag == null ) {
//not done in constructor because this method can't be called for
//all SAMRecords.
mSecondOfPairFlag = mRecord.getSecondOfPairFlag();
}
return mSecondOfPairFlag;
}
public void setSecondOfPairFlag(boolean b) {
mRecord.setSecondOfPairFlag(b);
mSecondOfPairFlag = b;
}
/**
* Checks whether an attribute has been set for the given key.
*
* Temporary attributes provide a way to label or attach arbitrary data to
* individual GATKSAMRecords. These attributes exist in memory only,
* and are never written to disk.
*
* @param key key
* @return True if an attribute has been set for this key.
*/
public boolean containsTemporaryAttribute(Object key) {
if(temporaryAttributes != null) {
return temporaryAttributes.containsKey(key);
}
return false;
}
/**
* Sets the key to the given value, replacing any previous value. The previous
* value is returned.
*
* Temporary attributes provide a way to label or attach arbitrary data to
* individual GATKSAMRecords. These attributes exist in memory only,
* and are never written to disk.
*
* @param key key
* @param value value
* @return attribute
*/
public Object setTemporaryAttribute(Object key, Object value) {
if(temporaryAttributes == null) {
temporaryAttributes = new HashMap<Object, Object>();
}
return temporaryAttributes.put(key, value);
}
/**
* Looks up the value associated with the given key.
*
* Temporary attributes provide a way to label or attach arbitrary data to
* individual GATKSAMRecords. These attributes exist in memory only,
* and are never written to disk.
*
* @param key key
* @return The value, or null.
*/
public Object getTemporaryAttribute(Object key) {
if(temporaryAttributes != null) {
return temporaryAttributes.get(key);
}
return null;
}
/**
* Removes the attribute that has the given key.
*
* Temporary attributes provide a way to label or attach arbitrary data to
* individual GATKSAMRecords. These attributes exist in memory only,
* and are never written to disk.
*
* @param key key
* @return The value that was associated with this key, or null.
*/
public Object removeTemporaryAttribute(Object key) {
if(temporaryAttributes != null) {
return temporaryAttributes.remove(key);
}
return null;
}
/////////////////////////////////////////////////////////////////////////////////
// *** The following methods just call the appropriate method in the record ***//
/////////////////////////////////////////////////////////////////////////////////
public String getReadName() { return mRecord.getReadName(); }
public int getReadNameLength() { return mRecord.getReadNameLength(); }
public void setReadName(String s) { mRecord.setReadName(s); }
public byte[] getReadBases() { return mRecord.getReadBases(); }
public void setReadBases(byte[] bytes) { mRecord.setReadBases(bytes); }
public int getReadLength() { return mRecord.getReadLength(); }
public byte[] getBaseQualities() { return mRecord.getBaseQualities(); }
public void setBaseQualities(byte[] bytes) { mRecord.setBaseQualities(bytes); }
public String getBaseQualityString() { return mRecord.getBaseQualityString(); }
public void setBaseQualityString(String s) { mRecord.setBaseQualityString(s); }
public byte[] getOriginalBaseQualities() { return mRecord.getOriginalBaseQualities(); }
public void setOriginalBaseQualities(byte[] bytes) { mRecord.setOriginalBaseQualities(bytes); }
public String getReferenceName() { return mRecord.getReferenceName(); }
public void setReferenceName(String s) { mRecord.setReferenceName(s); }
public Integer getReferenceIndex() { return mRecord.getReferenceIndex(); }
public void setReferenceIndex(int i) { mRecord.setReferenceIndex(i); }
public String getMateReferenceName() { return mRecord.getMateReferenceName(); }
public void setMateReferenceName(String s) { mRecord.setMateReferenceName(s); }
public Integer getMateReferenceIndex() { return mRecord.getMateReferenceIndex(); }
public void setMateReferenceIndex(int i) { mRecord.setMateReferenceIndex(i); }
public int getAlignmentStart() { return mRecord.getAlignmentStart(); }
public void setAlignmentStart(int i) { mRecord.setAlignmentStart(i); }
public int getAlignmentEnd() { return mRecord.getAlignmentEnd(); }
public int getUnclippedStart() { return mRecord.getUnclippedStart(); }
public int getUnclippedEnd() { return mRecord.getUnclippedEnd(); }
public void setAlignmentEnd(int i) { mRecord.setAlignmentEnd(i); }
public int getMateAlignmentStart() { return mRecord.getMateAlignmentStart(); }
public void setMateAlignmentStart(int i) { mRecord.setMateAlignmentStart(i); }
public int getInferredInsertSize() { return mRecord.getInferredInsertSize(); }
public void setInferredInsertSize(int i) { mRecord.setInferredInsertSize(i); }
public int getMappingQuality() { return mRecord.getMappingQuality(); }
public void setMappingQuality(int i) { mRecord.setMappingQuality(i); }
public String getCigarString() { return mRecord.getCigarString(); }
public void setCigarString(String s) { mRecord.setCigarString(s); }
public Cigar getCigar() { return mRecord.getCigar(); }
public int getCigarLength() { return mRecord.getCigarLength(); }
public void setCigar(Cigar cigar) { mRecord.setCigar(cigar); }
public int getFlags() { return mRecord.getFlags(); }
public void setFlags(int i) { mRecord.setFlags(i); }
public boolean getReadPairedFlag() { return mRecord.getReadPairedFlag(); }
public boolean getProperPairFlag() { return mRecord.getProperPairFlag(); }
public boolean getMateUnmappedFlag() { return mRecord.getMateUnmappedFlag(); }
public boolean getMateNegativeStrandFlag() { return mRecord.getMateNegativeStrandFlag(); }
public boolean getFirstOfPairFlag() { return mRecord.getFirstOfPairFlag(); }
public boolean getNotPrimaryAlignmentFlag() { return mRecord.getNotPrimaryAlignmentFlag(); }
public boolean getReadFailsVendorQualityCheckFlag() { return mRecord.getReadFailsVendorQualityCheckFlag(); }
public boolean getDuplicateReadFlag() { return mRecord.getDuplicateReadFlag(); }
public void setReadPairedFlag(boolean b) { mRecord.setReadPairedFlag(b); }
public void setProperPairFlag(boolean b) { mRecord.setProperPairFlag(b); }
public void setMateUnmappedFlag(boolean b) { mRecord.setMateUnmappedFlag(b); }
public void setMateNegativeStrandFlag(boolean b) { mRecord.setMateNegativeStrandFlag(b); }
public void setFirstOfPairFlag(boolean b) { mRecord.setFirstOfPairFlag(b); }
public void setNotPrimaryAlignmentFlag(boolean b) { mRecord.setNotPrimaryAlignmentFlag(b); }
public void setReadFailsVendorQualityCheckFlag(boolean b) { mRecord.setReadFailsVendorQualityCheckFlag(b); }
public void setDuplicateReadFlag(boolean b) { mRecord.setDuplicateReadFlag(b); }
public net.sf.samtools.SAMFileReader.ValidationStringency getValidationStringency() { return mRecord.getValidationStringency(); }
public void setValidationStringency(net.sf.samtools.SAMFileReader.ValidationStringency validationStringency) { mRecord.setValidationStringency(validationStringency); }
public Object getAttribute(final String tag) { return mRecord.getAttribute(tag); }
public Integer getIntegerAttribute(final String tag) { return mRecord.getIntegerAttribute(tag); }
public Short getShortAttribute(final String tag) { return mRecord.getShortAttribute(tag); }
public Byte getByteAttribute(final String tag) { return mRecord.getByteAttribute(tag); }
public String getStringAttribute(final String tag) { return mRecord.getStringAttribute(tag); }
public Character getCharacterAttribute(final String tag) { return mRecord.getCharacterAttribute(tag); }
public Float getFloatAttribute(final String tag) { return mRecord.getFloatAttribute(tag); }
public byte[] getByteArrayAttribute(final String tag) { return mRecord.getByteArrayAttribute(tag); }
protected Object getAttribute(final short tag) {
Object attribute;
try {
Method method = mRecord.getClass().getDeclaredMethod("getAttribute",Short.TYPE);
method.setAccessible(true);
attribute = method.invoke(mRecord,tag);
}
catch(Exception ex) {
throw new ReviewedStingException("Unable to invoke getAttribute method",ex);
}
return attribute;
}
public void setAttribute(final String tag, final Object value) { mRecord.setAttribute(tag,value); }
protected void setAttribute(final short tag, final Object value) {
try {
Method method = mRecord.getClass().getDeclaredMethod("setAttribute",Short.TYPE,Object.class);
method.setAccessible(true);
method.invoke(mRecord,tag,value);
}
catch(Exception ex) {
throw new ReviewedStingException("Unable to invoke setAttribute method",ex);
}
}
public void clearAttributes() { mRecord.clearAttributes(); }
protected void setAttributes(final SAMBinaryTagAndValue attributes) {
try {
Method method = mRecord.getClass().getDeclaredMethod("setAttributes",SAMBinaryTagAndValue.class);
method.setAccessible(true);
method.invoke(mRecord,attributes);
}
catch(Exception ex) {
throw new ReviewedStingException("Unable to invoke setAttributes method",ex);
}
}
protected SAMBinaryTagAndValue getBinaryAttributes() {
SAMBinaryTagAndValue binaryAttributes;
try {
Method method = mRecord.getClass().getDeclaredMethod("getBinaryAttributes");
method.setAccessible(true);
binaryAttributes = (SAMBinaryTagAndValue)method.invoke(mRecord);
}
catch(Exception ex) {
throw new ReviewedStingException("Unable to invoke getBinaryAttributes method",ex);
}
return binaryAttributes;
}
public List<SAMTagAndValue> getAttributes() { return mRecord.getAttributes(); }
public SAMFileHeader getHeader() { return mRecord.getHeader(); }
public void setHeader(SAMFileHeader samFileHeader) { mRecord.setHeader(samFileHeader); }
public byte[] getVariableBinaryRepresentation() { return mRecord.getVariableBinaryRepresentation(); }
public int getAttributesBinarySize() { return mRecord.getAttributesBinarySize(); }
public String format() { return mRecord.format(); }
public List<AlignmentBlock> getAlignmentBlocks() { return mRecord.getAlignmentBlocks(); }
public List<SAMValidationError> validateCigar(long l) { return mRecord.validateCigar(l); }
@Override
public boolean equals(Object o) {
if (this == o) return true;
// note -- this forbids a GATKSAMRecord being equal to its underlying SAMRecord
if (!(o instanceof GATKSAMRecord)) return false;
// note that we do not consider the GATKSAMRecord internal state at all
return mRecord.equals(((GATKSAMRecord)o).mRecord);
}
public int hashCode() { return mRecord.hashCode(); }
public List<SAMValidationError> isValid() { return mRecord.isValid(); }
public Object clone() throws CloneNotSupportedException { return mRecord.clone(); }
public String toString() { return mRecord.toString(); }
public SAMFileSource getFileSource() { return mRecord.getFileSource(); }
/**
* Sets a marker providing the source reader for this file and the position in the file from which the read originated.
* @param fileSource source of the given file.
*/
@Override
protected void setFileSource(final SAMFileSource fileSource) {
try {
Method method = SAMRecord.class.getDeclaredMethod("setFileSource",SAMFileSource.class);
method.setAccessible(true);
method.invoke(mRecord,fileSource);
}
catch(Exception ex) {
throw new ReviewedStingException("Unable to invoke setFileSource method",ex);
}
}
}
| true | true | public GATKSAMRecord(SAMRecord record, boolean useOriginalBaseQualities, byte defaultBaseQualities) {
super(null); // it doesn't matter - this isn't used
if ( record == null )
throw new IllegalArgumentException("The SAMRecord argument cannot be null");
mRecord = record;
mNegativeStrandFlag = mRecord.getReadNegativeStrandFlag();
mUnmappedFlag = mRecord.getReadUnmappedFlag();
// because attribute methods are declared to be final (and we can't overload them),
// we need to actually set all of the attributes here
List<SAMTagAndValue> attributes = record.getAttributes();
for ( SAMTagAndValue attribute : attributes )
setAttribute(attribute.tag, attribute.value);
// if we are using default quals, check if we need them, and add if necessary.
// 1. we need if reads are lacking or have incomplete quality scores
// 2. we add if defaultBaseQualities has a positive value
if (defaultBaseQualities >= 0) {
byte reads [] = record.getReadBases();
byte quals [] = record.getBaseQualities();
if (quals == null || quals.length < reads.length) {
byte new_quals [] = new byte [reads.length];
for (int i=0; i<reads.length; i++)
new_quals[i] = defaultBaseQualities;
record.setBaseQualities(new_quals);
}
}
// if we are using original quals, set them now if they are present in the record
if ( useOriginalBaseQualities ) {
byte[] originalQuals = mRecord.getOriginalBaseQualities();
if ( originalQuals != null )
mRecord.setBaseQualities(originalQuals);
}
// sanity check that the lengths of the base and quality strings are equal
if ( getBaseQualities().length != getReadLength() )
throw new UserException.MalformedBAM(this, String.format("Error: the number of base qualities does not match the number of bases in %s. Use -DBQ x to set a default base quality score to all reads so GATK can proceed.", mRecord.getReadName()));
}
| public GATKSAMRecord(SAMRecord record, boolean useOriginalBaseQualities, byte defaultBaseQualities) {
super(null); // it doesn't matter - this isn't used
if ( record == null )
throw new IllegalArgumentException("The SAMRecord argument cannot be null");
mRecord = record;
mNegativeStrandFlag = mRecord.getReadNegativeStrandFlag();
mUnmappedFlag = mRecord.getReadUnmappedFlag();
// because attribute methods are declared to be final (and we can't overload them),
// we need to actually set all of the attributes here
List<SAMTagAndValue> attributes = record.getAttributes();
for ( SAMTagAndValue attribute : attributes )
setAttribute(attribute.tag, attribute.value);
// if we are using default quals, check if we need them, and add if necessary.
// 1. we need if reads are lacking or have incomplete quality scores
// 2. we add if defaultBaseQualities has a positive value
if (defaultBaseQualities >= 0) {
byte reads [] = record.getReadBases();
byte quals [] = record.getBaseQualities();
if (quals == null || quals.length < reads.length) {
byte new_quals [] = new byte [reads.length];
for (int i=0; i<reads.length; i++)
new_quals[i] = defaultBaseQualities;
record.setBaseQualities(new_quals);
}
}
// if we are using original quals, set them now if they are present in the record
if ( useOriginalBaseQualities ) {
byte[] originalQuals = mRecord.getOriginalBaseQualities();
if ( originalQuals != null )
mRecord.setBaseQualities(originalQuals);
}
// sanity check that the lengths of the base and quality strings are equal
if ( getBaseQualities().length != getReadLength() )
throw new UserException.MalformedBAM(this, String.format("Error: the number of base qualities does not match the number of bases in %s.", mRecord.getReadName()));
}
|
diff --git a/src/dk/illution/computer/info/LoginActivity.java b/src/dk/illution/computer/info/LoginActivity.java
index e5f1eed..18c3901 100644
--- a/src/dk/illution/computer/info/LoginActivity.java
+++ b/src/dk/illution/computer/info/LoginActivity.java
@@ -1,173 +1,174 @@
package dk.illution.computer.info;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Scanner;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.app.ActionBar;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
class SignIn extends AsyncTask<String, Void, String> {
private Activity activity;
private Context appContext;
public SignIn (Activity activity) {
appContext = activity.getApplicationContext();
this.activity = activity;
}
protected String doInBackground (String... params) {
URL url;
HttpURLConnection connection;
SharedPreferences preferences = PreferenceManager
.getDefaultSharedPreferences(appContext);
try {
String response= "";
// Set the URL
url=new URL(preferences.getString("preference_endpoint", null) + "/login/device");
// Set parameters
String param = "username=" + URLEncoder.encode(params[0], "UTF-8") + "&password=" + URLEncoder.encode(params[1], "UTF-8");
// Open connection
connection = (HttpURLConnection)url.openConnection();
connection.setDoOutput(true);
+ connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("POST");
// Set headers
connection.setFixedLengthStreamingMode(param.getBytes().length);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// Send request
PrintWriter out = new PrintWriter(connection.getOutputStream());
out.print(param);
out.close();
// Get stream
Scanner inStream = new Scanner(connection.getInputStream());
// Loop through stream and add get the response
while(inStream.hasNextLine())
response+=(inStream.nextLine());
if (connection.getResponseCode() != 200) {
return "error.statusCode." + connection.getResponseCode();
}
// Return the response
return response;
}
// Catch some errors
catch (MalformedURLException ex) {
return "error.malformedUrl";
}
catch (IOException ex) {
return "error.io";
}
catch (Exception ex) {
return "error.general";
}
}
protected void onPostExecute(String response) {
if (response != null && !response.startsWith("error")) {
if (ComputerInfo.parseUserTokenResponse(response, appContext)) {
LoginActivity.dialog.hide();
ComputerInfo.launchComputerList(activity);
} else {
LoginActivity.dialog.hide();
Toast.makeText(appContext, this.activity.getString(R.string.login_error_validation), Toast.LENGTH_LONG).show();
}
} else if (response.equals("error.io")) {
LoginActivity.dialog.hide();
Toast.makeText(appContext, this.activity.getString(R.string.login_error_connection), Toast.LENGTH_LONG).show();
} else if (response.startsWith("error.statusCode")) {
Toast.makeText(appContext, this.activity.getString(R.string.login_error_status_code) + response, Toast.LENGTH_LONG).show();
} else if (response.startsWith("error.malformedUrl")) {
Toast.makeText(appContext, this.activity.getString(R.string.login_error_malformedUrl) + response, Toast.LENGTH_LONG).show();
} else if (response.startsWith("error.general")) {
Toast.makeText(appContext, this.activity.getString(R.string.login_error_general) + response, Toast.LENGTH_LONG).show();
}
if (response.startsWith("error")) {
LoginActivity.dialog.hide();
Log.d("ComputerInfo", "An error occured in the login process: " + response);
}
}
}
public class LoginActivity extends Activity {
public static ProgressDialog dialog;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
final Button loginButton = (Button) findViewById(R.id.login_button);
final Button signUpButton = (Button) findViewById(R.id.sign_up_button);
loginButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
final TextView usernameBox = (TextView) findViewById(R.id.username_box);
final TextView passwordBox = (TextView) findViewById(R.id.password_box);
dialog = ProgressDialog.show(LoginActivity.this, "",
LoginActivity.this.getString(R.string.login_loading), true);
dialog.setCancelable(true);
new SignIn(LoginActivity.this).execute(usernameBox.getText().toString(),
passwordBox.getText().toString());
}
});
signUpButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
ComputerInfo.launchComputerList(LoginActivity.this);
}
});
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
ComputerInfo.launchLoginSelect(LoginActivity.this);
return true;
case R.id.menu_preferences:
ComputerInfo.launchPreferences(this);
return true;
case R.id.menu_about:
ComputerInfo.launchAbout(this);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_login, menu);
return true;
}
}
diff --git a/src/dk/illution/computer/info/LoginSelectActivity.java b/src/dk/illution/computer/info/LoginSelectActivity.java
index 2104001..97b4269 100644
--- a/src/dk/illution/computer/info/LoginSelectActivity.java
+++ b/src/dk/illution/computer/info/LoginSelectActivity.java
@@ -1,185 +1,186 @@
package dk.illution.computer.info;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Scanner;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.AccountManagerCallback;
import android.accounts.AccountManagerFuture;
import android.accounts.OperationCanceledException;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
class GoogleAuthTokenValidator extends AsyncTask<String, Void, String> {
private Activity activity;
private Context appContext;
public GoogleAuthTokenValidator (Activity activity) {
appContext = activity.getApplicationContext();
this.activity = activity;
}
protected String doInBackground (String... params) {
URL url;
HttpURLConnection connection;
SharedPreferences preferences = PreferenceManager
.getDefaultSharedPreferences(appContext);
try {
String response= "";
// Set the URL
url=new URL(preferences.getString("preference_endpoint", null) + "/login/device/google?access_token=" + params[0]);
// Open connection
connection=(HttpURLConnection)url.openConnection();
connection.setDoOutput(true);
+ connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("GET");
// Set headers
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// Send request
PrintWriter out = new PrintWriter(connection.getOutputStream());
out.close();
// Get stream
Scanner inStream = new Scanner(connection.getInputStream());
// Loop through stream and add get the response
while(inStream.hasNextLine())
response+=(inStream.nextLine());
// Return the response
return response;
} catch (Exception e) {
return null;
}
}
protected void onPostExecute(String response) {
if (response != null) {
if (ComputerInfo.parseUserTokenResponse(response, appContext)) {
ComputerInfo.launchComputerList(activity);
} else {
Toast.makeText(appContext, this.activity.getString(R.string.login_error_google_validation), Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(appContext, this.activity.getString(R.string.login_error_connection), Toast.LENGTH_LONG).show();
}
}
}
public class LoginSelectActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_select);
PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
final Button usernameAndPasswordButton = (Button) findViewById(R.id.username_and_password_button);
final Button googleButton = (Button) findViewById(R.id.google_button);
usernameAndPasswordButton
.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
ComputerInfo.launchLogin(LoginSelectActivity.this);
}
});
googleButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
final Activity activity = LoginSelectActivity.this;
final Context context = activity.getApplicationContext();
AccountManager am = AccountManager.get(context);
final Account[] accounts = am.getAccountsByType("com.google");
CharSequence [] accountNames = new CharSequence[accounts.length];
if (accounts.length <= 0) {
Toast.makeText(context, LoginSelectActivity.this.getString(R.string.login_error_google_no_accounts), Toast.LENGTH_LONG).show();
return;
}
for (int i = 0; i <= accounts.length - 1; i++) {
accountNames[i] = accounts[i].name;
}
//Prepare the list dialog box
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
//Set its title
builder.setTitle("Choose an account");
//Set the list items and assign with the click listener
builder.setItems(accountNames, new DialogInterface.OnClickListener() {
// Click listener
public void onClick(DialogInterface dialog, int item) {
//
AccountManager manager = AccountManager.get(activity);
manager.getAuthToken(accounts[item], "oauth2:https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email", null, activity, new AccountManagerCallback<Bundle>() {
public void run(AccountManagerFuture<Bundle> future) {
try {
// If the user has authorized your application to use the tasks API
// a token is available.
String token = future.getResult().getString(AccountManager.KEY_AUTHTOKEN);
Log.d("ComputerInfo", token);
new GoogleAuthTokenValidator (LoginSelectActivity.this).execute(token);
// Now you can use the Tasks API...
} catch (OperationCanceledException e) {
// TODO: The user has denied you access to the API, you should handle that
} catch (Exception e) {
e.printStackTrace();
}
}
}, null);
}
});
AlertDialog alert = builder.create();
//display dialog box
alert.show();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_login_select, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_preferences:
ComputerInfo.launchPreferences(this);
return true;
case R.id.menu_about:
ComputerInfo.launchAbout(this);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
| false | false | null | null |
diff --git a/plugins/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/api/querydefn/Binding.java b/plugins/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/api/querydefn/Binding.java
index cb83fa2be..f7aa697bf 100644
--- a/plugins/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/api/querydefn/Binding.java
+++ b/plugins/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/api/querydefn/Binding.java
@@ -1,172 +1,171 @@
/*******************************************************************************
* Copyright (c) 2004, 2005 Actuate Corporation.
* 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:
* Actuate Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.birt.data.engine.api.querydefn;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.birt.core.data.DataType;
import org.eclipse.birt.data.engine.api.IBaseExpression;
import org.eclipse.birt.data.engine.api.IBinding;
import org.eclipse.birt.data.engine.core.DataException;
-import org.eclipse.birt.data.engine.i18n.ResourceConstants;
/**
*
*/
public class Binding implements IBinding
{
private List aggregateOn;
private List argument;
private IBaseExpression expr;
private IBaseExpression filter;
private String aggrFunc;
private String name;
private int dataType;
public Binding( String name )
{
this ( name, null );
}
public Binding( String name, IBaseExpression expr )
{
this.name = name;
this.expr = expr;
this.aggregateOn = new ArrayList();
this.argument = new ArrayList();
if ( expr != null )
this.dataType = expr.getDataType( );
else
this.dataType = DataType.ANY_TYPE;
}
/*
* (non-Javadoc)
* @see org.eclipse.birt.data.engine.api.IBinding#addAggregateOn(java.lang.String)
*/
public void addAggregateOn( String levelName ) throws DataException
{
if ( !this.aggregateOn.contains( levelName ) )
{
this.aggregateOn.add( levelName );
}
}
/*
* (non-Javadoc)
* @see org.eclipse.birt.data.engine.api.IBinding#addArgument(org.eclipse.birt.data.engine.api.IBaseExpression)
*/
public void addArgument( IBaseExpression expr )
{
this.argument.add( expr );
}
/*
* (non-Javadoc)
* @see org.eclipse.birt.data.engine.api.IBinding#getAggrFunction()
*/
public String getAggrFunction( )
{
return aggrFunc;
}
/*
* (non-Javadoc)
* @see org.eclipse.birt.data.engine.api.IBinding#getAggregatOns()
*/
public List getAggregatOns( )
{
return this.aggregateOn;
}
/*
* (non-Javadoc)
* @see org.eclipse.birt.data.engine.api.IBinding#getArguments()
*/
public List getArguments( )
{
return this.argument;
}
/*
* (non-Javadoc)
* @see org.eclipse.birt.data.engine.api.IBinding#getDataType()
*/
public int getDataType( )
{
return this.dataType;
}
/*
* (non-Javadoc)
* @see org.eclipse.birt.data.engine.api.IBinding#getFilter()
*/
public IBaseExpression getFilter( )
{
return this.filter;
}
/*
* (non-Javadoc)
* @see org.eclipse.birt.data.engine.api.IBinding#setAggrFunction(java.lang.String)
*/
public void setAggrFunction( String functionName )
{
this.aggrFunc = functionName;
}
/*
* (non-Javadoc)
* @see org.eclipse.birt.data.engine.api.IBinding#setDataType(int)
*/
public void setDataType( int type )
{
this.dataType = type;
}
/*
* (non-Javadoc)
* @see org.eclipse.birt.data.engine.api.IBinding#setExpression(java.lang.String)
*/
public void setExpression( IBaseExpression expr )
{
this.expr = expr;
}
/*
* (non-Javadoc)
* @see org.eclipse.birt.data.engine.api.IBinding#setFilter(org.eclipse.birt.data.engine.api.IBaseExpression)
*/
public void setFilter( IBaseExpression expr )
{
this.filter = expr;
}
/*
* (non-Javadoc)
* @see org.eclipse.birt.data.engine.api.IBinding#getBindingName()
*/
public String getBindingName( )
{
return this.name;
}
public IBaseExpression getExpression( )
{
return this.expr;
}
}
\ No newline at end of file
| true | false | null | null |
diff --git a/src/edu/jas/arith/BigComplex.java b/src/edu/jas/arith/BigComplex.java
index 9f05c773..b7a87050 100644
--- a/src/edu/jas/arith/BigComplex.java
+++ b/src/edu/jas/arith/BigComplex.java
@@ -1,714 +1,713 @@
/*
* $Id$
*/
package edu.jas.arith;
import java.math.BigInteger;
import java.util.Random;
import java.io.Reader;
import java.util.List;
import java.util.ArrayList;
import org.apache.log4j.Logger;
//import edu.jas.structure.RingElem;
import edu.jas.structure.GcdRingElem;
import edu.jas.structure.StarRingElem;
import edu.jas.structure.RingFactory;
import edu.jas.util.StringUtil;
/**
* BigComplex class based on BigRational implementing the RingElem
* interface and with the familiar SAC static method names.
* Objects of this class are immutable.
* @author Heinz Kredel
*/
public final class BigComplex implements StarRingElem<BigComplex>,
GcdRingElem<BigComplex>,
RingFactory<BigComplex> {
/** Real part of the data structure.
*/
protected final BigRational re;
/** Imaginary part of the data structure.
*/
protected final BigRational im;
private final static Random random = new Random();
private static final Logger logger = Logger.getLogger(BigComplex.class);
/** The constructor creates a BigComplex object
* from two BigRational objects real and imaginary part.
* @param r real part.
* @param i imaginary part.
*/
public BigComplex(BigRational r, BigRational i) {
re = r;
im = i;
}
/** The constructor creates a BigComplex object
* from a BigRational object as real part,
* the imaginary part is set to 0.
* @param r real part.
*/
public BigComplex(BigRational r) {
this(r,BigRational.ZERO);
}
/** The constructor creates a BigComplex object
* from a long element as real part,
* the imaginary part is set to 0.
* @param r real part.
*/
public BigComplex(long r) {
this(new BigRational(r),BigRational.ZERO);
}
/** The constructor creates a BigComplex object
* with real part 0 and imaginary part 0.
*/
public BigComplex() {
this(BigRational.ZERO);
}
/** The constructor creates a BigComplex object
* from a String representation.
* @param s string of a BigComplex.
* @throws NumberFormatException
*/
public BigComplex(String s) throws NumberFormatException {
if ( s == null || s.length() == 0) {
re = BigRational.ZERO;
im = BigRational.ZERO;
return;
}
s = s.trim();
int i = s.indexOf("i");
if ( i < 0 ) {
re = new BigRational( s );
im = BigRational.ZERO;
return;
}
//logger.warn("String constructor not done");
String sr = "";
if ( i > 0 ) {
sr = s.substring(0,i);
}
String si = "";
if ( i < s.length() ) {
si = s.substring(i+1,s.length());
}
//int j = sr.indexOf("+");
re = new BigRational( sr.trim() );
im = new BigRational( si.trim() );
}
/**
* Get the corresponding element factory.
* @return factory for this Element.
* @see edu.jas.structure.Element#factory()
*/
public BigComplex factory() {
return this;
}
/**
* Get a list of the generating elements.
* @return list of generators for the algebraic structure.
* @see edu.jas.structure.ElemFactory#generators()
*/
public List<BigComplex> generators() {
List<BigComplex> g = new ArrayList<BigComplex>(2);
g.add( getONE() );
g.add( getIMAG() );
return g;
}
/** Clone this.
* @see java.lang.Object#clone()
*/
@Override
public BigComplex clone() {
return new BigComplex( re, im );
}
/** Copy BigComplex element c.
* @param c BigComplex.
* @return a copy of c.
*/
public BigComplex copy(BigComplex c) {
return new BigComplex( c.re, c.im );
}
/** Get the zero element.
* @return 0 as BigComplex.
*/
public BigComplex getZERO() {
return ZERO;
}
/** Get the one element.
* @return 1 as BigComplex.
*/
public BigComplex getONE() {
return ONE;
}
/** Get the i element.
* @return i as BigComplex.
*/
public BigComplex getIMAG() {
return I;
}
/**
* Query if this ring is commutative.
* @return true.
*/
public boolean isCommutative() {
return true;
}
/**
* Query if this ring is associative.
* @return true.
*/
public boolean isAssociative() {
return true;
}
/**
* Query if this ring is a field.
* @return true.
*/
public boolean isField() {
return true;
}
/**
* Characteristic of this ring.
* @return characteristic of this ring.
*/
public java.math.BigInteger characteristic() {
return java.math.BigInteger.ZERO;
}
/** Get a BigComplex element from a BigInteger.
* @param a BigInteger.
* @return a BigComplex.
*/
public BigComplex fromInteger(BigInteger a) {
return new BigComplex( new BigRational(a) );
}
/** Get a BigComplex element from a long.
* @param a long.
* @return a BigComplex.
*/
public BigComplex fromInteger(long a) {
return new BigComplex( new BigRational( a ) );
}
/** The constant 0.
*/
public static final BigComplex ZERO =
new BigComplex();
/** The constant 1.
*/
public static final BigComplex ONE =
new BigComplex(BigRational.ONE);
/** The constant i.
*/
public static final BigComplex I =
new BigComplex(BigRational.ZERO,BigRational.ONE);
/** Get the real part.
* @return re.
*/
public BigRational getRe() { return re; }
/** Get the imaginary part.
* @return im.
*/
public BigRational getIm() { return im; }
/** Get the String representation.
*/
@Override
public String toString() {
String s = "" + re;
int i = im.compareTo( BigRational.ZERO );
//logger.info("compareTo "+im+" ? 0 = "+i);
if ( i == 0 ) return s;
s += "i" + im;
return s;
}
/** Get a scripting compatible string representation.
* @return script compatible representation for this Element.
* @see edu.jas.structure.Element#toScript()
*/
@Override
public String toScript() {
- // Python case
+ // Python case: (re,im) or (re,)
StringBuffer s = new StringBuffer();
- if ( im.isZERO() ) {
- s.append(re.toScript());
- } else {
- s.append("(");
- s.append(re.toScript());
- s.append(",").append(im.toScript());
- s.append(")");
+ s.append("(");
+ s.append(re.toScript());
+ s.append(",");
+ if ( !im.isZERO() ) {
+ s.append(im.toScript());
}
+ s.append(")");
return s.toString();
}
/** Get a scripting compatible string representation of the factory.
* @return script compatible representation for this ElemFactory.
* @see edu.jas.structure.Element#toScriptFactory()
*/
@Override
public String toScriptFactory() {
// Python case
return "CC()";
}
/** Complex number zero.
* @param A is a complex number.
* @return If A is 0 then true is returned, else false.
*/
public static boolean isCZERO(BigComplex A) {
if ( A == null ) return false;
return A.isZERO();
}
/** Is Complex number zero.
* @return If this is 0 then true is returned, else false.
* @see edu.jas.structure.RingElem#isZERO()
*/
public boolean isZERO() {
return re.equals( BigRational.ZERO )
&& im.equals( BigRational.ZERO );
}
/** Complex number one.
* @param A is a complex number.
* @return If A is 1 then true is returned, else false.
*/
public static boolean isCONE(BigComplex A) {
if ( A == null ) return false;
return A.isONE();
}
/** Is Complex number one.
* @return If this is 1 then true is returned, else false.
* @see edu.jas.structure.RingElem#isONE()
*/
public boolean isONE() {
return re.equals( BigRational.ONE )
&& im.equals( BigRational.ZERO );
}
/** Is Complex imaginary one.
* @return If this is i then true is returned, else false.
*/
public boolean isIMAG() {
return re.equals( BigRational.ZERO )
&& im.equals( BigRational.ONE );
}
/** Is Complex unit element.
* @return If this is a unit then true is returned, else false.
* @see edu.jas.structure.RingElem#isUnit()
*/
public boolean isUnit() {
return ( ! isZERO() );
}
/** Comparison with any other object.
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object b) {
if ( ! ( b instanceof BigComplex ) ) {
return false;
}
BigComplex bc = (BigComplex) b;
return re.equals( bc.re )
&& im.equals( bc.im );
}
/** Hash code for this BigComplex.
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return 37 * re.hashCode() + im.hashCode();
}
/** Since complex numbers are unordered,
* we use lexicographical order of re and im.
* @return 0 if this is equal to b;
* 1 if re > b.re, or re == b.re and im > b.im;
* -1 if re < b.re, or re == b.re and im < b.im
*/
@Override
public int compareTo(BigComplex b) {
int s = re.compareTo( b.re );
if ( s != 0 ) {
return s;
}
return im.compareTo( b.im );
}
/** Since complex numbers are unordered,
* we use lexicographical order of re and im.
* @return 0 if this is equal to 0;
* 1 if re > 0, or re == 0 and im > 0;
* -1 if re < 0, or re == 0 and im < 0
* @see edu.jas.structure.RingElem#signum()
*/
public int signum() {
int s = re.signum();
if ( s != 0 ) {
return s;
}
return im.signum();
}
/* arithmetic operations: +, -, -
*/
/** Complex number summation.
* @param B a BigComplex number.
* @return this+B.
*/
public BigComplex sum(BigComplex B) {
return new BigComplex( re.sum( B.re ),
im.sum( B.im ) );
}
/** Complex number sum.
* @param A and B are complex numbers.
* @return A+B.
*/
public static BigComplex CSUM(BigComplex A, BigComplex B) {
if ( A == null ) return null;
return A.sum(B);
}
/** Complex number difference.
* @param A and B are complex numbers.
* @return A-B.
*/
public static BigComplex CDIF(BigComplex A, BigComplex B) {
if ( A == null ) return null;
return A.subtract(B);
}
/** Complex number subtract.
* @param B a BigComplex number.
* @return this-B.
*/
public BigComplex subtract(BigComplex B) {
return new BigComplex( re.subtract( B.re ),
im.subtract( B.im ) );
}
/** Complex number negative.
* @param A is a complex number.
* @return -A
*/
public static BigComplex CNEG(BigComplex A) {
if ( A == null ) return null;
return A.negate();
}
/** Complex number negative.
* @return -this.
* @see edu.jas.structure.RingElem#negate()
*/
public BigComplex negate() {
return new BigComplex( re.negate(),
im.negate());
}
/** Complex number conjugate.
* @param A is a complex number.
* @return the complex conjugate of A.
*/
public static BigComplex CCON(BigComplex A) {
if ( A == null ) return null;
return A.conjugate();
}
/* arithmetic operations: conjugate, absolut value
*/
/** Complex number conjugate.
* @return the complex conjugate of this.
*/
public BigComplex conjugate() {
return new BigComplex(re, im.negate());
}
/** Complex number norm.
* @see edu.jas.structure.StarRingElem#norm()
* @return ||this||.
*/
public BigComplex norm() {
// this.conjugate().multiply(this);
BigRational v = re.multiply(re);
v = v.sum( im.multiply(im) );
return new BigComplex( v );
}
/** Complex number absolute value.
* @see edu.jas.structure.RingElem#abs()
* @return |this|^2.
* Note: The square root is not jet implemented.
*/
public BigComplex abs() {
BigComplex n = norm();
logger.error("abs() square root missing");
// n = n.sqrt();
return n;
}
/** Complex number absolute value.
* @param A is a complex number.
* @return the absolute value of A, a rational number.
* Note: The square root is not jet implemented.
*/
public static BigRational CABS(BigComplex A) {
if ( A == null ) return null;
return A.abs().re;
}
/** Complex number product.
* @param A and B are complex numbers.
* @return A*B.
*/
public static BigComplex CPROD(BigComplex A, BigComplex B) {
if ( A == null ) return null;
return A.multiply(B);
}
/* arithmetic operations: *, inverse, /
*/
/** Complex number product.
* @param B is a complex number.
* @return this*B.
*/
public BigComplex multiply(BigComplex B) {
return new BigComplex(
re.multiply(B.re).subtract(im.multiply(B.im)),
re.multiply(B.im).sum(im.multiply(B.re)) );
}
/** Complex number inverse.
* @param A is a non-zero complex number.
* @return S with S*A = 1.
*/
public static BigComplex CINV(BigComplex A) {
if ( A == null ) return null;
return A.inverse();
}
/** Complex number inverse.
* @return S with S*this = 1.
* @see edu.jas.structure.RingElem#inverse()
*/
public BigComplex inverse() {
BigRational a = norm().re.inverse();
return new BigComplex( re.multiply(a),
im.multiply(a.negate()) );
}
/** Complex number inverse.
* @param S is a complex number.
* @return 0.
*/
public BigComplex remainder(BigComplex S) {
if ( S.isZERO() ) {
throw new RuntimeException("division by zero");
}
return ZERO;
}
/** Complex number quotient.
* @param A and B are complex numbers, B non-zero.
* @return A/B.
*/
public static BigComplex CQ(BigComplex A, BigComplex B) {
if ( A == null ) return null;
return A.divide(B);
}
/** Complex number divide.
* @param B is a complex number, non-zero.
* @return this/B.
*/
public BigComplex divide (BigComplex B) {
return this.multiply( B.inverse() );
}
/** Complex number, random.
* Random rational numbers A and B are generated using random(n).
* Then R is the complex number with real part A and imaginary part B.
* @param n such that 0 ≤ A, B ≤ (2<sup>n</sup>-1).
* @return R.
*/
public BigComplex random(int n) {
return random(n,random);
}
/** Complex number, random.
* Random rational numbers A and B are generated using random(n).
* Then R is the complex number with real part A and imaginary part B.
* @param n such that 0 ≤ A, B ≤ (2<sup>n</sup>-1).
* @param rnd is a source for random bits.
* @return R.
*/
public BigComplex random(int n, Random rnd) {
BigRational r = BigRational.ONE.random( n, rnd );
BigRational i = BigRational.ONE.random( n, rnd );
return new BigComplex( r, i );
}
/** Complex number, random.
* Random rational numbers A and B are generated using random(n).
* Then R is the complex number with real part A and imaginary part B.
* @param n such that 0 ≤ A, B ≤ (2<sup>n</sup>-1).
* @return R.
*/
public static BigComplex CRAND(int n) {
return ONE.random(n,random);
}
/** Parse complex number from string.
* @param s String.
* @return BigComplex from s.
*/
public BigComplex parse(String s) {
return new BigComplex(s);
}
/** Parse complex number from Reader.
* @param r Reader.
* @return next BigComplex from r.
*/
public BigComplex parse(Reader r) {
return parse( StringUtil.nextString(r) );
}
/** Complex number greatest common divisor.
* @param S BigComplex.
* @return gcd(this,S).
*/
public BigComplex gcd(BigComplex S) {
if ( S == null || S.isZERO() ) {
return this;
}
if ( this.isZERO() ) {
return S;
}
return ONE;
}
/**
* BigComplex extended greatest common divisor.
* @param S BigComplex.
* @return [ gcd(this,S), a, b ] with a*this + b*S = gcd(this,S).
*/
public BigComplex[] egcd(BigComplex S) {
BigComplex[] ret = new BigComplex[3];
ret[0] = null;
ret[1] = null;
ret[2] = null;
if ( S == null || S.isZERO() ) {
ret[0] = this;
return ret;
}
if ( this.isZERO() ) {
ret[0] = S;
return ret;
}
BigComplex half = new BigComplex(new BigRational(1,2));
ret[0] = ONE;
ret[1] = this.inverse().multiply(half);
ret[2] = S.inverse().multiply(half);
return ret;
}
}
diff --git a/src/edu/jas/arith/BigRational.java b/src/edu/jas/arith/BigRational.java
index 74022995..98e14747 100644
--- a/src/edu/jas/arith/BigRational.java
+++ b/src/edu/jas/arith/BigRational.java
@@ -1,926 +1,924 @@
/*
* $Id$
*/
package edu.jas.arith;
import java.math.BigInteger;
import java.util.Random;
import java.io.Reader;
import java.util.List;
import java.util.ArrayList;
//import edu.jas.structure.RingElem;
import edu.jas.structure.GcdRingElem;
import edu.jas.structure.RingFactory;
import edu.jas.util.StringUtil;
/**
* Immutable arbitrary-precision rational numbers.
* BigRational class based on BigInteger implementing the RingElem
* interface and with the familiar SAC static method names.
* BigInteger is from java.math in the implementation.
* @author Heinz Kredel
*/
public final class BigRational implements GcdRingElem<BigRational>,
RingFactory<BigRational> {
/**
* Numerator part of the data structure.
*/
protected final BigInteger num;
/**
* Denominator part of the data structure.
*/
protected final BigInteger den;
/* from history: */
private final static BigInteger IZERO = BigInteger.ZERO;
private final static BigInteger IONE = BigInteger.ONE;
/**
* The Constant 0.
*/
public final static BigRational ZERO
= new BigRational(BigInteger.ZERO);
/**
* The Constant 1.
*/
public final static BigRational ONE
= new BigRational(BigInteger.ONE);
/* from history:
private final static BigRational RNZERO = ZERO;
private final static BigRational RNONE = ONE;
*/
private final static Random random = new Random();
/** Constructor for a BigRational from math.BigIntegers.
* @param n math.BigInteger.
* @param d math.BigInteger.
*/
protected BigRational(BigInteger n, BigInteger d) {
// assume gcd(n,d) == 1
num = n;
den = d;
}
/** Constructor for a BigRational from math.BigIntegers.
* @param n math.BigInteger.
*/
public BigRational(BigInteger n) {
num = n;
den = IONE; // be aware of static initialization order
//den = BigInteger.ONE;
}
/** Constructor for a BigRational from jas.arith.BigIntegers.
* @param n edu.jas.arith.BigInteger.
*/
public BigRational(edu.jas.arith.BigInteger n) {
this( n.getVal() );
}
/** Constructor for a BigRational from longs.
* @param n long.
* @param d long.
*/
public BigRational(long n, long d) {
BigInteger nu = BigInteger.valueOf(n);
BigInteger de = BigInteger.valueOf(d);
BigRational r = RNRED(nu,de);
num = r.num;
den = r.den;
}
/** Constructor for a BigRational from longs.
* @param n long.
*/
public BigRational(long n) {
num = BigInteger.valueOf(n);
den = IONE;
}
/** Constructor for a BigRational with no arguments.
*/
public BigRational() {
num = IZERO; den = IONE;
}
/** Constructor for a BigRational from String.
* @param s String.
* @throws NumberFormatException
*/
public BigRational(String s) throws NumberFormatException {
if ( s == null ) {
num = IZERO; den = IONE;
return;
}
if ( s.length() == 0) {
num = IZERO; den = IONE;
return;
}
BigInteger n;
BigInteger d;
int i = s.indexOf('/');
if ( i < 0 ) {
num = new BigInteger( s );
den = BigInteger.ONE;
return;
} else {
n = new BigInteger( s.substring(0,i) );
d = new BigInteger( s.substring( i+1, s.length() ) );
BigRational r = RNRED( n, d );
num = r.num;
den = r.den;
return;
}
}
/**
* Get the corresponding element factory.
* @return factory for this Element.
* @see edu.jas.structure.Element#factory()
*/
public BigRational factory() {
return this;
}
/**
* Get a list of the generating elements.
* @return list of generators for the algebraic structure.
* @see edu.jas.structure.ElemFactory#generators()
*/
public List<BigRational> generators() {
List<BigRational> g = new ArrayList<BigRational>(1);
g.add( getONE() );
return g;
}
/** Clone this.
* @see java.lang.Object#clone()
*/
@Override
public BigRational clone() {
return new BigRational( num, den );
}
/** Copy BigRational element c.
* @param c BigRational.
* @return a copy of c.
*/
public BigRational copy(BigRational c) {
return new BigRational( c.num, c.den );
}
/** Get the numerator.
* @return num.
*/
public BigInteger numerator() {
return num;
}
/** Get the denominator.
* @return den.
*/
public BigInteger denominator() {
return den;
}
/** Get the string representation.
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuffer s = new StringBuffer();
s.append(num);
if ( ! den.equals(BigInteger.ONE) ) {
s.append("/").append(den);
}
return s.toString();
}
/** Get a scripting compatible string representation.
* @return script compatible representation for this Element.
* @see edu.jas.structure.Element#toScript()
*/
@Override
public String toScript() {
- // Python case
+ // Python case: (num,den) or (num,)
StringBuffer s = new StringBuffer();
- if ( den.equals(BigInteger.ONE) ) {
- //s.append("("+num+",)");
- s.append(num);
- } else {
- s.append("(");
- s.append(num);
- s.append(",").append(den);
- s.append(")");
+ s.append("(");
+ s.append(num.toString());
+ s.append(",");
+ if ( !den.equals(BigInteger.ONE) ) {
+ s.append(den.toString());
}
+ s.append(")");
return s.toString();
}
/** Get a scripting compatible string representation of the factory.
* @return script compatible representation for this ElemFactory.
* @see edu.jas.structure.Element#toScriptFactory()
*/
@Override
public String toScriptFactory() {
// Python case
return "QQ()";
}
/** Get the zero element.
* @return 0 as BigRational.
*/
public BigRational getZERO() {
return ZERO;
}
/** Get the one element.
* @return 1 as BigRational.
*/
public BigRational getONE() {
return ONE;
}
/**
* Query if this ring is commutative.
* @return true.
*/
public boolean isCommutative() {
return true;
}
/**
* Query if this ring is associative.
* @return true.
*/
public boolean isAssociative() {
return true;
}
/**
* Query if this ring is a field.
* @return true.
*/
public boolean isField() {
return true;
}
/**
* Characteristic of this ring.
* @return characteristic of this ring.
*/
public java.math.BigInteger characteristic() {
return java.math.BigInteger.ZERO;
}
/** Get a BigRational element from a math.BigInteger.
* @param a math.BigInteger.
* @return BigRational from a.
*/
public BigRational fromInteger(BigInteger a) {
return new BigRational(a);
}
/** Get a BigRational element from a math.BigInteger.
* @param a math.BigInteger.
* @return BigRational from a.
*/
public static BigRational valueOf(BigInteger a) {
return new BigRational(a);
}
/** Get a BigRational element from a long.
* @param a long.
* @return BigRational from a.
*/
public BigRational fromInteger(long a) {
return new BigRational(a);
}
/** Get a BigRational element from a long.
* @param a long.
* @return BigRational from a.
*/
public static BigRational valueOf(long a) {
return new BigRational(a);
}
/** Is BigRational zero.
* @return If this is 0 then true is returned, else false.
* @see edu.jas.structure.RingElem#isZERO()
*/
public boolean isZERO() {
return num.equals( BigInteger.ZERO );
}
/** Is BigRational one.
* @return If this is 1 then true is returned, else false.
* @see edu.jas.structure.RingElem#isONE()
*/
public boolean isONE() {
return num.equals( den );
}
/** Is BigRational unit.
* @return If this is a unit then true is returned, else false.
* @see edu.jas.structure.RingElem#isUnit()
*/
public boolean isUnit() {
return ( ! isZERO() );
}
/** Comparison with any other object.
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals( Object b) {
if ( ! ( b instanceof BigRational ) ) {
return false;
}
BigRational br = (BigRational) b;
return num.equals( br.num )
&& den.equals( br.den );
}
/** Hash code for this BigRational.
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return 37 * num.hashCode() + den.hashCode();
}
/** Rational number reduction to lowest terms.
* @param n BigInteger.
* @param d BigInteger.
* @return a/b ~ n/d, gcd(a,b) = 1, b > 0.
*/
public static BigRational RNRED(BigInteger n, BigInteger d) {
BigInteger num;
BigInteger den;
if ( n.equals(IZERO) ) {
num = n; den = IONE;
return new BigRational(num,den);
}
BigInteger C = n.gcd(d);
num = n.divide(C);
den = d.divide(C);
if ( den.signum() < 0 ) {
num = num.negate(); den = den.negate();
}
return new BigRational(num,den);
}
/** Rational number absolute value.
* @return the absolute value of this.
* @see edu.jas.structure.RingElem#abs()
*/
public BigRational abs() {
if ( RNSIGN( this ) >= 0 ) {
return this;
} else {
return RNNEG(this);
}
}
/** Rational number absolute value.
* @param R is a rational number.
* @return the absolute value of R.
*/
public static BigRational RNABS(BigRational R) {
if ( R == null ) return null;
return R.abs();
}
/** Rational number comparison.
* @param S BigRational.
* @return SIGN(this-S).
*/
public int compareTo(BigRational S) {
BigInteger J2Y;
BigInteger J3Y;
BigInteger R1;
BigInteger R2;
BigInteger S1;
BigInteger S2;
int J1Y;
int SL;
int TL;
int RL;
if ( this.equals( ZERO ) ) {
return - RNSIGN( S );
}
if ( S.equals( ZERO ) ) {
return RNSIGN( this );
}
R1 = num; //this.numerator();
R2 = den; //this.denominator();
S1 = S.num;
S2 = S.den;
RL = R1.signum();
SL = S1.signum();
J1Y = (RL - SL);
TL = (J1Y / 2);
if ( TL != 0 ) {
return TL;
}
J3Y = R1.multiply( S2 );
J2Y = R2.multiply( S1 );
TL = J3Y.compareTo( J2Y );
return TL;
}
/** Rational number comparison.
* @param R BigRational.
* @param S BigRational.
* @return SIGN(R-S).
*/
public static int RNCOMP(BigRational R, BigRational S) {
if ( R == null ) return Integer.MAX_VALUE;
return R.compareTo(S);
}
/** Rational number denominator.
* @param R BigRational.
* @return R.denominator().
*/
public static BigInteger RNDEN(BigRational R) {
if ( R == null ) return null;
return R.den;
}
/** Rational number difference.
* @param S BigRational.
* @return this-S.
*/
public BigRational subtract(BigRational S) {
BigRational J1Y;
BigRational T;
J1Y = RNNEG( S );
T = RNSUM( this, J1Y );
return T;
}
/** Rational number difference.
* @param R BigRational.
* @param S BigRational.
* @return R-S.
*/
public static BigRational RNDIF(BigRational R, BigRational S) {
if ( R == null ) return S.negate();
return R.subtract(S);
}
/** Rational number decimal write. R is a rational number. n is a
non-negative integer. R is approximated by a decimal fraction D with
n decimal digits following the decimal point and D is written in the
output stream. The inaccuracy of the approximation is at most
(1/2)*10**-n. If ABS(D) is greater than ABS(R) then the last digit is
followed by a minus sign, if ABS(D) is less than ABS(R) then by a
plus sign.
* @param R
* @param NL
*/
public static void RNDWR(BigRational R, int NL) {
BigInteger num = R.num;
BigInteger den = R.den;
/* BigInteger p = new BigInteger("10");
p = p.pow(NL);
*/
double n = num.doubleValue();
double d = den.doubleValue();
double r = n/d;
System.out.print( String.valueOf( r ) );
return;
}
/** Rational number from integer.
* @param A BigInteger.
* @return A/1.
*/
public static BigRational RNINT(BigInteger A) {
return new BigRational( A );
}
/** Rational number inverse.
* @return 1/this.
* @see edu.jas.structure.RingElem#inverse()
*/
public BigRational inverse() {
BigInteger R1 = num; //R.nominator();
BigInteger R2 = den; //R.denominator();
BigInteger S1;
BigInteger S2;
if ( R1.signum() >= 0 ) {
S1 = R2;
S2 = R1;
} else {
S1 = R2.negate();
S2 = R1.negate();
}
return new BigRational(S1,S2);
}
/** Rational number inverse.
* @param R BigRational.
* @return 1/R.
*/
public static BigRational RNINV(BigRational R) {
if ( R == null ) return null;
return R.inverse();
}
/** Rational number negative.
* @return -this.
* @see edu.jas.structure.RingElem#negate()
*/
public BigRational negate() {
BigInteger n = num.negate();
return new BigRational( n, den );
}
/** Rational number negative.
* @param R BigRational.
* @return -R.
*/
public static BigRational RNNEG(BigRational R) {
if ( R == null ) return null;
return R.negate();
}
/** Rational number numerator.
* @param R BigRational.
* @return R.numerator().
*/
public static BigInteger RNNUM(BigRational R) {
if ( R == null ) return null;
return R.num;
}
/** Rational number product.
* @param S BigRational.
* @return this*S.
*/
public BigRational multiply(BigRational S) {
BigInteger D1 = null;
BigInteger D2 = null;
BigInteger R1 = null;
BigInteger R2 = null;
BigInteger RB1 = null;
BigInteger RB2 = null;
BigInteger S1 = null;
BigInteger S2 = null;
BigInteger SB1 = null;
BigInteger SB2 = null;
BigRational T;
BigInteger T1;
BigInteger T2;
if ( this.equals( ZERO ) || S.equals( ZERO ) ) {
T = ZERO;
return T;
}
R1 = num; //this.numerator();
R2 = den; //this.denominator();
S1 = S.num;
S2 = S.den;
if ( R2.equals( IONE ) && S2.equals( IONE ) ) {
T1 = R1.multiply( S1 );
T = new BigRational( T1, IONE );
return T;
}
if ( R2.equals( IONE ) ) {
D1 = R1.gcd( S2 );
RB1 = R1.divide( D1 );
SB2 = S2.divide( D1 );
T1 = RB1.multiply( S1 );
T = new BigRational( T1, SB2 );
return T;
}
if ( S2.equals( IONE ) ) {
D2 = S1.gcd( R2 );
SB1 = S1.divide( D2 );
RB2 = R2.divide( D2 );
T1 = SB1.multiply( R1 );
T = new BigRational( T1, RB2 );
return T;
}
D1 = R1.gcd( S2 );
RB1 = R1.divide( D1 );
SB2 = S2.divide( D1 );
D2 = S1.gcd( R2 );
SB1 = S1.divide( D2 );
RB2 = R2.divide( D2 );
T1 = RB1.multiply( SB1 );
T2 = RB2.multiply( SB2 );
T = new BigRational( T1, T2 );
return T;
}
/** Rational number product.
* @param R BigRational.
* @param S BigRational.
* @return R*S.
*/
public static BigRational RNPROD(BigRational R, BigRational S) {
if ( R == null ) return S;
return R.multiply(S);
}
/** Rational number quotient.
* @param S BigRational.
* @return this/S.
*/
public BigRational divide(BigRational S) {
return multiply( S.inverse() );
}
/** Rational number quotient.
* @param R BigRational.
* @param S BigRational.
* @return R/S.
*/
public static BigRational RNQ(BigRational R, BigRational S) {
if ( R == null ) return S.inverse();
return R.divide( S );
}
/** Rational number remainder.
* @param S BigRational.
* @return this-(this/S)*S
*/
public BigRational remainder(BigRational S) {
if ( S.isZERO() ) {
throw new RuntimeException("division by zero");
}
return ZERO;
}
/** Rational number, random.
* Random integers A, B and a random sign s are generated
* using BigInteger(n,random) and random.nextBoolen().
* Then R = s*A/(B+1), reduced to lowest terms.
* @param n such that 0 ≤ A, B ≤ (2<sup>n</sup>-1).
* @return a random BigRational.
*/
public BigRational random(int n) {
return random( n, random );
}
/** Rational number, random.
* Random integers A, B and a random sign s are generated
* using BigInteger(n,random) and random.nextBoolen().
* Then R = s*A/(B+1), reduced to lowest terms.
* @param n such that 0 ≤ A, B ≤ (2<sup>n</sup>-1).
* @param rnd is a source for random bits.
* @return a random BigRational.
*/
public BigRational random(int n, Random rnd) {
BigInteger A;
BigInteger B;
A = new BigInteger( n, rnd ); // always positive
if ( rnd.nextBoolean() ) {
A = A.negate();
}
B = new BigInteger( n, rnd ); // always positive
B = B.add( IONE );
return RNRED( A, B );
}
/** Rational number, random.
* Random integers A, B and a random sign s are generated
* using BigInteger(n,random) and random.nextBoolen().
* Then R = s*A/(B+1), reduced to lowest terms.
* @param NL such that 0 ≤ A, B ≤ (2<sup>n</sup>-1).
* @return a random BigRational.
*/
public static BigRational RNRAND(int NL) {
return ONE.random(NL,random);
}
/** Rational number sign.
* @see edu.jas.structure.RingElem#signum()
*/
public int signum() {
return num.signum();
}
/** Rational number sign.
* @param R BigRational.
* @return R.signum().
*/
public static int RNSIGN(BigRational R) {
if ( R == null ) return Integer.MAX_VALUE;
return R.signum();
}
/** Rational number sum.
* @param S BigRational.
* @return this+S.
*/
public BigRational sum(BigRational S) {
BigInteger D = null;
BigInteger E;
BigInteger J1Y;
BigInteger J2Y;
BigInteger R1 = null;
BigInteger R2 = null;
BigInteger RB2 = null;
BigInteger S1 = null;
BigInteger S2 = null;
BigInteger SB2 = null;
BigRational T;
BigInteger T1;
BigInteger T2;
if ( this.equals( ZERO ) ) {
T = S;
return T;
}
if ( S.equals( ZERO ) ) {
T = this;
return T;
}
R1 = num; //this.numerator();
R2 = den; //this.denominator();
S1 = S.num;
S2 = S.den;
if ( R2.equals( IONE ) && S2.equals( IONE ) ) {
T1 = R1.add( S1 );
T = new BigRational( T1, IONE );
return T;
}
if ( R2.equals( IONE ) ) {
T1 = R1.multiply( S2 );
T1 = T1.add( S1 );
T = new BigRational( T1, S2 );
return T;
}
if ( S2.equals( IONE ) ) {
T1 = R2.multiply( S1 );
T1 = T1.add( R1 );
T = new BigRational( T1, R2 );
return T;
}
D = R2.gcd( S2 );
RB2 = R2.divide( D );
SB2 = S2.divide( D );
J1Y = R1.multiply( SB2 );
J2Y = RB2.multiply( S1 );
T1 = J1Y.add( J2Y );
if ( T1.equals( IZERO ) ) {
T = ZERO;
return T;
}
if ( ! D.equals( IONE ) ) {
E = T1.gcd( D );
if ( ! E.equals( IONE ) ) {
T1 = T1.divide( E );
R2 = R2.divide( E );
}
}
T2 = R2.multiply( SB2 );
T = new BigRational( T1, T2 );
return T;
}
/** Rational number sum.
* @param R BigRational.
* @param S BigRational.
* @return R+S.
*/
public static BigRational RNSUM(BigRational R, BigRational S) {
if ( R == null ) return S;
return R.sum( S );
}
/** Parse rational number from String.
* @param s String.
* @return BigRational from s.
*/
public BigRational parse(String s) {
return new BigRational(s);
}
/** Parse rational number from Reader.
* @param r Reader.
* @return next BigRational from r.
*/
public BigRational parse(Reader r) {
return parse( StringUtil.nextString(r) );
}
/** Rational number greatest common divisor.
* @param S BigRational.
* @return gcd(this,S).
*/
public BigRational gcd(BigRational S) {
if ( S == null || S.isZERO() ) {
return this;
}
if ( this.isZERO() ) {
return S;
}
return ONE;
}
/**
* BigRational extended greatest common divisor.
* @param S BigRational.
* @return [ gcd(this,S), a, b ] with a*this + b*S = gcd(this,S).
*/
public BigRational[] egcd(BigRational S) {
BigRational[] ret = new BigRational[3];
ret[0] = null;
ret[1] = null;
ret[2] = null;
if ( S == null || S.isZERO() ) {
ret[0] = this;
return ret;
}
if ( this.isZERO() ) {
ret[0] = S;
return ret;
}
BigRational half = new BigRational(1,2);
ret[0] = ONE;
ret[1] = this.inverse().multiply(half);
ret[2] = S.inverse().multiply(half);
return ret;
}
}
| false | false | null | null |
diff --git a/src/main/java/net/minekingdom/continuum/world/Dimension.java b/src/main/java/net/minekingdom/continuum/world/Dimension.java
index fb3e86c..f135323 100644
--- a/src/main/java/net/minekingdom/continuum/world/Dimension.java
+++ b/src/main/java/net/minekingdom/continuum/world/Dimension.java
@@ -1,455 +1,455 @@
package net.minekingdom.continuum.world;
import java.util.List;
import net.minekingdom.continuum.Continuum;
import net.minekingdom.continuum.utils.GenUtils;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.bukkit.Bukkit;
import org.bukkit.Difficulty;
import org.bukkit.Server;
import org.bukkit.World;
import org.bukkit.World.Environment;
import org.bukkit.WorldCreator;
import org.bukkit.WorldType;
import org.bukkit.metadata.FixedMetadataValue;
import org.bukkit.metadata.MetadataValue;
import org.bukkit.permissions.Permissible;
import org.bukkit.permissions.Permission;
public class Dimension {
public final Permission ACCESS_PERMISSION;
protected final Server server;
protected final Universe universe;
protected final String name;
protected World handle;
protected long seed;
protected String generator;
protected Environment environment;
protected WorldType type;
protected double scale;
protected boolean loaded;
protected boolean monsters;
protected boolean animals;
protected int monsterSpawnLimit;
protected int waterMobSpawnLimit;
protected int animalSpawnLimit;
protected boolean pvp;
protected Difficulty difficulty;
protected boolean keepSpawnInMemory;
public Dimension(Server server, Universe universe, String name, long seed, String generator, Environment environment, WorldType type) {
this.server = server;
this.universe = universe;
this.ACCESS_PERMISSION = new Permission(universe.ACCESS_PERMISSION.getName() + "." + name);
this.ACCESS_PERMISSION.addParent(universe.ACCESS_PERMISSION, true);
server.getPluginManager().addPermission(ACCESS_PERMISSION);
server.getPluginManager().recalculatePermissionDefaults(Universe.ALL_ACCESS_PERMISSION);
this.name = name;
this.seed = seed;
this.generator = generator;
this.environment = environment;
this.type = type;
this.scale = 1;
this.monsters = true;
this.animals = true;
this.monsterSpawnLimit = -1;
this.animalSpawnLimit = -1;
this.waterMobSpawnLimit = -1;
this.difficulty = Difficulty.NORMAL;
this.pvp = true;
this.keepSpawnInMemory = false;
}
public Dimension(Server server, Universe parent, String name, long seed) {
this(server, parent, name, seed, "", Environment.NORMAL, WorldType.NORMAL);
}
public Dimension(Server server, Universe parent, String name, long seed, String generator) {
this(server, parent, name, seed, generator, Environment.NORMAL, WorldType.NORMAL);
}
public Dimension(Server server, Universe parent, String name, long seed, Environment environment) {
this(server, parent, name, seed, "", environment, WorldType.NORMAL);
}
public Dimension(Server server, Universe parent, String name, long seed, WorldType type) {
this(server, parent, name, seed, "", Environment.NORMAL, type);
}
public Dimension(Server server, Universe parent, String name, long seed, String generator, Environment environment) {
this(server, parent, name, seed, generator, environment, WorldType.NORMAL);
}
public Dimension(Server server, Universe parent, String name, long seed, String generator, WorldType type) {
this(server, parent, name, seed, generator, Environment.NORMAL, type);
}
public Dimension(Server server, Universe parent, String name, String generator) {
this(server, parent, name, GenUtils.generateSeed(), generator, Environment.NORMAL, WorldType.NORMAL);
}
public Dimension(Server server, Universe parent, String name, String generator, Environment environment) {
this(server, parent, name, GenUtils.generateSeed(), generator, environment, WorldType.NORMAL);
}
public Dimension(Server server, Universe parent, String name, String generator, WorldType type) {
this(server, parent, name, GenUtils.generateSeed(), generator, Environment.NORMAL, type);
}
public Dimension(Server server, Universe parent, String name, String generator, Environment environment, WorldType type) {
this(server, parent, name, GenUtils.generateSeed(), generator, environment, type);
}
public Dimension(Server server, Universe parent, String name, Environment environment) {
this(server, parent, name, GenUtils.generateSeed(), "", environment, WorldType.NORMAL);
}
public Dimension(Server server, Universe parent, String name, Environment environment, WorldType type) {
this(server, parent, name, GenUtils.generateSeed(), "", environment, type);
}
public Dimension(Server server, Universe parent, String name, WorldType type) {
this(server, parent, name, GenUtils.generateSeed(), "", Environment.NORMAL, type);
}
public Dimension(Server server, Universe parent, String name) {
this(server, parent, name, GenUtils.generateSeed(), "", Environment.NORMAL, WorldType.NORMAL);
}
/*-------------------------------------*
* Load functions *
*-------------------------------------*/
public boolean isLoaded() {
return this.loaded;
}
public boolean load() {
if (isLoaded()) {
throw new IllegalStateException("World is already loaded.");
}
WorldCreator creator = getWorldCreator();
try {
this.handle = server.createWorld(creator);
} catch (Throwable t) {
t.printStackTrace();
if (this.handle == null) {
this.handle = Bukkit.getWorld(creator.name());
if (handle == null
|| handle.getSeed() != creator.seed()
|| !handle.getWorldType().equals(creator.type())
|| !handle.getEnvironment().equals(creator.environment())) {
return false;
}
}
}
updateHandle();
this.handle.setMetadata("continuum.universe", new FixedMetadataValue(Continuum.getInstance(), this.universe));
this.handle.setMetadata("continuum.dimension", new FixedMetadataValue(Continuum.getInstance(), this));
this.loaded = true;
return true;
}
protected WorldCreator getWorldCreator() {
WorldCreator creator = new WorldCreator(universe.getName() + "_" + name);
if (seed != 0) {
creator.seed(seed);
}
if (environment != null) {
creator.environment(environment);
}
- if (generator != null) {
+ if (generator != null && !generator.trim().isEmpty()) {
creator.generator(generator);
}
if (type != null) {
creator.type(type);
}
return creator;
}
public void unload() {
unload(true);
}
public void unload(boolean save) {
if (!isLoaded()) {
throw new IllegalStateException("World is already unloaded.");
}
this.loaded = false;
this.server.unloadWorld(this.handle, save);
this.handle = null;
}
/*-------------------------------------*
* Update Functions *
*-------------------------------------*/
private void updateHandle() {
updateSpawnFlags();
updateMonsterSpawnLimit();
updateAnimalSpawnLimit();
updateWaterMobSpawnLimit();
updateDifficulty();
updatePVP();
updateKeepSpawnInMemory();
}
private void updateSpawnFlags() {
handle.setSpawnFlags(monsters, animals);
}
private void updateMonsterSpawnLimit() {
this.handle.setMonsterSpawnLimit(this.monsterSpawnLimit);
}
private void updateAnimalSpawnLimit() {
this.handle.setAnimalSpawnLimit(this.animalSpawnLimit);
}
private void updateWaterMobSpawnLimit() {
this.handle.setWaterAnimalSpawnLimit(this.waterMobSpawnLimit);
}
private void updateDifficulty() {
this.handle.setDifficulty(difficulty);
}
private void updatePVP() {
this.handle.setPVP(pvp);
}
private void updateKeepSpawnInMemory() {
try {
this.handle.setKeepSpawnInMemory(this.keepSpawnInMemory);
} catch (Throwable t) {
t.printStackTrace();
}
}
/*-------------------------------------*
* Mutators / Accessors *
*-------------------------------------*/
public String getName() {
return name;
}
public long getSeed() {
return seed;
}
public Dimension setSeed(long seed) {
this.seed = seed;
return this;
}
public String getGenerator() {
return generator;
}
public Dimension setGenerator(String generator) {
this.generator = generator;
return this;
}
public Environment getEnvironment() {
return environment;
}
public Dimension setEnvironment(Environment environment) {
this.environment = environment;
return this;
}
public WorldType getWorldType() {
return type;
}
public Dimension setWorldType(WorldType worldType) {
this.type = worldType;
return this;
}
public boolean hasMonsters() {
return monsters;
}
public Dimension setMonsters(boolean monsters) {
this.monsters = monsters;
if (isLoaded()) {
updateSpawnFlags();
}
return this;
}
public boolean hasAnimals() {
return animals;
}
public Dimension setAnimals(boolean animals) {
this.animals = animals;
if (isLoaded()) {
updateSpawnFlags();
}
return this;
}
public int getMonsterSpawnLimit() {
return this.monsterSpawnLimit;
}
public Dimension setMonsterSpawnLimit(int monsterSpawnLimit) {
this.monsterSpawnLimit = monsterSpawnLimit;
if (isLoaded()) {
updateMonsterSpawnLimit();
}
return this;
}
public int getAnimalSpawnLimit() {
return this.animalSpawnLimit;
}
public Dimension setAnimalSpawnLimit(int animalSpawnLimit) {
this.animalSpawnLimit = animalSpawnLimit;
if (isLoaded()) {
updateAnimalSpawnLimit();
}
return this;
}
public int getWaterMobSpawnLimit() {
return this.waterMobSpawnLimit;
}
public Dimension setWaterMobSpawnLimit(int waterMobSpawnLimit) {
this.waterMobSpawnLimit = waterMobSpawnLimit;
if (isLoaded()) {
updateWaterMobSpawnLimit();
}
return this;
}
public Difficulty getDifficulty() {
return difficulty;
}
public Dimension setDifficulty(Difficulty difficulty) {
this.difficulty = difficulty;
if (isLoaded()) {
updateDifficulty();
}
return this;
}
public boolean hasPVP() {
return pvp;
}
public Dimension setPVP(boolean pvp) {
this.pvp = pvp;
if (isLoaded()) {
updatePVP();
}
return this;
}
public boolean keepsSpawnInMemory() {
return keepSpawnInMemory;
}
public Dimension setKeepSpawnInMemory(boolean keepSpawnInMemory) {
this.keepSpawnInMemory = keepSpawnInMemory;
if (isLoaded()) {
updateKeepSpawnInMemory();
}
return this;
}
public double getScale() {
return this.scale;
}
public Dimension setScale(double scale) {
this.scale = scale;
return this;
}
public World getHandle() {
return handle;
}
public Universe getWorld() {
return this.universe;
}
/*-------------------------------------*
* Misc *
*-------------------------------------*/
public boolean canAccess(Permissible permissible) {
return permissible.hasPermission(ACCESS_PERMISSION);
}
@Override
public int hashCode() {
return new HashCodeBuilder()
.append(this.name)
.append(this.universe)
.toHashCode();
}
@Override
public boolean equals(Object o) {
if (!(o instanceof Dimension)) {
return false;
}
if (o == this) {
return true;
}
Dimension other = (Dimension) o;
return new EqualsBuilder()
.append(this.name, other.name)
.append(this.universe, other.universe)
.isEquals();
}
/*-------------------------------------*
* Static *
*-------------------------------------*/
public static Dimension get(World world) {
if (world != null) {
List<MetadataValue> meta = world.getMetadata("continuum.dimension");
if (meta.size() > 0 && meta.get(0).value() instanceof Dimension) {
return (Dimension) meta.get(0).value();
}
}
return null;
}
}
| true | false | null | null |
diff --git a/nuget-tests/src/jetbrains/buildServer/nuget/tests/server/tools/ToolsRegistryTest.java b/nuget-tests/src/jetbrains/buildServer/nuget/tests/server/tools/ToolsRegistryTest.java
index e893ad13..a7be25c7 100644
--- a/nuget-tests/src/jetbrains/buildServer/nuget/tests/server/tools/ToolsRegistryTest.java
+++ b/nuget-tests/src/jetbrains/buildServer/nuget/tests/server/tools/ToolsRegistryTest.java
@@ -1,117 +1,115 @@
/*
* Copyright 2000-2011 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jetbrains.buildServer.nuget.tests.server.tools;
import jetbrains.buildServer.BaseTestCase;
import jetbrains.buildServer.nuget.server.ToolPaths;
import jetbrains.buildServer.nuget.server.toolRegistry.NuGetInstalledTool;
import jetbrains.buildServer.nuget.server.toolRegistry.impl.PluginNaming;
import jetbrains.buildServer.nuget.server.toolRegistry.impl.ToolsRegistry;
import jetbrains.buildServer.nuget.server.toolRegistry.impl.ToolsWatcher;
import jetbrains.buildServer.util.FileUtil;
import org.jetbrains.annotations.NotNull;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.io.File;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Iterator;
+import java.util.*;
/**
* @author Eugene Petrenko ([email protected])
* Date: 30.09.11 17:07
*/
public class ToolsRegistryTest extends BaseTestCase {
private Mockery m;
private File myToolsHome;
private File myPackagesHome;
private File myAgentHome;
private ToolsRegistry myRegistry;
private ToolsWatcher myWatcher;
@BeforeMethod
@Override
protected void setUp() throws Exception {
super.setUp();
m = new Mockery();
myToolsHome = createTempDir();
myPackagesHome = createTempDir();
myAgentHome = createTempDir();
final ToolPaths path = m.mock(ToolPaths.class);
myWatcher = m.mock(ToolsWatcher.class);
m.checking(new Expectations(){{
allowing(path).getNuGetToolsPath(); will(returnValue(myToolsHome));
allowing(path).getNuGetToolsPackages(); will(returnValue(myPackagesHome));
allowing(path).getNuGetToolsAgentPluginsPath(); will(returnValue(myAgentHome));
}});
myRegistry = new ToolsRegistry(path, new PluginNaming(path), myWatcher);
}
@Test
public void test_empty() {
Assert.assertTrue(myRegistry.getTools().isEmpty());
}
private void file(@NotNull File root, @NotNull String path) {
final File dest = new File(root, path);
FileUtil.createParentDirs(dest);
FileUtil.writeFile(dest, "2qwerwer" + path);
}
@Test
public void test_one_package() {
nupkg("NuGet.CommandLine.1.2.3.4");
Assert.assertEquals(myRegistry.getTools().size(), 1);
}
private void nupkg(String name) {
file(myPackagesHome, name + ".nupkg");
file(myAgentHome, name + ".nupkg.zip");
file(myToolsHome, name + ".nupkg/tools/nuget.exe");
}
@Test
public void test_two_packages() {
nupkg("NuGet.CommandLine.1.2.3.4");
nupkg("NuGet.CommandLine.1.3.3.4");
nupkg("NuGet.CommandLine.1.2.6.4");
nupkg("NuGet.CommandLine.2.2.3.4.z");
nupkg("NuGet.CommandLine.2.2.3.14.y");
nupkg("NuGet.aaaamandLine.4.4.4");
final Collection<? extends NuGetInstalledTool> tools = myRegistry.getTools();
- final Iterator<String> versions = Arrays.asList("1.2.3.4", "1.2.6.4", "1.3.3.4", "2.2.3.4", "2.2.3.14", "4.4.4").iterator();
-
+ final List<String> names = new ArrayList<String>();
for (NuGetInstalledTool tool : tools) {
System.out.println("tool.getVersion() = " + tool.getVersion());
- final String v = versions.next();
- Assert.assertEquals(tool.getVersion(), v);
+ names.add(tool.getVersion());
}
+
+ Assert.assertEquals(names, Arrays.asList("NuGet.aaaamandLine.4.4.4", "1.2.3.4", "1.2.6.4", "1.3.3.4", "2.2.3.4.z", "2.2.3.14.y"));
}
}
| false | false | null | null |
diff --git a/core/src/main/java/org/jclouds/rest/binders/BindAsHostPrefix.java b/core/src/main/java/org/jclouds/rest/binders/BindAsHostPrefix.java
index ed3d80c1a..5886a3a92 100644
--- a/core/src/main/java/org/jclouds/rest/binders/BindAsHostPrefix.java
+++ b/core/src/main/java/org/jclouds/rest/binders/BindAsHostPrefix.java
@@ -1,60 +1,61 @@
/**
*
* Copyright (C) 2010 Cloud Conscious, LLC. <[email protected]>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.jclouds.rest.binders;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
-import static com.google.common.net.InternetDomainName.isValid;
+import static com.google.common.net.InternetDomainName.fromLenient;
+import static com.google.common.net.InternetDomainName.isValidLenient;
import javax.inject.Inject;
import javax.inject.Provider;
import javax.inject.Singleton;
import javax.ws.rs.core.UriBuilder;
import org.jclouds.http.HttpRequest;
import org.jclouds.rest.Binder;
import com.google.common.net.InternetDomainName;
/**
*
* @author Adrian Cole
*/
@Singleton
public class BindAsHostPrefix implements Binder {
private final Provider<UriBuilder> uriBuilderProvider;
@Inject
public BindAsHostPrefix(Provider<UriBuilder> uriBuilderProvider) {
this.uriBuilderProvider = uriBuilderProvider;
}
@Override
@SuppressWarnings("unchecked")
public <R extends HttpRequest> R bindToRequest(R request, Object payload) {
checkNotNull(payload, "hostprefix");
- checkArgument(isValid(request.getEndpoint().getHost()), "this is only valid for hostnames: " + request);
+ checkArgument(isValidLenient(request.getEndpoint().getHost()), "this is only valid for hostnames: " + request);
UriBuilder builder = uriBuilderProvider.get().uri(request.getEndpoint());
- InternetDomainName name = InternetDomainName.from(request.getEndpoint().getHost()).child(payload.toString());
+ InternetDomainName name = fromLenient(request.getEndpoint().getHost()).child(payload.toString());
builder.host(name.name());
return (R) request.toBuilder().endpoint(builder.build()).build();
}
}
| false | false | null | null |
diff --git a/core/src/visad/trunk/Gridded1DDoubleSet.java b/core/src/visad/trunk/Gridded1DDoubleSet.java
index 2621ae667..9c06665fb 100644
--- a/core/src/visad/trunk/Gridded1DDoubleSet.java
+++ b/core/src/visad/trunk/Gridded1DDoubleSet.java
@@ -1,753 +1,752 @@
//
// Gridded1DDoubleSet.java
//
/*
VisAD system for interactive analysis and visualization of numerical
data. Copyright (C) 1996 - 2002 Bill Hibbard, Curtis Rueden, Tom
Rink, Dave Glowacki, Steve Emmerson, Tom Whittaker, Don Murray, and
Tommy Jasmin.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 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
Library General Public License for more details.
You should have received a copy of the GNU Library 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 visad;
import java.lang.ref.WeakReference;
import java.util.WeakHashMap;
/**
Gridded1DDoubleSet is a Gridded1DSet with double-precision samples.<P>
*/
public class Gridded1DDoubleSet extends Gridded1DSet
implements GriddedDoubleSet {
double[] Low = new double[1];
double[] Hi = new double[1];
double LowX, HiX;
double[][] Samples;
/**
* A canonicalizing cache of previously-created instances. Because instances
* are immutable, a cache can be used to reduce memory usage by ensuring
* that each instance is truely unique. By implementing the cache using a
* {@link WeakHashMap}, this can be accomplished without the technique itself
* adversely affecting memory usage.
*/
private static final WeakHashMap cache = new WeakHashMap();
// Overridden Gridded1DSet constructors (float[][])
/** a 1-D sequence with no regular interval with null errors,
CoordinateSystem and Units are defaults from type */
public Gridded1DDoubleSet(MathType type, float[][] samples, int lengthX)
throws VisADException {
this(type, Set.floatToDouble(samples), lengthX, null, null, null, true);
}
public Gridded1DDoubleSet(MathType type, float[][] samples, int lengthX,
CoordinateSystem coord_sys, Unit[] units,
ErrorEstimate[] errors) throws VisADException {
this(type, Set.floatToDouble(samples), lengthX,
coord_sys, units, errors, true);
}
/** a 1-D sorted sequence with no regular interval. samples array
is organized float[1][number_of_samples] where lengthX =
number_of_samples. samples must be sorted (either increasing
or decreasing). coordinate_system and units must be compatible
with defaults for type, or may be null. errors may be null */
public Gridded1DDoubleSet(MathType type, float[][] samples, int lengthX,
CoordinateSystem coord_sys, Unit[] units,
ErrorEstimate[] errors, boolean copy)
throws VisADException {
this(type, Set.floatToDouble(samples), lengthX,
coord_sys, units, errors, copy);
}
// Corresponding Gridded1DDoubleSet constructors (double[][])
/** a 1-D sequence with no regular interval with null errors,
CoordinateSystem and Units are defaults from type */
public Gridded1DDoubleSet(MathType type, double[][] samples, int lengthX)
throws VisADException {
this(type, samples, lengthX, null, null, null, true);
}
public Gridded1DDoubleSet(MathType type, double[][] samples, int lengthX,
CoordinateSystem coord_sys, Unit[] units,
ErrorEstimate[] errors) throws VisADException {
this(type, samples, lengthX, coord_sys, units, errors, true);
}
/** a 1-D sorted sequence with no regular interval. samples array
is organized double[1][number_of_samples] where lengthX =
number_of_samples. samples must be sorted (either increasing
or decreasing). coordinate_system and units must be compatible
with defaults for type, or may be null. errors may be null */
public Gridded1DDoubleSet(MathType type, double[][] samples, int lengthX,
CoordinateSystem coord_sys, Unit[] units,
ErrorEstimate[] errors, boolean copy)
throws VisADException {
super(type, null, lengthX, coord_sys, units, errors, copy);
if (samples == null) {
throw new SetException("Gridded1DDoubleSet: samples are null");
}
init_doubles(samples, copy);
LowX = Low[0];
HiX = Hi[0];
LengthX = Lengths[0];
if (Samples != null && Lengths[0] > 1) {
// samples consistency test
for (int i=0; i<Length; i++) {
if (Samples[0][i] != Samples[0][i]) {
throw new SetException(
"Gridded1DDoubleSet: samples values may not be missing");
}
}
Ascending = (Samples[0][LengthX-1] > Samples[0][0]);
if (Ascending) {
for (int i=1; i<LengthX; i++) {
if (Samples[0][i] < Samples[0][i-1]) {
throw new SetException(
"Gridded1DDoubleSet: samples do not form a valid grid ("+i+")");
}
}
}
else { // !Ascending
for (int i=1; i<LengthX; i++) {
if (Samples[0][i] > Samples[0][i-1]) {
throw new SetException(
"Gridded1DDoubleSet: samples do not form a valid grid ("+i+")");
}
}
}
}
}
/**
* Returns an instance of this class. This method uses a weak cache of
* previously-created instances to reduce memory usage.
*
* @param type The type of the set. Must be a {@link
* RealType} or a single-component {@link
* RealTupleType} or {@link SetType}.
* @param samples The values in the set.
* <code>samples[i]</code> is the value of
* the ith sample point. Must be sorted (either
* increasing or decreasing). May be
* <code>null</code>. The array is not copied, so
* either don't modify it or clone it first.
* @param coord_sys The coordinate system for this, particular, set.
* Must be compatible with the default coordinate
* system. May be <code>null</code>.
* @param unit The unit for the samples. Must be compatible
* with the default unit. May be
* <code>null</code>.
* @param error The error estimate of the samples. May be
* <code>null</code>.
*/
public static synchronized Gridded1DDoubleSet create(
MathType type,
double[] samples,
CoordinateSystem coordSys,
Unit unit,
ErrorEstimate error)
throws VisADException
{
Gridded1DDoubleSet newSet =
new Gridded1DDoubleSet(
type, new double[][] {samples}, samples.length, coordSys,
new Unit[] {unit}, new ErrorEstimate[] {error}, false);
WeakReference ref = (WeakReference)cache.get(newSet);
if (ref == null)
{
/*
* The new instance is unique (any and all previously-created identical
* instances no longer exist).
*
* A WeakReference is used in the following because values of a
* WeakHashMap aren't "weak" themselves and must not strongly reference
* their associated keys either directly or indirectly.
*/
cache.put(newSet, new WeakReference(newSet));
}
else
{
/*
* The new instance is a duplicate of a previously-created one.
*/
Gridded1DDoubleSet oldSet = (Gridded1DDoubleSet)ref.get();
if (oldSet == null)
{
/* The previous instance no longer exists. Save the new instance. */
cache.put(newSet, new WeakReference(newSet));
}
else
{
/* The previous instance still exists. Reuse it to save memory. */
newSet = oldSet;
}
}
return newSet;
}
// Overridden Gridded1DSet methods (float[][])
public float[][] getSamples() throws VisADException {
return getSamples(true);
}
public float[][] getSamples(boolean copy) throws VisADException {
return Set.doubleToFloat(Samples);
}
/** convert an array of 1-D indices to an array of values in
R^DomainDimension */
public float[][] indexToValue(int[] index) throws VisADException {
return Set.doubleToFloat(indexToDouble(index));
}
/**
* Convert an array of values in R^DomainDimension to an array of
* 1-D indices. This Gridded1DDoubleSet must have at least two points in the
* set.
* @param value An array of coordinates. <code>value[i][j]
* <code> contains the <code>i</code>th component of the
* <code>j</code>th point.
* @return Indices of nearest points. RETURN_VALUE<code>[i]</code>
* will contain the index of the point in the set closest
* to <code>value[][i]</code> or <code>-1</code> if
* <code>value[][i]</code> lies outside the set.
*/
public int[] valueToIndex(float[][] value) throws VisADException {
return doubleToIndex(Set.floatToDouble(value));
}
public float[][] gridToValue(float[][] grid) throws VisADException {
return Set.doubleToFloat(gridToDouble(Set.floatToDouble(grid)));
}
/** transform an array of values in R^DomainDimension to an array
of non-integer grid coordinates */
public float[][] valueToGrid(float[][] value) throws VisADException {
return Set.doubleToFloat(doubleToGrid(Set.floatToDouble(value)));
}
/** for each of an array of values in R^DomainDimension, compute an array
of 1-D indices and an array of weights, to be used for interpolation;
indices[i] and weights[i] are null if i-th value is outside grid
(i.e., if no interpolation is possible) */
public void valueToInterp(float[][] value, int[][] indices,
float[][] weights) throws VisADException
{
int len = weights.length;
double[][] w = new double[len][];
- // for (int i=0; i<len; i++) w[i] = new double[weights[i].length];
doubleToInterp(Set.floatToDouble(value), indices, w);
for (int i=0; i<len; i++) {
if (w[i] != null) {
weights[i] = new float[w[i].length];
for (int j=0; j<w[i].length; j++) {
weights[i][j] = (float) w[i][j];
}
}
}
}
public float getLowX() {
return (float) LowX;
}
public float getHiX() {
return (float) HiX;
}
// Corresponding Gridded1DDoubleSet methods (double[][])
public double[][] getDoubles() throws VisADException {
return getDoubles(true);
}
public double[][] getDoubles(boolean copy) throws VisADException {
return copy ? Set.copyDoubles(Samples) : Samples;
}
/** convert an array of 1-D indices to an array of values in
R^DomainDimension */
public double[][] indexToDouble(int[] index) throws VisADException {
int length = index.length;
if (Samples == null) {
// not used - over-ridden by Linear1DSet.indexToValue
double[][] grid = new double[ManifoldDimension][length];
for (int i=0; i<length; i++) {
if (0 <= index[i] && index[i] < Length) {
grid[0][i] = (double) index[i];
}
else {
grid[0][i] = -1;
}
}
return gridToDouble(grid);
}
else {
double[][] values = new double[1][length];
for (int i=0; i<length; i++) {
if (0 <= index[i] && index[i] < Length) {
values[0][i] = Samples[0][index[i]];
}
else {
values[0][i] = Double.NaN;
}
}
return values;
}
}
public int[] doubleToIndex(double[][] value) throws VisADException {
if (value.length != DomainDimension) {
throw new SetException("Gridded1DDoubleSet.doubleToIndex: value dimension " +
value.length + " not equal to Domain dimension " +
DomainDimension);
}
int length = value[0].length;
int[] index = new int[length];
double[][] grid = doubleToGrid(value);
double[] grid0 = grid[0];
double g;
for (int i=0; i<length; i++) {
g = grid0[i];
index[i] = Double.isNaN(g) ? -1 : ((int) (g + 0.5));
}
return index;
}
/** transform an array of non-integer grid coordinates to an array
of values in R^DomainDimension */
public double[][] gridToDouble(double[][] grid) throws VisADException {
if (grid.length < DomainDimension) {
throw new SetException("Gridded1DDoubleSet.gridToDouble: grid dimension " +
grid.length + " not equal to Domain dimension " +
DomainDimension);
}
if (Lengths[0] < 2) {
throw new SetException("Gridded1DDoubleSet.gridToDouble: " +
"requires all grid dimensions to be > 1");
}
int length = grid[0].length;
double[][] value = new double[1][length];
for (int i=0; i<length; i++) {
// let g be the current grid coordinate
double g = grid[0][i];
if ( (g < -0.5) || (g > LengthX-0.5) ) {
value[0][i] = Double.NaN;
continue;
}
// calculate closest integer variable
int ig;
if (g < 0) ig = 0;
else if (g >= LengthX-1) ig = LengthX - 2;
else ig = (int) g;
double A = g - ig; // distance variable
// do the linear interpolation
value[0][i] = (1-A)*Samples[0][ig] + A*Samples[0][ig+1];
}
return value;
}
// WLH 6 Dec 2001
private int ig = -1;
/** transform an array of values in R^DomainDimension to an array
of non-integer grid coordinates */
public double[][] doubleToGrid(double[][] value) throws VisADException {
if (value.length < DomainDimension) {
throw new SetException("Gridded1DDoubleSet.doubleToGrid: value dimension " +
value.length + " not equal to Domain dimension " +
DomainDimension);
}
if (Lengths[0] < 2) {
throw new SetException("Gridded1DDoubleSet.doubleToGrid: " +
"requires all grid dimensions to be > 1");
}
double[] vals = value[0];
int length = vals.length;
double[] samps = Samples[0];
double[][] grid = new double[1][length];
/* WLH 6 Dec 2001
int ig = (LengthX - 1)/2;
*/
// use value from last call as first guess, if reasonable
if (ig < 0 || ig >= LengthX) {
ig = (LengthX - 1)/2;
}
for (int i=0; i<length; i++) {
if (Double.isNaN(vals[i])) grid[0][i] = Double.NaN;
else {
int lower = 0;
int upper = LengthX-1;
while (lower < upper) {
if ((vals[i] - samps[ig]) * (vals[i] - samps[ig+1]) <= 0) break;
if (Ascending ? samps[ig+1] < vals[i] : samps[ig+1] > vals[i]) {
lower = ig+1;
}
else if (Ascending ? samps[ig] > vals[i] : samps[ig] < vals[i]) {
upper = ig;
}
if (lower < upper) ig = (lower + upper) / 2;
}
// Newton's method
double solv = ig + (vals[i] - samps[ig]) / (samps[ig+1] - samps[ig]);
if (solv > -0.5 && solv < LengthX - 0.5) grid[0][i] = solv;
else {
grid[0][i] = Double.NaN;
// next guess should be in the middle if previous value was missing
ig = (LengthX - 1)/2;
}
}
}
return grid;
}
/** for each of an array of values in R^DomainDimension, compute an array
of 1-D indices and an array of weights, to be used for interpolation;
indices[i] and weights[i] are null if i-th value is outside grid
(i.e., if no interpolation is possible) */
public void doubleToInterp(double[][] value, int[][] indices,
double[][] weights) throws VisADException
{
if (value.length != DomainDimension) {
throw new SetException("Gridded1DDoubleSet.doubleToInterp: value dimension " +
value.length + " not equal to Domain dimension " +
DomainDimension);
}
int length = value[0].length; // number of values
if (indices.length != length) {
throw new SetException("Gridded1DDoubleinearLatLonSet.doubleToInterp: indices length " +
indices.length +
" doesn't match value[0] length " +
value[0].length);
}
if (weights.length != length) {
throw new SetException("Gridded1DDoubleSet.doubleToInterp: weights length " +
weights.length +
" doesn't match value[0] length " +
value[0].length);
}
// convert value array to grid coord array
double[][] grid = doubleToGrid(value);
int i, j, k; // loop indices
int lis; // temporary length of is & cs
int length_is; // final length of is & cs, varies by i
int isoff; // offset along one grid dimension
double a, b; // weights along one grid dimension; a + b = 1.0
int[] is; // array of indices, becomes part of indices
double[] cs; // array of coefficients, become part of weights
int base; // base index, as would be returned by valueToIndex
int[] l = new int[ManifoldDimension]; // integer 'factors' of base
// fractions with l; -0.5 <= c <= 0.5
double[] c = new double[ManifoldDimension];
// array of index offsets by grid dimension
int[] off = new int[ManifoldDimension];
off[0] = 1;
for (j=1; j<ManifoldDimension; j++) off[j] = off[j-1] * Lengths[j-1];
for (i=0; i<length; i++) {
// compute length_is, base, l & c
length_is = 1;
if (Double.isNaN(grid[ManifoldDimension-1][i])) {
base = -1;
}
else {
l[ManifoldDimension-1] = (int) (grid[ManifoldDimension-1][i] + 0.5);
// WLH 23 Dec 99
if (l[ManifoldDimension-1] == Lengths[ManifoldDimension-1]) {
l[ManifoldDimension-1]--;
}
c[ManifoldDimension-1] = grid[ManifoldDimension-1][i] -
((double) l[ManifoldDimension-1]);
if (!((l[ManifoldDimension-1] == 0 && c[ManifoldDimension-1] <= 0.0) ||
(l[ManifoldDimension-1] == Lengths[ManifoldDimension-1] - 1 &&
c[ManifoldDimension-1] >= 0.0))) {
// only interp along ManifoldDimension-1
// if between two valid grid coords
length_is *= 2;
}
base = l[ManifoldDimension-1];
}
for (j=ManifoldDimension-2; j>=0 && base>=0; j--) {
if (Double.isNaN(grid[j][i])) {
base = -1;
}
else {
l[j] = (int) (grid[j][i] + 0.5);
if (l[j] == Lengths[j]) l[j]--; // WLH 23 Dec 99
c[j] = grid[j][i] - ((double) l[j]);
if (!((l[j] == 0 && c[j] <= 0.0) ||
(l[j] == Lengths[j] - 1 && c[j] >= 0.0))) {
// only interp along dimension j if between two valid grid coords
length_is *= 2;
}
base = l[j] + Lengths[j] * base;
}
}
if (base < 0) {
// value is out of grid so return null
is = null;
cs = null;
}
else {
// create is & cs of proper length, and init first element
is = new int[length_is];
cs = new double[length_is];
is[0] = base;
cs[0] = 1.0f;
lis = 1;
for (j=0; j<ManifoldDimension; j++) {
if (!((l[j] == 0 && c[j] <= 0.0) ||
(l[j] == Lengths[j] - 1 && c[j] >= 0.0))) {
// only interp along dimension j if between two valid grid coords
if (c[j] >= 0.0) {
// grid coord above base
isoff = off[j];
a = 1.0f - c[j];
b = c[j];
}
else {
// grid coord below base
isoff = -off[j];
a = 1.0f + c[j];
b = -c[j];
}
// double is & cs; adjust new offsets; split weights
for (k=0; k<lis; k++) {
is[k+lis] = is[k] + isoff;
cs[k+lis] = cs[k] * b;
cs[k] *= a;
}
lis *= 2;
}
}
}
indices[i] = is;
weights[i] = cs;
}
}
public double getDoubleLowX() {
return LowX;
}
public double getDoubleHiX() {
return HiX;
}
// Miscellaneous Set methods that must be overridden
// (this code is duplicated throughout all *DoubleSet classes)
void init_doubles(double[][] samples, boolean copy)
throws VisADException {
if (samples.length != DomainDimension) {
throw new SetException("Gridded1DDoubleSet.init_doubles:" +
" samples dimension " + samples.length +
" not equal to Domain dimension " +
DomainDimension);
}
if (Length == 0) {
// Length set in init_lengths, but not called for IrregularSet
Length = samples[0].length;
}
else {
if (Length != samples[0].length) {
throw new SetException("Gridded1DDoubleSet.init_doubles: samples[0] length " +
samples[0].length +
" doesn't match expected length " + Length);
}
}
// MEM
if (copy) {
Samples = new double[DomainDimension][Length];
}
else {
Samples = samples;
}
for (int j=0; j<DomainDimension; j++) {
if (samples[j].length != Length) {
throw new SetException("Gridded1DDoubleSet.init_doubles: samples[" + j +
"] length " + samples[0].length +
" doesn't match expected length " + Length);
}
double[] samplesJ = samples[j];
double[] SamplesJ = Samples[j];
if (copy) {
System.arraycopy(samplesJ, 0, SamplesJ, 0, Length);
}
Low[j] = Double.POSITIVE_INFINITY;
Hi[j] = Double.NEGATIVE_INFINITY;
double sum = 0.0f;
for (int i=0; i<Length; i++) {
if (SamplesJ[i] == SamplesJ[i] && !Double.isInfinite(SamplesJ[i])) {
if (SamplesJ[i] < Low[j]) Low[j] = SamplesJ[i];
if (SamplesJ[i] > Hi[j]) Hi[j] = SamplesJ[i];
}
else {
SamplesJ[i] = Double.NaN;
}
sum += SamplesJ[i];
}
if (SetErrors[j] != null ) {
SetErrors[j] =
new ErrorEstimate(SetErrors[j].getErrorValue(), sum / Length,
Length, SetErrors[j].getUnit());
}
super.Low[j] = (float) Low[j];
super.Hi[j] = (float) Hi[j];
}
}
public void cram_missing(boolean[] range_select) {
int n = Math.min(range_select.length, Samples[0].length);
for (int i=0; i<n; i++) {
if (!range_select[i]) Samples[0][i] = Double.NaN;
}
}
public boolean isMissing() {
return (Samples == null);
}
public boolean equals(Object set) {
if (!(set instanceof Gridded1DDoubleSet) || set == null) return false;
if (this == set) return true;
if (testNotEqualsCache((Set) set)) return false;
if (testEqualsCache((Set) set)) return true;
if (!equalUnitAndCS((Set) set)) return false;
try {
int i, j;
if (DomainDimension != ((Gridded1DDoubleSet) set).getDimension() ||
ManifoldDimension !=
((Gridded1DDoubleSet) set).getManifoldDimension() ||
Length != ((Gridded1DDoubleSet) set).getLength()) return false;
for (j=0; j<ManifoldDimension; j++) {
if (Lengths[j] != ((Gridded1DDoubleSet) set).getLength(j)) {
return false;
}
}
// Sets are immutable, so no need for 'synchronized'
double[][] samples = ((Gridded1DDoubleSet) set).getDoubles(false);
if (Samples != null && samples != null) {
for (j=0; j<DomainDimension; j++) {
for (i=0; i<Length; i++) {
if (Samples[j][i] != samples[j][i]) {
addNotEqualsCache((Set) set);
return false;
}
}
}
}
else {
double[][] this_samples = getDoubles(false);
if (this_samples == null) {
if (samples != null) {
return false;
}
} else if (samples == null) {
return false;
} else {
for (j=0; j<DomainDimension; j++) {
for (i=0; i<Length; i++) {
if (this_samples[j][i] != samples[j][i]) {
addNotEqualsCache((Set) set);
return false;
}
}
}
}
}
addEqualsCache((Set) set);
return true;
}
catch (VisADException e) {
return false;
}
}
/**
* Returns the hash code of this instance. {@link Object#hashCode()} should be
* overridden whenever {@link Object#equals(Object)} is.
* @return The hash code of this instance (includes the
* values).
*/
public int hashCode()
{
if (!hashCodeSet)
{
hashCode = unitAndCSHashCode();
hashCode ^= DomainDimension ^ ManifoldDimension ^ Length;
for (int j=0; j<ManifoldDimension; j++)
hashCode ^= Lengths[j];
if (Samples != null)
for (int j=0; j<DomainDimension; j++)
for (int i=0; i<Length; i++)
hashCode ^= new Double(Samples[j][i]).hashCode();
hashCodeSet = true;
}
return hashCode;
}
/**
* Clones this instance.
*
* @return A clone of this instance.
*/
public Object clone() {
Gridded1DDoubleSet clone = (Gridded1DDoubleSet)super.clone();
if (Samples != null) {
/*
* The Samples array is cloned because getDoubles(false) allows clients
* to manipulate the array and the general clone() contract forbids
* cross-clone contamination.
*/
clone.Samples = (double[][])Samples.clone();
for (int i = 0; i < Samples.length; i++)
clone.Samples[i] = (double[])Samples[i].clone();
}
return clone;
}
public Object cloneButType(MathType type) throws VisADException {
return new Gridded1DDoubleSet(type, Samples, Length,
DomainCoordinateSystem, SetUnits, SetErrors);
}
}
diff --git a/core/src/visad/trunk/Gridded2DDoubleSet.java b/core/src/visad/trunk/Gridded2DDoubleSet.java
index e42956e24..75ac969e7 100644
--- a/core/src/visad/trunk/Gridded2DDoubleSet.java
+++ b/core/src/visad/trunk/Gridded2DDoubleSet.java
@@ -1,877 +1,881 @@
//
// Gridded2DDoubleSet.java
//
/*
VisAD system for interactive analysis and visualization of numerical
data. Copyright (C) 1996 - 2002 Bill Hibbard, Curtis Rueden, Tom
Rink, Dave Glowacki, Steve Emmerson, Tom Whittaker, Don Murray, and
Tommy Jasmin.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 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
Library General Public License for more details.
You should have received a copy of the GNU Library 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 visad;
/**
Gridded2DDoubleSet is a Gridded2DSet with double-precision samples.<P>
*/
public class Gridded2DDoubleSet extends Gridded2DSet
implements GriddedDoubleSet {
double[] Low = new double[2];
double[] Hi = new double[2];
double LowX, HiX, LowY, HiY;
double[][] Samples;
// Overridden Gridded2DSet constructors (float[][])
/** a 2-D set whose topology is a lengthX x lengthY grid, with
null errors, CoordinateSystem and Units are defaults from type */
public Gridded2DDoubleSet(MathType type, float[][] samples, int lengthX, int lengthY)
throws VisADException {
this(type, Set.floatToDouble(samples), lengthX, lengthY, null, null, null, true);
}
/** a 2-D set whose topology is a lengthX x lengthY grid;
samples array is organized float[2][number_of_samples] where
lengthX * lengthY = number_of_samples; samples must form a
non-degenerate 2-D grid (no bow-tie-shaped grid boxes); the
X component increases fastest in the second index of samples;
coordinate_system and units must be compatible with defaults
for type, or may be null; errors may be null */
public Gridded2DDoubleSet(MathType type, float[][] samples, int lengthX, int lengthY,
CoordinateSystem coord_sys, Unit[] units,
ErrorEstimate[] errors) throws VisADException {
this(type, Set.floatToDouble(samples), lengthX, lengthY, coord_sys,
units, errors, true);
}
Gridded2DDoubleSet(MathType type, float[][] samples, int lengthX, int lengthY,
CoordinateSystem coord_sys, Unit[] units,
ErrorEstimate[] errors, boolean copy)
throws VisADException {
this(type, Set.floatToDouble(samples), lengthX, lengthY, coord_sys,
units, errors, copy);
}
/** a 2-D set with manifold dimension = 1, with null errors,
CoordinateSystem and Units are defaults from type */
public Gridded2DDoubleSet(MathType type, float[][] samples, int lengthX)
throws VisADException {
this(type, Set.floatToDouble(samples), lengthX, null, null, null, true);
}
/** a 2-D set with manifold dimension = 1; samples array is
organized float[2][number_of_samples] where lengthX =
number_of_samples; no geometric constraint on samples;
coordinate_system and units must be compatible with defaults
for type, or may be null; errors may be null */
public Gridded2DDoubleSet(MathType type, float[][] samples, int lengthX,
CoordinateSystem coord_sys, Unit[] units,
ErrorEstimate[] errors) throws VisADException {
this(type, Set.floatToDouble(samples), lengthX, coord_sys, units, errors, true);
}
public Gridded2DDoubleSet(MathType type, float[][] samples, int lengthX,
CoordinateSystem coord_sys, Unit[] units,
ErrorEstimate[] errors, boolean copy)
throws VisADException {
this(type, Set.floatToDouble(samples), lengthX, coord_sys, units, errors, copy);
}
// Corresponding Gridded2DDoubleSet constructors (double[][])
/** a 2-D set whose topology is a lengthX x lengthY grid, with
null errors, CoordinateSystem and Units are defaults from type */
public Gridded2DDoubleSet(MathType type, double[][] samples, int lengthX, int lengthY)
throws VisADException {
this(type, samples, lengthX, lengthY, null, null, null, true);
}
/** a 2-D set whose topology is a lengthX x lengthY grid;
samples array is organized double[2][number_of_samples] where
lengthX * lengthY = number_of_samples; samples must form a
non-degenerate 2-D grid (no bow-tie-shaped grid boxes); the
X component increases fastest in the second index of samples;
coordinate_system and units must be compatible with defaults
for type, or may be null; errors may be null */
public Gridded2DDoubleSet(MathType type, double[][] samples, int lengthX, int lengthY,
CoordinateSystem coord_sys, Unit[] units,
ErrorEstimate[] errors) throws VisADException {
this(type, samples, lengthX, lengthY, coord_sys, units, errors, true);
}
public Gridded2DDoubleSet(MathType type, double[][] samples, int lengthX,
int lengthY, CoordinateSystem coord_sys, Unit[] units,
ErrorEstimate[] errors, boolean copy)
throws VisADException {
super(type, null, lengthX, lengthY, coord_sys, units, errors, copy);
if (samples == null) {
throw new SetException("Gridded2DDoubleSet: samples are null");
}
init_doubles(samples, copy);
LowX = Low[0];
HiX = Hi[0];
LengthX = Lengths[0];
LowY = Low[1];
HiY = Hi[1];
LengthY = Lengths[1];
if (Samples != null && Lengths[0] > 1 && Lengths[1] > 1) {
for (int i=0; i<Length; i++) {
if (Samples[0][i] != Samples[0][i]) {
throw new SetException(
"Gridded2DDoubleSet: samples values may not be missing");
}
}
// Samples consistency test
Pos = ( (Samples[0][1]-Samples[0][0])
*(Samples[1][LengthX+1]-Samples[1][1])
- (Samples[1][1]-Samples[1][0])
*(Samples[0][LengthX+1]-Samples[0][1]) > 0);
for (int j=0; j<LengthY-1; j++) {
for (int i=0; i<LengthX-1; i++) {
double[] v00 = new double[2];
double[] v10 = new double[2];
double[] v01 = new double[2];
double[] v11 = new double[2];
for (int v=0; v<2; v++) {
v00[v] = Samples[v][j*LengthX+i];
v10[v] = Samples[v][j*LengthX+i+1];
v01[v] = Samples[v][(j+1)*LengthX+i];
v11[v] = Samples[v][(j+1)*LengthX+i+1];
}
if ( ( (v10[0]-v00[0])*(v11[1]-v10[1])
- (v10[1]-v00[1])*(v11[0]-v10[0]) > 0 != Pos)
|| ( (v11[0]-v10[0])*(v01[1]-v11[1])
- (v11[1]-v10[1])*(v01[0]-v11[0]) > 0 != Pos)
|| ( (v01[0]-v11[0])*(v00[1]-v01[1])
- (v01[1]-v11[1])*(v00[0]-v01[0]) > 0 != Pos)
|| ( (v00[0]-v01[0])*(v10[1]-v00[1])
- (v00[1]-v01[1])*(v10[0]-v00[0]) > 0 != Pos) ) {
throw new SetException(
"Gridded2DDoubleSet: samples do not form a valid grid ("+i+","+j+")");
}
}
}
}
}
/** a 2-D set with manifold dimension = 1, with null errors,
CoordinateSystem and Units are defaults from type */
public Gridded2DDoubleSet(MathType type, double[][] samples, int lengthX)
throws VisADException {
this(type, samples, lengthX, null, null, null);
}
/** a 2-D set with manifold dimension = 1; samples array is
organized double[2][number_of_samples] where lengthX =
number_of_samples; no geometric constraint on samples;
coordinate_system and units must be compatible with defaults
for type, or may be null; errors may be null */
public Gridded2DDoubleSet(MathType type, double[][] samples, int lengthX,
CoordinateSystem coord_sys, Unit[] units,
ErrorEstimate[] errors) throws VisADException {
this(type, samples, lengthX, coord_sys, units, errors, true);
}
public Gridded2DDoubleSet(MathType type, double[][] samples, int lengthX,
CoordinateSystem coord_sys, Unit[] units,
ErrorEstimate[] errors, boolean copy)
throws VisADException {
super(type, null, lengthX, coord_sys, units, errors, copy);
if (samples == null) {
throw new SetException("Gridded2DDoubleSet: samples are null");
}
init_doubles(samples, copy);
LowX = Low[0];
HiX = Hi[0];
LengthX = Lengths[0];
LowY = Low[1];
HiY = Hi[1];
// no Samples consistency test
}
//END
// Overridden Gridded2DSet methods (float[][])
public float[][] getSamples() throws VisADException {
return getSamples(true);
}
public float[][] getSamples(boolean copy) throws VisADException {
return Set.doubleToFloat(Samples);
}
/** convert an array of 1-D indices to an array of values in R^DomainDimension */
public float[][] indexToValue(int[] index) throws VisADException {
return Set.doubleToFloat(indexToDouble(index));
}
/** convert an array of values in R^DomainDimension to an array of 1-D indices */
public int[] valueToIndex(float[][] value) throws VisADException {
return doubleToIndex(Set.floatToDouble(value));
}
/** transform an array of non-integer grid coordinates to an array
of values in R^DomainDimension */
public float[][] gridToValue(float[][] grid) throws VisADException {
return Set.doubleToFloat(gridToDouble(Set.floatToDouble(grid)));
}
/** transform an array of values in R^DomainDimension to an array
of non-integer grid coordinates */
public float[][] valueToGrid(float[][] value) throws VisADException {
return Set.doubleToFloat(doubleToGrid(Set.floatToDouble(value)));
}
/** for each of an array of values in R^DomainDimension, compute an array
of 1-D indices and an array of weights, to be used for interpolation;
indices[i] and weights[i] are null if i-th value is outside grid
(i.e., if no interpolation is possible) */
public void valueToInterp(float[][] value, int[][] indices,
float[][] weights) throws VisADException
{
int len = weights.length;
double[][] w = new double[len][];
- for (int i=0; i<len; i++) w[i] = new double[weights[i].length];
doubleToInterp(Set.floatToDouble(value), indices, w);
for (int i=0; i<len; i++) {
- System.arraycopy(w[i], 0, weights[i], 0, w.length);
+ if (w[i] != null) {
+ weights[i] = new float[w[i].length];
+ for (int j=0; j<w[i].length; j++) {
+ weights[i][j] = (float) w[i][j];
+ }
+ }
}
}
// Corresponding Gridded2DDoubleSet methods (double[][])
public double[][] getDoubles() throws VisADException {
return getDoubles(true);
}
public double[][] getDoubles(boolean copy) throws VisADException {
return copy ? Set.copyDoubles(Samples) : Samples;
}
/** convert an array of 1-D indices to an array of values in
R^DomainDimension */
public double[][] indexToDouble(int[] index) throws VisADException {
int length = index.length;
if (Samples == null) {
// not used - over-ridden by Linear2DSet.indexToValue
int indexX, indexY;
double[][] grid = new double[ManifoldDimension][length];
for (int i=0; i<length; i++) {
if (0 <= index[i] && index[i] < Length) {
indexX = index[i] % LengthX;
indexY = index[i] / LengthX;
}
else {
indexX = -1;
indexY = -1;
}
grid[0][i] = indexX;
grid[1][i] = indexY;
}
return gridToDouble(grid);
}
else {
double[][] values = new double[2][length];
for (int i=0; i<length; i++) {
if (0 <= index[i] && index[i] < Length) {
values[0][i] = Samples[0][index[i]];
values[1][i] = Samples[1][index[i]];
}
else {
values[0][i] = Double.NaN;
values[1][i] = Double.NaN;
}
}
return values;
}
}
/** convert an array of values in R^DomainDimension to an array of 1-D indices */
public int[] doubleToIndex(double[][] value) throws VisADException {
if (value.length != DomainDimension) {
throw new SetException("Gridded2DDoubleSet.doubleToIndex: value dimension " +
value.length + " not equal to Domain dimension " +
DomainDimension);
}
int length = value[0].length;
int[] index = new int[length];
double[][] grid = doubleToGrid(value);
double[] grid0 = grid[0];
double[] grid1 = grid[1];
double g0, g1;
for (int i=0; i<length; i++) {
g0 = grid0[i];
g1 = grid1[i];
/* WLH 24 Oct 97
index[i] = (Double.isNaN(g0) || Double.isNaN(g1)) ? -1 :
*/
// test for missing
index[i] = (g0 != g0 || g1 != g1) ? -1 :
((int) (g0 + 0.5)) + LengthX * ((int) (g1 + 0.5));
}
return index;
}
/** transform an array of non-integer grid coordinates to an array
of values in R^DomainDimension */
public double[][] gridToDouble(double[][] grid) throws VisADException {
if (grid.length != ManifoldDimension) {
throw new SetException("Gridded2DDoubleSet.gridToDouble: bad dimension");
}
if (ManifoldDimension < 2) {
throw new SetException("Gridded2DDoubleSet.gridToDouble: ManifoldDimension " +
"must be 2");
}
if (Lengths[0] < 2 || Lengths[1] < 2) {
throw new SetException("Gridded2DDoubleSet.gridToDouble: requires all grid " +
"dimensions to be > 1");
}
// avoid any ArrayOutOfBounds exceptions by taking the shortest length
int length = Math.min(grid[0].length, grid[1].length);
double[][] value = new double[2][length];
for (int i=0; i<length; i++) {
// let gx and gy by the current grid values
double gx = grid[0][i];
double gy = grid[1][i];
if ( (gx < -0.5) || (gy < -0.5) ||
(gx > LengthX-0.5) || (gy > LengthY-0.5) ) {
value[0][i] = value[1][i] = Double.NaN;
continue;
}
// calculate closest integer variables
int igx = (int) gx;
int igy = (int) gy;
if (igx < 0) igx = 0;
if (igx > LengthX-2) igx = LengthX-2;
if (igy < 0) igy = 0;
if (igy > LengthY-2) igy = LengthY-2;
// set up conversion to 1D Samples array
int[][] s = { {LengthX*igy+igx, // (0, 0)
LengthX*(igy+1)+igx}, // (0, 1)
{LengthX*igy+igx+1, // (1, 0)
LengthX*(igy+1)+igx+1} }; // (1, 1)
if (gx+gy-igx-igy-1 <= 0) {
// point is in LOWER triangle
for (int j=0; j<2; j++) {
value[j][i] = Samples[j][s[0][0]]
+ (gx-igx)*(Samples[j][s[1][0]]-Samples[j][s[0][0]])
+ (gy-igy)*(Samples[j][s[0][1]]-Samples[j][s[0][0]]);
}
}
else {
// point is in UPPER triangle
for (int j=0; j<2; j++) {
value[j][i] = Samples[j][s[1][1]]
+ (1+igx-gx)*(Samples[j][s[0][1]]-Samples[j][s[1][1]])
+ (1+igy-gy)*(Samples[j][s[1][0]]-Samples[j][s[1][1]]);
}
}
}
return value;
}
// WLH 6 Dec 2001
private int gx = -1;
private int gy = -1;
/** transform an array of values in R^DomainDimension to an array
of non-integer grid coordinates */
public double[][] doubleToGrid(double[][] value) throws VisADException {
if (value.length < DomainDimension) {
throw new SetException("Gridded2DDoubleSet.doubleToGrid: bad dimension");
}
if (ManifoldDimension < 2) {
throw new SetException("Gridded2DDoubleSet.doubleToGrid: ManifoldDimension " +
"must be 2");
}
if (Lengths[0] < 2 || Lengths[1] < 2) {
throw new SetException("Gridded2DDoubleSet.doubleToGrid: requires all grid " +
"dimensions to be > 1");
}
int length = Math.min(value[0].length, value[1].length);
double[][] grid = new double[ManifoldDimension][length];
// (gx, gy) is the current grid box guess
/* WLH 6 Dec 2001
int gx = (LengthX-1)/2;
int gy = (LengthY-1)/2;
*/
// use value from last call as first guess, if reasonable
if (gx < 0 || gx >= LengthX || gy < 0 || gy >= LengthY) {
gx = (LengthX-1)/2;
gy = (LengthY-1)/2;
}
boolean lowertri = true;
for (int i=0; i<length; i++) {
// grid box guess starts at previous box unless there was no solution
/* WLH 24 Oct 97
if ( (i != 0) && (Double.isNaN(grid[0][i-1])) )
*/
// test for missing
if ( (i != 0) && grid[0][i-1] != grid[0][i-1] ) {
gx = (LengthX-1)/2;
gy = (LengthY-1)/2;
}
// if the loop doesn't find the answer, the result should be NaN
grid[0][i] = grid[1][i] = Double.NaN;
for (int itnum=0; itnum<2*(LengthX+LengthY); itnum++) {
// define the four vertices of the current grid box
double[] v0 = {Samples[0][gy*LengthX+gx],
Samples[1][gy*LengthX+gx]};
double[] v1 = {Samples[0][gy*LengthX+gx+1],
Samples[1][gy*LengthX+gx+1]};
double[] v2 = {Samples[0][(gy+1)*LengthX+gx],
Samples[1][(gy+1)*LengthX+gx]};
double[] v3 = {Samples[0][(gy+1)*LengthX+gx+1],
Samples[1][(gy+1)*LengthX+gx+1]};
// Both cases use diagonal D-B and point distances P-B and P-D
double[] bd = {v2[0]-v1[0], v2[1]-v1[1]};
double[] bp = {value[0][i]-v1[0], value[1][i]-v1[1]};
double[] dp = {value[0][i]-v2[0], value[1][i]-v2[1]};
// check the LOWER triangle of the grid box
if (lowertri) {
double[] ab = {v1[0]-v0[0], v1[1]-v0[1]};
double[] da = {v0[0]-v2[0], v0[1]-v2[1]};
double[] ap = {value[0][i]-v0[0], value[1][i]-v0[1]};
double tval1 = ab[0]*ap[1]-ab[1]*ap[0];
double tval2 = bd[0]*bp[1]-bd[1]*bp[0];
double tval3 = da[0]*dp[1]-da[1]*dp[0];
boolean test1 = (tval1 == 0) || ((tval1 > 0) == Pos);
boolean test2 = (tval2 == 0) || ((tval2 > 0) == Pos);
boolean test3 = (tval3 == 0) || ((tval3 > 0) == Pos);
int ogx = gx;
int ogy = gy;
if (!test1 && !test2) { // Go UP & RIGHT
gx++;
gy--;
}
else if (!test2 && !test3) { // Go DOWN & LEFT
gx--;
gy++;
}
else if (!test1 && !test3) { // Go UP & LEFT
gx--;
gy--;
}
else if (!test1) { // Go UP
gy--;
}
else if (!test3) { // Go LEFT
gx--;
}
// Snap guesses back into the grid
if (gx < 0) gx = 0;
if (gx > LengthX-2) gx = LengthX-2;
if (gy < 0) gy = 0;
if (gy > LengthY-2) gy = LengthY-2;
if ( (gx == ogx) && (gy == ogy) && (test2) ) {
// Found correct grid triangle
// Solve the point with the reverse interpolation
grid[0][i] = ((value[0][i]-v0[0])*(v2[1]-v0[1])
+ (v0[1]-value[1][i])*(v2[0]-v0[0]))
/ ((v1[0]-v0[0])*(v2[1]-v0[1])
+ (v0[1]-v1[1])*(v2[0]-v0[0])) + gx;
grid[1][i] = ((value[0][i]-v0[0])*(v1[1]-v0[1])
+ (v0[1]-value[1][i])*(v1[0]-v0[0]))
/ ((v2[0]-v0[0])*(v1[1]-v0[1])
+ (v0[1]-v2[1])*(v1[0]-v0[0])) + gy;
break;
}
else {
lowertri = false;
}
}
// check the UPPER triangle of the grid box
else {
double[] bc = {v3[0]-v1[0], v3[1]-v1[1]};
double[] cd = {v2[0]-v3[0], v2[1]-v3[1]};
double[] cp = {value[0][i]-v3[0], value[1][i]-v3[1]};
double tval1 = bc[0]*bp[1]-bc[1]*bp[0];
double tval2 = cd[0]*cp[1]-cd[1]*cp[0];
double tval3 = bd[0]*dp[1]-bd[1]*dp[0];
boolean test1 = (tval1 == 0) || ((tval1 > 0) == Pos);
boolean test2 = (tval2 == 0) || ((tval2 > 0) == Pos);
boolean test3 = (tval3 == 0) || ((tval3 < 0) == Pos);
int ogx = gx;
int ogy = gy;
if (!test1 && !test3) { // Go UP & RIGHT
gx++;
gy--;
}
else if (!test2 && !test3) { // Go DOWN & LEFT
gx--;
gy++;
}
else if (!test1 && !test2) { // Go DOWN & RIGHT
gx++;
gy++;
}
else if (!test1) { // Go RIGHT
gx++;
}
else if (!test2) { // Go DOWN
gy++;
}
// Snap guesses back into the grid
if (gx < 0) gx = 0;
if (gx > LengthX-2) gx = LengthX-2;
if (gy < 0) gy = 0;
if (gy > LengthY-2) gy = LengthY-2;
if ( (gx == ogx) && (gy == ogy) && (test3) ) {
// Found correct grid triangle
// Solve the point with the reverse interpolation
grid[0][i] = ((v3[0]-value[0][i])*(v1[1]-v3[1])
+ (value[1][i]-v3[1])*(v1[0]-v3[0]))
/ ((v2[0]-v3[0])*(v1[1]-v3[1])
- (v2[1]-v3[1])*(v1[0]-v3[0])) + gx + 1;
grid[1][i] = ((v2[1]-v3[1])*(v3[0]-value[0][i])
+ (v2[0]-v3[0])*(value[1][i]-v3[1]))
/ ((v1[0]-v3[0])*(v2[1]-v3[1])
- (v2[0]-v3[0])*(v1[1]-v3[1])) + gy + 1;
break;
}
else {
lowertri = true;
}
}
if ( (grid[0][i] >= LengthX-0.5) || (grid[1][i] >= LengthY-0.5)
|| (grid[0][i] <= -0.5) || (grid[1][i] <= -0.5) ) {
grid[0][i] = grid[1][i] = Double.NaN;
}
}
}
return grid;
}
/** for each of an array of values in R^DomainDimension, compute an array
of 1-D indices and an array of weights, to be used for interpolation;
indices[i] and weights[i] are null if i-th value is outside grid
(i.e., if no interpolation is possible) */
public void doubleToInterp(double[][] value, int[][] indices,
double[][] weights) throws VisADException
{
if (value.length != DomainDimension) {
throw new SetException("Gridded2DDoubleSet.doubleToInterp: value dimension " +
value.length + " not equal to Domain dimension " +
DomainDimension);
}
int length = value[0].length; // number of values
if (indices.length != length) {
throw new SetException("Gridded2DDoubleSet.valueToInterp: indices length " +
indices.length +
" doesn't match value[0] length " +
value[0].length);
}
if (weights.length != length) {
throw new SetException("Gridded2DDoubleSet.valueToInterp: weights length " +
weights.length +
" doesn't match value[0] length " +
value[0].length);
}
// convert value array to grid coord array
double[][] grid = doubleToGrid(value);
int i, j, k; // loop indices
int lis; // temporary length of is & cs
int length_is; // final length of is & cs, varies by i
int isoff; // offset along one grid dimension
double a, b; // weights along one grid dimension; a + b = 1.0
int[] is; // array of indices, becomes part of indices
double[] cs; // array of coefficients, become part of weights
int base; // base index, as would be returned by valueToIndex
int[] l = new int[ManifoldDimension]; // integer 'factors' of base
// fractions with l; -0.5 <= c <= 0.5
double[] c = new double[ManifoldDimension];
// array of index offsets by grid dimension
int[] off = new int[ManifoldDimension];
off[0] = 1;
for (j=1; j<ManifoldDimension; j++) off[j] = off[j-1] * Lengths[j-1];
for (i=0; i<length; i++) {
// compute length_is, base, l & c
length_is = 1;
if (Double.isNaN(grid[ManifoldDimension-1][i])) {
base = -1;
}
else {
l[ManifoldDimension-1] = (int) (grid[ManifoldDimension-1][i] + 0.5);
// WLH 23 Dec 99
if (l[ManifoldDimension-1] == Lengths[ManifoldDimension-1]) {
l[ManifoldDimension-1]--;
}
c[ManifoldDimension-1] = grid[ManifoldDimension-1][i] -
((double) l[ManifoldDimension-1]);
if (!((l[ManifoldDimension-1] == 0 && c[ManifoldDimension-1] <= 0.0) ||
(l[ManifoldDimension-1] == Lengths[ManifoldDimension-1] - 1 &&
c[ManifoldDimension-1] >= 0.0))) {
// only interp along ManifoldDimension-1
// if between two valid grid coords
length_is *= 2;
}
base = l[ManifoldDimension-1];
}
for (j=ManifoldDimension-2; j>=0 && base>=0; j--) {
if (Double.isNaN(grid[j][i])) {
base = -1;
}
else {
l[j] = (int) (grid[j][i] + 0.5);
if (l[j] == Lengths[j]) l[j]--; // WLH 23 Dec 99
c[j] = grid[j][i] - ((double) l[j]);
if (!((l[j] == 0 && c[j] <= 0.0) ||
(l[j] == Lengths[j] - 1 && c[j] >= 0.0))) {
// only interp along dimension j if between two valid grid coords
length_is *= 2;
}
base = l[j] + Lengths[j] * base;
}
}
if (base < 0) {
// value is out of grid so return null
is = null;
cs = null;
}
else {
// create is & cs of proper length, and init first element
is = new int[length_is];
cs = new double[length_is];
is[0] = base;
cs[0] = 1.0f;
lis = 1;
for (j=0; j<ManifoldDimension; j++) {
if (!((l[j] == 0 && c[j] <= 0.0) ||
(l[j] == Lengths[j] - 1 && c[j] >= 0.0))) {
// only interp along dimension j if between two valid grid coords
if (c[j] >= 0.0) {
// grid coord above base
isoff = off[j];
a = 1.0f - c[j];
b = c[j];
}
else {
// grid coord below base
isoff = -off[j];
a = 1.0f + c[j];
b = -c[j];
}
// double is & cs; adjust new offsets; split weights
for (k=0; k<lis; k++) {
is[k+lis] = is[k] + isoff;
cs[k+lis] = cs[k] * b;
cs[k] *= a;
}
lis *= 2;
}
}
}
indices[i] = is;
weights[i] = cs;
}
}
// Miscellaneous Set methods that must be overridden
// (this code is duplicated throughout all *DoubleSet classes)
void init_doubles(double[][] samples, boolean copy)
throws VisADException {
if (samples.length != DomainDimension) {
throw new SetException("Gridded2DDoubleSet.init_doubles: samples " +
" dimension " + samples.length +
" not equal to domain dimension " +
DomainDimension);
}
if (Length == 0) {
// Length set in init_lengths, but not called for IrregularSet
Length = samples[0].length;
}
else {
if (Length != samples[0].length) {
throw new SetException("Gridded2DDoubleSet.init_doubles: " +
"samples[0] length " + samples[0].length +
" doesn't match expected length " + Length);
}
}
// MEM
if (copy) {
Samples = new double[DomainDimension][Length];
}
else {
Samples = samples;
}
for (int j=0; j<DomainDimension; j++) {
if (samples[j].length != Length) {
throw new SetException("Gridded2DDoubleSet.init_doubles: " +
"samples[" + j + "] length " +
samples[0].length +
" doesn't match expected length " + Length);
}
double[] samplesJ = samples[j];
double[] SamplesJ = Samples[j];
if (copy) {
System.arraycopy(samplesJ, 0, SamplesJ, 0, Length);
}
Low[j] = Double.POSITIVE_INFINITY;
Hi[j] = Double.NEGATIVE_INFINITY;
double sum = 0.0f;
for (int i=0; i<Length; i++) {
if (SamplesJ[i] == SamplesJ[i] && !Double.isInfinite(SamplesJ[i])) {
if (SamplesJ[i] < Low[j]) Low[j] = SamplesJ[i];
if (SamplesJ[i] > Hi[j]) Hi[j] = SamplesJ[i];
}
else {
SamplesJ[i] = Double.NaN;
}
sum += SamplesJ[i];
}
if (SetErrors[j] != null ) {
SetErrors[j] =
new ErrorEstimate(SetErrors[j].getErrorValue(), sum / Length,
Length, SetErrors[j].getUnit());
}
super.Low[j] = (float) Low[j];
super.Hi[j] = (float) Hi[j];
}
}
public void cram_missing(boolean[] range_select) {
int n = Math.min(range_select.length, Samples[0].length);
for (int i=0; i<n; i++) {
if (!range_select[i]) Samples[0][i] = Double.NaN;
}
}
public boolean isMissing() {
return (Samples == null);
}
public boolean equals(Object set) {
if (!(set instanceof Gridded2DDoubleSet) || set == null) return false;
if (this == set) return true;
if (testNotEqualsCache((Set) set)) return false;
if (testEqualsCache((Set) set)) return true;
if (!equalUnitAndCS((Set) set)) return false;
try {
int i, j;
if (DomainDimension != ((Gridded2DDoubleSet) set).getDimension() ||
ManifoldDimension !=
((Gridded2DDoubleSet) set).getManifoldDimension() ||
Length != ((Gridded2DDoubleSet) set).getLength()) return false;
for (j=0; j<ManifoldDimension; j++) {
if (Lengths[j] != ((Gridded2DDoubleSet) set).getLength(j)) {
return false;
}
}
// Sets are immutable, so no need for 'synchronized'
double[][] samples = ((Gridded2DDoubleSet) set).getDoubles(false);
if (Samples != null && samples != null) {
for (j=0; j<DomainDimension; j++) {
for (i=0; i<Length; i++) {
if (Samples[j][i] != samples[j][i]) {
addNotEqualsCache((Set) set);
return false;
}
}
}
}
else {
double[][] this_samples = getDoubles(false);
if (this_samples == null) {
if (samples != null) {
return false;
}
} else if (samples == null) {
return false;
} else {
for (j=0; j<DomainDimension; j++) {
for (i=0; i<Length; i++) {
if (this_samples[j][i] != samples[j][i]) {
addNotEqualsCache((Set) set);
return false;
}
}
}
}
}
addEqualsCache((Set) set);
return true;
}
catch (VisADException e) {
return false;
}
}
/**
* Clones this instance.
*
* @return A clone of this instance.
*/
public Object clone() {
Gridded2DDoubleSet clone = (Gridded2DDoubleSet)super.clone();
if (Samples != null) {
/*
* The Samples array is cloned because getDoubles(false) allows clients
* to manipulate the array and the general clone() contract forbids
* cross-clone contamination.
*/
clone.Samples = (double[][])Samples.clone();
for (int i = 0; i < Samples.length; i++)
clone.Samples[i] = (double[])Samples[i].clone();
}
return clone;
}
public Object cloneButType(MathType type) throws VisADException {
if (ManifoldDimension == 2) {
return new Gridded2DDoubleSet(type, Samples, LengthX, LengthY,
DomainCoordinateSystem, SetUnits, SetErrors);
}
else {
return new Gridded2DDoubleSet(type, Samples, LengthX,
DomainCoordinateSystem, SetUnits, SetErrors);
}
}
/* WLH 3 April 2003
public Object cloneButType(MathType type) throws VisADException {
return new Gridded2DDoubleSet(type, Samples, Length,
DomainCoordinateSystem, SetUnits, SetErrors);
}
*/
}
diff --git a/core/src/visad/trunk/Gridded3DDoubleSet.java b/core/src/visad/trunk/Gridded3DDoubleSet.java
index 8d1ad6ba7..834f75732 100644
--- a/core/src/visad/trunk/Gridded3DDoubleSet.java
+++ b/core/src/visad/trunk/Gridded3DDoubleSet.java
@@ -1,1930 +1,1934 @@
//
// Gridded3DDoubleSet.java
//
/*
VisAD system for interactive analysis and visualization of numerical
data. Copyright (C) 1996 - 2002 Bill Hibbard, Curtis Rueden, Tom
Rink, Dave Glowacki, Steve Emmerson, Tom Whittaker, Don Murray, and
Tommy Jasmin.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 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
Library General Public License for more details.
You should have received a copy of the GNU Library 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 visad;
/**
Gridded3DDoubleSet is a Gridded3DSet with double-precision samples.<P>
*/
public class Gridded3DDoubleSet extends Gridded3DSet
implements GriddedDoubleSet {
double[] Low = new double[3];
double[] Hi = new double[3];
double LowX, HiX, LowY, HiY, LowZ, HiZ;
double[][] Samples;
// Overridden Gridded3DSet constructors (float[][])
/** a 3-D set whose topology is a lengthX x lengthY x lengthZ
grid, with null errors, CoordinateSystem and Units are
defaults from type */
public Gridded3DDoubleSet(MathType type, float[][] samples, int lengthX,
int lengthY, int lengthZ) throws VisADException {
this(type, Set.floatToDouble(samples), lengthX, lengthY, lengthZ,
null, null, null, true);
}
/** a 3-D set whose topology is a lengthX x lengthY x lengthZ
grid; samples array is organized float[3][number_of_samples]
where lengthX * lengthY * lengthZ = number_of_samples;
samples must form a non-degenerate 3-D grid (no bow-tie-shaped
grid cubes); the X component increases fastest and the Z
component slowest in the second index of samples;
coordinate_system and units must be compatible with defaults
for type, or may be null; errors may be null */
public Gridded3DDoubleSet(MathType type, float[][] samples,
int lengthX, int lengthY, int lengthZ,
CoordinateSystem coord_sys, Unit[] units,
ErrorEstimate[] errors) throws VisADException {
this(type, Set.floatToDouble(samples), lengthX, lengthY, lengthZ,
coord_sys, units, errors, true);
}
public Gridded3DDoubleSet(MathType type, float[][] samples,
int lengthX, int lengthY, int lengthZ,
CoordinateSystem coord_sys, Unit[] units,
ErrorEstimate[] errors, boolean copy)
throws VisADException {
this(type, Set.floatToDouble(samples), lengthX, lengthY, lengthZ,
coord_sys, units, errors, copy);
}
/** a 3-D set with manifold dimension = 2, with null errors,
CoordinateSystem and Units are defaults from type */
public Gridded3DDoubleSet(MathType type, float[][] samples, int lengthX,
int lengthY) throws VisADException {
this(type, Set.floatToDouble(samples), lengthX, lengthY,
null, null, null, true);
}
/** a 3-D set with manifold dimension = 2; samples array is
organized float[3][number_of_samples] where lengthX * lengthY
= number_of_samples; no geometric constraint on samples; the
X component increases fastest in the second index of samples;
coordinate_system and units must be compatible with defaults
for type, or may be null; errors may be null */
public Gridded3DDoubleSet(MathType type, float[][] samples,
int lengthX, int lengthY,
CoordinateSystem coord_sys, Unit[] units,
ErrorEstimate[] errors) throws VisADException {
this(type, Set.floatToDouble(samples), lengthX, lengthY,
coord_sys, units, errors, true);
}
public Gridded3DDoubleSet(MathType type, float[][] samples,
int lengthX, int lengthY,
CoordinateSystem coord_sys, Unit[] units,
ErrorEstimate[] errors, boolean copy)
throws VisADException {
this(type, Set.floatToDouble(samples), lengthX, lengthY,
coord_sys, units, errors, copy);
}
/** a 3-D set with manifold dimension = 1, with null errors,
CoordinateSystem and Units are defaults from type */
public Gridded3DDoubleSet(MathType type, float[][] samples, int lengthX)
throws VisADException {
this(type, Set.floatToDouble(samples), lengthX, null, null, null, true);
}
/** a 3-D set with manifold dimension = 1; samples array is
organized float[3][number_of_samples] where lengthX =
number_of_samples; no geometric constraint on samples;
coordinate_system and units must be compatible with defaults
for type, or may be null; errors may be null */
public Gridded3DDoubleSet(MathType type, float[][] samples, int lengthX,
CoordinateSystem coord_sys, Unit[] units,
ErrorEstimate[] errors) throws VisADException {
this(type, Set.floatToDouble(samples), lengthX,
coord_sys, units, errors, true);
}
public Gridded3DDoubleSet(MathType type, float[][] samples, int lengthX,
CoordinateSystem coord_sys, Unit[] units,
ErrorEstimate[] errors, boolean copy)
throws VisADException {
this(type, Set.floatToDouble(samples), lengthX,
coord_sys, units, errors, copy);
}
// Corresponding Gridded3DDoubleSet constructors (double[][])
/** a 3-D set whose topology is a lengthX x lengthY x lengthZ
grid, with null errors, CoordinateSystem and Units are
defaults from type */
public Gridded3DDoubleSet(MathType type, double[][] samples, int lengthX,
int lengthY, int lengthZ) throws VisADException {
this(type, samples, lengthX, lengthY, lengthZ, null, null, null, true);
}
/** a 3-D set whose topology is a lengthX x lengthY x lengthZ
grid; samples array is organized double[3][number_of_samples]
where lengthX * lengthY * lengthZ = number_of_samples;
samples must form a non-degenerate 3-D grid (no bow-tie-shaped
grid cubes); the X component increases fastest and the Z
component slowest in the second index of samples;
coordinate_system and units must be compatible with defaults
for type, or may be null; errors may be null */
public Gridded3DDoubleSet(MathType type, double[][] samples,
int lengthX, int lengthY, int lengthZ,
CoordinateSystem coord_sys, Unit[] units,
ErrorEstimate[] errors) throws VisADException {
this(type, samples, lengthX, lengthY, lengthZ,
coord_sys, units, errors, true);
}
public Gridded3DDoubleSet(MathType type, double[][] samples,
int lengthX, int lengthY, int lengthZ,
CoordinateSystem coord_sys, Unit[] units,
ErrorEstimate[] errors, boolean copy)
throws VisADException {
super(type, null, lengthX, lengthY, lengthZ,
coord_sys, units, errors, copy);
if (samples == null) {
throw new SetException("Gridded3DDoubleSet: samples are null");
}
init_doubles(samples, copy);
LowX = Low[0];
HiX = Hi[0];
LengthX = Lengths[0];
LowY = Low[1];
HiY = Hi[1];
LengthY = Lengths[1];
LowZ = Low[2];
HiZ = Hi[2];
LengthZ = Lengths[2];
if (Samples != null &&
Lengths[0] > 1 && Lengths[1] > 1 && Lengths[2] > 1) {
for (int i=0; i<Length; i++) {
if (Samples[0][i] != Samples[0][i]) {
throw new SetException(
"Gridded3DDoubleSet: samples values may not be missing");
}
}
// Samples consistency test
double[] t000 = new double[3];
double[] t100 = new double[3];
double[] t010 = new double[3];
double[] t001 = new double[3];
double[] t110 = new double[3];
double[] t101 = new double[3];
double[] t011 = new double[3];
double[] t111 = new double[3];
for (int v=0; v<3; v++) {
t000[v] = Samples[v][0];
t100[v] = Samples[v][1];
t010[v] = Samples[v][LengthX];
t001[v] = Samples[v][LengthY*LengthX];
t110[v] = Samples[v][LengthX+1];
t101[v] = Samples[v][LengthY*LengthX+1];
t011[v] = Samples[v][(LengthY+1)*LengthX];
t111[v] = Samples[v][(LengthY+1)*LengthX+1];
}
Pos = ( ( (t100[1]-t000[1])*(t101[2]-t100[2])
- (t100[2]-t000[2])*(t101[1]-t100[1]) )
*(t110[0]-t100[0]) )
+ ( ( (t100[2]-t000[2])*(t101[0]-t100[0])
- (t100[0]-t000[0])*(t101[2]-t100[2]) )
*(t110[1]-t100[1]) )
+ ( ( (t100[0]-t000[0])*(t101[1]-t100[1])
- (t100[1]-t000[1])*(t101[0]-t100[0]) )
*(t110[2]-t100[2]) ) > 0;
for (int k=0; k<LengthZ-1; k++) {
for (int j=0; j<LengthY-1; j++) {
for (int i=0; i<LengthX-1; i++) {
double[] v000 = new double[3];
double[] v100 = new double[3];
double[] v010 = new double[3];
double[] v001 = new double[3];
double[] v110 = new double[3];
double[] v101 = new double[3];
double[] v011 = new double[3];
double[] v111 = new double[3];
for (int v=0; v<3; v++) {
int zadd = LengthY*LengthX;
int base = k*zadd + j*LengthX + i;
v000[v] = Samples[v][base];
v100[v] = Samples[v][base+1];
v010[v] = Samples[v][base+LengthX];
v001[v] = Samples[v][base+zadd];
v110[v] = Samples[v][base+LengthX+1];
v101[v] = Samples[v][base+zadd+1];
v011[v] = Samples[v][base+zadd+LengthX];
v111[v] = Samples[v][base+zadd+LengthX+1];
}
if ((( ( (v100[1]-v000[1])*(v101[2]-v100[2]) // test 1
- (v100[2]-v000[2])*(v101[1]-v100[1]) )
*(v110[0]-v100[0]) )
+ ( ( (v100[2]-v000[2])*(v101[0]-v100[0])
- (v100[0]-v000[0])*(v101[2]-v100[2]) )
*(v110[1]-v100[1]) )
+ ( ( (v100[0]-v000[0])*(v101[1]-v100[1])
- (v100[1]-v000[1])*(v101[0]-v100[0]) )
*(v110[2]-v100[2]) ) > 0 != Pos)
|| (( ( (v101[1]-v100[1])*(v001[2]-v101[2]) // test 2
- (v101[2]-v100[2])*(v001[1]-v101[1]) )
*(v111[0]-v101[0]) )
+ ( ( (v101[2]-v100[2])*(v001[0]-v101[0])
- (v101[0]-v100[0])*(v001[2]-v101[2]) )
*(v111[1]-v101[1]) )
+ ( ( (v101[0]-v100[0])*(v001[1]-v101[1])
- (v101[1]-v100[1])*(v001[0]-v101[0]) )
*(v111[2]-v101[2]) ) > 0 != Pos)
|| (( ( (v001[1]-v101[1])*(v000[2]-v001[2]) // test 3
- (v001[2]-v101[2])*(v000[1]-v001[1]) )
*(v011[0]-v001[0]) )
+ ( ( (v001[2]-v101[2])*(v000[0]-v001[0])
- (v001[0]-v101[0])*(v000[2]-v001[2]) )
*(v011[1]-v001[1]) )
+ ( ( (v001[0]-v101[0])*(v000[1]-v001[1])
- (v001[1]-v101[1])*(v000[0]-v001[0]) )
*(v011[2]-v001[2]) ) > 0 != Pos)
|| (( ( (v000[1]-v001[1])*(v100[2]-v000[2]) // test 4
- (v000[2]-v001[2])*(v100[1]-v000[1]) )
*(v010[0]-v000[0]) )
+ ( ( (v000[2]-v001[2])*(v100[0]-v000[0])
- (v000[0]-v001[0])*(v100[2]-v000[2]) )
*(v010[1]-v000[1]) )
+ ( ( (v000[0]-v001[0])*(v100[1]-v000[1])
- (v000[1]-v001[1])*(v100[0]-v000[0]) )
*(v010[2]-v000[2]) ) > 0 != Pos)
|| (( ( (v110[1]-v111[1])*(v010[2]-v110[2]) // test 5
- (v110[2]-v111[2])*(v010[1]-v110[1]) )
*(v100[0]-v110[0]) )
+ ( ( (v110[2]-v111[2])*(v010[0]-v110[0])
- (v110[0]-v111[0])*(v010[2]-v110[2]) )
*(v100[1]-v110[1]) )
+ ( ( (v110[0]-v111[0])*(v010[1]-v110[1])
- (v110[1]-v111[1])*(v010[0]-v110[0]) )
*(v100[2]-v110[2]) ) > 0 != Pos)
|| (( ( (v111[1]-v011[1])*(v110[2]-v111[2]) // test 6
- (v111[2]-v011[2])*(v110[1]-v111[1]) )
*(v101[0]-v111[0]) )
+ ( ( (v111[2]-v011[2])*(v110[0]-v111[0])
- (v111[0]-v011[0])*(v110[2]-v111[2]) )
*(v101[1]-v111[1]) )
+ ( ( (v111[0]-v011[0])*(v110[1]-v111[1])
- (v111[1]-v011[1])*(v110[0]-v111[0]) )
*(v101[2]-v111[2]) ) > 0 != Pos)
|| (( ( (v011[1]-v010[1])*(v111[2]-v011[2]) // test 7
- (v011[2]-v010[2])*(v111[1]-v011[1]) )
*(v001[0]-v011[0]) )
+ ( ( (v011[2]-v010[2])*(v111[0]-v011[0])
- (v011[0]-v010[0])*(v111[2]-v011[2]) )
*(v001[1]-v011[1]) )
+ ( ( (v011[0]-v010[0])*(v111[1]-v011[1])
- (v011[1]-v010[1])*(v111[0]-v011[0]) )
*(v001[2]-v011[2]) ) > 0 != Pos)
|| (( ( (v010[1]-v110[1])*(v011[2]-v010[2]) // test 8
- (v010[2]-v110[2])*(v011[1]-v010[1]) )
*(v000[0]-v010[0]) )
+ ( ( (v010[2]-v110[2])*(v011[0]-v010[0])
- (v010[0]-v110[0])*(v011[2]-v010[2]) )
*(v000[1]-v010[1]) )
+ ( ( (v010[0]-v110[0])*(v011[1]-v010[1])
- (v010[1]-v110[1])*(v011[0]-v010[0]) )
*(v000[2]-v010[2]) ) > 0 != Pos)) {
throw new SetException("Gridded3DDoubleSet: samples do not form "
+"a valid grid ("+i+","+j+","+k+")");
}
}
}
}
}
}
/** a 3-D set with manifold dimension = 2, with null errors,
CoordinateSystem and Units are defaults from type */
public Gridded3DDoubleSet(MathType type, double[][] samples, int lengthX,
int lengthY) throws VisADException {
this(type, samples, lengthX, lengthY, null, null, null, true);
}
/** a 3-D set with manifold dimension = 2; samples array is
organized double[3][number_of_samples] where lengthX * lengthY
= number_of_samples; no geometric constraint on samples; the
X component increases fastest in the second index of samples;
coordinate_system and units must be compatible with defaults
for type, or may be null; errors may be null */
public Gridded3DDoubleSet(MathType type, double[][] samples,
int lengthX, int lengthY,
CoordinateSystem coord_sys, Unit[] units,
ErrorEstimate[] errors) throws VisADException {
this(type, samples, lengthX, lengthY, coord_sys, units, errors, true);
}
public Gridded3DDoubleSet(MathType type, double[][] samples,
int lengthX, int lengthY,
CoordinateSystem coord_sys, Unit[] units,
ErrorEstimate[] errors, boolean copy)
throws VisADException {
super(type, null, lengthX, lengthY, coord_sys, units, errors, copy);
if (samples == null) {
throw new SetException("Gridded3DDoubleSet: samples are null");
}
init_doubles(samples, copy);
LowX = Low[0];
HiX = Hi[0];
LengthX = Lengths[0];
LowY = Low[1];
HiY = Hi[1];
LengthY = Lengths[1];
LowZ = Low[2];
HiZ = Hi[2];
// no Samples consistency test
}
/** a 3-D set with manifold dimension = 1, with null errors,
CoordinateSystem and Units are defaults from type */
public Gridded3DDoubleSet(MathType type, double[][] samples, int lengthX)
throws VisADException {
this(type, samples, lengthX, null, null, null, true);
}
/** a 3-D set with manifold dimension = 1; samples array is
organized double[3][number_of_samples] where lengthX =
number_of_samples; no geometric constraint on samples;
coordinate_system and units must be compatible with defaults
for type, or may be null; errors may be null */
public Gridded3DDoubleSet(MathType type, double[][] samples, int lengthX,
CoordinateSystem coord_sys, Unit[] units,
ErrorEstimate[] errors) throws VisADException {
this(type, samples, lengthX, coord_sys, units, errors, true);
}
public Gridded3DDoubleSet(MathType type, double[][] samples, int lengthX,
CoordinateSystem coord_sys, Unit[] units,
ErrorEstimate[] errors, boolean copy)
throws VisADException {
super(type, null, lengthX, coord_sys, units, errors, copy);
if (samples == null) {
throw new SetException("Gridded3DDoubleSet: samples are null");
}
init_doubles(samples, copy);
LowX = Low[0];
HiX = Hi[0];
LengthX = Lengths[0];
LowY = Low[1];
HiY = Hi[1];
LowZ = Low[2];
HiZ = Hi[2];
// no Samples consistency test
}
// Overridden Gridded3DSet methods (float[][])
public float[][] getSamples() throws VisADException {
return getSamples(true);
}
public float[][] getSamples(boolean copy) throws VisADException {
return Set.doubleToFloat(Samples);
}
/** convert an array of 1-D indices to an array of values in R^DomainDimension */
public float[][] indexToValue(int[] index) throws VisADException {
return Set.doubleToFloat(indexToDouble(index));
}
/** convert an array of values in R^DomainDimension to an array of 1-D indices */
public int[] valueToIndex(float[][] value) throws VisADException {
return doubleToIndex(Set.floatToDouble(value));
}
/** transform an array of non-integer grid coordinates to an array
of values in R^DomainDimension */
public float[][] gridToValue(float[][] grid) throws VisADException {
return Set.doubleToFloat(gridToDouble(Set.floatToDouble(grid)));
}
/** transform an array of values in R^DomainDimension to an array
of non-integer grid coordinates */
public float[][] valueToGrid(float[][] value) throws VisADException {
return Set.doubleToFloat(doubleToGrid(Set.floatToDouble(value)));
}
/** for each of an array of values in R^DomainDimension, compute an array
of 1-D indices and an array of weights, to be used for interpolation;
indices[i] and weights[i] are null if i-th value is outside grid
(i.e., if no interpolation is possible) */
public void valueToInterp(float[][] value, int[][] indices,
float[][] weights) throws VisADException
{
int len = weights.length;
double[][] w = new double[len][];
- for (int i=0; i<len; i++) w[i] = new double[weights[i].length];
doubleToInterp(Set.floatToDouble(value), indices, w);
for (int i=0; i<len; i++) {
- System.arraycopy(w[i], 0, weights[i], 0, w.length);
+ if (w[i] != null) {
+ weights[i] = new float[w[i].length];
+ for (int j=0; j<w[i].length; j++) {
+ weights[i][j] = (float) w[i][j];
+ }
+ }
}
}
// Corresponding Gridded3DDoubleSet methods (double[][])
public double[][] getDoubles() throws VisADException {
return getDoubles(true);
}
public double[][] getDoubles(boolean copy) throws VisADException {
return copy ? Set.copyDoubles(Samples) : Samples;
}
/** convert an array of 1-D indices to an array of values in
R^DomainDimension */
public double[][] indexToDouble(int[] index) throws VisADException {
int length = index.length;
if (Samples == null) {
// not used - over-ridden by Linear3DSet.indexToValue
int indexX, indexY, indexZ;
int k;
double[][] grid = new double[ManifoldDimension][length];
for (int i=0; i<length; i++) {
if (0 <= index[i] && index[i] < Length) {
indexX = index[i] % LengthX;
k = index[i] / LengthX;
indexY = k % LengthY;
indexZ = k / LengthY;
}
else {
indexX = -1;
indexY = -1;
indexZ = -1;
}
grid[0][i] = indexX;
grid[1][i] = indexY;
grid[2][i] = indexZ;
}
return gridToDouble(grid);
}
else {
double[][] values = new double[3][length];
for (int i=0; i<length; i++) {
if (0 <= index[i] && index[i] < Length) {
values[0][i] = Samples[0][index[i]];
values[1][i] = Samples[1][index[i]];
values[2][i] = Samples[2][index[i]];
}
else {
values[0][i] = Double.NaN;
values[1][i] = Double.NaN;
values[2][i] = Double.NaN;
}
}
return values;
}
}
/** convert an array of values in R^DomainDimension to an array of 1-D indices */
public int[] doubleToIndex(double[][] value) throws VisADException {
if (value.length != DomainDimension) {
throw new SetException("Gridded3DDoubleSet.doubleToIndex: value dimension " +
value.length + " not equal to Domain dimension " +
DomainDimension);
}
int length = value[0].length;
int[] index = new int[length];
double[][] grid = doubleToGrid(value);
double[] grid0 = grid[0];
double[] grid1 = grid[1];
double[] grid2 = grid[2];
double g0, g1, g2;
for (int i=0; i<length; i++) {
g0 = grid0[i];
g1 = grid1[i];
g2 = grid2[i];
// test for missing
index[i] = (g0 != g0 || g1 != g1 || g2 != g2) ? -1 :
((int) (g0 + 0.5)) + LengthX*( ((int) (g1 + 0.5)) +
LengthY*((int) (g2 + 0.5)));
}
return index;
}
/** transform an array of non-integer grid coordinates to an array
of values in R^DomainDimension */
public double[][] gridToDouble(double[][] grid) throws VisADException {
if (grid.length != ManifoldDimension) {
throw new SetException("Gridded3DDoubleSet.gridToDouble: grid dimension " +
grid.length +
" not equal to Manifold dimension " +
ManifoldDimension);
}
if (ManifoldDimension == 3) {
return gridToDouble3D(grid);
}
else if (ManifoldDimension == 2) {
return gridToDouble2D(grid);
}
else {
throw new SetException("Gridded3DDoubleSet.gridToDouble: ManifoldDimension " +
"must be 2 or 3");
}
}
private double[][] gridToDouble2D(double[][] grid) throws VisADException {
if (Lengths[0] < 2 || Lengths[1] < 2) {
throw new SetException("Gridded3DDoubleSet.gridToDouble: requires all grid " +
"dimensions to be > 1");
}
// avoid any ArrayOutOfBounds exceptions by taking the shortest length
int length = Math.min(grid[0].length, grid[1].length);
double[][] value = new double[3][length];
for (int i=0; i<length; i++) {
// let gx and gy by the current grid values
double gx = grid[0][i];
double gy = grid[1][i];
if ( (gx < -0.5) || (gy < -0.5) ||
(gx > LengthX-0.5) || (gy > LengthY-0.5) ) {
value[0][i] = value[1][i] = value[2][i] = Double.NaN;
continue;
}
// calculate closest integer variables
int igx = (int) gx;
int igy = (int) gy;
if (igx < 0) igx = 0;
if (igx > LengthX-2) igx = LengthX-2;
if (igy < 0) igy = 0;
if (igy > LengthY-2) igy = LengthY-2;
// set up conversion to 1D Samples array
int[][] s = { {LengthX*igy+igx, // (0, 0)
LengthX*(igy+1)+igx}, // (0, 1)
{LengthX*igy+igx+1, // (1, 0)
LengthX*(igy+1)+igx+1} }; // (1, 1)
if (gx+gy-igx-igy-1 <= 0) {
// point is in LOWER triangle
for (int j=0; j<3; j++) {
value[j][i] = Samples[j][s[0][0]]
+ (gx-igx)*(Samples[j][s[1][0]]-Samples[j][s[0][0]])
+ (gy-igy)*(Samples[j][s[0][1]]-Samples[j][s[0][0]]);
}
}
else {
// point is in UPPER triangle
for (int j=0; j<3; j++) {
value[j][i] = Samples[j][s[1][1]]
+ (1+igx-gx)*(Samples[j][s[0][1]]-Samples[j][s[1][1]])
+ (1+igy-gy)*(Samples[j][s[1][0]]-Samples[j][s[1][1]]);
}
}
}
return value;
}
private double[][] gridToDouble3D(double[][] grid) throws VisADException {
if (Lengths[0] < 2 || Lengths[1] < 2 || Lengths[2] < 2) {
throw new SetException("Gridded3DDoubleSet.gridToDouble: requires all grid " +
"dimensions to be > 1");
}
// avoid any ArrayOutOfBounds exceptions by taking the shortest length
int length = Math.min(grid[0].length, grid[1].length);
length = Math.min(length, grid[2].length);
double[][] value = new double[3][length];
for (int i=0; i<length; i++) {
// let gx, gy, and gz be the current grid values
double gx = grid[0][i];
double gy = grid[1][i];
double gz = grid[2][i];
if ( (gx < -0.5) || (gy < -0.5) || (gz < -0.5) ||
(gx > LengthX-0.5) || (gy > LengthY-0.5) || (gz > LengthZ-0.5) ) {
value[0][i] = value[1][i] = value[2][i] = Double.NaN;
continue;
}
// calculate closest integer variables
int igx, igy, igz;
if (gx < 0) igx = 0;
else if (gx > LengthX-2) igx = LengthX - 2;
else igx = (int) gx;
if (gy < 0) igy = 0;
else if (gy > LengthY-2) igy = LengthY - 2;
else igy = (int) gy;
if (gz < 0) igz = 0;
else if (gz > LengthZ-2) igz = LengthZ - 2;
else igz = (int) gz;
// determine tetrahedralization type
boolean evencube = ((igx+igy+igz) % 2 == 0);
// calculate distances from integer grid point
double s, t, u;
if (evencube) {
s = gx - igx;
t = gy - igy;
u = gz - igz;
}
else {
s = 1 + igx - gx;
t = 1 + igy - gy;
u = 1 + igz - gz;
}
// Define vertices of grid box
int zadd = LengthY*LengthX;
int base = igz*zadd + igy*LengthX + igx;
int ai = base+zadd; // 0, 0, 1
int bi = base+zadd+1; // 1, 0, 1
int ci = base+zadd+LengthX+1; // 1, 1, 1
int di = base+zadd+LengthX; // 0, 1, 1
int ei = base; // 0, 0, 0
int fi = base+1; // 1, 0, 0
int gi = base+LengthX+1; // 1, 1, 0
int hi = base+LengthX; // 0, 1, 0
double[] A = new double[3];
double[] B = new double[3];
double[] C = new double[3];
double[] D = new double[3];
double[] E = new double[3];
double[] F = new double[3];
double[] G = new double[3];
double[] H = new double[3];
if (evencube) {
A[0] = Samples[0][ai];
A[1] = Samples[1][ai];
A[2] = Samples[2][ai];
B[0] = Samples[0][bi];
B[1] = Samples[1][bi];
B[2] = Samples[2][bi];
C[0] = Samples[0][ci];
C[1] = Samples[1][ci];
C[2] = Samples[2][ci];
D[0] = Samples[0][di];
D[1] = Samples[1][di];
D[2] = Samples[2][di];
E[0] = Samples[0][ei];
E[1] = Samples[1][ei];
E[2] = Samples[2][ei];
F[0] = Samples[0][fi];
F[1] = Samples[1][fi];
F[2] = Samples[2][fi];
G[0] = Samples[0][gi];
G[1] = Samples[1][gi];
G[2] = Samples[2][gi];
H[0] = Samples[0][hi];
H[1] = Samples[1][hi];
H[2] = Samples[2][hi];
}
else {
G[0] = Samples[0][ai];
G[1] = Samples[1][ai];
G[2] = Samples[2][ai];
H[0] = Samples[0][bi];
H[1] = Samples[1][bi];
H[2] = Samples[2][bi];
E[0] = Samples[0][ci];
E[1] = Samples[1][ci];
E[2] = Samples[2][ci];
F[0] = Samples[0][di];
F[1] = Samples[1][di];
F[2] = Samples[2][di];
C[0] = Samples[0][ei];
C[1] = Samples[1][ei];
C[2] = Samples[2][ei];
D[0] = Samples[0][fi];
D[1] = Samples[1][fi];
D[2] = Samples[2][fi];
A[0] = Samples[0][gi];
A[1] = Samples[1][gi];
A[2] = Samples[2][gi];
B[0] = Samples[0][hi];
B[1] = Samples[1][hi];
B[2] = Samples[2][hi];
}
// These tests determine which tetrahedron the point is in
boolean test1 = (1 - s - t - u >= 0);
boolean test2 = (s - t + u - 1 >= 0);
boolean test3 = (t - s + u - 1 >= 0);
boolean test4 = (s + t - u - 1 >= 0);
// These cases handle grid coordinates off the grid
// (Different tetrahedrons must be chosen accordingly)
if ( (gx < 0) || (gx > LengthX-1)
|| (gy < 0) || (gy > LengthY-1)
|| (gz < 0) || (gz > LengthZ-1) ) {
boolean OX, OY, OZ, MX, MY, MZ, LX, LY, LZ;
OX = OY = OZ = MX = MY = MZ = LX = LY = LZ = false;
if (igx == 0) OX = true;
if (igy == 0) OY = true;
if (igz == 0) OZ = true;
if (igx == LengthX-2) LX = true;
if (igy == LengthY-2) LY = true;
if (igz == LengthZ-2) LZ = true;
if (!OX && !LX) MX = true;
if (!OY && !LY) MY = true;
if (!OZ && !LZ) MZ = true;
test1 = test2 = test3 = test4 = false;
// 26 cases
if (evencube) {
if (!LX && !LY && !LZ) test1 = true;
else if ( (LX && OY && MZ) || (MX && OY && LZ)
|| (LX && MY && LZ) || (LX && OY && LZ)
|| (MX && MY && LZ) || (LX && MY && MZ) ) test2 = true;
else if ( (OX && LY && MZ) || (OX && MY && LZ)
|| (MX && LY && LZ) || (OX && LY && LZ)
|| (MX && LY && MZ) ) test3 = true;
else if ( (MX && LY && OZ) || (LX && MY && OZ)
|| (LX && LY && MZ) || (LX && LY && OZ) ) test4 = true;
}
else {
if (!OX && !OY && !OZ) test1 = true;
else if ( (OX && MY && OZ) || (MX && LY && OZ)
|| (OX && LY && MZ) || (OX && LY && OZ)
|| (MX && MY && OZ) || (OX && MY && MZ) ) test2 = true;
else if ( (LX && MY && OZ) || (MX && OY && OZ)
|| (LX && OY && MZ) || (LX && OY && OZ)
|| (MX && OY && MZ) ) test3 = true;
else if ( (OX && OY && MZ) || (OX && MY && OZ)
|| (MX && OY && LZ) || (OX && OY && LZ) ) test4 = true;
}
}
if (test1) {
for (int j=0; j<3; j++) {
value[j][i] = E[j] + s*(F[j]-E[j])
+ t*(H[j]-E[j])
+ u*(A[j]-E[j]);
}
}
else if (test2) {
for (int j=0; j<3; j++) {
value[j][i] = B[j] + (1-s)*(A[j]-B[j])
+ t*(C[j]-B[j])
+ (1-u)*(F[j]-B[j]);
}
}
else if (test3) {
for (int j=0; j<3; j++) {
value[j][i] = D[j] + s*(C[j]-D[j])
+ (1-t)*(A[j]-D[j])
+ (1-u)*(H[j]-D[j]);
}
}
else if (test4) {
for (int j=0; j<3; j++) {
value[j][i] = G[j] + (1-s)*(H[j]-G[j])
+ (1-t)*(F[j]-G[j])
+ u*(C[j]-G[j]);
}
}
else {
for (int j=0; j<3; j++) {
value[j][i] = (H[j]+F[j]+A[j]-C[j])/2 + s*(C[j]+F[j]-H[j]-A[j])/2
+ t*(C[j]-F[j]+H[j]-A[j])/2
+ u*(C[j]-F[j]-H[j]+A[j])/2;
}
}
}
return value;
}
// WLH 6 Dec 2001
private int gx = -1;
private int gy = -1;
private int gz = -1;
/** transform an array of values in R^DomainDimension to an array
of non-integer grid coordinates */
public double[][] doubleToGrid(double[][] value) throws VisADException {
if (value.length < DomainDimension) {
throw new SetException("Gridded3DDoubleSet.doubleToGrid: value dimension " +
value.length + " not equal to Domain dimension " +
DomainDimension);
}
if (ManifoldDimension < 3) {
throw new SetException("Gridded3DDoubleSet.doubleToGrid: ManifoldDimension " +
"must be 3");
}
if (Lengths[0] < 2 || Lengths[1] < 2 || Lengths[2] < 2) {
throw new SetException("Gridded3DDoubleSet.doubleToGrid: requires all grid " +
"dimensions to be > 1");
}
// Avoid any ArrayOutOfBounds exceptions by taking the shortest length
int length = Math.min(value[0].length, value[1].length);
length = Math.min(length, value[2].length);
double[][] grid = new double[ManifoldDimension][length];
// (gx, gy, gz) is the current grid box guess
/* WLH 6 Dec 2001
int gx = (LengthX-1)/2;
int gy = (LengthY-1)/2;
int gz = (LengthZ-1)/2;
*/
// use value from last call as first guess, if reasonable
if (gx < 0 || gx >= LengthX || gy < 0 || gy >= LengthY ||
gz < 0 || gz >= LengthZ) {
gx = (LengthX-1)/2;
gy = (LengthY-1)/2;
gz = (LengthZ-1)/2;
}
for (int i=0; i<length; i++) {
// a flag indicating whether point is off the grid
boolean offgrid = false;
// the first guess should be the last box unless there was no solution
// test for missing
if ( (i != 0) && grid[0][i-1] != grid[0][i-1] ) {
gx = (LengthX-1)/2;
gy = (LengthY-1)/2;
gz = (LengthZ-1)/2;
}
int tetnum = 5; // Tetrahedron number in which to start search
// if the iteration loop fails, the result should be NaN
grid[0][i] = grid[1][i] = grid[2][i] = Double.NaN;
for (int itnum=0; itnum<2*(LengthX+LengthY+LengthZ); itnum++) {
// determine tetrahedralization type
boolean evencube = ((gx+gy+gz) % 2 == 0);
// Define vertices of grid box
int zadd = LengthY*LengthX;
int base = gz*zadd + gy*LengthX + gx;
int ai = base+zadd; // 0, 0, 1
int bi = base+zadd+1; // 1, 0, 1
int ci = base+zadd+LengthX+1; // 1, 1, 1
int di = base+zadd+LengthX; // 0, 1, 1
int ei = base; // 0, 0, 0
int fi = base+1; // 1, 0, 0
int gi = base+LengthX+1; // 1, 1, 0
int hi = base+LengthX; // 0, 1, 0
double[] A = new double[3];
double[] B = new double[3];
double[] C = new double[3];
double[] D = new double[3];
double[] E = new double[3];
double[] F = new double[3];
double[] G = new double[3];
double[] H = new double[3];
if (evencube) {
A[0] = Samples[0][ai];
A[1] = Samples[1][ai];
A[2] = Samples[2][ai];
B[0] = Samples[0][bi];
B[1] = Samples[1][bi];
B[2] = Samples[2][bi];
C[0] = Samples[0][ci];
C[1] = Samples[1][ci];
C[2] = Samples[2][ci];
D[0] = Samples[0][di];
D[1] = Samples[1][di];
D[2] = Samples[2][di];
E[0] = Samples[0][ei];
E[1] = Samples[1][ei];
E[2] = Samples[2][ei];
F[0] = Samples[0][fi];
F[1] = Samples[1][fi];
F[2] = Samples[2][fi];
G[0] = Samples[0][gi];
G[1] = Samples[1][gi];
G[2] = Samples[2][gi];
H[0] = Samples[0][hi];
H[1] = Samples[1][hi];
H[2] = Samples[2][hi];
}
else {
G[0] = Samples[0][ai];
G[1] = Samples[1][ai];
G[2] = Samples[2][ai];
H[0] = Samples[0][bi];
H[1] = Samples[1][bi];
H[2] = Samples[2][bi];
E[0] = Samples[0][ci];
E[1] = Samples[1][ci];
E[2] = Samples[2][ci];
F[0] = Samples[0][di];
F[1] = Samples[1][di];
F[2] = Samples[2][di];
C[0] = Samples[0][ei];
C[1] = Samples[1][ei];
C[2] = Samples[2][ei];
D[0] = Samples[0][fi];
D[1] = Samples[1][fi];
D[2] = Samples[2][fi];
A[0] = Samples[0][gi];
A[1] = Samples[1][gi];
A[2] = Samples[2][gi];
B[0] = Samples[0][hi];
B[1] = Samples[1][hi];
B[2] = Samples[2][hi];
}
// Compute tests and go to a new box depending on results
boolean test1, test2, test3, test4;
double tval1, tval2, tval3, tval4;
int ogx = gx;
int ogy = gy;
int ogz = gz;
if (tetnum==1) {
tval1 = ( (E[1]-A[1])*(F[2]-E[2]) - (E[2]-A[2])*(F[1]-E[1]) )
*(value[0][i]-E[0])
+ ( (E[2]-A[2])*(F[0]-E[0]) - (E[0]-A[0])*(F[2]-E[2]) )
*(value[1][i]-E[1])
+ ( (E[0]-A[0])*(F[1]-E[1]) - (E[1]-A[1])*(F[0]-E[0]) )
*(value[2][i]-E[2]);
tval2 = ( (E[1]-H[1])*(A[2]-E[2]) - (E[2]-H[2])*(A[1]-E[1]) )
*(value[0][i]-E[0])
+ ( (E[2]-H[2])*(A[0]-E[0]) - (E[0]-H[0])*(A[2]-E[2]) )
*(value[1][i]-E[1])
+ ( (E[0]-H[0])*(A[1]-E[1]) - (E[1]-H[1])*(A[0]-E[0]) )
*(value[2][i]-E[2]);
tval3 = ( (E[1]-F[1])*(H[2]-E[2]) - (E[2]-F[2])*(H[1]-E[1]) )
*(value[0][i]-E[0])
+ ( (E[2]-F[2])*(H[0]-E[0]) - (E[0]-F[0])*(H[2]-E[2]) )
*(value[1][i]-E[1])
+ ( (E[0]-F[0])*(H[1]-E[1]) - (E[1]-F[1])*(H[0]-E[0]) )
*(value[2][i]-E[2]);
test1 = (tval1 == 0) || ((tval1 > 0) == (!evencube)^Pos);
test2 = (tval2 == 0) || ((tval2 > 0) == (!evencube)^Pos);
test3 = (tval3 == 0) || ((tval3 > 0) == (!evencube)^Pos);
// if a test failed go to a new box
int updown = (evencube) ? -1 : 1;
if (!test1) gy += updown; // UP/DOWN
if (!test2) gx += updown; // LEFT/RIGHT
if (!test3) gz += updown; // BACK/FORWARD
tetnum = 5;
// Snap coordinates back onto grid in case they fell off.
if (gx < 0) gx = 0;
if (gy < 0) gy = 0;
if (gz < 0) gz = 0;
if (gx > LengthX-2) gx = LengthX-2;
if (gy > LengthY-2) gy = LengthY-2;
if (gz > LengthZ-2) gz = LengthZ-2;
// Detect if the point is off the grid entirely
if ( (gx == ogx) && (gy == ogy) && (gz == ogz)
&& (!test1 || !test2 || !test3) && !offgrid ) {
offgrid = true;
continue;
}
// If all tests pass then this is the correct tetrahedron
if ( ( (gx == ogx) && (gy == ogy) && (gz == ogz) )
|| offgrid) {
// solve point
double[] M = new double[3];
double[] N = new double[3];
double[] O = new double[3];
double[] P = new double[3];
double[] X = new double[3];
double[] Y = new double[3];
for (int j=0; j<3; j++) {
M[j] = (F[j]-E[j])*(A[(j+1)%3]-E[(j+1)%3])
- (F[(j+1)%3]-E[(j+1)%3])*(A[j]-E[j]);
N[j] = (H[j]-E[j])*(A[(j+1)%3]-E[(j+1)%3])
- (H[(j+1)%3]-E[(j+1)%3])*(A[j]-E[j]);
O[j] = (F[(j+1)%3]-E[(j+1)%3])*(A[(j+2)%3]-E[(j+2)%3])
- (F[(j+2)%3]-E[(j+2)%3])*(A[(j+1)%3]-E[(j+1)%3]);
P[j] = (H[(j+1)%3]-E[(j+1)%3])*(A[(j+2)%3]-E[(j+2)%3])
- (H[(j+2)%3]-E[(j+2)%3])*(A[(j+1)%3]-E[(j+1)%3]);
X[j] = value[(j+2)%3][i]*(A[(j+1)%3]-E[(j+1)%3])
- value[(j+1)%3][i]*(A[(j+2)%3]-E[(j+2)%3])
+ E[(j+1)%3]*A[(j+2)%3] - E[(j+2)%3]*A[(j+1)%3];
Y[j] = value[j][i]*(A[(j+1)%3]-E[(j+1)%3])
- value[(j+1)%3][i]*(A[j]-E[j])
+ E[(j+1)%3]*A[j] - E[j]*A[(j+1)%3];
}
double s, t, u;
// these if statements handle skewed grids
double d0 = M[0]*P[0] - N[0]*O[0];
double d1 = M[1]*P[1] - N[1]*O[1];
double d2 = M[2]*P[2] - N[2]*O[2];
double ad0 = Math.abs(d0);
double ad1 = Math.abs(d1);
double ad2 = Math.abs(d2);
if (ad0 > ad1 && ad0 > ad2) {
s = (N[0]*X[0] + P[0]*Y[0])/d0;
t = -(M[0]*X[0] + O[0]*Y[0])/d0;
}
else if (ad1 > ad2) {
s = (N[1]*X[1] + P[1]*Y[1])/d1;
t = -(M[1]*X[1] + O[1]*Y[1])/d1;
}
else {
s = (N[2]*X[2] + P[2]*Y[2])/d2;
t = -(M[2]*X[2] + O[2]*Y[2])/d2;
}
d0 = A[0]-E[0];
d1 = A[1]-E[1];
d2 = A[2]-E[2];
ad0 = Math.abs(d0);
ad1 = Math.abs(d1);
ad2 = Math.abs(d2);
if (ad0 > ad1 && ad0 > ad2) {
u = ( value[0][i] - E[0] - s*(F[0]-E[0])
- t*(H[0]-E[0]) ) / d0;
}
else if (ad1 > ad2) {
u = ( value[1][i] - E[1] - s*(F[1]-E[1])
- t*(H[1]-E[1]) ) / d1;
}
else {
u = ( value[2][i] - E[2] - s*(F[2]-E[2])
- t*(H[2]-E[2]) ) / d2;
}
if (evencube) {
grid[0][i] = gx+s;
grid[1][i] = gy+t;
grid[2][i] = gz+u;
}
else {
grid[0][i] = gx+1-s;
grid[1][i] = gy+1-t;
grid[2][i] = gz+1-u;
}
break;
}
}
else if (tetnum==2) {
tval1 = ( (B[1]-C[1])*(F[2]-B[2]) - (B[2]-C[2])*(F[1]-B[1]) )
*(value[0][i]-B[0])
+ ( (B[2]-C[2])*(F[0]-B[0]) - (B[0]-C[0])*(F[2]-B[2]) )
*(value[1][i]-B[1])
+ ( (B[0]-C[0])*(F[1]-B[1]) - (B[1]-C[1])*(F[0]-B[0]) )
*(value[2][i]-B[2]);
tval2 = ( (B[1]-A[1])*(C[2]-B[2]) - (B[2]-A[2])*(C[1]-B[1]) )
*(value[0][i]-B[0])
+ ( (B[2]-A[2])*(C[0]-B[0]) - (B[0]-A[0])*(C[2]-B[2]) )
*(value[1][i]-B[1])
+ ( (B[0]-A[0])*(C[1]-B[1]) - (B[1]-A[1])*(C[0]-B[0]) )
*(value[2][i]-B[2]);
tval3 = ( (B[1]-F[1])*(A[2]-B[2]) - (B[2]-F[2])*(A[1]-B[1]) )
*(value[0][i]-B[0])
+ ( (B[2]-F[2])*(A[0]-B[0]) - (B[0]-F[0])*(A[2]-B[2]) )
*(value[1][i]-B[1])
+ ( (B[0]-F[0])*(A[1]-B[1]) - (B[1]-F[1])*(A[0]-B[0]) )
*(value[2][i]-B[2]);
test1 = (tval1 == 0) || ((tval1 > 0) == (!evencube)^Pos);
test2 = (tval2 == 0) || ((tval2 > 0) == (!evencube)^Pos);
test3 = (tval3 == 0) || ((tval3 > 0) == (!evencube)^Pos);
// if a test failed go to a new box
if (!test1 && evencube) gx++; // RIGHT
if (!test1 && !evencube) gx--; // LEFT
if (!test2 && evencube) gz++; // FORWARD
if (!test2 && !evencube) gz--; // BACK
if (!test3 && evencube) gy--; // UP
if (!test3 && !evencube) gy++; // DOWN
tetnum = 5;
// Snap coordinates back onto grid in case they fell off
if (gx < 0) gx = 0;
if (gy < 0) gy = 0;
if (gz < 0) gz = 0;
if (gx > LengthX-2) gx = LengthX-2;
if (gy > LengthY-2) gy = LengthY-2;
if (gz > LengthZ-2) gz = LengthZ-2;
// Detect if the point is off the grid entirely
if ( (gx == ogx) && (gy == ogy) && (gz == ogz)
&& (!test1 || !test2 || !test3) && !offgrid ) {
offgrid = true;
continue;
}
// If all tests pass then this is the correct tetrahedron
if ( ( (gx == ogx) && (gy == ogy) && (gz == ogz) )
|| offgrid) {
// solve point
double[] M = new double[3];
double[] N = new double[3];
double[] O = new double[3];
double[] P = new double[3];
double[] X = new double[3];
double[] Y = new double[3];
for (int j=0; j<3; j++) {
M[j] = (A[j]-B[j])*(F[(j+1)%3]-B[(j+1)%3])
- (A[(j+1)%3]-B[(j+1)%3])*(F[j]-B[j]);
N[j] = (C[j]-B[j])*(F[(j+1)%3]-B[(j+1)%3])
- (C[(j+1)%3]-B[(j+1)%3])*(F[j]-B[j]);
O[j] = (A[(j+1)%3]-B[(j+1)%3])*(F[(j+2)%3]-B[(j+2)%3])
- (A[(j+2)%3]-B[(j+2)%3])*(F[(j+1)%3]-B[(j+1)%3]);
P[j] = (C[(j+1)%3]-B[(j+1)%3])*(F[(j+2)%3]-B[(j+2)%3])
- (C[(j+2)%3]-B[(j+2)%3])*(F[(j+1)%3]-B[(j+1)%3]);
X[j] = value[(j+2)%3][i]*(F[(j+1)%3]-B[(j+1)%3])
- value[(j+1)%3][i]*(F[(j+2)%3]-B[(j+2)%3])
+ B[(j+1)%3]*F[(j+2)%3] - B[(j+2)%3]*F[(j+1)%3];
Y[j] = value[j][i]*(F[(j+1)%3]-B[(j+1)%3])
- value[1][i]*(F[j]-B[j])
+ B[(j+1)%3]*F[j] - B[j]*F[(j+1)%3];
}
double s, t, u;
// these if statements handle skewed grids
double d0 = M[0]*P[0] - N[0]*O[0];
double d1 = M[1]*P[1] - N[1]*O[1];
double d2 = M[2]*P[2] - N[2]*O[2];
double ad0 = Math.abs(d0);
double ad1 = Math.abs(d1);
double ad2 = Math.abs(d2);
if (ad0 > ad1 && ad0 > ad2) {
s = 1 - (N[0]*X[0] + P[0]*Y[0])/d0;
t = -(M[0]*X[0] + O[0]*Y[0])/d0;
}
else if (ad1 > ad2) {
s = 1 - (N[1]*X[1] + P[1]*Y[1])/d1;
t = -(M[1]*X[1] + O[1]*Y[1])/d1;
}
else {
s = 1 - (N[2]*X[2] + P[2]*Y[2])/d2;
t = -(M[2]*X[2] + O[2]*Y[2])/d2;
}
d0 = F[0]-B[0];
d1 = F[1]-B[1];
d2 = F[2]-B[2];
ad0 = Math.abs(d0);
ad1 = Math.abs(d1);
ad2 = Math.abs(d2);
if (ad0 > ad1 && ad0 > ad2) {
u = 1 - ( value[0][i] - B[0] - (1-s)*(A[0]-B[0])
- t*(C[0]-B[0]) ) / d0;
}
else if (ad1 > ad2) {
u = 1 - ( value[1][i] - B[1] - (1-s)*(A[1]-B[1])
- t*(C[1]-B[1]) ) / d1;
}
else {
u = 1 - ( value[2][i] - B[2] - (1-s)*(A[2]-B[2])
- t*(C[2]-B[2]) ) / d2;
}
if (evencube) {
grid[0][i] = gx+s;
grid[1][i] = gy+t;
grid[2][i] = gz+u;
}
else {
grid[0][i] = gx+1-s;
grid[1][i] = gy+1-t;
grid[2][i] = gz+1-u;
}
break;
}
}
else if (tetnum==3) {
tval1 = ( (D[1]-A[1])*(H[2]-D[2]) - (D[2]-A[2])*(H[1]-D[1]) )
*(value[0][i]-D[0])
+ ( (D[2]-A[2])*(H[0]-D[0]) - (D[0]-A[0])*(H[2]-D[2]) )
*(value[1][i]-D[1])
+ ( (D[0]-A[0])*(H[1]-D[1]) - (D[1]-A[1])*(H[0]-D[0]) )
*(value[2][i]-D[2]);
tval2 = ( (D[1]-C[1])*(A[2]-D[2]) - (D[2]-C[2])*(A[1]-D[1]) )
*(value[0][i]-D[0])
+ ( (D[2]-C[2])*(A[0]-D[0]) - (D[0]-C[0])*(A[2]-D[2]) )
*(value[1][i]-D[1])
+ ( (D[0]-C[0])*(A[1]-D[1]) - (D[1]-C[1])*(A[0]-D[0]) )
*(value[2][i]-D[2]);
tval3 = ( (D[1]-H[1])*(C[2]-D[2]) - (D[2]-H[2])*(C[1]-D[1]) )
*(value[0][i]-D[0])
+ ( (D[2]-H[2])*(C[0]-D[0]) - (D[0]-H[0])*(C[2]-D[2]) )
*(value[1][i]-D[1])
+ ( (D[0]-H[0])*(C[1]-D[1]) - (D[1]-H[1])*(C[0]-D[0]) )
*(value[2][i]-D[2]);
test1 = (tval1 == 0) || ((tval1 > 0) == (!evencube)^Pos);
test2 = (tval2 == 0) || ((tval2 > 0) == (!evencube)^Pos);
test3 = (tval3 == 0) || ((tval3 > 0) == (!evencube)^Pos);
// if a test failed go to a new box
if (!test1 && evencube) gx--; // LEFT
if (!test1 && !evencube) gx++; // RIGHT
if (!test2 && evencube) gz++; // FORWARD
if (!test2 && !evencube) gz--; // BACK
if (!test3 && evencube) gy++; // DOWN
if (!test3 && !evencube) gy--; // UP
tetnum = 5;
// Snap coordinates back onto grid in case they fell off
if (gx < 0) gx = 0;
if (gy < 0) gy = 0;
if (gz < 0) gz = 0;
if (gx > LengthX-2) gx = LengthX-2;
if (gy > LengthY-2) gy = LengthY-2;
if (gz > LengthZ-2) gz = LengthZ-2;
// Detect if the point is off the grid entirely
if ( (gx == ogx) && (gy == ogy) && (gz == ogz)
&& (!test1 || !test2 || !test3) && !offgrid ) {
offgrid = true;
continue;
}
// If all tests pass then this is the correct tetrahedron
if ( ( (gx == ogx) && (gy == ogy) && (gz == ogz) )
|| offgrid) {
// solve point
double[] M = new double[3];
double[] N = new double[3];
double[] O = new double[3];
double[] P = new double[3];
double[] X = new double[3];
double[] Y = new double[3];
for (int j=0; j<3; j++) {
M[j] = (C[j]-D[j])*(H[(j+1)%3]-D[(j+1)%3])
- (C[(j+1)%3]-D[(j+1)%3])*(H[j]-D[j]);
N[j] = (A[j]-D[j])*(H[(j+1)%3]-D[(j+1)%3])
- (A[(j+1)%3]-D[(j+1)%3])*(H[j]-D[j]);
O[j] = (C[(j+1)%3]-D[(j+1)%3])*(H[(j+2)%3]-D[(j+2)%3])
- (C[(j+2)%3]-D[(j+2)%3])*(H[(j+1)%3]-D[(j+1)%3]);
P[j] = (A[(j+1)%3]-D[(j+1)%3])*(H[(j+2)%3]-D[(j+2)%3])
- (A[(j+2)%3]-D[(j+2)%3])*(H[(j+1)%3]-D[(j+1)%3]);
X[j] = value[(j+2)%3][i]*(H[(j+1)%3]-D[(j+1)%3])
- value[(j+1)%3][i]*(H[(j+2)%3]-D[(j+2)%3])
+ D[(j+1)%3]*H[(j+2)%3] - D[(j+2)%3]*H[(j+1)%3];
Y[j] = value[j][i]*(H[(j+1)%3]-D[(j+1)%3])
- value[(j+1)%3][i]*(H[j]-D[j])
+ D[(j+1)%3]*H[j] - D[j]*H[(j+1)%3];
}
double s, t, u;
// these if statements handle skewed grids
double d0 = M[0]*P[0] - N[0]*O[0];
double d1 = M[1]*P[1] - N[1]*O[1];
double d2 = M[2]*P[2] - N[2]*O[2];
double ad0 = Math.abs(d0);
double ad1 = Math.abs(d1);
double ad2 = Math.abs(d2);
if (ad0 > ad1 && ad0 > ad2) {
s = (N[0]*X[0] + P[0]*Y[0])/d0;
t = 1 + (M[0]*X[0] + O[0]*Y[0])/d0;
}
else if (ad1 > ad2) {
s = (N[1]*X[1] + P[1]*Y[1])/d1;
t = 1 + (M[1]*X[1] + O[1]*Y[1])/d1;
}
else {
s = (N[2]*X[2] + P[2]*Y[2])/d2;
t = 1 + (M[2]*X[2] + O[2]*Y[2])/d2;
}
d0 = H[0]-D[0];
d1 = H[1]-D[1];
d2 = H[2]-D[2];
ad0 = Math.abs(d0);
ad1 = Math.abs(d1);
ad2 = Math.abs(d2);
if (ad0 > ad1 && ad0 > ad2) {
u = 1 - ( value[0][i] - D[0] - s*(C[0]-D[0])
- (1-t)*(A[0]-D[0]) ) / d0;
}
else if (ad1 > ad2) {
u = 1 - ( value[1][i] - D[1] - s*(C[1]-D[1])
- (1-t)*(A[1]-D[1]) ) / d1;
}
else {
u = 1 - ( value[2][i] - D[2] - s*(C[2]-D[2])
- (1-t)*(A[2]-D[2]) ) / d2;
}
if (evencube) {
grid[0][i] = gx+s;
grid[1][i] = gy+t;
grid[2][i] = gz+u;
}
else {
grid[0][i] = gx+1-s;
grid[1][i] = gy+1-t;
grid[2][i] = gz+1-u;
}
break;
}
}
else if (tetnum==4) {
tval1 = ( (G[1]-C[1])*(H[2]-G[2]) - (G[2]-C[2])*(H[1]-G[1]) )
*(value[0][i]-G[0])
+ ( (G[2]-C[2])*(H[0]-G[0]) - (G[0]-C[0])*(H[2]-G[2]) )
*(value[1][i]-G[1])
+ ( (G[0]-C[0])*(H[1]-G[1]) - (G[1]-C[1])*(H[0]-G[0]) )
*(value[2][i]-G[2]);
tval2 = ( (G[1]-F[1])*(C[2]-G[2]) - (G[2]-F[2])*(C[1]-G[1]) )
*(value[0][i]-G[0])
+ ( (G[2]-F[2])*(C[0]-G[0]) - (G[0]-F[0])*(C[2]-G[2]) )
*(value[1][i]-G[1])
+ ( (G[0]-F[0])*(C[1]-G[1]) - (G[1]-F[1])*(C[0]-G[0]) )
*(value[2][i]-G[2]);
tval3 = ( (G[1]-H[1])*(F[2]-G[2]) - (G[2]-H[2])*(F[1]-G[1]) )
*(value[0][i]-G[0])
+ ( (G[2]-H[2])*(F[0]-G[0]) - (G[0]-H[0])*(F[2]-G[2]) )
*(value[1][i]-G[1])
+ ( (G[0]-H[0])*(F[1]-G[1]) - (G[1]-H[1])*(F[0]-G[0]) )
*(value[2][i]-G[2]);
test1 = (tval1 == 0) || ((tval1 > 0) == (!evencube)^Pos);
test2 = (tval2 == 0) || ((tval2 > 0) == (!evencube)^Pos);
test3 = (tval3 == 0) || ((tval3 > 0) == (!evencube)^Pos);
// if a test failed go to a new box
if (!test1 && evencube) gy++; // DOWN
if (!test1 && !evencube) gy--; // UP
if (!test2 && evencube) gx++; // RIGHT
if (!test2 && !evencube) gx--; // LEFT
if (!test3 && evencube) gz--; // BACK
if (!test3 && !evencube) gz++; // FORWARD
tetnum = 5;
// Snap coordinates back onto grid in case they fell off
if (gx < 0) gx = 0;
if (gy < 0) gy = 0;
if (gz < 0) gz = 0;
if (gx > LengthX-2) gx = LengthX-2;
if (gy > LengthY-2) gy = LengthY-2;
if (gz > LengthZ-2) gz = LengthZ-2;
// Detect if the point is off the grid entirely
if ( (gx == ogx) && (gy == ogy) && (gz == ogz)
&& (!test1 || !test2 || !test3) && !offgrid ) {
offgrid = true;
continue;
}
// If all tests pass then this is the correct tetrahedron
if ( ( (gx == ogx) && (gy == ogy) && (gz == ogz) )
|| offgrid) {
// solve point
double[] M = new double[3];
double[] N = new double[3];
double[] O = new double[3];
double[] P = new double[3];
double[] X = new double[3];
double[] Y = new double[3];
for (int j=0; j<3; j++) {
M[j] = (H[j]-G[j])*(C[(j+1)%3]-G[(j+1)%3])
- (H[(j+1)%3]-G[(j+1)%3])*(C[j]-G[j]);
N[j] = (F[j]-G[j])*(C[(j+1)%3]-G[(j+1)%3])
- (F[(j+1)%3]-G[(j+1)%3])*(C[j]-G[j]);
O[j] = (H[(j+1)%3]-G[(j+1)%3])*(C[(j+2)%3]-G[(j+2)%3])
- (H[(j+2)%3]-G[(j+2)%3])*(C[(j+1)%3]-G[(j+1)%3]);
P[j] = (F[(j+1)%3]-G[(j+1)%3])*(C[(j+2)%3]-G[(j+2)%3])
- (F[(j+2)%3]-G[(j+2)%3])*(C[(j+1)%3]-G[(j+1)%3]);
X[j] = value[(j+2)%3][i]*(C[(j+1)%3]-G[(j+1)%3])
- value[(j+1)%3][i]*(C[(j+2)%3]-G[(j+2)%3])
+ G[(j+1)%3]*C[(j+2)%3] - G[(j+2)%3]*C[(j+1)%3];
Y[j] = value[j][i]*(C[(j+1)%3]-G[(j+1)%3])
- value[(j+1)%3][i]*(C[j]-G[j])
+ G[(j+1)%3]*C[j] - G[j]*C[(j+1)%3];
}
double s, t, u;
// these if statements handle skewed grids
double d0 = M[0]*P[0] - N[0]*O[0];
double d1 = M[1]*P[1] - N[1]*O[1];
double d2 = M[2]*P[2] - N[2]*O[2];
double ad0 = Math.abs(d0);
double ad1 = Math.abs(d1);
double ad2 = Math.abs(d2);
if (ad0 > ad1 && ad0 > ad2) {
s = 1 - (N[0]*X[0] + P[0]*Y[0])/d0;
t = 1 + (M[0]*X[0] + O[0]*Y[0])/d0;
}
else if (ad1 > ad2) {
s = 1 - (N[1]*X[1] + P[1]*Y[1])/d1;
t = 1 + (M[1]*X[1] + O[1]*Y[1])/d1;
}
else {
s = 1 - (N[2]*X[2] + P[2]*Y[2])/d2;
t = 1 + (M[2]*X[2] + O[2]*Y[2])/d2;
}
d0 = C[0]-G[0];
d1 = C[1]-G[1];
d2 = C[2]-G[2];
ad0 = Math.abs(d0);
ad1 = Math.abs(d1);
ad2 = Math.abs(d2);
if (ad0 > ad1 && ad0 > ad2) {
u = ( value[0][i] - G[0] - (1-s)*(H[0]-G[0])
- (1-t)*(F[0]-G[0]) ) / d0;
}
else if (ad1 > ad2) {
u = ( value[1][i] - G[1] - (1-s)*(H[1]-G[1])
- (1-t)*(F[1]-G[1]) ) / d1;
}
else {
u = ( value[2][i] - G[2] - (1-s)*(H[2]-G[2])
- (1-t)*(F[2]-G[2]) ) / d2;
}
if (evencube) {
grid[0][i] = gx+s;
grid[1][i] = gy+t;
grid[2][i] = gz+u;
}
else {
grid[0][i] = gx+1-s;
grid[1][i] = gy+1-t;
grid[2][i] = gz+1-u;
}
break;
}
}
else { // tetnum==5
tval1 = ( (F[1]-H[1])*(A[2]-F[2]) - (F[2]-H[2])*(A[1]-F[1]) )
*(value[0][i]-F[0])
+ ( (F[2]-H[2])*(A[0]-F[0]) - (F[0]-H[0])*(A[2]-F[2]) )
*(value[1][i]-F[1])
+ ( (F[0]-H[0])*(A[1]-F[1]) - (F[1]-H[1])*(A[0]-F[0]) )
*(value[2][i]-F[2]);
tval2 = ( (C[1]-F[1])*(A[2]-C[2]) - (C[2]-F[2])*(A[1]-C[1]) )
*(value[0][i]-C[0])
+ ( (C[2]-F[2])*(A[0]-C[0]) - (C[0]-F[0])*(A[2]-C[2]) )
*(value[1][i]-C[1])
+ ( (C[0]-F[0])*(A[1]-C[1]) - (C[1]-F[1])*(A[0]-C[0]) )
*(value[2][i]-C[2]);
tval3 = ( (C[1]-A[1])*(H[2]-C[2]) - (C[2]-A[2])*(H[1]-C[1]) )
*(value[0][i]-C[0])
+ ( (C[2]-A[2])*(H[0]-C[0]) - (C[0]-A[0])*(H[2]-C[2]) )
*(value[1][i]-C[1])
+ ( (C[0]-A[0])*(H[1]-C[1]) - (C[1]-A[1])*(H[0]-C[0]) )
*(value[2][i]-C[2]);
tval4 = ( (F[1]-C[1])*(H[2]-F[2]) - (F[2]-C[2])*(H[1]-F[1]) )
*(value[0][i]-F[0])
+ ( (F[2]-C[2])*(H[0]-F[0]) - (F[0]-C[0])*(H[2]-F[2]) )
*(value[1][i]-F[1])
+ ( (F[0]-C[0])*(H[1]-F[1]) - (F[1]-C[1])*(H[0]-F[0]) )
*(value[2][i]-F[2]);
test1 = (tval1 == 0) || ((tval1 > 0) == (!evencube)^Pos);
test2 = (tval2 == 0) || ((tval2 > 0) == (!evencube)^Pos);
test3 = (tval3 == 0) || ((tval3 > 0) == (!evencube)^Pos);
test4 = (tval4 == 0) || ((tval4 > 0) == (!evencube)^Pos);
// if a test failed go to a new tetrahedron
if (!test1 && test2 && test3 && test4) tetnum = 1;
if (test1 && !test2 && test3 && test4) tetnum = 2;
if (test1 && test2 && !test3 && test4) tetnum = 3;
if (test1 && test2 && test3 && !test4) tetnum = 4;
if ( (!test1 && !test2 && evencube)
|| (!test3 && !test4 && !evencube) ) gy--; // GO UP
if ( (!test1 && !test3 && evencube)
|| (!test2 && !test4 && !evencube) ) gx--; // GO LEFT
if ( (!test1 && !test4 && evencube)
|| (!test2 && !test3 && !evencube) ) gz--; // GO BACK
if ( (!test2 && !test3 && evencube)
|| (!test1 && !test4 && !evencube) ) gz++; // GO FORWARD
if ( (!test2 && !test4 && evencube)
|| (!test1 && !test3 && !evencube) ) gx++; // GO RIGHT
if ( (!test3 && !test4 && evencube)
|| (!test1 && !test2 && !evencube) ) gy++; // GO DOWN
// Snap coordinates back onto grid in case they fell off
if (gx < 0) gx = 0;
if (gy < 0) gy = 0;
if (gz < 0) gz = 0;
if (gx > LengthX-2) gx = LengthX-2;
if (gy > LengthY-2) gy = LengthY-2;
if (gz > LengthZ-2) gz = LengthZ-2;
// Detect if the point is off the grid entirely
if ( ( (gx == ogx) && (gy == ogy) && (gz == ogz)
&& (!test1 || !test2 || !test3 || !test4)
&& (tetnum == 5)) || offgrid) {
offgrid = true;
boolean OX, OY, OZ, MX, MY, MZ, LX, LY, LZ;
OX = OY = OZ = MX = MY = MZ = LX = LY = LZ = false;
if (gx == 0) OX = true;
if (gy == 0) OY = true;
if (gz == 0) OZ = true;
if (gx == LengthX-2) LX = true;
if (gy == LengthY-2) LY = true;
if (gz == LengthZ-2) LZ = true;
if (!OX && !LX) MX = true;
if (!OY && !LY) MY = true;
if (!OZ && !LZ) MZ = true;
test1 = test2 = test3 = test4 = false;
// 26 cases
if (evencube) {
if (!LX && !LY && !LZ) tetnum = 1;
else if ( (LX && OY && MZ) || (MX && OY && LZ)
|| (LX && MY && LZ) || (LX && OY && LZ)
|| (MX && MY && LZ) || (LX && MY && MZ) ) tetnum = 2;
else if ( (OX && LY && MZ) || (OX && MY && LZ)
|| (MX && LY && LZ) || (OX && LY && LZ)
|| (MX && LY && MZ) ) tetnum = 3;
else if ( (MX && LY && OZ) || (LX && MY && OZ)
|| (LX && LY && MZ) || (LX && LY && OZ) ) tetnum = 4;
}
else {
if (!OX && !OY && !OZ) tetnum = 1;
else if ( (OX && MY && OZ) || (MX && LY && OZ)
|| (OX && LY && MZ) || (OX && LY && OZ)
|| (MX && MY && OZ) || (OX && MY && MZ) ) tetnum = 2;
else if ( (LX && MY && OZ) || (MX && OY && OZ)
|| (LX && OY && MZ) || (LX && OY && OZ)
|| (MX && OY && MZ) ) tetnum = 3;
else if ( (OX && OY && MZ) || (OX && MY && OZ)
|| (MX && OY && LZ) || (OX && OY && LZ) ) tetnum = 4;
}
}
// If all tests pass then this is the correct tetrahedron
if ( (gx == ogx) && (gy == ogy) && (gz == ogz) && (tetnum == 5) ) {
// solve point
double[] Q = new double[3];
for (int j=0; j<3; j++) {
Q[j] = (H[j] + F[j] + A[j] - C[j])/2;
}
double[] M = new double[3];
double[] N = new double[3];
double[] O = new double[3];
double[] P = new double[3];
double[] X = new double[3];
double[] Y = new double[3];
for (int j=0; j<3; j++) {
M[j] = (F[j]-Q[j])*(A[(j+1)%3]-Q[(j+1)%3])
- (F[(j+1)%3]-Q[(j+1)%3])*(A[j]-Q[j]);
N[j] = (H[j]-Q[j])*(A[(j+1)%3]-Q[(j+1)%3])
- (H[(j+1)%3]-Q[(j+1)%3])*(A[j]-Q[j]);
O[j] = (F[(j+1)%3]-Q[(j+1)%3])*(A[(j+2)%3]-Q[(j+2)%3])
- (F[(j+2)%3]-Q[(j+2)%3])*(A[(j+1)%3]-Q[(j+1)%3]);
P[j] = (H[(j+1)%3]-Q[(j+1)%3])*(A[(j+2)%3]-Q[(j+2)%3])
- (H[(j+2)%3]-Q[(j+2)%3])*(A[(j+1)%3]-Q[(j+1)%3]);
X[j] = value[(j+2)%3][i]*(A[(j+1)%3]-Q[(j+1)%3])
- value[(j+1)%3][i]*(A[(j+2)%3]-Q[(j+2)%3])
+ Q[(j+1)%3]*A[(j+2)%3] - Q[(j+2)%3]*A[(j+1)%3];
Y[j] = value[j][i]*(A[(j+1)%3]-Q[(j+1)%3])
- value[(j+1)%3][i]*(A[j]-Q[j])
+ Q[(j+1)%3]*A[j] - Q[j]*A[(j+1)%3];
}
double s, t, u;
// these if statements handle skewed grids
double d0 = M[0]*P[0] - N[0]*O[0];
double d1 = M[1]*P[1] - N[1]*O[1];
double d2 = M[2]*P[2] - N[2]*O[2];
double ad0 = Math.abs(d0);
double ad1 = Math.abs(d1);
double ad2 = Math.abs(d2);
if (ad0 > ad1 && ad0 > ad2) {
s = (N[0]*X[0] + P[0]*Y[0])/d0;
t = -(M[0]*X[0] + O[0]*Y[0])/d0;
}
else if (ad1 > ad2) {
s = (N[1]*X[1] + P[1]*Y[1])/d1;
t = -(M[1]*X[1] + O[1]*Y[1])/d1;
}
else {
s = (N[2]*X[2] + P[2]*Y[2])/d2;
t = -(M[2]*X[2] + O[2]*Y[2])/d2;
}
d0 = A[0]-Q[0];
d1 = A[1]-Q[1];
d2 = A[2]-Q[2];
ad0 = Math.abs(d0);
ad1 = Math.abs(d1);
ad2 = Math.abs(d2);
if (ad0 > ad1 && ad0 > ad2) {
u = ( value[0][i] - Q[0] - s*(F[0]-Q[0])
- t*(H[0]-Q[0]) ) / d0;
}
else if (ad1 > ad2) {
u = ( value[1][i] - Q[1] - s*(F[1]-Q[1])
- t*(H[1]-Q[1]) ) / d1;
}
else {
u = ( value[2][i] - Q[2] - s*(F[2]-Q[2])
- t*(H[2]-Q[2]) ) / d2;
}
if (evencube) {
grid[0][i] = gx+s;
grid[1][i] = gy+t;
grid[2][i] = gz+u;
}
else {
grid[0][i] = gx+1-s;
grid[1][i] = gy+1-t;
grid[2][i] = gz+1-u;
}
break;
}
}
}
// allow estimations up to 0.5 boxes outside of defined samples
if ( (grid[0][i] <= -0.5) || (grid[0][i] >= LengthX-0.5)
|| (grid[1][i] <= -0.5) || (grid[1][i] >= LengthY-0.5)
|| (grid[2][i] <= -0.5) || (grid[2][i] >= LengthZ-0.5) ) {
grid[0][i] = grid[1][i] = grid[2][i] = Double.NaN;
}
}
return grid;
}
/** for each of an array of values in R^DomainDimension, compute an array
of 1-D indices and an array of weights, to be used for interpolation;
indices[i] and weights[i] are null if i-th value is outside grid
(i.e., if no interpolation is possible) */
public void doubleToInterp(double[][] value, int[][] indices,
double[][] weights) throws VisADException
{
if (value.length != DomainDimension) {
throw new SetException("Gridded3DDoubleSet.doubleToInterp: value dimension " +
value.length + " not equal to Domain dimension " +
DomainDimension);
}
int length = value[0].length; // number of values
if (indices.length != length) {
throw new SetException("Gridded3DDoubleSet.doubleToInterp: indices length " +
indices.length +
" doesn't match value[0] length " +
value[0].length);
}
if (weights.length != length) {
throw new SetException("Gridded3DDoubleSet.doubleToInterp: weights length " +
weights.length +
" doesn't match value[0] length " +
value[0].length);
}
// convert value array to grid coord array
double[][] grid = doubleToGrid(value);
int i, j, k; // loop indices
int lis; // temporary length of is & cs
int length_is; // final length of is & cs, varies by i
int isoff; // offset along one grid dimension
double a, b; // weights along one grid dimension; a + b = 1.0
int[] is; // array of indices, becomes part of indices
double[] cs; // array of coefficients, become part of weights
int base; // base index, as would be returned by valueToIndex
int[] l = new int[ManifoldDimension]; // integer 'factors' of base
// fractions with l; -0.5 <= c <= 0.5
double[] c = new double[ManifoldDimension];
// array of index offsets by grid dimension
int[] off = new int[ManifoldDimension];
off[0] = 1;
for (j=1; j<ManifoldDimension; j++) off[j] = off[j-1] * Lengths[j-1];
for (i=0; i<length; i++) {
// compute length_is, base, l & c
length_is = 1;
if (Double.isNaN(grid[ManifoldDimension-1][i])) {
base = -1;
}
else {
l[ManifoldDimension-1] = (int) (grid[ManifoldDimension-1][i] + 0.5);
// WLH 23 Dec 99
if (l[ManifoldDimension-1] == Lengths[ManifoldDimension-1]) {
l[ManifoldDimension-1]--;
}
c[ManifoldDimension-1] = grid[ManifoldDimension-1][i] -
((double) l[ManifoldDimension-1]);
if (!((l[ManifoldDimension-1] == 0 && c[ManifoldDimension-1] <= 0.0) ||
(l[ManifoldDimension-1] == Lengths[ManifoldDimension-1] - 1 &&
c[ManifoldDimension-1] >= 0.0))) {
// only interp along ManifoldDimension-1
// if between two valid grid coords
length_is *= 2;
}
base = l[ManifoldDimension-1];
}
for (j=ManifoldDimension-2; j>=0 && base>=0; j--) {
if (Double.isNaN(grid[j][i])) {
base = -1;
}
else {
l[j] = (int) (grid[j][i] + 0.5);
if (l[j] == Lengths[j]) l[j]--; // WLH 23 Dec 99
c[j] = grid[j][i] - ((double) l[j]);
if (!((l[j] == 0 && c[j] <= 0.0) ||
(l[j] == Lengths[j] - 1 && c[j] >= 0.0))) {
// only interp along dimension j if between two valid grid coords
length_is *= 2;
}
base = l[j] + Lengths[j] * base;
}
}
if (base < 0) {
// value is out of grid so return null
is = null;
cs = null;
}
else {
// create is & cs of proper length, and init first element
is = new int[length_is];
cs = new double[length_is];
is[0] = base;
cs[0] = 1.0f;
lis = 1;
for (j=0; j<ManifoldDimension; j++) {
if (!((l[j] == 0 && c[j] <= 0.0) ||
(l[j] == Lengths[j] - 1 && c[j] >= 0.0))) {
// only interp along dimension j if between two valid grid coords
if (c[j] >= 0.0) {
// grid coord above base
isoff = off[j];
a = 1.0f - c[j];
b = c[j];
}
else {
// grid coord below base
isoff = -off[j];
a = 1.0f + c[j];
b = -c[j];
}
// double is & cs; adjust new offsets; split weights
for (k=0; k<lis; k++) {
is[k+lis] = is[k] + isoff;
cs[k+lis] = cs[k] * b;
cs[k] *= a;
}
lis *= 2;
}
}
}
indices[i] = is;
weights[i] = cs;
}
}
// Miscellaneous Set methods that must be overridden
// (this code is duplicated throughout all *DoubleSet classes)
void init_doubles(double[][] samples, boolean copy)
throws VisADException {
if (samples.length != DomainDimension) {
throw new SetException("Gridded3DDoubleSet.init_doubles: samples dimension " +
samples.length +
" not equal to Domain dimension " +
DomainDimension);
}
if (Length == 0) {
// Length set in init_lengths, but not called for IrregularSet
Length = samples[0].length;
}
else {
if (Length != samples[0].length) {
throw new SetException("Gridded3DDoubleSet.init_doubles: " +
"samples[0] length " + samples[0].length +
" doesn't match expected length " + Length);
}
}
// MEM
if (copy) {
Samples = new double[DomainDimension][Length];
}
else {
Samples = samples;
}
for (int j=0; j<DomainDimension; j++) {
if (samples[j].length != Length) {
throw new SetException("Gridded3DDoubleSet.init_doubles: " +
"samples[" + j + "] length " +
samples[0].length +
" doesn't match expected length " + Length);
}
double[] samplesJ = samples[j];
double[] SamplesJ = Samples[j];
if (copy) {
System.arraycopy(samplesJ, 0, SamplesJ, 0, Length);
}
Low[j] = Double.POSITIVE_INFINITY;
Hi[j] = Double.NEGATIVE_INFINITY;
double sum = 0.0f;
for (int i=0; i<Length; i++) {
if (SamplesJ[i] == SamplesJ[i] && !Double.isInfinite(SamplesJ[i])) {
if (SamplesJ[i] < Low[j]) Low[j] = SamplesJ[i];
if (SamplesJ[i] > Hi[j]) Hi[j] = SamplesJ[i];
}
else {
SamplesJ[i] = Double.NaN;
}
sum += SamplesJ[i];
}
if (SetErrors[j] != null ) {
SetErrors[j] =
new ErrorEstimate(SetErrors[j].getErrorValue(), sum / Length,
Length, SetErrors[j].getUnit());
}
super.Low[j] = (float) Low[j];
super.Hi[j] = (float) Hi[j];
}
}
public void cram_missing(boolean[] range_select) {
int n = Math.min(range_select.length, Samples[0].length);
for (int i=0; i<n; i++) {
if (!range_select[i]) Samples[0][i] = Double.NaN;
}
}
public boolean isMissing() {
return (Samples == null);
}
public boolean equals(Object set) {
if (!(set instanceof Gridded3DDoubleSet) || set == null) return false;
if (this == set) return true;
if (testNotEqualsCache((Set) set)) return false;
if (testEqualsCache((Set) set)) return true;
if (!equalUnitAndCS((Set) set)) return false;
try {
int i, j;
if (DomainDimension != ((Gridded3DDoubleSet) set).getDimension() ||
ManifoldDimension !=
((Gridded3DDoubleSet) set).getManifoldDimension() ||
Length != ((Gridded3DDoubleSet) set).getLength()) return false;
for (j=0; j<ManifoldDimension; j++) {
if (Lengths[j] != ((Gridded3DDoubleSet) set).getLength(j)) {
return false;
}
}
// Sets are immutable, so no need for 'synchronized'
double[][] samples = ((Gridded3DDoubleSet) set).getDoubles(false);
if (Samples != null && samples != null) {
for (j=0; j<DomainDimension; j++) {
for (i=0; i<Length; i++) {
if (Samples[j][i] != samples[j][i]) {
addNotEqualsCache((Set) set);
return false;
}
}
}
}
else {
double[][] this_samples = getDoubles(false);
if (this_samples == null) {
if (samples != null) {
return false;
}
} else if (samples == null) {
return false;
} else {
for (j=0; j<DomainDimension; j++) {
for (i=0; i<Length; i++) {
if (this_samples[j][i] != samples[j][i]) {
addNotEqualsCache((Set) set);
return false;
}
}
}
}
}
addEqualsCache((Set) set);
return true;
}
catch (VisADException e) {
return false;
}
}
/**
* Clones this instance.
*
* @return A clone of this instance.
*/
public Object clone() {
Gridded3DDoubleSet clone = (Gridded3DDoubleSet)super.clone();
if (Samples != null) {
/*
* The Samples array is cloned because getDoubles(false) allows clients
* to manipulate the array and the general clone() contract forbids
* cross-clone contamination.
*/
clone.Samples = (double[][])Samples.clone();
for (int i = 0; i < Samples.length; i++)
clone.Samples[i] = (double[])Samples[i].clone();
}
return clone;
}
public Object cloneButType(MathType type) throws VisADException {
if (ManifoldDimension == 3) {
return new Gridded3DDoubleSet(type, Samples, LengthX, LengthY, LengthZ,
DomainCoordinateSystem, SetUnits, SetErrors);
}
else if (ManifoldDimension == 2) {
return new Gridded3DDoubleSet(type, Samples, LengthX, LengthY,
DomainCoordinateSystem, SetUnits, SetErrors);
}
else {
return new Gridded3DDoubleSet(type, Samples, LengthX,
DomainCoordinateSystem, SetUnits, SetErrors);
}
}
/* WLH 3 April 2003
public Object cloneButType(MathType type) throws VisADException {
return new Gridded3DDoubleSet(type, Samples, Length,
DomainCoordinateSystem, SetUnits, SetErrors);
}
*/
}
| false | false | null | null |
diff --git a/server/cluster-mgmt/src/main/java/com/vmware/bdd/service/impl/ClusteringService.java b/server/cluster-mgmt/src/main/java/com/vmware/bdd/service/impl/ClusteringService.java
index 1896c4ce..7895c7c0 100644
--- a/server/cluster-mgmt/src/main/java/com/vmware/bdd/service/impl/ClusteringService.java
+++ b/server/cluster-mgmt/src/main/java/com/vmware/bdd/service/impl/ClusteringService.java
@@ -1,1706 +1,1704 @@
/***************************************************************************
* Copyright (c) 2012-2013 VMware, Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
***************************************************************************/
package com.vmware.bdd.service.impl;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
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 java.util.Set;
import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.vmware.bdd.apitypes.ClusterRead.ClusterStatus;
import com.vmware.bdd.service.IClusterInitializerService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import com.google.gson.Gson;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.vmware.aurora.composition.CreateVMFolderSP;
import com.vmware.aurora.composition.DeleteVMFolderSP;
import com.vmware.aurora.composition.DiskSchema;
import com.vmware.aurora.composition.DiskSchema.Disk;
import com.vmware.aurora.composition.NetworkSchema.Network;
import com.vmware.aurora.composition.VmSchema;
import com.vmware.aurora.composition.concurrent.ExecutionResult;
import com.vmware.aurora.composition.concurrent.Scheduler;
import com.vmware.aurora.global.Configuration;
import com.vmware.aurora.util.CmsWorker;
import com.vmware.aurora.vc.DeviceId;
import com.vmware.aurora.vc.VcCache;
import com.vmware.aurora.vc.VcCluster;
import com.vmware.aurora.vc.VcDatacenter;
import com.vmware.aurora.vc.VcDatastore;
import com.vmware.aurora.vc.VcHost;
import com.vmware.aurora.vc.VcInventory;
import com.vmware.aurora.vc.VcResourcePool;
import com.vmware.aurora.vc.VcSnapshot;
import com.vmware.aurora.vc.VcVirtualMachine;
import com.vmware.aurora.vc.vcevent.VcEventRouter;
import com.vmware.aurora.vc.vcservice.VcContext;
import com.vmware.aurora.vc.vcservice.VcSession;
import com.vmware.bdd.apitypes.ClusterCreate;
import com.vmware.bdd.apitypes.IpBlock;
import com.vmware.bdd.apitypes.NetworkAdd;
import com.vmware.bdd.apitypes.NodeGroupCreate;
import com.vmware.bdd.apitypes.Priority;
import com.vmware.bdd.apitypes.StorageRead.DiskScsiControllerType;
import com.vmware.bdd.apitypes.StorageRead.DiskType;
import com.vmware.bdd.dal.IResourcePoolDAO;
import com.vmware.bdd.entity.ClusterEntity;
import com.vmware.bdd.entity.NodeEntity;
import com.vmware.bdd.entity.resmgmt.ResourceReservation;
import com.vmware.bdd.exception.BddException;
import com.vmware.bdd.exception.ClusteringServiceException;
import com.vmware.bdd.exception.VcProviderException;
import com.vmware.bdd.fastclone.copier.impl.AbstractFastCopierFactory;
import com.vmware.bdd.fastclone.copier.impl.InnerHostTargetSelector;
import com.vmware.bdd.fastclone.copier.impl.VmClonerFactory;
import com.vmware.bdd.fastclone.intf.FastCloneService;
import com.vmware.bdd.fastclone.intf.TargetSelector;
import com.vmware.bdd.fastclone.resource.impl.VmCreateSpec;
import com.vmware.bdd.fastclone.service.impl.FastCloneServiceImpl;
import com.vmware.bdd.manager.ClusterConfigManager;
import com.vmware.bdd.manager.ClusterEntityManager;
import com.vmware.bdd.placement.Container;
import com.vmware.bdd.placement.entity.AbstractDatacenter.AbstractHost;
import com.vmware.bdd.placement.entity.BaseNode;
import com.vmware.bdd.placement.exception.PlacementException;
import com.vmware.bdd.placement.interfaces.IPlacementService;
import com.vmware.bdd.service.IClusteringService;
import com.vmware.bdd.service.job.ClusterNodeUpdator;
import com.vmware.bdd.service.job.StatusUpdater;
import com.vmware.bdd.service.resmgmt.INetworkService;
import com.vmware.bdd.service.resmgmt.IResourceService;
import com.vmware.bdd.service.sp.BaseProgressCallback;
import com.vmware.bdd.service.sp.ConfigIOShareSP;
import com.vmware.bdd.service.sp.CreateResourcePoolSP;
import com.vmware.bdd.service.sp.CreateVmPrePowerOn;
import com.vmware.bdd.service.sp.DeleteRpSp;
import com.vmware.bdd.service.sp.DeleteVmByIdSP;
import com.vmware.bdd.service.sp.NoProgressUpdateCallback;
import com.vmware.bdd.service.sp.QueryIpAddress;
import com.vmware.bdd.service.sp.SetAutoElasticitySP;
import com.vmware.bdd.service.sp.StartVmSP;
import com.vmware.bdd.service.sp.StopVmSP;
import com.vmware.bdd.service.sp.TakeSnapshotSP;
import com.vmware.bdd.service.sp.UpdateVmProgressCallback;
import com.vmware.bdd.service.sp.VcEventProcessor;
import com.vmware.bdd.service.utils.VcResourceUtils;
import com.vmware.bdd.spectypes.DiskSpec;
import com.vmware.bdd.spectypes.HadoopRole;
import com.vmware.bdd.utils.AuAssert;
import com.vmware.bdd.utils.CommonUtil;
import com.vmware.bdd.utils.ConfigInfo;
import com.vmware.bdd.utils.Constants;
import com.vmware.bdd.utils.JobUtils;
import com.vmware.bdd.utils.VcVmUtil;
import com.vmware.vim.binding.vim.Folder;
import com.vmware.vim.binding.vim.vm.device.VirtualDevice;
import com.vmware.vim.binding.vim.vm.device.VirtualDisk;
import com.vmware.vim.binding.vim.vm.device.VirtualDiskOption.DiskMode;
public class ClusteringService implements IClusteringService {
private static final int VC_RP_MAX_NAME_LENGTH = 80;
private static final Logger logger = Logger
.getLogger(ClusteringService.class);
private ClusterConfigManager configMgr;
private ClusterEntityManager clusterEntityMgr;
private IResourcePoolDAO rpDao;
private INetworkService networkMgr;
private IResourceService resMgr;
private IPlacementService placementService;
private IClusterInitializerService clusterInitializerService;
private String templateSnapId;
private VcVirtualMachine templateVm;
private BaseNode templateNode;
private String templateNetworkLabel;
private static boolean initialized = false;
private int cloneConcurrency;
public INetworkService getNetworkMgr() {
return networkMgr;
}
public void setNetworkMgr(INetworkService networkMgr) {
this.networkMgr = networkMgr;
}
public ClusterConfigManager getConfigMgr() {
return configMgr;
}
public void setConfigMgr(ClusterConfigManager configMgr) {
this.configMgr = configMgr;
}
@Autowired
public void setResMgr(IResourceService resMgr) {
this.resMgr = resMgr;
}
@Autowired
public void setPlacementService(IPlacementService placementService) {
this.placementService = placementService;
}
public IClusterInitializerService getClusterInitializerService() {
return clusterInitializerService;
}
@Autowired
public void setClusterInitializerService(IClusterInitializerService clusterInitializerService) {
this.clusterInitializerService = clusterInitializerService;
}
public ClusterEntityManager getClusterEntityMgr() {
return clusterEntityMgr;
}
@Autowired
public void setClusterEntityMgr(ClusterEntityManager clusterEntityMgr) {
this.clusterEntityMgr = clusterEntityMgr;
}
public IResourcePoolDAO getRpDao() {
return rpDao;
}
@Autowired
public void setRpDao(IResourcePoolDAO rpDao) {
this.rpDao = rpDao;
}
public String getTemplateSnapId() {
return templateSnapId;
}
public String getTemplateVmId() {
return templateVm.getId();
}
public synchronized void init() {
if (!initialized) {
// XXX hack to approve bootstrap instance id, should be moved out of Configuration
Configuration
.approveBootstrapInstanceId(Configuration.BootstrapUsage.ALLOWED);
Configuration
.approveBootstrapInstanceId(Configuration.BootstrapUsage.FINALIZED);
VcContext.initVcContext();
new VcEventRouter();
CmsWorker.addPeriodic(new VcInventory.SyncInventoryRequest());
VcInventory.loadInventory();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
logger.warn("interupted during sleep " + e.getMessage());
}
// add event handler for Serengeti after VC event handler is registered.
new VcEventProcessor(getClusterEntityMgr());
String poolSize =
Configuration.getNonEmptyString("serengeti.scheduler.poolsize");
if (poolSize == null) {
Scheduler.init(Constants.DEFAULT_SCHEDULER_POOL_SIZE,
Constants.DEFAULT_SCHEDULER_POOL_SIZE);
} else {
Scheduler.init(Integer.parseInt(poolSize),
Integer.parseInt(poolSize));
}
String concurrency =
Configuration
.getNonEmptyString("serengeti.singlevm.concurrency");
if (concurrency != null) {
cloneConcurrency = Integer.parseInt(concurrency);
} else {
cloneConcurrency = 1;
}
CmsWorker.addPeriodic(new ClusterNodeUpdator(getClusterEntityMgr()));
snapshotTemplateVM();
loadTemplateNetworkLable();
convertTemplateVm();
clusterInitializerService.transformClusterStatus(ClusterStatus.PROVISIONING, ClusterStatus.PROVISION_ERROR);
initialized = true;
}
}
synchronized public void destroy() {
Scheduler.shutdown(true);
}
private void convertTemplateVm() {
templateNode = new BaseNode(templateVm.getName());
List<DiskSpec> diskSpecs = new ArrayList<DiskSpec>();
for (DeviceId slot : templateVm.getVirtualDiskIds()) {
VirtualDisk vmdk = (VirtualDisk) templateVm.getVirtualDevice(slot);
DiskSpec spec = new DiskSpec();
spec.setSize((int) (vmdk.getCapacityInKB() / (1024 * 1024)));
spec.setDiskType(DiskType.SYSTEM_DISK);
spec.setController(DiskScsiControllerType.LSI_CONTROLLER);
diskSpecs.add(spec);
}
templateNode.setDisks(diskSpecs);
}
private VcVirtualMachine getTemplateVm() {
String serverMobId =
Configuration.getString(Constants.SERENGETI_SERVER_VM_MOBID);
if (serverMobId == null) {
throw ClusteringServiceException.TEMPLATE_ID_NOT_FOUND();
}
VcVirtualMachine serverVm = VcCache.get(serverMobId);
if (ConfigInfo.isDeployAsVApp()) {
VcResourcePool vApp = serverVm.getParentVApp();
initUUID(vApp.getName());
for (VcVirtualMachine vm : vApp.getChildVMs()) {
// assume only two vm under serengeti vApp, serengeti server and
// template
if (!vm.getName().equals(serverVm.getName())) {
logger.info("got template vm: " + vm.getName());
return vm;
}
}
return null;
} else {
String templateVmName = ConfigInfo.getTemplateVmName();
logger.info(templateVmName);
Folder parentFolder = VcResourceUtils.findParentFolderOfVm(serverVm);
AuAssert.check(parentFolder != null);
initUUID(parentFolder.getName());
return VcResourceUtils.findTemplateVmWithinFolder(parentFolder,
templateVmName);
}
}
private void initUUID(String uuid) {
if (ConfigInfo.isInitUUID()) {
ConfigInfo.setSerengetiUUID(uuid);
ConfigInfo.setInitUUID(false);
ConfigInfo.save();
}
}
private void snapshotTemplateVM() {
final VcVirtualMachine templateVM = getTemplateVm();
if (templateVM == null) {
throw ClusteringServiceException.TEMPLATE_VM_NOT_FOUND();
}
try {
final VcSnapshot snapshot =
templateVM.getSnapshotByName(Constants.ROOT_SNAPSTHOT_NAME);
if (snapshot == null) {
if (!ConfigInfo.isJustUpgraded()) {
TakeSnapshotSP snapshotSp =
new TakeSnapshotSP(templateVM.getId(),
Constants.ROOT_SNAPSTHOT_NAME,
Constants.ROOT_SNAPSTHOT_DESC);
snapshotSp.call();
templateSnapId = snapshotSp.getSnapId();
}
} else {
if (ConfigInfo.isJustUpgraded()) {
VcContext.inVcSessionDo(new VcSession<Boolean>() {
@Override
protected boolean isTaskSession() {
return true;
}
@Override
protected Boolean body() throws Exception {
snapshot.remove();
return true;
}
});
ConfigInfo.setJustUpgraded(false);
ConfigInfo.save();
} else {
templateSnapId = snapshot.getName();
}
}
this.templateVm = templateVM;
} catch (Exception e) {
logger.error("Clustering service initialization error.");
throw BddException.INTERNAL(e,
"Clustering service initialization error.");
}
}
private void loadTemplateNetworkLable() {
templateNetworkLabel = VcContext.inVcSessionDo(new VcSession<String>() {
@Override
protected String body() throws Exception {
VirtualDevice[] devices =
templateVm.getConfig().getHardware().getDevice();
for (VirtualDevice device : devices) {
if (device.getKey() == 4000) {
return device.getDeviceInfo().getLabel();
}
}
return null;
}
});
}
public static Map<String, String> getNetworkGuestVariable(
NetworkAdd networkAdd, String ipAddress, String guestHostName) {
Map<String, String> networkJson = new HashMap<String, String>();
networkJson
.put(Constants.GUEST_VARIABLE_POLICY_KEY, networkAdd.getType());
networkJson.put(Constants.GUEST_VARIABLE_IP_KEY, ipAddress);
networkJson.put(Constants.GUEST_VARIABLE_NETMASK_KEY,
networkAdd.getNetmask());
networkJson.put(Constants.GUEST_VARIABLE_GATEWAY_KEY,
networkAdd.getGateway());
networkJson.put(Constants.GUEST_VARIABLE_HOSTNAME_KEY, guestHostName);
networkJson.put(Constants.GUEST_VARIABLE_DNS_KEY_0, networkAdd.getDns1());
networkJson.put(Constants.GUEST_VARIABLE_DNS_KEY_1, networkAdd.getDns2());
return networkJson;
}
private void setNetworkSchema(List<BaseNode> vNodes) {
logger.info("Start to set network schema for template nic.");
for (BaseNode node : vNodes) {
List<Network> networks = node.getVmSchema().networkSchema.networks;
if (!networks.isEmpty()) {
// reset the first network label since template vm contains one nic by default
networks.get(0).nicLabel = templateNetworkLabel;
}
}
}
/**
* cluster create, resize, resume will all call this method for static ip
* allocation the network contains all allocated ip address to this cluster,
* so some of them may already be occupied by existing node. So we need to
* detect if that ip is allocated, before assign that one to one node
*
* @param networkAdd
* @param vNodes
* @param occupiedIps
*/
private void allocateStaticIp(NetworkAdd networkAdd, List<BaseNode> vNodes,
Set<String> occupiedIps) {
if (networkAdd.isDhcp()) {
// no need to allocate ip for dhcp
logger.info("using dhcp network.");
return;
}
logger.info("Start to allocate static ip address for each VM.");
List<String> availableIps =
IpBlock.getIpAddressFromIpBlock(networkAdd.getIp());
+ availableIps.removeAll(occupiedIps);
AuAssert.check(availableIps.size() == vNodes.size());
for (int i = 0; i < availableIps.size(); i++) {
- if (occupiedIps.contains(availableIps.get(i))) {
- continue;
- }
vNodes.get(i).setIpAddress(availableIps.get(i));
}
logger.info("Finished to allocate static ip address for VM.");
}
private String getMaprActiveJobTrackerIp(final String maprNodeIP,
final String clusterName) {
String activeJobTrackerIp = "";
String errorMsg = "";
JSch jsch = new JSch();
String sshUser = Configuration.getString("mapr.ssh.user", "serengeti");
int sshPort = Configuration.getInt("mapr.ssh.port", 22);
String prvKeyFile =
Configuration.getString("serengeti.ssh.private.key.file",
"/home/serengeti/.ssh/id_rsa");
ChannelExec channel = null;
try {
Session session = jsch.getSession(sshUser, maprNodeIP, sshPort);
jsch.addIdentity(prvKeyFile);
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.setTimeout(15000);
session.connect();
logger.debug("SSH session is connected!");
channel = (ChannelExec) session.openChannel("exec");
if (channel != null) {
logger.debug("SSH channel is connected!");
StringBuffer buff = new StringBuffer();
String cmd =
"maprcli node list -filter \"[rp==/*]and[svc==jobtracker]\" -columns ip";
logger.debug("exec command is: " + cmd);
channel.setPty(true); //to enable sudo
channel.setCommand("sudo " + cmd);
BufferedReader in =
new BufferedReader(new InputStreamReader(
channel.getInputStream()));
channel.connect();
if (!canChannelConnect(channel)) {
errorMsg =
"Get active Jobtracker ip: SSH channel is not connected !";
logger.error(errorMsg);
throw BddException.INTERNAL(null, errorMsg);
}
while (true) {
String line = in.readLine();
buff.append(line);
logger.debug("jobtracker message: " + line);
if (channel.isClosed()) {
int exitStatus = channel.getExitStatus();
logger.debug("Exit status from exec is: " + exitStatus);
break;
}
}
in.close();
Pattern ipPattern = Pattern.compile(Constants.IP_PATTERN);
Matcher matcher = ipPattern.matcher(buff.toString());
if (matcher.find()) {
activeJobTrackerIp = matcher.group();
} else {
errorMsg =
"Cannot find jobtracker ip info in cluster" + clusterName;
logger.error(errorMsg);
throw BddException.INTERNAL(null, errorMsg);
}
} else {
errorMsg = "Get active Jobtracker ip: cannot open SSH channel.";
logger.error(errorMsg);
throw BddException.INTERNAL(null, errorMsg);
}
} catch (JSchException e) {
errorMsg = "SSH unknow error: " + e.getMessage();
logger.error(errorMsg);
throw BddException.INTERNAL(null, errorMsg);
} catch (IOException e) {
errorMsg = "Obtain active jobtracker ip error: " + e.getMessage();
logger.error(errorMsg);
throw BddException.INTERNAL(null, errorMsg);
} finally {
channel.disconnect();
}
return activeJobTrackerIp;
}
private boolean canChannelConnect(ChannelExec channel) {
if (channel == null) {
return false;
}
if (channel.isConnected()) {
return true;
}
try {
channel.connect();
} catch (JSchException e) {
String errorMsg = "SSH connection failed: " + e.getMessage();
logger.error(errorMsg);
throw BddException.INTERNAL(null, errorMsg);
}
return channel.isConnected();
}
private void updateVhmMasterMoid(String clusterName) {
ClusterEntity cluster = getClusterEntityMgr().findByName(clusterName);
if (cluster.getVhmMasterMoid() == null) {
List<NodeEntity> nodes =
getClusterEntityMgr().findAllNodes(clusterName);
for (NodeEntity node : nodes) {
if (node.getMoId() != null
&& node.getNodeGroup().getRoles() != null) {
@SuppressWarnings("unchecked")
List<String> roles =
new Gson().fromJson(node.getNodeGroup().getRoles(),
List.class);
if (cluster.getDistro().equalsIgnoreCase(Constants.MAPR_VENDOR)) {
if (roles
.contains(HadoopRole.MAPR_JOBTRACKER_ROLE.toString())) {
String thisJtIp = node.getIpAddress();
String activeJtIp;
try {
activeJtIp =
getMaprActiveJobTrackerIp(thisJtIp, clusterName);
logger.info("fetched active JT Ip: " + activeJtIp);
} catch (Exception e) {
continue;
}
AuAssert.check(!CommonUtil.isBlank(thisJtIp),
"falied to query active JobTracker Ip");
for (NodeEntity jt : nodes) {
if (jt.getIpAddress().equals(activeJtIp)) {
cluster.setVhmMasterMoid(jt.getMoId());
break;
}
}
break;
}
} else {
if (roles.contains(HadoopRole.HADOOP_JOBTRACKER_ROLE
.toString())) {
cluster.setVhmMasterMoid(node.getMoId());
break;
}
}
}
}
}
getClusterEntityMgr().update(cluster);
}
@SuppressWarnings("unchecked")
public boolean setAutoElasticity(String clusterName, boolean refreshAllNodes) {
logger.info("set auto elasticity for cluster " + clusterName);
ClusterEntity cluster = getClusterEntityMgr().findByName(clusterName);
List<NodeEntity> nodes = clusterEntityMgr.findAllNodes(clusterName);
Boolean enableAutoElasticity = cluster.getAutomationEnable();
if (enableAutoElasticity == null) {
return true;
}
String masterMoId = cluster.getVhmMasterMoid();
if (masterMoId == null) {
// this will only occurs when creating cluster
updateVhmMasterMoid(clusterName);
cluster = getClusterEntityMgr().findByName(clusterName);
masterMoId = cluster.getVhmMasterMoid();
if (masterMoId == null) {
logger.error("masterMoId missed.");
throw ClusteringServiceException.SET_AUTO_ELASTICITY_FAILED(cluster
.getName());
}
}
String serengetiUUID = ConfigInfo.getSerengetiRootFolder();
int minComputeNodeNum = cluster.getVhmMinNum();
String jobTrackerPort = cluster.getVhmJobTrackerPort();
VcVirtualMachine vcVm = VcCache.getIgnoreMissing(masterMoId);
if (vcVm == null) {
logger.error("cannot find vhm master node");
return false;
}
String masterUUID = vcVm.getConfig().getUuid();
Callable<Void>[] storeProcedures = new Callable[nodes.size()];
int i = 0;
for (NodeEntity node : nodes) {
VcVirtualMachine vm = VcCache.getIgnoreMissing(node.getMoId());
if (vm == null) {
logger.error("cannot find node: " + node.getVmName());
return false;
}
if (!refreshAllNodes && !vm.getId().equalsIgnoreCase(masterMoId)) {
continue;
}
List<String> roles =
new Gson().fromJson(node.getNodeGroup().getRoles(), List.class);
String distroVendor =
node.getNodeGroup().getCluster().getDistroVendor();
boolean isComputeOnlyNode =
CommonUtil.isComputeOnly(roles, distroVendor);
SetAutoElasticitySP sp =
new SetAutoElasticitySP(vm, serengetiUUID, masterMoId,
masterUUID, enableAutoElasticity, minComputeNodeNum,
jobTrackerPort, isComputeOnlyNode);
storeProcedures[i] = sp;
i++;
}
try {
// execute store procedures to set auto elasticity
logger.info("ClusteringService, start to set auto elasticity.");
boolean success = true;
NoProgressUpdateCallback callback = new NoProgressUpdateCallback();
ExecutionResult[] result =
Scheduler
.executeStoredProcedures(
com.vmware.aurora.composition.concurrent.Priority.BACKGROUND,
storeProcedures, callback);
if (result == null) {
logger.error("set auto elasticity failed.");
throw ClusteringServiceException
.SET_AUTO_ELASTICITY_FAILED(clusterName);
}
for (i = 0; i < storeProcedures.length; i++) {
if (result[i].throwable != null) {
logger.error("failed to set auto elasticity",
result[i].throwable);
success = false;
}
}
return success;
} catch (Exception e) {
logger.error("error in setting auto elasticity", e);
throw BddException.INTERNAL(e, e.getMessage());
}
}
@SuppressWarnings("unchecked")
private Map<String, Folder> createVcFolders(ClusterCreate cluster) {
logger.info("createVcFolders, start to create cluster Folder.");
// get all nodegroups
Callable<Void>[] storeProcedures = new Callable[1];
Folder clusterFolder = null;
if (cluster.getNodeGroups().length > 0) {
// create cluster folder first
NodeGroupCreate group = cluster.getNodeGroups()[0];
String path = group.getVmFolderPath();
String[] folderNames = path.split("/");
List<String> folderList = new ArrayList<String>();
for (int i = 0; i < folderNames.length - 1; i++) {
folderList.add(folderNames[i]);
}
CreateVMFolderSP sp =
new CreateVMFolderSP(templateVm.getDatacenter(), null,
folderList);
storeProcedures[0] = sp;
Map<String, Folder> folders =
executeFolderCreationProcedures(cluster, storeProcedures);
for (String name : folders.keySet()) {
clusterFolder = folders.get(name);
break;
}
}
logger.info("createVcFolders, start to create group Folders.");
storeProcedures = new Callable[cluster.getNodeGroups().length];
int i = 0;
for (NodeGroupCreate group : cluster.getNodeGroups()) {
List<String> folderList = new ArrayList<String>();
folderList.add(group.getName());
CreateVMFolderSP sp =
new CreateVMFolderSP(templateVm.getDatacenter(), clusterFolder,
folderList);
storeProcedures[i] = sp;
i++;
}
return executeFolderCreationProcedures(cluster, storeProcedures);
}
private Map<String, Folder> executeFolderCreationProcedures(
ClusterCreate cluster, Callable<Void>[] storeProcedures) {
Map<String, Folder> folders = new HashMap<String, Folder>();
try {
// execute store procedures to create vc folders
NoProgressUpdateCallback callback = new NoProgressUpdateCallback();
ExecutionResult[] result =
Scheduler
.executeStoredProcedures(
com.vmware.aurora.composition.concurrent.Priority.BACKGROUND,
storeProcedures, callback);
if (result == null) {
logger.error("No folder is created.");
throw ClusteringServiceException.CREATE_FOLDER_FAILED(cluster
.getName());
}
int total = 0;
boolean success = true;
for (int i = 0; i < storeProcedures.length; i++) {
CreateVMFolderSP sp = (CreateVMFolderSP) storeProcedures[i];
if (result[i].finished && result[i].throwable == null) {
++total;
Folder childFolder =
sp.getResult().get(sp.getResult().size() - 1);
folders.put(childFolder.getName(), childFolder);
} else if (result[i].throwable != null) {
logger.error("Failed to create vm folder", result[i].throwable);
success = false;
}
}
logger.info(total + " Folders are created.");
if (!success) {
throw ClusteringServiceException.CREATE_FOLDER_FAILED(cluster
.getName());
}
return folders;
} catch (Exception e) {
logger.error("error in creating VC folders", e);
throw BddException.INTERNAL(e, e.getMessage());
}
}
private void executeResourcePoolStoreProcedures(Callable<Void>[] defineSPs,
String type, String clusterName) throws InterruptedException {
if (defineSPs.length == 0) {
logger.debug("no resource pool need to be created.");
return;
}
NoProgressUpdateCallback callback = new NoProgressUpdateCallback();
ExecutionResult[] result =
Scheduler.executeStoredProcedures(
com.vmware.aurora.composition.concurrent.Priority.BACKGROUND,
defineSPs, callback);
if (result == null) {
logger.error("No " + type + " resource pool is created.");
throw ClusteringServiceException
.CREATE_RESOURCE_POOL_FAILED(clusterName);
}
int total = 0;
boolean success = true;
for (int i = 0; i < defineSPs.length; i++) {
if (result[i].finished && result[i].throwable == null) {
++total;
} else if (result[i].throwable != null) {
logger.error("Failed to create " + type + " resource pool(s)",
result[i].throwable);
success = false;
}
}
logger.info(total + " " + type + " resource pool(s) are created.");
if (!success) {
throw ClusteringServiceException
.CREATE_RESOURCE_POOL_FAILED(clusterName);
}
}
private Map<String, Integer> collectResourcePoolInfo(List<BaseNode> vNodes,
Map<String, List<String>> vcClusterRpNamesMap,
Map<Long, List<NodeGroupCreate>> rpNodeGroupsMap) {
List<String> resourcePoolNames = null;
List<NodeGroupCreate> nodeGroups = null;
int resourcePoolNameCount = 0;
int nodeGroupNameCount = 0;
for (BaseNode baseNode : vNodes) {
String vcCluster = baseNode.getTargetVcCluster();
VcCluster cluster = VcResourceUtils.findVcCluster(vcCluster);
if (!cluster.getConfig().getDRSEnabled()) {
logger.debug("DRS disabled for cluster " + vcCluster
+ ", do not create child rp for this cluster.");
continue;
}
AuAssert.check(!CommonUtil.isBlank(vcCluster),
"Vc cluster name cannot be null!");
if (!vcClusterRpNamesMap.containsKey(vcCluster)) {
resourcePoolNames = new ArrayList<String>();
} else {
resourcePoolNames = vcClusterRpNamesMap.get(vcCluster);
}
String vcRp = baseNode.getTargetRp();
long rpHashCode = vcCluster.hashCode() ^ (vcCluster + vcRp).hashCode();
if (!rpNodeGroupsMap.containsKey(rpHashCode)) {
nodeGroups = new ArrayList<NodeGroupCreate>();
} else {
nodeGroups = rpNodeGroupsMap.get(rpHashCode);
}
NodeGroupCreate nodeGroup = baseNode.getNodeGroup();
if (!getAllNodeGroupNames(nodeGroups).contains(nodeGroup.getName())) {
nodeGroups.add(nodeGroup);
rpNodeGroupsMap.put(rpHashCode, nodeGroups);
nodeGroupNameCount++;
}
if (!resourcePoolNames.contains(vcRp)) {
resourcePoolNames.add(vcRp);
vcClusterRpNamesMap.put(vcCluster, resourcePoolNames);
resourcePoolNameCount++;
}
}
Map<String, Integer> countResult = new HashMap<String, Integer>();
countResult.put("resourcePoolNameCount", resourcePoolNameCount);
countResult.put("nodeGroupNameCount", nodeGroupNameCount);
return countResult;
}
private List<String> getAllNodeGroupNames(List<NodeGroupCreate> nodeGroups) {
List<String> nodeGroupNames = new ArrayList<String>();
for (NodeGroupCreate nodeGroup : nodeGroups) {
nodeGroupNames.add(nodeGroup.getName());
}
return nodeGroupNames;
}
private String createVcResourcePools(List<BaseNode> vNodes) {
logger.info("createVcResourcePools, start to create VC ResourcePool(s).");
/*
* define cluster resource pool name.
*/
String clusterName = vNodes.get(0).getClusterName();
String uuid = ConfigInfo.getSerengetiUUID();
String clusterRpName = uuid + "-" + clusterName;
if (clusterRpName.length() > VC_RP_MAX_NAME_LENGTH) {
throw ClusteringServiceException.CLUSTER_NAME_TOO_LONG(clusterName);
}
/*
* prepare resource pool names and node group per resource pool for creating cluster
* resource pools and node group resource pool(s).
*/
Map<String, List<String>> vcClusterRpNamesMap =
new HashMap<String, List<String>>();
Map<Long, List<NodeGroupCreate>> rpNodeGroupsMap =
new HashMap<Long, List<NodeGroupCreate>>();
Map<String, Integer> countResult =
collectResourcePoolInfo(vNodes, vcClusterRpNamesMap,
rpNodeGroupsMap);
try {
/*
* define cluster store procedures of resource pool(s)
*/
int resourcePoolNameCount = countResult.get("resourcePoolNameCount");
Callable<Void>[] clusterSPs = new Callable[resourcePoolNameCount];
int i = 0;
for (Entry<String, List<String>> vcClusterRpNamesEntry : vcClusterRpNamesMap
.entrySet()) {
String vcClusterName = vcClusterRpNamesEntry.getKey();
VcCluster vcCluster = VcResourceUtils.findVcCluster(vcClusterName);
if (vcCluster == null) {
String errorMsg =
"Can not find vc cluster '" + vcClusterName + "'.";
logger.error(errorMsg);
throw BddException.INTERNAL(null, errorMsg);
}
List<String> resourcePoolNames = vcClusterRpNamesEntry.getValue();
for (String resourcePoolName : resourcePoolNames) {
VcResourcePool parentVcResourcePool =
VcResourceUtils.findRPInVCCluster(vcClusterName,
resourcePoolName);
if (parentVcResourcePool == null) {
String errorMsg =
"Can not find vc resource pool '" + resourcePoolName
+ "'.";
logger.error(errorMsg);
throw BddException.INTERNAL(null, errorMsg);
}
CreateResourcePoolSP clusterSP =
new CreateResourcePoolSP(parentVcResourcePool,
clusterRpName);
clusterSPs[i] = clusterSP;
i++;
}
}
// execute store procedures to create cluster resource pool(s)
logger.info("ClusteringService, start to create cluster resource pool(s).");
executeResourcePoolStoreProcedures(clusterSPs, "cluster", clusterName);
/*
* define node group store procedures of resource pool(s)
*/
int nodeGroupNameCount = countResult.get("nodeGroupNameCount");
Callable<Void>[] nodeGroupSPs = new Callable[nodeGroupNameCount];
i = 0;
for (Entry<String, List<String>> vcClusterRpNamesEntry : vcClusterRpNamesMap
.entrySet()) {
String vcClusterName = vcClusterRpNamesEntry.getKey();
VcCluster vcCluster = VcResourceUtils.findVcCluster(vcClusterName);
if (vcCluster == null) {
String errorMsg =
"Can not find vc cluster '" + vcClusterName + "'.";
logger.error(errorMsg);
throw BddException.INTERNAL(null, errorMsg);
}
if (!vcCluster.getConfig().getDRSEnabled()) {
continue;
}
List<String> resourcePoolNames = vcClusterRpNamesEntry.getValue();
for (String resourcePoolName : resourcePoolNames) {
VcResourcePool parentVcResourcePool = null;
String vcRPName =
CommonUtil.isBlank(resourcePoolName) ? clusterRpName
: resourcePoolName + "/" + clusterRpName;
parentVcResourcePool =
VcResourceUtils.findRPInVCCluster(vcClusterName, vcRPName);
if (parentVcResourcePool == null) {
String errorMsg =
"Can not find vc resource pool '"
+ vcRPName
+ "' "
+ (CommonUtil.isBlank(resourcePoolName) ? ""
: " in the vc resource pool '"
+ resourcePoolName + "'") + ".";
logger.error(errorMsg);
throw BddException.INTERNAL(null, errorMsg);
}
long rpHashCode =
vcClusterName.hashCode()
^ (vcClusterName + resourcePoolName).hashCode();
for (NodeGroupCreate nodeGroup : rpNodeGroupsMap.get(rpHashCode)) {
AuAssert
.check(nodeGroup != null,
"create node group resource pool failed: node group cannot be null !");
if (nodeGroup.getName().length() > 80) {
throw ClusteringServiceException
.GROUP_NAME_TOO_LONG(clusterName);
}
CreateResourcePoolSP nodeGroupSP =
new CreateResourcePoolSP(parentVcResourcePool,
nodeGroup.getName(), nodeGroup);
nodeGroupSPs[i] = nodeGroupSP;
i++;
}
}
}
//execute store procedures to create node group resource pool(s)
logger.info("ClusteringService, start to create node group resource pool(s).");
executeResourcePoolStoreProcedures(nodeGroupSPs, "node group",
clusterName);
} catch (Exception e) {
logger.error("error in creating VC ResourcePool(s)", e);
throw BddException.INTERNAL(e, e.getMessage());
}
return clusterRpName;
}
@SuppressWarnings("unchecked")
@Override
public boolean createVcVms(NetworkAdd networkAdd, List<BaseNode> vNodes,
StatusUpdater statusUpdator, Set<String> occupiedIps) {
if (vNodes.isEmpty()) {
logger.info("No vm to be created.");
return true;
}
setNetworkSchema(vNodes);
allocateStaticIp(networkAdd, vNodes, occupiedIps);
Map<String, Folder> folders = createVcFolders(vNodes.get(0).getCluster());
String clusterRpName = createVcResourcePools(vNodes);
logger.info("syncCreateVMs, start to create VMs.");
FastCloneService<VmCreateSpec> cloneSrv =
new FastCloneServiceImpl<VmCreateSpec>();
// set copier factory
AbstractFastCopierFactory<VmCreateSpec> copierFactory =
new VmClonerFactory();
cloneSrv.setFastCopierFactory(copierFactory);
TargetSelector<VmCreateSpec> selector =
new InnerHostTargetSelector<VmCreateSpec>();
cloneSrv.setTargetSelector(selector);
VmCreateSpec sourceSpec = new VmCreateSpec();
// update vm info in vc cache, in case snapshot is removed by others
VcVmUtil.updateVm(templateVm.getId());
sourceSpec.setVmId(templateVm.getId());
sourceSpec.setVmName(templateVm.getName());
sourceSpec.setTargetHost(templateVm.getHost());
cloneSrv.addResource(sourceSpec, cloneConcurrency);
List<VmCreateSpec> specs = new ArrayList<VmCreateSpec>();
Map<String, BaseNode> nodeMap = new HashMap<String, BaseNode>();
for (BaseNode vNode : vNodes) {
// prepare for cloning result
nodeMap.put(vNode.getVmName(), vNode);
vNode.setSuccess(false);
vNode.setFinished(true);
// generate create spec for fast clone
VmCreateSpec spec = new VmCreateSpec();
VmSchema createSchema = getVmSchema(vNode);
spec.setSchema(createSchema);
Map<String, String> guestVariable =
getNetworkGuestVariable(networkAdd, vNode.getIpAddress(),
vNode.getGuestHostName());
spec.setBootupConfigs(guestVariable);
// timeout is 10 mintues
QueryIpAddress query =
new QueryIpAddress(Constants.VM_POWER_ON_WAITING_SEC);
spec.setPostPowerOn(query);
spec.setPrePowerOn(getPrePowerOnFunc(vNode));
spec.setLinkedClone(false);
spec.setTargetDs(getVcDatastore(vNode));
spec.setTargetFolder(folders.get(vNode.getGroupName()));
spec.setTargetHost(VcResourceUtils.findHost(vNode.getTargetHost()));
spec.setTargetRp(getVcResourcePool(vNode, clusterRpName));
spec.setVmName(vNode.getVmName());
specs.add(spec);
}
cloneSrv.addConsumers(specs);
try {
UpdateVmProgressCallback callback =
new UpdateVmProgressCallback(clusterEntityMgr, statusUpdator,
vNodes.get(0).getClusterName());
cloneSrv.setProgressCallback(callback);
// call fast clone service to copy templates
logger.info("ClusteringService, start to cloning template.");
boolean success = cloneSrv.start();
logger.info(cloneSrv.getCopied().size() + " VMs are created.");
for (VmCreateSpec spec : cloneSrv.getCopied()) {
BaseNode node = nodeMap.get(spec.getVmName());
node.setVmMobId(spec.getVmId());
VcVirtualMachine vm = VcCache.getIgnoreMissing(spec.getVmId());
if (vm != null) {
boolean vmSucc = VcVmUtil.setBaseNodeForVm(node, vm);
if (!vmSucc) {
success = vmSucc;
}
}
node.setSuccess(success);
}
return success;
} catch (Exception e) {
logger.error("error in cloning VMs", e);
throw BddException.INTERNAL(e, e.getMessage());
}
}
private CreateVmPrePowerOn getPrePowerOnFunc(BaseNode vNode) {
String haFlag = vNode.getNodeGroup().getHaFlag();
boolean ha = false;
boolean ft = false;
if (haFlag != null && Constants.HA_FLAG_ON.equals(haFlag.toLowerCase())) {
ha = true;
}
if (haFlag != null && Constants.HA_FLAG_FT.equals(haFlag.toLowerCase())) {
ha = true;
ft = true;
if (vNode.getNodeGroup().getCpuNum() > 1) {
throw ClusteringServiceException.CPU_NUMBER_MORE_THAN_ONE(vNode
.getVmName());
}
logger.debug("ft is enabled is for VM " + vNode.getVmName());
logger.debug("set disk mode to persistent for VM " + vNode.getVmName());
// change disk mode to persistent, instead of independent_persisten, since FT requires this
DiskSchema diskSchema = vNode.getVmSchema().diskSchema;
if (diskSchema.getDisks() != null) {
for (Disk disk : diskSchema.getDisks()) {
disk.mode = DiskMode.persistent;
}
}
}
ClusterEntity clusterEntity =
getClusterEntityMgr().findByName(vNode.getClusterName());
CreateVmPrePowerOn prePowerOn =
new CreateVmPrePowerOn(ha, ft, clusterEntity.getIoShares());
return prePowerOn;
}
private static VcDatastore getVcDatastore(BaseNode vNode) {
VcDatastore ds = VcResourceUtils.findDSInVcByName(vNode.getTargetDs());
if (ds != null) {
return ds;
}
logger.error("target data store " + vNode.getTargetDs()
+ " is not found.");
throw ClusteringServiceException.TARGET_VC_DATASTORE_NOT_FOUND(vNode
.getTargetDs());
}
private VcResourcePool getVcResourcePool(BaseNode vNode,
final String clusterRpName) {
try {
String vcRPName = "";
VcCluster cluster =
VcResourceUtils.findVcCluster(vNode.getTargetVcCluster());
if (!cluster.getConfig().getDRSEnabled()) {
logger.debug("DRS disabled for cluster "
+ vNode.getTargetVcCluster()
+ ", put VM under cluster directly.");
return cluster.getRootRP();
}
if (CommonUtil.isBlank(vNode.getTargetRp())) {
vcRPName = clusterRpName + "/" + vNode.getNodeGroup().getName();
} else {
vcRPName =
vNode.getTargetRp() + "/" + clusterRpName + "/"
+ vNode.getNodeGroup().getName();
}
VcResourcePool rp =
VcResourceUtils.findRPInVCCluster(vNode.getTargetVcCluster(),
vcRPName);
if (rp == null) {
throw ClusteringServiceException.TARGET_VC_RP_NOT_FOUND(
vNode.getTargetVcCluster(), vNode.getTargetRp());
}
return rp;
} catch (Exception e) {
logger.error("Failed to get VC resource pool " + vNode.getTargetRp()
+ " in vc cluster " + vNode.getTargetVcCluster(), e);
throw ClusteringServiceException.TARGET_VC_RP_NOT_FOUND(
vNode.getTargetVcCluster(), vNode.getTargetRp());
}
}
private VmSchema getVmSchema(BaseNode vNode) {
VmSchema schema = vNode.getVmSchema();
schema.diskSchema.setParent(getTemplateVmId());
schema.diskSchema.setParentSnap(getTemplateSnapId());
return schema;
}
@Override
public List<BaseNode> getPlacementPlan(ClusterCreate clusterSpec,
List<BaseNode> existedNodes) {
logger.info("Begin to calculate provision plan.");
logger.info("Calling resource manager to get available vc hosts");
Container container = new Container();
List<VcCluster> clusters = resMgr.getAvailableClusters();
AuAssert.check(clusters != null && clusters.size() != 0);
for (VcCluster cl : clusters) {
VcResourceUtils.refreshDatastore(cl);
container.addResource(cl);
}
container.SetTemplateNode(templateNode);
if (clusterSpec.getHostToRackMap() != null
&& clusterSpec.getHostToRackMap().size() != 0) {
container.addRackMap(clusterSpec.getHostToRackMap());
}
// rack topology file validation
Set<String> validRacks = new HashSet<String>();
List<AbstractHost> hosts = container.getAllHosts();
for (AbstractHost host : hosts) {
if (container.getRack(host) != null) {
// this rack is valid as it contains at least one host
validRacks.add(container.getRack(host));
}
}
for (NodeGroupCreate nodeGroup : clusterSpec.getNodeGroups()) {
if (nodeGroup.getPlacementPolicies() != null
&& nodeGroup.getPlacementPolicies().getGroupRacks() != null
&& validRacks.size() == 0) {
throw PlacementException.INVALID_RACK_INFO(clusterSpec.getName(),
nodeGroup.getName());
}
}
List<BaseNode> baseNodes =
placementService.getPlacementPlan(container, clusterSpec,
existedNodes);
for (BaseNode baseNode : baseNodes) {
baseNode.setNodeAction(Constants.NODE_ACTION_CLONING_VM);
}
logger.info("Finished calculating provision plan");
return baseNodes;
}
@Override
public boolean startCluster(final String name, StatusUpdater statusUpdator) {
logger.info("startCluster, start.");
List<NodeEntity> nodes = clusterEntityMgr.findAllNodes(name);
logger.info("startCluster, start to create store procedures.");
List<Callable<Void>> storeProcedures = new ArrayList<Callable<Void>>();
for (int i = 0; i < nodes.size(); i++) {
NodeEntity node = nodes.get(i);
if (node.getMoId() == null) {
logger.info("VC vm does not exist for node: " + node.getVmName());
continue;
}
VcVirtualMachine vcVm = VcCache.getIgnoreMissing(node.getMoId());
if (vcVm == null) {
// cannot find VM
logger.info("VC vm does not exist for node: " + node.getVmName());
continue;
}
QueryIpAddress query = new QueryIpAddress(600);
VcHost host = null;
if (node.getHostName() != null) {
host = VcResourceUtils.findHost(node.getHostName());
}
StartVmSP startSp = new StartVmSP(vcVm, query, host);
storeProcedures.add(startSp);
}
try {
if (storeProcedures.isEmpty()) {
logger.info("no VM is available. Return directly.");
return true;
}
Callable<Void>[] storeProceduresArray =
storeProcedures.toArray(new Callable[0]);
// execute store procedures to start VMs
logger.info("ClusteringService, start to start vms.");
UpdateVmProgressCallback callback =
new UpdateVmProgressCallback(clusterEntityMgr, statusUpdator,
name);
ExecutionResult[] result =
Scheduler
.executeStoredProcedures(
com.vmware.aurora.composition.concurrent.Priority.BACKGROUND,
storeProceduresArray, callback);
if (result == null) {
logger.error("No VM is started.");
return false;
}
boolean success = true;
int total = 0;
for (int i = 0; i < storeProceduresArray.length; i++) {
if (result[i].finished && result[i].throwable == null) {
++total;
} else if (result[i].throwable != null) {
StartVmSP sp = (StartVmSP) storeProceduresArray[i];
VcVirtualMachine vm = sp.getVcVm();
if (vm != null && VcVmUtil.getIpAddress(vm, false) != null) {
++total;
} else {
logger.error(
"Failed to start VM " + nodes.get(i).getVmName(),
result[i].throwable);
success = false;
}
}
}
logger.info(total + " VMs are started.");
return success;
} catch (Exception e) {
logger.error("error in staring VMs", e);
throw BddException.INTERNAL(e, e.getMessage());
}
}
@Override
public boolean stopCluster(final String name, StatusUpdater statusUpdator) {
logger.info("stopCluster, start.");
List<NodeEntity> nodes = clusterEntityMgr.findAllNodes(name);
logger.info("stopCluster, start to create store procedures.");
List<Callable<Void>> storeProcedures = new ArrayList<Callable<Void>>();
for (int i = 0; i < nodes.size(); i++) {
NodeEntity node = nodes.get(i);
if (node.getMoId() == null) {
logger.info("VC vm does not exist for node: " + node.getVmName());
continue;
}
VcVirtualMachine vcVm = VcCache.getIgnoreMissing(node.getMoId());
if (vcVm == null) {
logger.info("VC vm does not exist for node: " + node.getVmName());
continue;
}
StopVmSP stopSp = new StopVmSP(vcVm);
storeProcedures.add(stopSp);
}
try {
if (storeProcedures.isEmpty()) {
logger.info("no VM is available. Return directly.");
return true;
}
Callable<Void>[] storeProceduresArray =
storeProcedures.toArray(new Callable[0]);
// execute store procedures to start VMs
logger.info("ClusteringService, start to stop vms.");
UpdateVmProgressCallback callback =
new UpdateVmProgressCallback(clusterEntityMgr, statusUpdator,
name);
ExecutionResult[] result =
Scheduler
.executeStoredProcedures(
com.vmware.aurora.composition.concurrent.Priority.BACKGROUND,
storeProceduresArray, callback);
if (result == null) {
logger.error("No VM is stoped.");
return false;
}
boolean success = true;
int total = 0;
for (int i = 0; i < storeProceduresArray.length; i++) {
if (result[i].finished && result[i].throwable == null) {
++total;
} else if (result[i].throwable != null) {
StopVmSP sp = (StopVmSP) storeProceduresArray[i];
VcVirtualMachine vm = sp.getVcVm();
if (vm == null || vm.isPoweredOff()) {
++total;
} else {
logger.error("Failed to stop VM " + nodes.get(i).getVmName(),
result[i].throwable);
success = false;
}
}
}
logger.info(total + " VMs are stoped.");
return success;
} catch (Exception e) {
logger.error("error in stoping VMs", e);
throw BddException.INTERNAL(e, e.getMessage());
}
}
public boolean removeBadNodes(ClusterCreate cluster,
List<BaseNode> existingNodes, List<BaseNode> deletedNodes,
Set<String> occupiedIps, StatusUpdater statusUpdator) {
logger.info("Start to remove node violate placement policy "
+ "or in wrong status in cluster: " + cluster.getName());
// call tm to remove bad nodes
List<BaseNode> badNodes =
placementService.getBadNodes(cluster, existingNodes);
if (badNodes == null) {
badNodes = new ArrayList<BaseNode>();
}
// append node in wrong status
for (BaseNode node : deletedNodes) {
if (node.getVmMobId() != null) {
badNodes.add(node);
}
}
if (badNodes != null && badNodes.size() > 0) {
boolean deleted = syncDeleteVMs(badNodes, statusUpdator);
afterBadVcVmDelete(existingNodes, deletedNodes, badNodes, occupiedIps);
return deleted;
}
return true;
}
public List<BaseNode> getBadNodes(ClusterCreate cluster,
List<BaseNode> existingNodes) {
return placementService.getBadNodes(cluster, existingNodes);
}
private void afterBadVcVmDelete(List<BaseNode> existingNodes,
List<BaseNode> deletedNodes, List<BaseNode> vcDeletedNodes,
Set<String> occupiedIps) {
// clean up in memory node list
deletedNodes.addAll(vcDeletedNodes);
Set<String> deletedNodeNames = new HashSet<String>();
for (BaseNode vNode : vcDeletedNodes) {
deletedNodeNames.add(vNode.getVmName());
}
for (Iterator<BaseNode> ite = existingNodes.iterator(); ite.hasNext();) {
BaseNode vNode = ite.next();
if (deletedNodeNames.contains(vNode.getVmName())) {
occupiedIps.remove(vNode.getIpAddress());
ite.remove();
}
}
}
@Override
public boolean deleteCluster(final String name, StatusUpdater statusUpdator) {
logger.info("Start to delete cluster: " + name);
List<NodeEntity> nodes = clusterEntityMgr.findAllNodes(name);
List<BaseNode> vNodes = JobUtils.convertNodeEntities(null, null, nodes);
boolean deleted = syncDeleteVMs(vNodes, statusUpdator);
if (nodes.size() > 0) {
try {
deleteChildRps(name, vNodes);
} catch (Exception e) {
logger.error("ignore delete resource pool error.", e);
}
try {
deleteFolders(vNodes.get(0));
} catch (Exception e) {
logger.error("ignore delete folder error.", e);
}
}
return deleted;
}
private void deleteChildRps(String hadoopClusterName, List<BaseNode> vNodes) {
logger.info("Start to delete child resource pools for cluster: "
+ hadoopClusterName);
Map<String, Map<String, VcResourcePool>> clusterMap =
new HashMap<String, Map<String, VcResourcePool>>();
for (BaseNode node : vNodes) {
String vcClusterName = node.getTargetVcCluster();
AuAssert.check(vcClusterName != null);
String vcRpName = node.getTargetRp();
if (clusterMap.get(vcClusterName) == null) {
clusterMap
.put(vcClusterName, new HashMap<String, VcResourcePool>());
}
Map<String, VcResourcePool> rpMap = clusterMap.get(vcClusterName);
if (rpMap.get(vcRpName) == null) {
VcResourcePool vcRp =
VcResourceUtils.findRPInVCCluster(vcClusterName, vcRpName);
if (vcRp != null) {
rpMap.put(vcRpName, vcRp);
}
}
}
List<VcResourcePool> rps = new ArrayList<VcResourcePool>();
for (Map<String, VcResourcePool> map : clusterMap.values()) {
rps.addAll(map.values());
}
Callable<Void>[] storedProcedures = new Callable[rps.size()];
String childRp = ConfigInfo.getSerengetiUUID() + "-" + hadoopClusterName;
int i = 0;
for (VcResourcePool rp : rps) {
DeleteRpSp sp = new DeleteRpSp(rp, childRp);
storedProcedures[i] = sp;
i++;
}
try {
NoProgressUpdateCallback callback = new NoProgressUpdateCallback();
ExecutionResult[] result =
Scheduler
.executeStoredProcedures(
com.vmware.aurora.composition.concurrent.Priority.BACKGROUND,
storedProcedures, callback);
if (result == null || result.length == 0) {
logger.error("No rp is deleted.");
return;
}
int total = 0;
for (int j = 0; j < storedProcedures.length; j++) {
if (result[j].throwable != null) {
DeleteRpSp sp = (DeleteRpSp) storedProcedures[j];
logger.error(
"Failed to delete child resource pool "
+ sp.getDeleteRpName() + " under " + sp.getVcRp(),
result[j].throwable);
} else {
total++;
}
}
} catch (Exception e) {
logger.error("error in deleting resource pools", e);
throw BddException.INTERNAL(e, e.getMessage());
}
}
/**
* this method will delete the cluster root folder, if there is any VM
* existed and powered on in the folder, the folder deletion will fail.
*
* @param folderNames
*/
private void deleteFolders(BaseNode node) throws BddException {
String path = node.getVmFolder();
// path format: <serengeti...>/<cluster name>/<group name>
String[] folderNames = path.split("/");
AuAssert.check(folderNames.length == 3);
VcDatacenter dc = templateVm.getDatacenter();
List<String> deletedFolders = new ArrayList<String>();
deletedFolders.add(folderNames[0]);
deletedFolders.add(folderNames[1]);
Folder folder = null;
try {
folder = VcResourceUtils.findFolderByNameList(dc, deletedFolders);
} catch (Exception e) {
logger.error("error in deleting folders", e);
throw BddException.INTERNAL(e, e.getMessage());
}
String clusterFolderName = folderNames[0] + "/" + folderNames[1];
logger.info("find cluster root folder: " + clusterFolderName);
List<Folder> folders = new ArrayList<Folder>();
folders.add(folder);
DeleteVMFolderSP sp = new DeleteVMFolderSP(folders, true, false);
Callable<Void>[] storedProcedures = new Callable[1];
storedProcedures[0] = sp;
try {
NoProgressUpdateCallback callback = new NoProgressUpdateCallback();
ExecutionResult[] result =
Scheduler
.executeStoredProcedures(
com.vmware.aurora.composition.concurrent.Priority.BACKGROUND,
storedProcedures, callback);
if (result == null || result.length == 0) {
logger.error("No folder is deleted.");
return;
}
if (result[0].finished && result[0].throwable == null) {
logger.info("Cluster folder " + clusterFolderName + " is deleted.");
} else {
logger.info("Failed to delete cluster folder " + clusterFolderName,
result[0].throwable);
}
} catch (Exception e) {
logger.error("error in deleting folders", e);
throw BddException.INTERNAL(e, e.getMessage());
}
}
@SuppressWarnings("unchecked")
public boolean syncDeleteVMs(List<BaseNode> badNodes,
StatusUpdater statusUpdator) {
logger.info("syncDeleteVMs, start to create store procedures.");
List<Callable<Void>> storeProcedures = new ArrayList<Callable<Void>>();
for (int i = 0; i < badNodes.size(); i++) {
BaseNode node = badNodes.get(i);
if (node.getVmMobId() == null) {
// vm is already deleted
continue;
}
DeleteVmByIdSP deleteSp = new DeleteVmByIdSP(node.getVmMobId());
storeProcedures.add(deleteSp);
}
try {
if (storeProcedures.isEmpty()) {
logger.info("no VM is created. Return directly.");
return true;
}
Callable<Void>[] storeProceduresArray =
storeProcedures.toArray(new Callable[0]);
// execute store procedures to delete VMs
logger.info("ClusteringService, start to delete vms.");
BaseProgressCallback callback =
new BaseProgressCallback(statusUpdator, 0, 50);
ExecutionResult[] result =
Scheduler
.executeStoredProcedures(
com.vmware.aurora.composition.concurrent.Priority.BACKGROUND,
storeProceduresArray, callback);
if (result == null) {
logger.error("No VM is deleted.");
return false;
}
int total = 0;
boolean failed = false;
for (int i = 0; i < storeProceduresArray.length; i++) {
BaseNode vNode = badNodes.get(i);
if (result[i].finished && result[i].throwable == null) {
vNode.setSuccess(true);
vNode.setVmMobId(null);
++total;
} else if (result[i].throwable != null) {
logger.error("Failed to delete VM " + vNode.getVmName(),
result[i].throwable);
vNode.setSuccess(false);
failed = true;
}
vNode.setFinished(true);
}
logger.info(total + " VMs are deleted.");
return !failed;
} catch (Exception e) {
logger.error("error in deleting VMs", e);
throw BddException.INTERNAL(e, e.getMessage());
}
}
@Override
public UUID reserveResource(String clusterName) {
ResourceReservation reservation = new ResourceReservation();
reservation.setClusterName(clusterName);
return resMgr.reserveResoruce(reservation);
}
@Override
public void commitReservation(UUID reservationId) throws VcProviderException {
resMgr.commitReservation(reservationId);
}
@Override
public int configIOShares(String clusterName, List<NodeEntity> targetNodes,
Priority ioShares) {
AuAssert.check(clusterName != null && targetNodes != null
&& !targetNodes.isEmpty());
Callable<Void>[] storeProcedures = new Callable[targetNodes.size()];
int i = 0;
for (NodeEntity node : targetNodes) {
ConfigIOShareSP ioShareSP =
new ConfigIOShareSP(node.getMoId(), ioShares);
storeProcedures[i] = ioShareSP;
i++;
}
try {
// execute store procedures to configure io shares
logger.info("ClusteringService, start to reconfigure vm's io shares.");
NoProgressUpdateCallback callback = new NoProgressUpdateCallback();
ExecutionResult[] result =
Scheduler
.executeStoredProcedures(
com.vmware.aurora.composition.concurrent.Priority.BACKGROUND,
storeProcedures, callback);
if (result == null) {
logger.error("No VM's io share level is reconfigured.");
throw ClusteringServiceException
.RECONFIGURE_IO_SHARE_FAILED(clusterName);
}
int total = 0;
boolean success = true;
for (i = 0; i < storeProcedures.length; i++) {
if (result[i].finished && result[i].throwable == null) {
++total;
} else if (result[i].throwable != null) {
logger.error("Failed to reconfigure vm", result[i].throwable);
success = false;
}
}
logger.info(total + " vms are reconfigured.");
if (!success) {
throw ClusteringServiceException
.RECONFIGURE_IO_SHARE_FAILED(clusterName);
}
return total;
} catch (Exception e) {
logger.error("error in reconfiguring vm io shares", e);
throw BddException.INTERNAL(e, e.getMessage());
}
}
@Override
public boolean startSingleVM(String clusterName, String nodeName,
StatusUpdater statusUpdator) {
NodeEntity node = this.clusterEntityMgr.findNodeByName(nodeName);
QueryIpAddress query = new QueryIpAddress(600);
VcHost host = null;
if (node.getHostName() != null) {
host = VcResourceUtils.findHost(node.getHostName());
}
VcVirtualMachine vcVm = VcCache.getIgnoreMissing(node.getMoId());
if (vcVm == null) {
logger.info("VC vm does not exist for node: " + node.getVmName());
return false;
}
StartVmSP startVMSP = new StartVmSP(vcVm, query, host);
return VcVmUtil.runSPOnSingleVM(node, startVMSP);
}
@Override
public boolean stopSingleVM(String clusterName, String nodeName,
StatusUpdater statusUpdator, boolean... vmPoweroff) {
NodeEntity node = this.clusterEntityMgr.findNodeByName(nodeName);
if (node.getMoId() == null) {
logger.error("vm mobid for node " + node.getVmName() + " is null");
return false;
}
VcVirtualMachine vcVm = VcCache.getIgnoreMissing(node.getMoId());
if (vcVm == null) {
logger.info("VC vm does not exist for node: " + node.getVmName());
return false;
}
StopVmSP stopVMSP;
if (vmPoweroff.length > 0 && vmPoweroff[0]) {
stopVMSP = new StopVmSP(vcVm, true);
} else {
stopVMSP = new StopVmSP(vcVm);
}
return VcVmUtil.runSPOnSingleVM(node, stopVMSP);
}
}
diff --git a/server/cluster-mgmt/src/main/java/com/vmware/bdd/utils/VcVmUtil.java b/server/cluster-mgmt/src/main/java/com/vmware/bdd/utils/VcVmUtil.java
index 846153bf..5e4bac95 100644
--- a/server/cluster-mgmt/src/main/java/com/vmware/bdd/utils/VcVmUtil.java
+++ b/server/cluster-mgmt/src/main/java/com/vmware/bdd/utils/VcVmUtil.java
@@ -1,473 +1,476 @@
/***************************************************************************
* Copyright (c) 2012-2013 VMware, Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
***************************************************************************/
package com.vmware.bdd.utils;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.Callable;
import org.apache.log4j.Logger;
import com.vmware.aurora.composition.DiskSchema;
import com.vmware.aurora.composition.DiskSchema.Disk;
import com.vmware.aurora.composition.NetworkSchema;
import com.vmware.aurora.composition.NetworkSchema.Network;
import com.vmware.aurora.composition.ResourceSchema;
import com.vmware.aurora.composition.VmSchema;
import com.vmware.aurora.composition.concurrent.ExecutionResult;
import com.vmware.aurora.composition.concurrent.Scheduler;
import com.vmware.aurora.vc.DeviceId;
import com.vmware.aurora.vc.DiskSpec.AllocationType;
import com.vmware.aurora.vc.MoUtil;
import com.vmware.aurora.vc.VcCache;
import com.vmware.aurora.vc.VcCluster;
import com.vmware.aurora.vc.VcDatastore;
import com.vmware.aurora.vc.VcResourcePool;
import com.vmware.aurora.vc.VcVirtualMachine;
import com.vmware.aurora.vc.VmConfigUtil;
import com.vmware.aurora.vc.vcservice.VcContext;
import com.vmware.aurora.vc.vcservice.VcSession;
import com.vmware.bdd.apitypes.ClusterCreate;
import com.vmware.bdd.apitypes.NodeGroupCreate;
import com.vmware.bdd.apitypes.NodeStatus;
import com.vmware.bdd.apitypes.Priority;
import com.vmware.bdd.entity.DiskEntity;
import com.vmware.bdd.entity.NodeEntity;
import com.vmware.bdd.entity.VcResourcePoolEntity;
import com.vmware.bdd.exception.BddException;
import com.vmware.bdd.exception.ClusteringServiceException;
import com.vmware.bdd.placement.entity.BaseNode;
import com.vmware.bdd.service.sp.NoProgressUpdateCallback;
import com.vmware.bdd.service.utils.VcResourceUtils;
import com.vmware.bdd.spectypes.DiskSpec;
import com.vmware.vim.binding.impl.vim.SharesInfoImpl;
import com.vmware.vim.binding.impl.vim.StorageResourceManager_Impl.IOAllocationInfoImpl;
import com.vmware.vim.binding.impl.vim.vm.device.VirtualDeviceSpecImpl;
import com.vmware.vim.binding.vim.Datastore;
import com.vmware.vim.binding.vim.SharesInfo;
import com.vmware.vim.binding.vim.SharesInfo.Level;
import com.vmware.vim.binding.vim.StorageResourceManager.IOAllocationInfo;
import com.vmware.vim.binding.vim.VirtualMachine.FaultToleranceState;
import com.vmware.vim.binding.vim.vm.GuestInfo;
import com.vmware.vim.binding.vim.vm.device.VirtualDevice;
import com.vmware.vim.binding.vim.vm.device.VirtualDeviceSpec;
import com.vmware.vim.binding.vim.vm.device.VirtualDisk;
import com.vmware.vim.binding.vim.vm.device.VirtualDiskOption.DiskMode;
public class VcVmUtil {
private static final Logger logger = Logger.getLogger(VcVmUtil.class);
private static final String DEFAULT_NIC_1_LABEL = "Network adapter 1";
public static String getIpAddress(final VcVirtualMachine vcVm,
boolean inSession) {
try {
if (inSession) {
return vcVm.queryGuest().getIpAddress();
}
String ip = VcContext.inVcSessionDo(new VcSession<String>() {
@Override
protected boolean isTaskSession() {
return true;
}
@Override
public String body() throws Exception {
GuestInfo guest = vcVm.queryGuest();
return guest.getIpAddress();
}
});
return ip;
} catch (Exception e) {
throw BddException.wrapIfNeeded(e, e.getLocalizedMessage());
}
}
public static String getGuestHostName(final VcVirtualMachine vcVm,
boolean inSession) {
try {
if (inSession) {
return vcVm.queryGuest().getHostName();
}
String hostName = VcContext.inVcSessionDo(new VcSession<String>() {
@Override
protected boolean isTaskSession() {
return true;
}
@Override
public String body() throws Exception {
GuestInfo guest = vcVm.queryGuest();
return guest.getHostName();
}
});
return hostName;
} catch (Exception e) {
throw BddException.wrapIfNeeded(e, e.getLocalizedMessage());
}
}
public static boolean setBaseNodeForVm(BaseNode vNode, VcVirtualMachine vm) {
boolean success = true;
String vmName = vm.getName();
vm = VcCache.getIgnoreMissing(vm.getId()); //reload vm in case vm is changed from vc
if (vm == null) {
logger.info("vm " + vmName
+ "is created, and then removed afterwards.");
}
String ip = null;
if (vm != null) {
ip = VcVmUtil.getIpAddress(vm, false);
}
if (ip != null) {
vNode.setSuccess(true);
vNode.setIpAddress(ip);
vNode.setGuestHostName(VcVmUtil.getGuestHostName(vm, false));
vNode.setTargetHost(vm.getHost().getName());
vNode.setVmMobId(vm.getId());
if (vm.isPoweredOn()) {
vNode.setNodeStatus(NodeStatus.VM_READY);
vNode.setNodeAction(null);
} else {
vNode.setNodeStatus(NodeStatus.POWERED_OFF);
vNode.setNodeAction(Constants.NODE_ACTION_CLONING_FAILED);
}
} else {
vNode.setSuccess(false);
+ // in static ip case, vNode contains the allocated address,
+ // here reset the value in case the ip is unavailable from vc
+ vNode.setIpAddress(null);
if (vm != null) {
vNode.setVmMobId(vm.getId());
if (vm.isPoweredOn()) {
vNode.setNodeStatus(NodeStatus.POWERED_ON);
vNode.setNodeAction(Constants.NODE_ACTION_GET_IP_FAILED);
} else {
vNode.setNodeStatus(NodeStatus.POWERED_OFF);
vNode.setNodeAction(Constants.NODE_ACTION_CLONING_FAILED);
}
}
success = false;
logger.error("Failed to get ip address of VM " + vNode.getVmName());
}
if (success) {
String haFlag = vNode.getNodeGroup().getHaFlag();
if (haFlag != null
&& Constants.HA_FLAG_FT.equals(haFlag.toLowerCase())) {
// ha is enabled, need to check if secondary VM is ready either
logger.error("Failed to power on FT secondary VM for node "
+ vm.getName() + ", " + "FT state " + vm.getFTState()
+ " is unexpected.");
return verifyFTState(vm);
}
}
return success;
}
public static boolean verifyFTState(final VcVirtualMachine vm) {
try {
VcContext.inVcSessionDo(new VcSession<Void>() {
@Override
public Void body() throws Exception {
vm.updateRuntime();
return null;
}
});
} catch (Exception e) {
logger.error("Failed to update VM " + vm.getName()
+ " runtime information,"
+ " this may cause the FT state wrong.");
}
if (vm.getFTState() == null
|| vm.getFTState() != FaultToleranceState.running) {
return false;
}
return true;
}
public static VirtualDisk findVirtualDisk(String vmMobId, String externalAddr) {
VcVirtualMachine vm = VcCache.getIgnoreMissing(vmMobId);
DeviceId diskId = new DeviceId(externalAddr);
VirtualDevice device = vm.getVirtualDevice(diskId);
if (device == null)
return null;
AuAssert.check(device instanceof VirtualDisk);
return (VirtualDisk) device;
}
public static void populateDiskInfo(final DiskEntity diskEntity,
final String vmMobId) {
VcContext.inVcSessionDo(new VcSession<Void>() {
@Override
protected boolean isTaskSession() {
return true;
}
@Override
protected Void body() throws Exception {
VirtualDisk vDisk =
findVirtualDisk(vmMobId, diskEntity.getExternalAddress());
if (vDisk == null)
return null;
VirtualDisk.FlatVer2BackingInfo backing =
(VirtualDisk.FlatVer2BackingInfo) vDisk.getBacking();
Datastore ds = MoUtil.getManagedObject(backing.getDatastore());
diskEntity.setSizeInMB((int) (vDisk.getCapacityInKB() / 1024));
diskEntity.setDatastoreName(ds.getName());
diskEntity.setVmdkPath(backing.getFileName());
diskEntity.setDatastoreMoId(MoUtil.morefToString(ds._getRef()));
diskEntity.setDiskMode(backing.getDiskMode());
return null;
}
});
}
public static boolean isDatastoreAccessible(String dsMobId) {
final VcDatastore ds = VcCache.getIgnoreMissing(dsMobId);
try {
VcContext.inVcSessionDo(new VcSession<Void>() {
@Override
protected boolean isTaskSession() {
return true;
}
@Override
protected Void body() throws Exception {
ds.update();
return null;
}
});
} catch (Exception e) {
logger.info("failed to update datastore " + ds.getName()
+ ", ignore this error.");
}
if (ds != null && ds.isAccessible())
return true;
return false;
}
public static void updateVm(String vmId) {
final VcVirtualMachine vm = VcCache.getIgnoreMissing(vmId);
try {
VcContext.inVcSessionDo(new VcSession<Void>() {
@Override
protected boolean isTaskSession() {
return true;
}
@Override
protected Void body() throws Exception {
vm.update();
return null;
}
});
} catch (Exception e) {
logger.info("failed to update vm " + vm.getName()
+ ", ignore this error.");
}
}
public static boolean configIOShares(final String vmId,
final Priority ioShares) {
final VcVirtualMachine vcVm = VcCache.getIgnoreMissing(vmId);
if (vcVm == null) {
logger.info("vm " + vmId + " is not found.");
return false;
}
VcContext.inVcSessionDo(new VcSession<Void>() {
@Override
protected Void body() throws Exception {
List<VirtualDeviceSpec> deviceSpecs =
new ArrayList<VirtualDeviceSpec>();
for (DeviceId slot : vcVm.getVirtualDiskIds()) {
SharesInfo shares = new SharesInfoImpl();
shares.setLevel(Level.valueOf(ioShares.toString().toLowerCase()));
IOAllocationInfo allocationInfo = new IOAllocationInfoImpl();
allocationInfo.setShares(shares);
VirtualDisk vmdk = (VirtualDisk) vcVm.getVirtualDevice(slot);
vmdk.setStorageIOAllocation(allocationInfo);
VirtualDeviceSpec spec = new VirtualDeviceSpecImpl();
spec.setOperation(VirtualDeviceSpec.Operation.edit);
spec.setDevice(vmdk);
deviceSpecs.add(spec);
}
logger.info("reconfiguring disks in vm " + vmId
+ " io share level to " + ioShares);
vcVm.reconfigure(VmConfigUtil.createConfigSpec(deviceSpecs));
logger.info("reconfigured disks in vm " + vmId
+ " io share level to " + ioShares);
return null;
}
protected boolean isTaskSession() {
return true;
}
});
return true;
}
public static boolean runSPOnSingleVM(NodeEntity node, Callable<Void> call) {
boolean operationResult = true;
if (node == null || node.getMoId() == null) {
logger.info("VC vm does not exist for node: " + node == null ? null
: node.getVmName());
return false;
}
VcVirtualMachine vcVm = VcCache.getIgnoreMissing(node.getMoId());
if (vcVm == null) {
// cannot find VM
logger.info("VC vm does not exist for node: " + node.getVmName());
return false;
}
@SuppressWarnings("unchecked")
Callable<Void>[] storeProceduresArray = new Callable[1];
storeProceduresArray[0] = call;
NoProgressUpdateCallback callback = new NoProgressUpdateCallback();
try {
ExecutionResult[] result =
Scheduler
.executeStoredProcedures(
com.vmware.aurora.composition.concurrent.Priority.BACKGROUND,
storeProceduresArray, callback);
if (result == null) {
logger.error("No result from composition layer");
return false;
} else {
if (result[0].finished && result[0].throwable == null) {
operationResult = true;
logger.info("successfully run operation on vm for node: "
+ node.getVmName());
} else {
operationResult = false;
logger.error("failed in run operation on vm for node: "
+ node.getVmName());
}
}
} catch (Exception e) {
operationResult = false;
logger.error("error in run operation on vm.", e);
}
return operationResult;
}
// get the parent vc resource pool of the node
public static VcResourcePool getTargetRp(String clusterName,
String groupName, NodeEntity node) {
String clusterRpName = ConfigInfo.getSerengetiUUID() + "-" + clusterName;
VcResourcePoolEntity rpEntity = node.getVcRp();
String vcRPName = "";
try {
VcCluster cluster =
VcResourceUtils.findVcCluster(rpEntity.getVcCluster());
if (!cluster.getConfig().getDRSEnabled()) {
logger.debug("DRS disabled for cluster " + rpEntity.getVcCluster()
+ ", put VM under cluster directly.");
return cluster.getRootRP();
}
if (CommonUtil.isBlank(rpEntity.getVcResourcePool())) {
vcRPName = clusterRpName + "/" + groupName;
} else {
vcRPName =
rpEntity.getVcResourcePool() + "/" + clusterRpName + "/"
+ groupName;
}
VcResourcePool rp =
VcResourceUtils.findRPInVCCluster(rpEntity.getVcCluster(),
vcRPName);
if (rp == null) {
throw ClusteringServiceException.TARGET_VC_RP_NOT_FOUND(
rpEntity.getVcCluster(), vcRPName);
}
return rp;
} catch (Exception e) {
logger.error("Failed to get VC resource pool " + vcRPName
+ " in vc cluster " + rpEntity.getVcCluster(), e);
throw ClusteringServiceException.TARGET_VC_RP_NOT_FOUND(
rpEntity.getVcCluster(), vcRPName);
}
}
public static VmSchema getVmSchema(ClusterCreate spec, String nodeGroup,
List<DiskSpec> diskSet, String templateVmId, String templateVmSnapId) {
NodeGroupCreate groupSpec = spec.getNodeGroup(nodeGroup);
VmSchema schema = new VmSchema();
// prepare resource schema
ResourceSchema resourceSchema = new ResourceSchema();
resourceSchema.name = "Resource Schema";
resourceSchema.cpuReservationMHz = 0;
resourceSchema.memReservationSize = 0;
resourceSchema.numCPUs = groupSpec.getCpuNum();
resourceSchema.memSize = groupSpec.getMemCapacityMB();
resourceSchema.priority =
com.vmware.aurora.interfaces.model.IDatabaseConfig.Priority.Normal;
schema.resourceSchema = resourceSchema;
// prepare disk schema
DiskSchema diskSchema = new DiskSchema();
ArrayList<Disk> disks = new ArrayList<Disk>(diskSet.size());
for (DiskSpec disk : diskSet) {
Disk tmDisk = new Disk();
tmDisk.name = disk.getName();
tmDisk.type = disk.getDiskType().getType();
tmDisk.initialSizeMB = disk.getSize() * 1024;
if (disk.getAllocType() != null && !disk.getAllocType().isEmpty())
tmDisk.allocationType =
AllocationType.valueOf(disk.getAllocType().toUpperCase());
else
tmDisk.allocationType = null;
tmDisk.datastore = disk.getTargetDs();
tmDisk.externalAddress = disk.getExternalAddress();
tmDisk.vmdkPath = disk.getVmdkPath();
tmDisk.mode = DiskMode.valueOf(disk.getDiskMode());
disks.add(tmDisk);
}
diskSchema.setParent(templateVmId);
diskSchema.setParentSnap(templateVmSnapId);
diskSchema.setDisks(disks);
schema.diskSchema = diskSchema;
// prepare network schema
Network network = new Network();
network.vcNetwork = spec.getNetworking().get(0).getPortGroup();
network.nicLabel = DEFAULT_NIC_1_LABEL;
ArrayList<Network> networks = new ArrayList<Network>();
networks.add(network);
NetworkSchema networkSchema = new NetworkSchema();
networkSchema.name = "Network Schema";
networkSchema.networks = networks;
schema.networkSchema = networkSchema;
return schema;
}
public static long makeVmMemoryDivisibleBy4(long memory) {
return CommonUtil.makeVmMemoryDivisibleBy4(memory);
}
public static void addBootupUUID(Map<String, String> bootupConfigs) {
AuAssert.check(bootupConfigs != null);
bootupConfigs.put(Constants.GUEST_VARIABLE_BOOTUP_UUID, UUID.randomUUID()
.toString());
}
}
| false | false | null | null |
diff --git a/src/interiores/business/models/backtracking/FurnitureVariable.java b/src/interiores/business/models/backtracking/FurnitureVariable.java
index 4d19917..a192421 100644
--- a/src/interiores/business/models/backtracking/FurnitureVariable.java
+++ b/src/interiores/business/models/backtracking/FurnitureVariable.java
@@ -1,280 +1,283 @@
package interiores.business.models.backtracking;
import interiores.business.models.Orientation;
import interiores.business.models.backtracking.Area.Area;
import interiores.business.models.constraints.Constraint;
import interiores.business.models.constraints.furniture.BacktrackingTimeTrimmer;
import interiores.business.models.constraints.furniture.InexhaustiveTrimmer;
import interiores.business.models.constraints.furniture.PreliminarTrimmer;
import interiores.business.models.room.FurnitureModel;
import interiores.shared.backtracking.Value;
import interiores.shared.backtracking.Variable;
import interiores.utils.Dimension;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class FurnitureVariable
extends InterioresVariable
{
@XmlElementWrapper
protected Map<Class, Constraint> furnitureConstraints;
@XmlTransient
protected Domain domain;
/**
* Represents the iteration of the algorithm.
*/
@XmlTransient
public int iteration;
@XmlTransient
private float minPrice;
private int maxWidth;
private int maxDepth;
private int minSize;
/**
* Default constructor.
* JAXB needs it!
*/
public FurnitureVariable()
{ }
/**
* Default Constructor. The resulting variable has as domain the models in
* "models", every position in room and all orientations.
* The set of restrictions is "unaryConstraints". Its resolution defaults to 5.
* @pre the iteration of the variableSet is 0
*/
public FurnitureVariable(String typeName)
{
super(typeName);
furnitureConstraints = new HashMap();
}
public FurnitureVariable(String id, String typeName, FurnitureValue value) {
this(typeName);
assignValue(value);
}
@Override
public boolean isConstant() {
return false;
}
public void createDomain(HashSet<FurnitureModel> models, Dimension roomSize, int variableCount) {
domain = new Domain(models, roomSize, variableCount);
iteration = 0;
initializeMaxMinFields();
undoAssignValue();
}
public Collection<Constraint> getConstraints() {
return furnitureConstraints.values();
}
/**
* Resets the iterators so that they will iterate through all of the
* variables' domains, for the iteration "iteration" of the algorithm.
*/
public void resetIterators(int iteration) {
// update internal iteration
this.iteration = iteration;
domain.resetIterators(iteration);
}
//Pre: we have not iterated through all domain values yet.
@Override
public Value getNextDomainValue() {
return domain.getNextDomainValue(iteration);
}
//Pre: the 3 iterators point to valid values
@Override
public boolean hasMoreValues() {
return domain.hasMoreValues(iteration);
}
/**
* Moves positions, models and orientations which are still valid to the
* next level.
* To do this operation, we move all values preliminarily, and then move
* back those that are not valid.
*/
//pre: variable has an assigned value.
//pre: if trimDomain or undoTrimDomain has already been called once,
// "iteration" value must be related to the value of "iteration" of the
// previous call (+1 if it was a trimDomain or equal if it was a
// undoTrimDomain).
// otherwise, it must be 0.
//
@Override
public void trimDomain(Variable variable, int iteration) {
this.iteration = iteration;
// 1) preliminar move of all positions
forwardIteration();
// 2) Run trimmers
for (Constraint constraint : furnitureConstraints.values())
if (constraint instanceof BacktrackingTimeTrimmer)
((BacktrackingTimeTrimmer) constraint).trim(this);
}
/**
* Merges back values from step "iteration"+1 to "iteration" level.
* To do this operation, we swap the containers first if the destination
* level's container has less elements.
*/
//pre: trimDomain has already been called once.
// "iteration" value must be related to the value of "iteration" of the
// previous call to trimDomain or undoTrimDomain (equal if it was
// trimDomain or -1 if it was undoTrimDomain).
@Override
public void undoTrimDomain(Variable variable, Value value, int iteration) {
domain.reverseIteration(iteration);
}
public Domain getDomain() {
return domain;
}
/**
* Returns the price of the cheapest model.
* @return
*/
public float getMinPrice() {
return minPrice;
}
private void initializeMaxMinFields() {
minPrice = -1;
maxWidth = 0;
maxDepth = 0;
minSize = -1;
for (FurnitureModel model : domain.getModels(0)) {
if (minPrice == -1 || model.getPrice() < minPrice)
minPrice = model.getPrice();
if (model.getSize().width > maxWidth)
maxWidth = model.getSize().width;
if (model.getSize().depth > maxDepth)
maxDepth = model.getSize().depth;
if (minSize == -1 || model.areaSize() < minSize)
minSize = model.areaSize();
}
if (minPrice == -1) minPrice = 0;
if (minSize == -1) minSize = 0;
}
public int domainSize() {
return domain.domainSize(iteration);
}
public int smallestModelSize() {
return minSize;
}
public void triggerPreliminarTrimmers() {
for (Constraint constraint : furnitureConstraints.values()) {
if (constraint instanceof PreliminarTrimmer) {
PreliminarTrimmer preliminarTrimmer = (PreliminarTrimmer) constraint;
preliminarTrimmer.preliminarTrim(this);
}
//ditch it if it doesn't implement any other interface
if (! (constraint instanceof InexhaustiveTrimmer));
//removing constraints unhabilitated
//furnitureConstraints.remove(constraint.getClass());
}
}
public boolean constraintsSatisfied() {
- for (Constraint constraint : furnitureConstraints.values())
- if (! ((InexhaustiveTrimmer) constraint).isSatisfied(this))
- return false;
+ for (Constraint constraint : furnitureConstraints.values()) {
+ if (constraint instanceof InexhaustiveTrimmer) {
+ if (! ((InexhaustiveTrimmer) constraint).isSatisfied(this))
+ return false;
+ }
+ }
return true;
}
public int getMaxWidth() {
return maxWidth;
}
public int getMaxDepth() {
return maxDepth;
}
//FUNCTIONS TO MODIFY THE DOMAIN
//forwardIteration(), and consfraint - variable interface
/**
* Moves all values of the current iteration to the next iteration
*/
public void forwardIteration() {
domain.forwardIteration(iteration);
}
//CONSTRAINT - VARIABLE INTERFACE
public void eliminateExceptP(Area validPositions) {
domain.eliminateExceptP(validPositions);
}
/**
* Any value of the domain of the next iteration included in the
* parameter is trimmed (moved to the previous iteration)
* @param invalidArea
*/
public void trimP(Area invalidArea) {
// Debug.println("In trimP:");
// Debug.println("We have this area:");
// Debug.println(this.getDomain().getPositions(iteration+1).toString());
// Debug.println("And we remove this area from it:");
// Debug.println(invalidArea.toString());
domain.trimP(invalidArea, iteration);
// Debug.println("And the result is this area: ");
// Debug.println(this.getDomain().getPositions(iteration+1).toString());
}
/**
* Any value of the domain of the next iteration not included in the
* parameter is trimmed (moved to the previous iteration)
* @param validArea
*/
public void trimExceptP(Area validArea) {
domain.trimExceptP(validArea, iteration);
}
public void eliminateExceptM(HashSet<FurnitureModel> validModels) {
domain.eliminateExceptM(validModels);
}
public void eliminateExceptO(HashSet<Orientation> validOrientations) {
domain.eliminateExceptO(validOrientations);
}
public void trimExceptM(HashSet<FurnitureModel> validModels) {
domain.trimExceptM(validModels, iteration);
}
public void trimExceptO(HashSet<Orientation> validOrientations) {
domain.trimExceptO(validOrientations, iteration);
}
}
\ No newline at end of file
| true | false | null | null |
diff --git a/ide/eclipse/data-services/org.wso2.developerstudio.eclipse.ds.editor/src/org/wso2/developerstudio/eclipse/ds/presentation/md/DetailSection.java b/ide/eclipse/data-services/org.wso2.developerstudio.eclipse.ds.editor/src/org/wso2/developerstudio/eclipse/ds/presentation/md/DetailSection.java
index edd0d6a97..42a5dff91 100755
--- a/ide/eclipse/data-services/org.wso2.developerstudio.eclipse.ds.editor/src/org/wso2/developerstudio/eclipse/ds/presentation/md/DetailSection.java
+++ b/ide/eclipse/data-services/org.wso2.developerstudio.eclipse.ds.editor/src/org/wso2/developerstudio/eclipse/ds/presentation/md/DetailSection.java
@@ -1,1429 +1,1437 @@
package org.wso2.developerstudio.eclipse.ds.presentation.md;
import java.util.ArrayList;
import java.util.Iterator;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.impl.EAttributeImpl;
import org.eclipse.emf.edit.domain.EditingDomain;
import org.eclipse.emf.edit.provider.AdapterFactoryItemDelegator;
import org.eclipse.emf.edit.provider.IItemPropertyDescriptor;
import org.eclipse.emf.edit.provider.ItemPropertyDescriptor;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.wso2.developerstudio.eclipse.ds.AttributeMapping;
import org.wso2.developerstudio.eclipse.ds.CallQuery;
import org.wso2.developerstudio.eclipse.ds.ConfigurationProperty;
import org.wso2.developerstudio.eclipse.ds.CustomValidator;
import org.wso2.developerstudio.eclipse.ds.DataService;
import org.wso2.developerstudio.eclipse.ds.DataSourceConfiguration;
import org.wso2.developerstudio.eclipse.ds.Description;
import org.wso2.developerstudio.eclipse.ds.DoubleRangeValidator;
import org.wso2.developerstudio.eclipse.ds.DsPackage;
import org.wso2.developerstudio.eclipse.ds.ElementMapping;
import org.wso2.developerstudio.eclipse.ds.EventTrigger;
import org.wso2.developerstudio.eclipse.ds.ExcelQuery;
import org.wso2.developerstudio.eclipse.ds.Expression;
import org.wso2.developerstudio.eclipse.ds.GSpreadQuery;
import org.wso2.developerstudio.eclipse.ds.HasHeader;
import org.wso2.developerstudio.eclipse.ds.LengthValidator;
import org.wso2.developerstudio.eclipse.ds.LongRangeValidator;
import org.wso2.developerstudio.eclipse.ds.MaxRowCount;
import org.wso2.developerstudio.eclipse.ds.Operation;
import org.wso2.developerstudio.eclipse.ds.ParameterMapping;
import org.wso2.developerstudio.eclipse.ds.PatternValidator;
import org.wso2.developerstudio.eclipse.ds.Query;
import org.wso2.developerstudio.eclipse.ds.QueryParameter;
import org.wso2.developerstudio.eclipse.ds.QueryProperty;
import org.wso2.developerstudio.eclipse.ds.QueryPropertyList;
import org.wso2.developerstudio.eclipse.ds.Resource;
import org.wso2.developerstudio.eclipse.ds.ResultMapping;
import org.wso2.developerstudio.eclipse.ds.Sparql;
import org.wso2.developerstudio.eclipse.ds.Sql;
import org.wso2.developerstudio.eclipse.ds.StartingRow;
import org.wso2.developerstudio.eclipse.ds.Subscription;
import org.wso2.developerstudio.eclipse.ds.TargetTopic;
import org.wso2.developerstudio.eclipse.ds.WorkBookName;
import org.wso2.developerstudio.eclipse.ds.WorkSheetNumber;
import org.wso2.developerstudio.eclipse.ds.actions.DSActionConstants;
import org.wso2.developerstudio.eclipse.ds.presentation.DsEditor;
public class DetailSection {
private FormToolkit toolkit;
private AdapterFactoryItemDelegator adapterFactoryItemDelegator;
private Composite detailsclient;
private Object selectedObject;
private DetailSectionUiUtil sectionUtil;
private EditingDomain editingDomain;
private DataService dataService;
public DetailSection(FormToolkit toolkit,
AdapterFactoryItemDelegator adapterFactoryItemDelegator,
Composite detailsclient, Object input,DsEditor editor) {
this.toolkit = toolkit;
this.adapterFactoryItemDelegator = adapterFactoryItemDelegator;
this.detailsclient = detailsclient;
this.selectedObject = input;
this.editingDomain = editor.getEditingDomain();
this.dataService = editor.getDataService();
this.sectionUtil = new DetailSectionUiUtil(editor.getDataService(), editingDomain);
}
private Label labelMaker(String s) {
Label l = toolkit.createLabel(detailsclient, s, SWT.NONE);
GridData gd = new GridData();
l.setLayoutData(gd);
return l;
}
public void createSection(final Object input) {
if (input != null) {
customizeUibasedOnInput(input,detailsclient);
} else {
labelMaker("No data to show in the Detail section");
}
toolkit.paintBordersFor(detailsclient);
}
private void customizeUibasedOnInput(Object input,Composite detailsclient){
//On Data service selection
if(input instanceof DataService){
DataService dataService = (DataService)input;
dataServiceObjectConfigurator(dataService);
//On description selection
}else if(input instanceof Description){
Description description = (Description)input;
labelMaker("");
labelMaker("");
labelMaker(DetailSectionCustomUiConstants.DATA_SERVICE_DESCRIPTION);
sectionUtil.getAttributeField(detailsclient,toolkit,input,description.getValue(),
DsPackage.eINSTANCE.getDescription_Value(),DetailSectionCustomUiConstants.STRING);
//On Data Source selection
}else if(input instanceof DataSourceConfiguration){
DataSourceConfiguration config = (DataSourceConfiguration)input;
labelMaker("");
labelMaker("");
labelMaker(DetailSectionCustomUiConstants.DATA_SOURCE_CONFIGURATION_ID);
sectionUtil.getAttributeField(detailsclient,toolkit,input,config.getId(),
DsPackage.eINSTANCE.getDataSourceConfiguration_Id(),DetailSectionCustomUiConstants.STRING);
if(config != null){
EList<ConfigurationProperty> configProperties = config.getProperty();
Iterator<ConfigurationProperty>iterator = configProperties.iterator();
while (iterator.hasNext()) {
ConfigurationProperty configurationProperty = (ConfigurationProperty) iterator.next();
configurationPropertyObjectConfigurator(configurationProperty);
}
}
//On configuration property selction
}else if(input instanceof ConfigurationProperty){
ConfigurationProperty configProperty = (ConfigurationProperty)input;
configurationPropertyObjectConfigurator(configProperty);
//On query selction
}else if(input instanceof Query){
Query query = (Query)input;
queryObjectConfigurator(query);
}else if(input instanceof Sql ){
Sql sql = (Sql)input;
labelMaker(DetailSectionCustomUiConstants.QUERY_SQL);
sectionUtil.getMultilineTextFileld(detailsclient, toolkit, input, sql.getValue(),
DsPackage.eINSTANCE.getSql_Value(), DetailSectionCustomUiConstants.STRING);
labelMaker("");
labelMaker("");
}else if(input instanceof Sparql){
Sparql sparql = (Sparql)input;
labelMaker(DetailSectionCustomUiConstants.QUERY_SPARQL);
sectionUtil.getMultilineTextFileld(detailsclient, toolkit, input, sparql.getValue(),
DsPackage.eINSTANCE.getSparql_Value(), DetailSectionCustomUiConstants.STRING);
labelMaker("");
labelMaker("");
}else if(input instanceof QueryPropertyList){
QueryPropertyList propList = (QueryPropertyList)input;
EList<QueryProperty> queryProperties = propList.getProperty();
Iterator<QueryProperty> iterator = queryProperties.iterator();
while(iterator.hasNext()){
QueryProperty queryProperty = (QueryProperty)iterator.next();
queryPropertyObjectConfigurator(queryProperty);
}
}else if(input instanceof QueryProperty){
QueryProperty property = (QueryProperty)input;
queryPropertyObjectConfigurator(property);
}else if(input instanceof ResultMapping){
ResultMapping result = (ResultMapping)input;
resultObjectConfigurator(result);
}else if(input instanceof ElementMapping){
ElementMapping element = (ElementMapping)input;
elementMappingObjectConfigurator(element);
}else if(input instanceof AttributeMapping ){
AttributeMapping attributeMap = (AttributeMapping)input;
attributeMappingObjectConfiguretor(attributeMap);
}else if(input instanceof ExcelQuery){
//no attributes to display
}else if(input instanceof WorkBookName){
WorkBookName wrkBook = (WorkBookName)input;
labelMaker(DetailSectionCustomUiConstants.EXCEL_WORKBOOK_NAME);
sectionUtil.getAttributeField(detailsclient, toolkit, wrkBook, wrkBook.getValue(),
DsPackage.eINSTANCE.getWorkBookName_Value(),DetailSectionCustomUiConstants.STRING);
}else if(input instanceof HasHeader){
HasHeader hasHeader = (HasHeader)input;
labelMaker(DetailSectionCustomUiConstants.EXCEL_HAS_HEADER);
sectionUtil.getBooleanComboField(detailsclient, toolkit,hasHeader,hasHeader.isValue(),
DsPackage.eINSTANCE.getHasHeader_Value());
}else if(input instanceof StartingRow){
StartingRow str = (StartingRow)input;
labelMaker(DetailSectionCustomUiConstants.EXCEL_STARTING_ROW);
String existingVal = new Long(str.getValue()).toString();
sectionUtil.getAttributeField(detailsclient, toolkit, str, existingVal,
DsPackage.eINSTANCE.getStartingRow_Value(), DetailSectionCustomUiConstants.LONG);
}else if(input instanceof MaxRowCount){
MaxRowCount mxrc = (MaxRowCount)input;
labelMaker(DetailSectionCustomUiConstants.EXCEL_MAX_ROW_COUNT);
String existingVal = new Long(mxrc.getValue()).toString();
sectionUtil.getAttributeField(detailsclient, toolkit, mxrc, existingVal,
DsPackage.eINSTANCE.getMaxRowCount_Value(), DetailSectionCustomUiConstants.LONG);
}else if(input instanceof GSpreadQuery){
//no attributes to display
}else if(input instanceof WorkSheetNumber){
WorkSheetNumber wrkshtnum = (WorkSheetNumber)input;
labelMaker(DetailSectionCustomUiConstants.GSPRED_WORK_SHEET_NUM);
String existingVal = new Long(wrkshtnum.getValue()).toString();
sectionUtil.getAttributeField(detailsclient, toolkit, wrkshtnum, existingVal,
DsPackage.eINSTANCE.getWorkSheetNumber_Value(),DetailSectionCustomUiConstants.LONG);
}else if(input instanceof QueryParameter){
QueryParameter queryParm = (QueryParameter)input;
queryParamObjectConfigurator(queryParm);
}else if(input instanceof LongRangeValidator ){
LongRangeValidator longrval = (LongRangeValidator)input;
validatorObjectConfigurator(longrval, DetailSectionCustomUiConstants.LONG);
}else if(input instanceof DoubleRangeValidator){
DoubleRangeValidator doublerval = (DoubleRangeValidator)input;
validatorObjectConfigurator(doublerval, DetailSectionCustomUiConstants.DOUBLE);
}else if(input instanceof LengthValidator){
LengthValidator lengthaval = (LengthValidator)input;
validatorObjectConfigurator(lengthaval, DetailSectionCustomUiConstants.LONG);
}else if(input instanceof PatternValidator ){
labelMaker("");
labelMaker("");
PatternValidator pValiditor = (PatternValidator)input;
labelMaker(DetailSectionCustomUiConstants.VALIDATOR_PATTORN);
sectionUtil.getMultilineTextFileld(detailsclient, toolkit, pValiditor, pValiditor.getPattern(),
DsPackage.eINSTANCE.getPatternValidator_Pattern(), DetailSectionCustomUiConstants.STRING);
}else if(input instanceof CustomValidator){
labelMaker("");
labelMaker("");
CustomValidator customValidator = (CustomValidator)input;
labelMaker(DetailSectionCustomUiConstants.VALIDATOR_CUSTOM);
sectionUtil.getAttributeField(detailsclient, toolkit, customValidator, customValidator.getClass_(),
DsPackage.eINSTANCE.getCustomValidator_Class(),DetailSectionCustomUiConstants.STRING);
}else if(input instanceof EventTrigger){
EventTrigger eventTirg = (EventTrigger)input;
eventTriggerObejecConfigurator(eventTirg);
}else if(input instanceof Expression){
labelMaker("");
labelMaker("");
Expression expr = (Expression)input;
labelMaker(DetailSectionCustomUiConstants.EVENT_TRIGGER_EXPRESSION);
sectionUtil.getAttributeField(detailsclient, toolkit, expr, expr.getValue(),
DsPackage.eINSTANCE.getExpression_Value(),DetailSectionCustomUiConstants.STRING);
}else if(input instanceof TargetTopic){
labelMaker("");
labelMaker("");
TargetTopic ttpic = (TargetTopic)input;
labelMaker(DetailSectionCustomUiConstants.EVENT_TRIGGER_TARGET_TOPIC);
sectionUtil.getAttributeField(detailsclient, toolkit, ttpic, ttpic.getValue(),
DsPackage.eINSTANCE.getTargetTopic_Value(),DetailSectionCustomUiConstants.STRING);
}else if(input instanceof Subscription){
labelMaker("");
labelMaker("");
Subscription subscription = (Subscription)input;
labelMaker(DetailSectionCustomUiConstants.EVENT_TRIGGER_SUBSCRIPTION);
sectionUtil.getAttributeField(detailsclient, toolkit, subscription, subscription.getValue(),
DsPackage.eINSTANCE.getSubscription_Value(), DetailSectionCustomUiConstants.STRING);
}else if(input instanceof Operation){
Operation operation = (Operation)input;
operationObjectConfigurator(operation);
}else if(input instanceof CallQuery && dataService != null) {
CallQuery callQuery = (CallQuery)input;
EList<Query> queryList = dataService.getQuery();
Query [] q = queryList.toArray(new Query [0]);
String [] displayValues = new String [q.length];
for(int i = 0;i< q.length ;i++){
displayValues [i] = q[i].getId();
}
labelMaker("");
labelMaker("");
labelMaker(DetailSectionCustomUiConstants.CALL_QUERY_LINK);
sectionUtil.getCustomComboField(detailsclient, toolkit, callQuery, callQuery.getHref(),
DsPackage.eINSTANCE.getCallQuery_Href(), displayValues);
}else if(input instanceof ParameterMapping){
ParameterMapping paramMapping = (ParameterMapping)input;
paramMapObjectConfigurator(paramMapping);
}else if(input instanceof Resource){
Resource resource = (Resource)input;
resourceObjectConfigurator(resource);
}
}
private void dataServiceObjectConfigurator(DataService dataService){
ArrayList<IItemPropertyDescriptor> detailPropertyDescriptors = (ArrayList<IItemPropertyDescriptor>)
adapterFactoryItemDelegator
.getPropertyDescriptors(dataService);
labelMaker("");
labelMaker("");
for (Iterator<IItemPropertyDescriptor> i = detailPropertyDescriptors.iterator(); i.hasNext();) {
ItemPropertyDescriptor desc = (ItemPropertyDescriptor) i.next();
String displayName = desc.getDisplayName(dataService);
if (desc.getFeature(dataService) instanceof EAttributeImpl) {
if(displayName.equals(DetailSectionCustomUiConstants.DATA_SERVICE_NAME)){
labelMaker(displayName);
sectionUtil.getAttributeField(detailsclient, toolkit,
selectedObject, dataService.getName(),
DsPackage.eINSTANCE.getDataService_Name(),
DetailSectionCustomUiConstants.STRING);
labelMaker("");
labelMaker("");
// Fixing
// TOOLS-1008.(org.wso2.developerstudio.eclipse.ds.provider.DataServiceItemProvider
// also has relevant change)
Description description = dataService.getDescription();
if (description != null) {
labelMaker(DetailSectionCustomUiConstants.DATA_SERVICE_DESCRIPTION);
sectionUtil.getAttributeField(detailsclient, toolkit,
description, description.getValue(),
DsPackage.eINSTANCE.getDescription_Value(),
DetailSectionCustomUiConstants.STRING);
labelMaker("");
labelMaker("");
}
}
if(displayName.equals(DetailSectionCustomUiConstants.DATA_SERVICE_GROUP)){
labelMaker(displayName);
sectionUtil.getAttributeField(detailsclient,toolkit,selectedObject,dataService.getServiceGroup(),
DsPackage.eINSTANCE.getDataService_ServiceGroup(),DetailSectionCustomUiConstants.STRING);
labelMaker("");
labelMaker("");
}
if(displayName.equals(DetailSectionCustomUiConstants.DATA_SERVICE_NAMESPACE)){
labelMaker(displayName);
sectionUtil.getAttributeField(detailsclient, toolkit, selectedObject, dataService.getServiceNamespace(),
DsPackage.eINSTANCE.getDataService_ServiceNamespace(), DetailSectionCustomUiConstants.STRING);
labelMaker("");
labelMaker("");
}
if(displayName.equals(DetailSectionCustomUiConstants.BASE_URI)){
labelMaker(displayName);
sectionUtil.getAttributeField(detailsclient,toolkit,selectedObject,dataService.getBaseURI(),
DsPackage.eINSTANCE.getDataService_BaseURI(),DetailSectionCustomUiConstants.STRING);
labelMaker("");
labelMaker("");
}
if(displayName.equals(DetailSectionCustomUiConstants.ENABLE_BATCH_REQUESTS)){
labelMaker(displayName);
sectionUtil.getBooleanComboField(detailsclient,toolkit,selectedObject,dataService.isEnableBatchRequests()
,DsPackage.eINSTANCE.getDataService_EnableBatchRequests());
labelMaker("");
labelMaker("");
}
if(displayName.equals(DetailSectionCustomUiConstants.ENABLE_BOX_CARRING)){
labelMaker(displayName);
sectionUtil.getBooleanComboField(detailsclient,toolkit,selectedObject,dataService.isEnableBoxcarring()
,DsPackage.eINSTANCE.getDataService_EnableBoxcarring());
labelMaker("");
labelMaker("");
}
if(displayName.equals(DetailSectionCustomUiConstants.ENABLE_DTP)){
labelMaker(displayName);
sectionUtil.getBooleanComboField(detailsclient,toolkit,selectedObject,dataService.isEnableDTP(),
DsPackage.eINSTANCE.getDataService_EnableDTP());
labelMaker("");
labelMaker("");
}
}
}
}
private void configurationPropertyObjectConfigurator(ConfigurationProperty configProperty){
labelMaker("");
labelMaker("");
if (configProperty.getName() != null && configProperty.getName().equals(DSActionConstants.DRIVER_PROPERTY)) {
labelMaker(DSActionConstants.DRIVER_DISPLAY);
}
if (configProperty.getName() != null && configProperty.getName()
.equals(DSActionConstants.PROTOCOL_PROPERTY)) {
labelMaker(DSActionConstants.PROTOCOL_DISPLAY);
}
if (configProperty.getName() != null && configProperty.getName().equals(DSActionConstants.USER_PROPERTY)) {
labelMaker(DSActionConstants.USER_DISPLAY);
}
if (configProperty.getName() != null && configProperty.getName()
.equals(DSActionConstants.PASSWORD_PROPERTY)) {
labelMaker(DSActionConstants.PASSWORD_DISPLAY);
}
if (configProperty.getName() != null && configProperty.getName().equals(
DSActionConstants.MINPOOLSIZE_PROPERTY)) {
labelMaker(DSActionConstants.MINPOOLSIZE_DISPLAY);
}
if (configProperty.getName() != null && configProperty.getName().equals(
DSActionConstants.MAXPOOLSIZE_PROPERTY)) {
labelMaker(DSActionConstants.MAXPOOLSIZE_DISPLAY);
}
if (configProperty.getName() != null && configProperty.getName().equals(
DSActionConstants.VALIDATIONQUERY_PROPERTY)) {
labelMaker(DSActionConstants.VALIDATIONQUERY_DISPLAY);
}
if (configProperty.getName() != null && configProperty.getName().equals(
DSActionConstants.ENABLE_AUTO_COMMIT)) {
labelMaker(DSActionConstants.ENABLE_AUTO_COMMIT_DISPLAY);
}
// CSV constants
if (configProperty.getName() != null && configProperty.getName().equals(
DSActionConstants.CSV_DATASOURCE_PROPERTY)) {
labelMaker(DSActionConstants.CSV_DATASOURCE_DISPLAY);
}
if (configProperty.getName() != null && configProperty.getName().equals(
DSActionConstants.COLUMN_SEPERATOR_PROPERTY)) {
labelMaker(DSActionConstants.COLUMN_SEPERATOR_DISPLAY);
}
if (configProperty.getName() != null && configProperty.getName().equals(
DSActionConstants.STARTING_ROW_PROPERTY)) {
labelMaker(DSActionConstants.STARTING_ROW_DISPLAY);
}
if (configProperty.getName() != null && configProperty.getName().equals(
DSActionConstants.MAX_ROW_COUNT_PROPERTY)) {
labelMaker(DSActionConstants.MAX_ROW_COUNT_DISPLAY);
}
if (configProperty.getName() != null && configProperty.getName().equals(
DSActionConstants.HAS_HEADER_PROPERTY)) {
labelMaker(DSActionConstants.HAS_HEADER_DISPLAY);
}
//Excel
if(configProperty.getName() != null && configProperty.getName().equals(DSActionConstants.EXCEL_DATASOURCE_PROPERTY)){
labelMaker(DSActionConstants.EXCEL_DATASOURCE_DISPLAY);
}
// JDNI type
if (configProperty.getName() != null && configProperty.getName().equals(
DSActionConstants.JNDI_CONTEXT_PROPERTY)) {
labelMaker(DSActionConstants.JNDI_CONTEXT_DISPLAY);
}
if (configProperty.getName() != null && configProperty.getName().equals(
DSActionConstants.JNDI_PROVIDER_URL_PROPERTY)) {
labelMaker(DSActionConstants.JNDI_PROVIDER_URL_DISPLAY);
}
if (configProperty.getName() != null && configProperty.getName().equals(
DSActionConstants.JNDI_RESOURCE_PROPERTY)) {
labelMaker(DSActionConstants.JNDI_RESOURCE_DISPLAY);
}
if (configProperty.getName() != null && configProperty.getName().equals(
DSActionConstants.JNDI_PASSWORD_PROPERTY)) {
labelMaker(DSActionConstants.JNDI_PASSWORD_DISPLAY);
}
// Gspread
if (configProperty.getName() != null && configProperty.getName().equals(
DSActionConstants.GSPREAD_DATASOURCE_PROPERTY)) {
labelMaker(DSActionConstants.GSPREAD_DATASOURCE_DISPLAY);
}
if (configProperty.getName() != null && configProperty.getName().equals(
DSActionConstants.GSPREAD_VISIBILITY_PROPERTY)) {
labelMaker(DSActionConstants.GSPREAD_VISIBILITY_DISPLAY);
}
if (configProperty.getName() != null && configProperty.getName().equals(
DSActionConstants.GSPREAD_USERNAME_PROPERTY)) {
labelMaker(DSActionConstants.GSPREAD_USERNAME_DISPLAY);
}
if (configProperty.getName() != null && configProperty.getName().equals(
DSActionConstants.GSPREAD_PASSWORD_PROPERTY)) {
labelMaker(DSActionConstants.GSPREAD_PASSWORD_DISPLAY);
}
// Carbon data Source
if (configProperty.getName() != null && configProperty.getName().equals(
DSActionConstants.CARBON_DATASOURCE_NAME_PROPERTY)) {
labelMaker(DSActionConstants.CARBON_DATASOURCE_NAME_DISPLAY);
}
if (configProperty.getName() != null && configProperty.getName().equals(
DSActionConstants.ENABLE_AUTO_COMMIT)) {
sectionUtil.getBooleanComboWithStringPersistance(detailsclient,
toolkit, configProperty, configProperty.getValue(),
DsPackage.eINSTANCE.getConfigurationProperty_Value());
} else {
sectionUtil.getAttributeField(detailsclient, toolkit, configProperty,
configProperty.getValue(),
DsPackage.eINSTANCE.getConfigurationProperty_Value(),
DetailSectionCustomUiConstants.STRING);
}
}
private void queryObjectConfigurator(Query query){
ArrayList<IItemPropertyDescriptor> detailPropertyDescriptors = (ArrayList<IItemPropertyDescriptor>)
adapterFactoryItemDelegator
.getPropertyDescriptors(query);
labelMaker("");
labelMaker("");
StyledText keyColText = null;
Combo rgkCombo = null;
Label keyColLabel = null;
for (Iterator<IItemPropertyDescriptor> i = detailPropertyDescriptors.iterator(); i.hasNext();) {
ItemPropertyDescriptor desc = (ItemPropertyDescriptor) i.next();
String displayName = desc.getDisplayName(query);
if (desc.getFeature(query) instanceof EAttributeImpl) {
if(displayName.equals(DetailSectionCustomUiConstants.QUERY_ID)){
labelMaker(displayName);
sectionUtil.getAttributeField(detailsclient, toolkit, query, query.getId(),
DsPackage.eINSTANCE.getQuery_Id(),DetailSectionCustomUiConstants.STRING);
labelMaker("");
labelMaker("");
}
if(displayName.equals(DetailSectionCustomUiConstants.QUERY_USE_CONFIG) && dataService != null){
EList<DataSourceConfiguration> configList = dataService.getConfig();
DataSourceConfiguration [] confArr = configList.toArray(new DataSourceConfiguration [0]);
String [] displayValues = new String [confArr.length];
for(int j = 0;j< confArr.length ; j++){
displayValues[j] = confArr[j].getId();
}
labelMaker(displayName);
sectionUtil.getCustomComboField(detailsclient, toolkit, query, query.getUseConfig(),
DsPackage.eINSTANCE.getQuery_UseConfig(),displayValues);
labelMaker("");
labelMaker("");
}
if(displayName.equals(DetailSectionCustomUiConstants.QUERY_INPUT_EVENT_TRIGGER) && dataService != null){
EList<EventTrigger> eventList = dataService.getEventTrigger();
EventTrigger [] eventArr = eventList.toArray(new EventTrigger [0]);
String [] displayValues = new String [eventArr.length];
for(int j = 0 ; j < eventArr.length ; j++){
displayValues[j] = eventArr[j].getId();
}
labelMaker(displayName);
sectionUtil.getCustomComboField(detailsclient, toolkit, query, query.getInputEventTrigger(),
DsPackage.eINSTANCE.getQuery_InputEventTrigger(), displayValues);
labelMaker("");
labelMaker("");
}
if(displayName.equals(DetailSectionCustomUiConstants.QUERY_OUTPUT_EVENT_TRIGGER)){
EList<EventTrigger> eventList = dataService.getEventTrigger();
EventTrigger [] eventArr = eventList.toArray(new EventTrigger [0]);
String [] displayValues = new String [eventArr.length];
for(int j = 0 ; j < eventArr.length ; j++){
displayValues[j] = eventArr[j].getId();
}
labelMaker(displayName);
sectionUtil.getCustomComboField(detailsclient, toolkit, query, query.getOutputEventTrigger(),
DsPackage.eINSTANCE.getQuery_OutputEventTrigger(), displayValues);
labelMaker("");
labelMaker("");
}
if(displayName.equals(DetailSectionCustomUiConstants.QUERY_RETURN_GENERATED_KEYS)){
labelMaker(displayName);
rgkCombo = sectionUtil.getBooleanComboField(detailsclient, toolkit, query,
query.isReturnGeneratedKeys(), DsPackage.eINSTANCE.getQuery_ReturnGeneratedKeys());
labelMaker("");
labelMaker("");
}
if(displayName.equals(DetailSectionCustomUiConstants.QUERY_KEY_COLUMNS)){
keyColLabel = labelMaker(displayName);
keyColText = sectionUtil.getAttributeField(detailsclient, toolkit, query, query.getKeyColumns(),
DsPackage.eINSTANCE.getQuery_KeyColumns(), DetailSectionCustomUiConstants.STRING);
if(rgkCombo != null && rgkCombo.getSelectionIndex() == 1){
keyColLabel.setVisible(false);
keyColText.setVisible(false);
}
if(rgkCombo != null && keyColText != null && keyColLabel != null){
addSelectionListnerForRgkCombo(rgkCombo,keyColText,keyColLabel);
}
labelMaker("");
labelMaker("");
}
}
}
}
private void addSelectionListnerForRgkCombo(final Combo rgkCombo,final StyledText keyColText,final Label keyColLabel){
rgkCombo.addListener(SWT.Selection, new Listener() {
@Override
public void handleEvent(Event event) {
if(rgkCombo.getSelectionIndex() == 0){
keyColText.setVisible(true);
keyColLabel.setVisible(true);
}else{
keyColText.setVisible(false);
keyColLabel.setVisible(false);
}
}
});
}
private void queryPropertyObjectConfigurator(QueryProperty queryProperty){
labelMaker("");
labelMaker("");
if(queryProperty.getName() != null && queryProperty.getName().equals(DetailSectionCustomUiConstants.QUERY_TIMEOUT)){
labelMaker(DetailSectionCustomUiConstants.QUERY_TIMEOUT_DISPLAY);
}
if(queryProperty.getName() != null && queryProperty.getName().equals(DetailSectionCustomUiConstants.FETCH_DIRECTION)){
labelMaker(DetailSectionCustomUiConstants.FETCH_DIRECTION_DISPLAY);
}
if(queryProperty.getName() != null && queryProperty.getName().equals(DetailSectionCustomUiConstants.FETCH_SIZE)){
labelMaker(DetailSectionCustomUiConstants.FETCH_SIZE_DISPLAY);
}
if(queryProperty.getName() != null && queryProperty.getName().equals(DetailSectionCustomUiConstants.MAX_FIELD_SIZE)){
labelMaker(DetailSectionCustomUiConstants.MAX_FIELD_SIZE_DISPLAY);
}
if(queryProperty.getName() != null && queryProperty.getName().equals(DetailSectionCustomUiConstants.MAX_ROWS)){
labelMaker(DetailSectionCustomUiConstants.MAX_ROWS_DISPLAY);
}
sectionUtil.getAttributeField(detailsclient, toolkit, queryProperty, queryProperty.getValue(),
DsPackage.eINSTANCE.getQueryProperty_Value(), DetailSectionCustomUiConstants.STRING);
//TODO add other properties as well
}
private void resultObjectConfigurator(ResultMapping result){
ArrayList<IItemPropertyDescriptor> detailPropertyDescriptors = (ArrayList<IItemPropertyDescriptor>)
adapterFactoryItemDelegator
.getPropertyDescriptors(result);
labelMaker("");
labelMaker("");
for (Iterator<IItemPropertyDescriptor> i = detailPropertyDescriptors.iterator(); i.hasNext();) {
ItemPropertyDescriptor desc = (ItemPropertyDescriptor) i.next();
String displayName = desc.getDisplayName(result);
if (desc.getFeature(result) instanceof EAttributeImpl) {
if(displayName.equals(DetailSectionCustomUiConstants.RESULT_GROUPED_BY_ELEMENT)){
labelMaker(DetailSectionCustomUiConstants.RESULT_GROUPED_BY_ELEMENT);
sectionUtil.getAttributeField(detailsclient, toolkit, result, result.getElementName()
,DsPackage.eINSTANCE.getResultMapping_ElementName(),DetailSectionCustomUiConstants.STRING);
labelMaker("");
labelMaker("");
}
if(displayName.equals(DetailSectionCustomUiConstants.RESULT_ROW_NAME)){
labelMaker(DetailSectionCustomUiConstants.RESULT_ROW_NAME);
sectionUtil.getAttributeField(detailsclient, toolkit, result, result.getRowName()
,DsPackage.eINSTANCE.getResultMapping_RowName(),DetailSectionCustomUiConstants.STRING);
labelMaker("");
labelMaker("");
}
if(displayName.equals(DetailSectionCustomUiConstants.RESULT_ROW_NAMESPACE)){
labelMaker(DetailSectionCustomUiConstants.RESULT_ROW_NAMESPACE);
sectionUtil.getAttributeField(detailsclient, toolkit, result, result.getDefaultNamespace(),
DsPackage.eINSTANCE.getResultMapping_DefaultNamespace(), DetailSectionCustomUiConstants.STRING);
labelMaker("");
labelMaker("");
}
if(displayName.equals(DetailSectionCustomUiConstants.RESULT_XSLT_PATH)){
//TODO implement or re-use existing XSLT path confgurator.
}
if(displayName.equals(DetailSectionCustomUiConstants.RESULT_USE_COLUMN_NUMBERS)){
labelMaker(DetailSectionCustomUiConstants.RESULT_USE_COLUMN_NUMBERS);
sectionUtil.getBooleanComboField(detailsclient, toolkit, result, result.isUseColumnNumbers(),
DsPackage.eINSTANCE.getResultMapping_UseColumnNumbers());
labelMaker("");
labelMaker("");
}
}
}
}
private void elementMappingObjectConfigurator(ElementMapping element){
ArrayList<IItemPropertyDescriptor> detailPropertyDescriptors = (ArrayList<IItemPropertyDescriptor>)
adapterFactoryItemDelegator
.getPropertyDescriptors(element);
labelMaker("");
labelMaker("");
for (Iterator<IItemPropertyDescriptor> i = detailPropertyDescriptors.iterator(); i.hasNext();) {
ItemPropertyDescriptor desc = (ItemPropertyDescriptor) i.next();
String displayName = desc.getDisplayName(element);
if(displayName.equals(DetailSectionCustomUiConstants.ELEMENT_MAPPING_OUTPUT_FIELD)){
labelMaker(DetailSectionCustomUiConstants.ELEMENT_MAPPING_OUTPUT_FIELD);
sectionUtil.getAttributeField(detailsclient, toolkit, element, element.getName()
,DsPackage.eINSTANCE.getElementMapping_Name(), DetailSectionCustomUiConstants.STRING);
labelMaker("");
labelMaker("");
}
if(displayName.equals(DetailSectionCustomUiConstants.ELEMENT_MAPPING_COLUMN_NAME)){
//Fixed TOOLS-1012.
String labelString = DetailSectionCustomUiConstants.ELEMENT_MAPPING_COLUMN_NAME;
if(element != null){
Object result = editingDomain.getParent(element);
if(result != null && editingDomain.getParent(element) instanceof ResultMapping){
ResultMapping resultMapping = (ResultMapping)result;
if(resultMapping.isUseColumnNumbers()){
labelString = DetailSectionCustomUiConstants.ELEMENT_MAPPING_COLUMN_NUMBUR;
}
}
}
labelMaker(labelString);
sectionUtil.getAttributeField(detailsclient, toolkit, element, element.getColumn()
,DsPackage.eINSTANCE.getElementMapping_Column(),DetailSectionCustomUiConstants.STRING);
labelMaker("");
labelMaker("");
}
if(displayName.equals(DetailSectionCustomUiConstants.ELEMENT_MAPPING_EXPORT)){
labelMaker(DetailSectionCustomUiConstants.ELEMENT_MAPPING_EXPORT);
sectionUtil.getAttributeField(detailsclient, toolkit, element, element.getExport(),
DsPackage.eINSTANCE.getElementMapping_Export(), DetailSectionCustomUiConstants.STRING);
labelMaker("");
labelMaker("");
}
if(displayName.equals(DetailSectionCustomUiConstants.ELEMENT_MAPPING_EXPORT_TYPE)){
labelMaker(DetailSectionCustomUiConstants.ELEMENT_MAPPING_EXPORT_TYPE);
String [] displayValues = {"ARRAY","SCALAR"};
sectionUtil.getCustomComboField(detailsclient, toolkit, element, element.getExportType(),
DsPackage.eINSTANCE.getElementMapping_ExportType(), displayValues);
labelMaker("");
labelMaker("");
}
if(displayName.equals(DetailSectionCustomUiConstants.ELEMENT_MAPPING_SCHEMA_TYPE)){
String [] displayValues = {"xs:string","xs:integer","xs:boolean",
"xs:float","xs:double","xs:decimal",
"xs:dateTime","xs:time","xs:date",
"xs:long","xs:base64Binary"};
labelMaker(DetailSectionCustomUiConstants.ELEMENT_MAPPING_SCHEMA_TYPE);
sectionUtil.getCustomComboField(detailsclient, toolkit, element, element.getXsdType(),
DsPackage.eINSTANCE.getElementMapping_XsdType(),displayValues);
labelMaker("");
labelMaker("");
}
if(displayName.equals(DetailSectionCustomUiConstants.ELEMENT_MAPING_ALLOWED_USER_ROLES)){
labelMaker(DetailSectionCustomUiConstants.ELEMENT_MAPING_ALLOWED_USER_ROLES);
sectionUtil.getAttributeField(detailsclient, toolkit, element, element.getRequiredRoles(),
DsPackage.eINSTANCE.getElementMapping_RequiredRoles(), DetailSectionCustomUiConstants.STRING);
labelMaker("");
labelMaker("");
}
if(displayName.equals(DetailSectionCustomUiConstants.ELEMENT_MAPPING_NAMESPACE)){
labelMaker(DetailSectionCustomUiConstants.ELEMENT_MAPPING_NAMESPACE);
sectionUtil.getAttributeField(detailsclient, toolkit, element, element.getNamespace(),
DsPackage.eINSTANCE.getElementMapping_Namespace(), DetailSectionCustomUiConstants.STRING);
labelMaker("");
labelMaker("");
}
}
}
private void attributeMappingObjectConfiguretor(AttributeMapping attributeMapping){
ArrayList<IItemPropertyDescriptor> detailPropertyDescriptors = (ArrayList<IItemPropertyDescriptor>)
adapterFactoryItemDelegator
.getPropertyDescriptors(attributeMapping);
labelMaker("");
labelMaker("");
for (Iterator<IItemPropertyDescriptor> i = detailPropertyDescriptors.iterator(); i.hasNext();) {
ItemPropertyDescriptor desc = (ItemPropertyDescriptor) i.next();
String displayName = desc.getDisplayName(attributeMapping);
if(displayName.equals(DetailSectionCustomUiConstants.ELEMENT_MAPPING_OUTPUT_FIELD)){
labelMaker(DetailSectionCustomUiConstants.ELEMENT_MAPPING_OUTPUT_FIELD);
sectionUtil.getAttributeField(detailsclient, toolkit, attributeMapping, attributeMapping.getName()
,DsPackage.eINSTANCE.getAttributeMapping_Name(), DetailSectionCustomUiConstants.STRING);
labelMaker("");
labelMaker("");
}
if(displayName.equals(DetailSectionCustomUiConstants.ELEMENT_MAPPING_COLUMN_NAME)){
//Fixed TOOLS-1012.
String labelString = DetailSectionCustomUiConstants.ELEMENT_MAPPING_COLUMN_NAME;
if(attributeMapping != null){
Object result = editingDomain.getParent(attributeMapping);
if(result != null && editingDomain.getParent(attributeMapping) instanceof ResultMapping){
ResultMapping resultMapping = (ResultMapping)result;
if(resultMapping.isUseColumnNumbers()){
labelString = DetailSectionCustomUiConstants.ELEMENT_MAPPING_COLUMN_NUMBUR;
}
}
}
labelMaker(labelString);
sectionUtil.getAttributeField(detailsclient, toolkit, attributeMapping, attributeMapping.getColumn()
,DsPackage.eINSTANCE.getAttributeMapping_Column(),DetailSectionCustomUiConstants.STRING);
labelMaker("");
labelMaker("");
}
if(displayName.equals(DetailSectionCustomUiConstants.ELEMENT_MAPPING_SCHEMA_TYPE)){
String [] displayValues = {"xs:string","xs:integer","xs:boolean",
"xs:float","xs:double","xs:decimal",
"xs:dateTime","xs:time","xs:date",
"xs:long","xs:base64Binary"};
labelMaker(DetailSectionCustomUiConstants.ELEMENT_MAPPING_SCHEMA_TYPE);
sectionUtil.getCustomComboField(detailsclient, toolkit, attributeMapping, attributeMapping.getXsdType(),
DsPackage.eINSTANCE.getAttributeMapping_XsdType(), displayValues);
labelMaker("");
labelMaker("");
}
if(displayName.equals(DetailSectionCustomUiConstants.ELEMENT_MAPING_ALLOWED_USER_ROLES)){
labelMaker(DetailSectionCustomUiConstants.ELEMENT_MAPING_ALLOWED_USER_ROLES);
sectionUtil.getAttributeField(detailsclient, toolkit, attributeMapping, attributeMapping.getRequiredRoles(),
DsPackage.eINSTANCE.getAttributeMapping_RequiredRoles(), DetailSectionCustomUiConstants.STRING);
labelMaker("");
labelMaker("");
}
}
}
private void queryParamObjectConfigurator(QueryParameter queryParam){
ArrayList<IItemPropertyDescriptor> detailPropertyDescriptors = (ArrayList<IItemPropertyDescriptor>)
adapterFactoryItemDelegator
.getPropertyDescriptors(queryParam);
labelMaker("");
labelMaker("");
for (Iterator<IItemPropertyDescriptor> i = detailPropertyDescriptors.iterator(); i.hasNext();) {
ItemPropertyDescriptor desc = (ItemPropertyDescriptor) i.next();
String displayName = desc.getDisplayName(queryParam);
if(displayName.equals(DetailSectionCustomUiConstants.QUERY_PARAM_DEFAULT_VAL)){
labelMaker(DetailSectionCustomUiConstants.QUERY_PARAM_DEFAULT_VAL);
sectionUtil.getAttributeField(detailsclient, toolkit, queryParam, queryParam.getDefaultValue(),
DsPackage.eINSTANCE.getQueryParameter_DefaultValue(), DetailSectionCustomUiConstants.STRING);
labelMaker("");
labelMaker("");
}
if(displayName.equals(DetailSectionCustomUiConstants.QUERY_PARAM_MAPPING_NAME)){
labelMaker(DetailSectionCustomUiConstants.QUERY_PARAM_MAPPING_NAME);
sectionUtil.getAttributeField(detailsclient, toolkit, queryParam, queryParam.getName(),
DsPackage.eINSTANCE.getQueryParameter_Name(), DetailSectionCustomUiConstants.STRING);
labelMaker("");
labelMaker("");
}
if(displayName.equals(DetailSectionCustomUiConstants.QUERY_PARAM_ORDINAL)){
labelMaker(DetailSectionCustomUiConstants.QUERY_PARAM_ORDINAL);
String ordinal = new Integer(queryParam.getOrdinal()).toString();
sectionUtil.getAttributeField(detailsclient, toolkit, queryParam,ordinal ,
DsPackage.eINSTANCE.getQueryParameter_Ordinal(), DetailSectionCustomUiConstants.INTEGER);
labelMaker("");
labelMaker("");
}
if(displayName.equals(DetailSectionCustomUiConstants.QUERY_PARAM_TYPE)){
labelMaker(DetailSectionCustomUiConstants.QUERY_PARAM_TYPE);
String [] displayValues = {"SCALAR","ARRAY"};
- sectionUtil.getCustomComboField(detailsclient, toolkit,queryParam, queryParam.getParamType(),
+ Combo paramTypeCombo = sectionUtil.getCustomComboField(detailsclient, toolkit,queryParam, queryParam.getParamType(),
DsPackage.eINSTANCE.getQueryParameter_ParamType(),displayValues);
+ paramTypeCombo.select(0);
labelMaker("");
labelMaker("");
}
if(displayName.equals(DetailSectionCustomUiConstants.QUERY_PARAM_SQL_TYPE)){
+ String [] displayValues = {"STRING","INTEGER","REAL"
+ ,"DOUBLE","NUMERIC","TINYINT",
+ "SMALLINT","BIGINT","DATE",
+ "TIME","TIMESTAMP",
+ "BIT","ORACLE_REF_CURSOR",
+ "BINARY"};
labelMaker(DetailSectionCustomUiConstants.QUERY_PARAM_SQL_TYPE);
- sectionUtil.getAttributeField(detailsclient, toolkit, queryParam, queryParam.getSqlType(),
- DsPackage.eINSTANCE.getQueryParameter_SqlType(), DetailSectionCustomUiConstants.STRING);
+ Combo sqlTypeCombo = sectionUtil.getCustomComboField(detailsclient, toolkit, queryParam, queryParam.getSqlType(),
+ DsPackage.eINSTANCE.getQueryParameter_SqlType(), displayValues);
+ sqlTypeCombo.select(0);
labelMaker("");
labelMaker("");
}
if(displayName.equals(DetailSectionCustomUiConstants.QUERY_PARAM_STRUCT_TYPE)){
labelMaker(DetailSectionCustomUiConstants.QUERY_PARAM_STRUCT_TYPE);
sectionUtil.getAttributeField(detailsclient, toolkit, queryParam, queryParam.getStructType(),
DsPackage.eINSTANCE.getQueryParameter_StructType(),DetailSectionCustomUiConstants.STRING);
labelMaker("");
labelMaker("");
}
if(displayName.equals(DetailSectionCustomUiConstants.QUERY_PARAM_IN_OUT)){
String [] displayValues = {"IN","OUT"};
labelMaker(DetailSectionCustomUiConstants.QUERY_PARAM_IN_OUT);
String intialValue = queryParam.getType();
sectionUtil.getCustomComboField(detailsclient, toolkit, queryParam,intialValue,
DsPackage.eINSTANCE.getQueryParameter_Type(),displayValues );
labelMaker("");
labelMaker("");
}
}
}
private void validatorObjectConfigurator(Object validatorObject,String type){
ArrayList<IItemPropertyDescriptor> detailPropertyDescriptors = (ArrayList<IItemPropertyDescriptor>)
adapterFactoryItemDelegator
.getPropertyDescriptors(validatorObject);
labelMaker("");
labelMaker("");
if(validatorObject instanceof LongRangeValidator && type.equals(DetailSectionCustomUiConstants.LONG)){
LongRangeValidator lval = (LongRangeValidator)validatorObject;
for (Iterator<IItemPropertyDescriptor> i = detailPropertyDescriptors.iterator(); i.hasNext();) {
ItemPropertyDescriptor desc = (ItemPropertyDescriptor) i.next();
String displayName = desc.getDisplayName(validatorObject);
if(displayName.equals(DetailSectionCustomUiConstants.VALIDATOR_MAXIMUM)){
String initVal = new Long(lval.getMaximum()).toString();
labelMaker(DetailSectionCustomUiConstants.VALIDATOR_MAXIMUM);
sectionUtil.getAttributeField(detailsclient, toolkit, lval,initVal ,
DsPackage.eINSTANCE.getLongRangeValidator_Maximum(),DetailSectionCustomUiConstants.LONG );
labelMaker("");
labelMaker("");
}
if(displayName.equals(DetailSectionCustomUiConstants.VALIDATOR_MINIMUM)){
String initVal = new Long(lval.getMinimum()).toString();
labelMaker(DetailSectionCustomUiConstants.VALIDATOR_MINIMUM);
sectionUtil.getAttributeField(detailsclient, toolkit, lval, initVal,
DsPackage.eINSTANCE.getLongRangeValidator_Minimum(), DetailSectionCustomUiConstants.LONG);
labelMaker("");
labelMaker("");
}
}
}else if(validatorObject instanceof DoubleRangeValidator && type.equals(DetailSectionCustomUiConstants.DOUBLE)){
DoubleRangeValidator dval = (DoubleRangeValidator)validatorObject;
for (Iterator<IItemPropertyDescriptor> i = detailPropertyDescriptors.iterator(); i.hasNext();) {
ItemPropertyDescriptor desc = (ItemPropertyDescriptor) i.next();
String displayName = desc.getDisplayName(validatorObject);
if(displayName.equals(DetailSectionCustomUiConstants.VALIDATOR_MAXIMUM)){
String initVal = new Double(dval.getMaximum()).toString();
labelMaker(DetailSectionCustomUiConstants.VALIDATOR_MAXIMUM);
sectionUtil.getAttributeField(detailsclient, toolkit, dval,initVal ,
DsPackage.eINSTANCE.getDoubleRangeValidator_Maximum(),DetailSectionCustomUiConstants.DOUBLE );
labelMaker("");
labelMaker("");
}
if(displayName.equals(DetailSectionCustomUiConstants.VALIDATOR_MINIMUM)){
String initVal = new Double(dval.getMinimum()).toString();
labelMaker(DetailSectionCustomUiConstants.VALIDATOR_MINIMUM);
sectionUtil.getAttributeField(detailsclient, toolkit, dval, initVal,
DsPackage.eINSTANCE.getDoubleRangeValidator_Minimum(), DetailSectionCustomUiConstants.DOUBLE);
labelMaker("");
labelMaker("");
}
}
}else if(validatorObject instanceof LengthValidator && type.equals(DetailSectionCustomUiConstants.LONG)){
LengthValidator lval = (LengthValidator)validatorObject;
for (Iterator<IItemPropertyDescriptor> i = detailPropertyDescriptors.iterator(); i.hasNext();) {
ItemPropertyDescriptor desc = (ItemPropertyDescriptor) i.next();
String displayName = desc.getDisplayName(validatorObject);
if(displayName.equals(DetailSectionCustomUiConstants.VALIDATOR_MAXIMUM)){
String initVal = new Long(lval.getMaximum()).toString();
labelMaker(DetailSectionCustomUiConstants.VALIDATOR_MAXIMUM);
sectionUtil.getAttributeField(detailsclient, toolkit, lval,initVal ,
DsPackage.eINSTANCE.getLengthValidator_Maximum(),DetailSectionCustomUiConstants.LONG );
labelMaker("");
labelMaker("");
}
if(displayName.equals(DetailSectionCustomUiConstants.VALIDATOR_MINIMUM)){
String initVal = new Long(lval.getMinimum()).toString();
labelMaker(DetailSectionCustomUiConstants.VALIDATOR_MINIMUM);
sectionUtil.getAttributeField(detailsclient, toolkit, lval, initVal,
DsPackage.eINSTANCE.getLengthValidator_Minimum(), DetailSectionCustomUiConstants.LONG);
labelMaker("");
labelMaker("");
}
}
}
}
private void eventTriggerObejecConfigurator(EventTrigger eventTrigger){
ArrayList<IItemPropertyDescriptor> detailPropertyDescriptors = (ArrayList<IItemPropertyDescriptor>)
adapterFactoryItemDelegator
.getPropertyDescriptors(eventTrigger);
labelMaker("");
labelMaker("");
for (Iterator<IItemPropertyDescriptor> i = detailPropertyDescriptors.iterator(); i.hasNext();) {
ItemPropertyDescriptor desc = (ItemPropertyDescriptor) i.next();
String displayName = desc.getDisplayName(eventTrigger);
if (desc.getFeature(eventTrigger) instanceof EAttributeImpl) {
if(displayName.equals(DetailSectionCustomUiConstants.EVENT_TRIGGER_ID)){
labelMaker(DetailSectionCustomUiConstants.EVENT_TRIGGER_ID);
sectionUtil.getAttributeField(detailsclient, toolkit, eventTrigger, eventTrigger.getId(),
DsPackage.eINSTANCE.getEventTrigger_Id(),DetailSectionCustomUiConstants.STRING);
labelMaker("");
labelMaker("");
}
if(displayName.equals(DetailSectionCustomUiConstants.EVENT_TRIGGER_LANGUAGE)){
labelMaker(DetailSectionCustomUiConstants.EVENT_TRIGGER_LANGUAGE);
sectionUtil.getAttributeField(detailsclient, toolkit, eventTrigger, eventTrigger.getLanguage(),
DsPackage.eINSTANCE.getEventTrigger_Language(),DetailSectionCustomUiConstants.STRING);
}
}
}
}
private void operationObjectConfigurator(Operation operation){
ArrayList<IItemPropertyDescriptor> detailPropertyDescriptors = (ArrayList<IItemPropertyDescriptor>)
adapterFactoryItemDelegator
.getPropertyDescriptors(operation);
labelMaker("");
labelMaker("");
for (Iterator<IItemPropertyDescriptor> i = detailPropertyDescriptors.iterator(); i.hasNext();) {
ItemPropertyDescriptor desc = (ItemPropertyDescriptor) i.next();
String displayName = desc.getDisplayName(operation);
if (desc.getFeature(operation) instanceof EAttributeImpl) {
if(displayName.equals(DetailSectionCustomUiConstants.OPERATION_NAME)){
labelMaker(DetailSectionCustomUiConstants.OPERATION_NAME);
sectionUtil.getAttributeField(detailsclient, toolkit, operation, operation.getName(),
DsPackage.eINSTANCE.getOperation_Name(),DetailSectionCustomUiConstants.STRING);
labelMaker("");
labelMaker("");
}
if(displayName.equals(DetailSectionCustomUiConstants.OPERATION_DISABLE_STREAMING)){
labelMaker(DetailSectionCustomUiConstants.OPERATION_DISABLE_STREAMING);
sectionUtil.getBooleanComboField(detailsclient, toolkit, operation,operation.isDisableStreaming() ,
DsPackage.eINSTANCE.getOperation_DisableStreaming());
labelMaker("");
labelMaker("");
}
if(displayName.equals(DetailSectionCustomUiConstants.OPERATION_RETURN_REQUEST_STATUS)){
labelMaker(DetailSectionCustomUiConstants.OPERATION_RETURN_REQUEST_STATUS);
sectionUtil.getBooleanComboField(detailsclient, toolkit, operation, operation.isReturnRequestStatus(),
DsPackage.eINSTANCE.getOperation_ReturnRequestStatus());
}
}
}
}
private void paramMapObjectConfigurator(ParameterMapping paramMapping){
ArrayList<IItemPropertyDescriptor> detailPropertyDescriptors = (ArrayList<IItemPropertyDescriptor>)
adapterFactoryItemDelegator
.getPropertyDescriptors(paramMapping);
labelMaker("");
labelMaker("");
for (Iterator<IItemPropertyDescriptor> i = detailPropertyDescriptors.iterator(); i.hasNext();) {
ItemPropertyDescriptor desc = (ItemPropertyDescriptor) i.next();
String displayName = desc.getDisplayName(paramMapping);
if (desc.getFeature(paramMapping) instanceof EAttributeImpl) {
if(displayName.equals(DetailSectionCustomUiConstants.PARAM_MAPPING_PARAM_NAME)){
labelMaker(DetailSectionCustomUiConstants.PARAM_MAPPING_PARAM_NAME);
sectionUtil.getAttributeField(detailsclient, toolkit, paramMapping, paramMapping.getName(),
DsPackage.eINSTANCE.getParameterMapping_Name(),DetailSectionCustomUiConstants.STRING);
labelMaker("");
labelMaker("");
}
if(displayName.equals(DetailSectionCustomUiConstants.PARAM_MAPPING_PARAM)){
labelMaker(DetailSectionCustomUiConstants.PARAM_MAPPING_PARAM);
sectionUtil.getAttributeField(detailsclient, toolkit, paramMapping, paramMapping.getQueryParam(),
DsPackage.eINSTANCE.getParameterMapping_QueryParam(),DetailSectionCustomUiConstants.STRING);
labelMaker("");
labelMaker("");
}
if(displayName.equals(DetailSectionCustomUiConstants.PARAM_MAPPING_COLUMN)){
labelMaker(DetailSectionCustomUiConstants.PARAM_MAPPING_COLUMN);
sectionUtil.getAttributeField(detailsclient, toolkit, paramMapping, paramMapping.getColumn(),
DsPackage.eINSTANCE.getParameterMapping_Column(),DetailSectionCustomUiConstants.STRING);
labelMaker("");
labelMaker("");
}
}
}
}
private void resourceObjectConfigurator(Resource resource){
ArrayList<IItemPropertyDescriptor> detailPropertyDescriptors = (ArrayList<IItemPropertyDescriptor>)
adapterFactoryItemDelegator
.getPropertyDescriptors(resource);
labelMaker("");
labelMaker("");
for (Iterator<IItemPropertyDescriptor> i = detailPropertyDescriptors.iterator(); i.hasNext();) {
ItemPropertyDescriptor desc = (ItemPropertyDescriptor) i.next();
String displayName = desc.getDisplayName(resource);
if (desc.getFeature(resource) instanceof EAttributeImpl) {
if(displayName.equals(DetailSectionCustomUiConstants.RESOUCE_PATH)){
labelMaker(DetailSectionCustomUiConstants.RESOUCE_PATH);
sectionUtil.getAttributeField(detailsclient, toolkit, resource, resource.getPath(),
DsPackage.eINSTANCE.getResource_Path(),DetailSectionCustomUiConstants.STRING);
labelMaker("");
labelMaker("");
}
if(displayName.equals(DetailSectionCustomUiConstants.RESOURCE_METHOD)){
String [] displayValues = {"GET","PUT","POST","DELETE"};
labelMaker(DetailSectionCustomUiConstants.RESOURCE_METHOD);
sectionUtil.getCustomComboField(detailsclient, toolkit, resource, resource.getMethod(),
DsPackage.eINSTANCE.getResource_Method(),displayValues );
labelMaker("");
labelMaker("");
}
/*if(displayName.equals(DetailSectionCustomUiConstants.RESOURCE_RETURN_REQUEST_STATUS)){
labelMaker(DetailSectionCustomUiConstants.RESOURCE_RETURN_REQUEST_STATUS);
sectionUtil.getBooleanComboField(detailsclient, toolkit, resource, resource.isReturnRequestStatus(),
DsPackage.eINSTANCE.getResource_ReturnRequestStatus());
}*/
}
}
}
}
| false | false | null | null |
diff --git a/src/net/java/sip/communicator/plugin/branding/AboutWindow.java b/src/net/java/sip/communicator/plugin/branding/AboutWindow.java
index 3902bf674..3a183d588 100644
--- a/src/net/java/sip/communicator/plugin/branding/AboutWindow.java
+++ b/src/net/java/sip/communicator/plugin/branding/AboutWindow.java
@@ -1,414 +1,433 @@
/*
* SIP Communicator, the OpenSource Java VoIP and Instant Messaging client.
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package net.java.sip.communicator.plugin.branding;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.imageio.*;
import javax.swing.*;
import javax.swing.event.*;
import net.java.sip.communicator.service.browserlauncher.*;
import net.java.sip.communicator.service.gui.*;
import net.java.sip.communicator.service.resources.*;
import net.java.sip.communicator.util.*;
import net.java.sip.communicator.util.skin.*;
import net.java.sip.communicator.util.swing.*;
import net.java.sip.communicator.util.swing.plaf.*;
import org.osgi.framework.*;
/**
* The <tt>AboutWindow</tt> is containing information about the application
* name, version, license etc..
*
* @author Yana Stamcheva
* @author Adam Netocny
+ * @author Lyubomir Marinov
*/
public class AboutWindow
extends JDialog
implements HyperlinkListener,
ActionListener,
ExportedWindow,
Skinnable
{
/**
* The global/shared <code>AboutWindow</code> currently showing.
*/
private static AboutWindow aboutWindow;
private final SIPCommTextFieldUI textFieldUI;
/**
* Shows a <code>AboutWindow</code> creating it first if necessary. The
* shown instance is shared in order to prevent displaying multiple
* instances of one and the same <code>AboutWindow</code>.
*/
public static void showAboutWindow()
{
if (aboutWindow == null)
{
aboutWindow = new AboutWindow(null);
/*
* When the global/shared AboutWindow closes, don't keep a reference
* to it and let it be garbage-collected.
*/
aboutWindow.addWindowListener(new WindowAdapter()
{
+ @Override
public void windowClosed(WindowEvent e)
{
if (aboutWindow == e.getWindow())
aboutWindow = null;
}
});
}
aboutWindow.setVisible(true);
}
private static final int DEFAULT_TEXT_INDENT
= BrandingActivator.getResources()
.getSettingsInt("plugin.branding.ABOUT_TEXT_INDENT");
/**
* Creates an <tt>AboutWindow</tt> by specifying the parent frame owner.
* @param owner the parent owner
*/
public AboutWindow(Frame owner)
{
super(owner);
ResourceManagementService resources = BrandingActivator.getResources();
String applicationName
= resources.getSettingsString("service.gui.APPLICATION_NAME");
this.setTitle(
resources.getI18NString("plugin.branding.ABOUT_WINDOW_TITLE",
new String[]{applicationName}));
setModal(false);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
JPanel mainPanel = new WindowBackground();
mainPanel.setLayout(new BorderLayout());
JPanel textPanel = new JPanel();
textPanel.setPreferredSize(new Dimension(470, 280));
textPanel.setLayout(new BoxLayout(textPanel, BoxLayout.Y_AXIS));
textPanel.setBorder(BorderFactory
.createEmptyBorder(15, 15, 15, 15));
textPanel.setOpaque(false);
JLabel titleLabel = null;
if (isApplicationNameShown())
{
titleLabel = new JLabel(applicationName);
titleLabel.setFont(titleLabel.getFont().deriveFont(Font.BOLD, 28));
titleLabel.setForeground(Constants.TITLE_COLOR);
titleLabel.setAlignmentX(Component.RIGHT_ALIGNMENT);
}
JTextField versionLabel
= new JTextField(" "
+ System.getProperty("sip-communicator.version"));
// Force the use of the custom text field UI in order to fix an
// incorrect rendering on Ubuntu.
textFieldUI = new SIPCommTextFieldUI();
versionLabel.setUI(textFieldUI);
versionLabel.setBorder(null);
versionLabel.setOpaque(false);
versionLabel.setEditable(false);
versionLabel.setFont(versionLabel.getFont().deriveFont(Font.BOLD, 18));
versionLabel.setForeground(Constants.TITLE_COLOR);
versionLabel.setAlignmentX(Component.RIGHT_ALIGNMENT);
versionLabel.setHorizontalAlignment(JTextField.RIGHT);
int logoAreaFontSize
= resources.getSettingsInt("plugin.branding.ABOUT_LOGO_FONT_SIZE");
// FIXME: the message exceeds the window length
JTextArea logoArea =
new JTextArea(resources.getI18NString(
"plugin.branding.LOGO_MESSAGE"));
logoArea.setFont(
logoArea.getFont().deriveFont(Font.BOLD, logoAreaFontSize));
logoArea.setForeground(Constants.TITLE_COLOR);
logoArea.setOpaque(false);
logoArea.setLineWrap(true);
logoArea.setWrapStyleWord(true);
logoArea.setEditable(false);
logoArea.setPreferredSize(new Dimension(100, 20));
logoArea.setAlignmentX(Component.RIGHT_ALIGNMENT);
logoArea.setBorder(BorderFactory
.createEmptyBorder(30, DEFAULT_TEXT_INDENT, 0, 0));
StyledHTMLEditorPane rightsArea = new StyledHTMLEditorPane();
rightsArea.setContentType("text/html");
rightsArea.appendToEnd(resources.getI18NString(
"plugin.branding.COPYRIGHT",
new String[]
{ Constants.TEXT_COLOR }));
rightsArea.setPreferredSize(new Dimension(50, 20));
rightsArea
.setBorder(BorderFactory
.createEmptyBorder(0, DEFAULT_TEXT_INDENT, 0, 0));
rightsArea.setOpaque(false);
rightsArea.setEditable(false);
rightsArea.setAlignmentX(Component.RIGHT_ALIGNMENT);
rightsArea.addHyperlinkListener(this);
StyledHTMLEditorPane licenseArea = new StyledHTMLEditorPane();
licenseArea.setContentType("text/html");
licenseArea.appendToEnd(resources.
getI18NString("plugin.branding.LICENSE",
new String[]{Constants.TEXT_COLOR}));
licenseArea.setPreferredSize(new Dimension(50, 20));
licenseArea.setBorder(
BorderFactory.createEmptyBorder(
resources.getSettingsInt("plugin.branding.ABOUT_PARAGRAPH_GAP"),
DEFAULT_TEXT_INDENT,
0, 0));
licenseArea.setOpaque(false);
licenseArea.setEditable(false);
licenseArea.setAlignmentX(Component.RIGHT_ALIGNMENT);
licenseArea.addHyperlinkListener(this);
if (titleLabel != null)
textPanel.add(titleLabel);
textPanel.add(versionLabel);
textPanel.add(logoArea);
textPanel.add(rightsArea);
textPanel.add(licenseArea);
JButton okButton
= new JButton(resources.getI18NString("service.gui.OK"));
this.getRootPane().setDefaultButton(okButton);
okButton.setMnemonic(resources.getI18nMnemonic("service.gui.OK"));
okButton.addActionListener(this);
JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
buttonPanel.add(okButton);
buttonPanel.setOpaque(false);
mainPanel.add(textPanel, BorderLayout.CENTER);
mainPanel.add(buttonPanel, BorderLayout.SOUTH);
this.getContentPane().add(mainPanel);
this.pack();
this.setResizable(false);
setLocationRelativeTo(getParent());
this.getRootPane().getActionMap().put("close", new CloseAction());
InputMap imap = this.getRootPane().getInputMap(
JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
imap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), "close");
if(OSUtils.IS_MAC)
{
imap.put(
KeyStroke.getKeyStroke(KeyEvent.VK_W, InputEvent.META_DOWN_MASK),
"close");
imap.put(
KeyStroke.getKeyStroke(KeyEvent.VK_W, InputEvent.CTRL_DOWN_MASK),
"close");
}
GuiUtils.addWindow(this);
}
/**
* Reloads text field UI.
*/
public void loadSkin()
{
textFieldUI.loadSkin();
}
/**
* Constructs the window background in order to have a background image.
*/
private static class WindowBackground
extends JPanel
implements Skinnable
{
- private final Logger logger =
- Logger.getLogger(WindowBackground.class.getName());
+ private static final Logger logger
+ = Logger.getLogger(WindowBackground.class);
private Image bgImage = null;
public WindowBackground()
{
loadSkin();
}
/**
* Reloads resources for this component.
*/
public void loadSkin()
{
try
{
bgImage = ImageIO.read(BrandingActivator.getResources().
getImageURL("plugin.branding.ABOUT_WINDOW_BACKGROUND"));
this.setPreferredSize(new Dimension(bgImage.getWidth(this),
bgImage.getHeight(this)));
}
catch (IOException e)
{
logger.error("Error cannot obtain background image", e);
bgImage = null;
}
}
+ @Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
g = g.create();
try
{
AntialiasingManager.activateAntialiasing(g);
- g.drawImage(bgImage, 0, 0, null);
+ int bgImageWidth = bgImage.getWidth(null);
+ int bgImageHeight = bgImage.getHeight(null);
+ boolean bgImageHasBeenDrawn = false;
+
+ if ((bgImageWidth != -1) && (bgImageHeight != -1))
+ {
+ int width = getWidth();
+ int height = getHeight();
+
+ if ((bgImageWidth < width) || (bgImageHeight < height))
+ {
+ g.drawImage(bgImage, 0, 0, width, height, null);
+ bgImageHasBeenDrawn = true;
+ }
+ }
+
+ if (!bgImageHasBeenDrawn)
+ g.drawImage(bgImage, 0, 0, null);
}
finally
{
g.dispose();
}
}
}
/**
* Opens a browser when the link has been activated (clicked).
* @param e the <tt>HyperlinkEvent</tt> that notified us
*/
public void hyperlinkUpdate(HyperlinkEvent e)
{
if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED)
{
String href = e.getDescription();
ServiceReference serviceReference = BrandingActivator
.getBundleContext().getServiceReference(
BrowserLauncherService.class.getName());
if (serviceReference != null)
{
BrowserLauncherService browserLauncherService
= (BrowserLauncherService) BrandingActivator
.getBundleContext().getService(serviceReference);
browserLauncherService.openURL(href);
-
}
}
}
/**
* Indicates that the ok button has been pressed. Closes the window.
* @param e the <tt>ActionEvent</tt> that notified us
*/
public void actionPerformed(ActionEvent e)
{
setVisible(false);
dispose();
}
/**
* Implements the <tt>ExportedWindow.getIdentifier()</tt> method.
* @return the identifier of this exported window
*/
public WindowID getIdentifier()
{
return ExportedWindow.ABOUT_WINDOW;
}
/**
* This dialog could not be minimized.
*/
public void minimize()
{
}
/**
* This dialog could not be maximized.
*/
public void maximize()
{
}
/**
* Implements the <tt>ExportedWindow.bringToFront()</tt> method. Brings
* this window to front.
*/
public void bringToFront()
{
this.toFront();
}
/**
* The source of the window
* @return the source of the window
*/
public Object getSource()
{
return this;
}
/**
* Implementation of {@link ExportedWindow#setParams(Object[])}.
*/
public void setParams(Object[] windowParams) {}
/**
* The action invoked when user presses Escape key.
*/
private class CloseAction extends UIAction
{
public void actionPerformed(ActionEvent e)
{
setVisible(false);
dispose();
}
}
/**
* Indicates if the application name should be shown.
*
* @return <tt>true</tt> if the application name should be shown,
* <tt>false</tt> - otherwise
*/
private boolean isApplicationNameShown()
{
String showApplicationNameProp
= BrandingActivator.getResources().getSettingsString(
"plugin.branding.IS_APPLICATION_NAME_SHOWN");
if (showApplicationNameProp != null
&& showApplicationNameProp.length() > 0)
{
- return new Boolean(showApplicationNameProp).booleanValue();
+ return Boolean.parseBoolean(showApplicationNameProp);
}
return true;
}
}
| false | false | null | null |
diff --git a/src/main/java/net/cubespace/RegionShop/Core/Sell.java b/src/main/java/net/cubespace/RegionShop/Core/Sell.java
index fc818b0..4c1c218 100644
--- a/src/main/java/net/cubespace/RegionShop/Core/Sell.java
+++ b/src/main/java/net/cubespace/RegionShop/Core/Sell.java
@@ -1,223 +1,223 @@
package net.cubespace.RegionShop.Core;
import com.j256.ormlite.dao.ForeignCollection;
import net.cubespace.RegionShop.Bukkit.Plugin;
import net.cubespace.RegionShop.Config.ConfigManager;
import net.cubespace.RegionShop.Config.Files.Sub.Group;
import net.cubespace.RegionShop.Database.Database;
import net.cubespace.RegionShop.Database.ItemStorageHolder;
import net.cubespace.RegionShop.Database.PlayerOwns;
import net.cubespace.RegionShop.Database.Repository.TransactionRepository;
import net.cubespace.RegionShop.Database.Table.ItemStorage;
import net.cubespace.RegionShop.Database.Table.Items;
import net.cubespace.RegionShop.Database.Table.Transaction;
import net.cubespace.RegionShop.Util.ItemName;
import net.cubespace.RegionShop.Util.Logger;
import net.cubespace.RegionShop.Util.VaultBridge;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import java.sql.SQLException;
import java.util.List;
public class Sell {
public static void sell(final ItemStack itemStack, List<Items> items, Player player, final ItemStorageHolder region) {
player.getInventory().removeItem(itemStack);
ForeignCollection<PlayerOwns> playerList = region.getOwners();
boolean isOwner = false;
for(PlayerOwns player1 : playerList) {
if(player1.getPlayer().getName().equals(player.getName().toLowerCase())) {
isOwner = true;
}
}
if(isOwner) {
player.sendMessage(ConfigManager.main.Chat_prefix + ConfigManager.language.Sell_NotYourItem);
player.getInventory().setItemInHand(itemStack);
return;
}
//Check if there is Place inside the Shop
Group group = ConfigManager.groups.getGroup(region.getItemStorage().getSetting());
if(region.getItemStorage().getItemAmount() + itemStack.getAmount() >= group.Storage) {
player.sendMessage(ConfigManager.main.Chat_prefix + ConfigManager.language.Sell_FullStorage);
player.getInventory().setItemInHand(itemStack);
return;
}
//Check all items
for(final Items item : items) {
if (item != null && item.getBuy() > 0) {
Float price = (itemStack.getAmount() / item.getUnitAmount()) * item.getBuy();
if (region.getItemStorage().isServershop() || VaultBridge.has(item.getOwner(), itemStack.getAmount() * item.getBuy()) ) {
String dataName = ItemName.getDataName(itemStack);
String niceItemName;
if(dataName.endsWith(" ")) {
niceItemName = dataName + ItemName.nicer(itemStack.getType().toString());
} else if(!dataName.equals("")) {
niceItemName = dataName;
} else {
niceItemName = ItemName.nicer(itemStack.getType().toString());
}
if(!region.getItemStorage().isServershop()) {
OfflinePlayer owner = Plugin.getInstance().getServer().getOfflinePlayer(item.getOwner());
if (owner != null) {
if(owner.isOnline()) {
Plugin.getInstance().getServer().getPlayer(item.getOwner()).sendMessage(ConfigManager.main.Chat_prefix + ConfigManager.language.Sell_OwnerHint.
replace("%player", player.getDisplayName()).
replace("%amount", ((Integer)itemStack.getAmount()).toString()).
replace("%item", niceItemName).
replace("%shop", region.getName()).
replace("%price", price.toString()));
}
TransactionRepository.generateTransaction(owner, Transaction.TransactionType.BUY, region.getName(), player.getWorld().getName(), player.getName(), item.getMeta().getItemID(), itemStack.getAmount(), item.getBuy().doubleValue(), 0.0, item.getUnitAmount());
}
VaultBridge.withdrawPlayer(item.getOwner(), itemStack.getAmount() * item.getBuy());
}
VaultBridge.depositPlayer(player.getName(), itemStack.getAmount() * item.getBuy());
player.sendMessage(ConfigManager.main.Chat_prefix + ConfigManager.language.Sell_PlayerHint.
replace("%player", player.getDisplayName()).
replace("%amount", ((Integer) itemStack.getAmount()).toString()).
replace("%item", niceItemName).
replace("%shop", region.getName()).
replace("%price", price.toString()).
replace("%owner", item.getOwner()));
item.setCurrentAmount(item.getCurrentAmount() + itemStack.getAmount());
item.setBought(item.getBought() + itemStack.getAmount());
ItemStorage itemStorage = region.getItemStorage();
itemStorage.setItemAmount(itemStorage.getItemAmount() + itemStack.getAmount());
try {
Database.getDAO(ItemStorage.class).update(itemStorage);
Database.getDAO(Items.class).update(item);
} catch (SQLException e) {
Logger.error("Could not update Items/ItemStorage", e);
}
TransactionRepository.generateTransaction(player, Transaction.TransactionType.SELL, region.getName(), player.getWorld().getName(), item.getOwner(), item.getMeta().getItemID(), itemStack.getAmount(), 0.0, item.getBuy().doubleValue(), item.getUnitAmount());
return;
}
}
}
//No item found :(
player.sendMessage(ConfigManager.main.Chat_prefix + ConfigManager.language.Sell_OwnerHasNotEnoughMoney);
player.getInventory().setItemInHand(itemStack);
}
public static void sell(final ItemStack itemStack, final Items item, Player player, final ItemStorageHolder region) {
player.getInventory().removeItem(itemStack);
ForeignCollection<PlayerOwns> playerList = region.getOwners();
boolean isOwner = false;
for(PlayerOwns player1 : playerList) {
if(player1.getPlayer().getName().equals(player.getName().toLowerCase())) {
isOwner = true;
}
}
if(isOwner) {
player.sendMessage(ConfigManager.main.Chat_prefix + ConfigManager.language.Sell_NotYourItem);
player.getInventory().setItemInHand(itemStack);
return;
}
if(item.getBuy() <= 0.0) {
player.sendMessage(ConfigManager.main.Chat_prefix + ConfigManager.language.Sell_DoesNotBuy);
player.getInventory().setItemInHand(itemStack);
return;
}
Group group = ConfigManager.groups.getGroup(region.getItemStorage().getSetting());
if(region.getItemStorage().getItemAmount() + itemStack.getAmount() >= group.Storage) {
player.sendMessage(ConfigManager.main.Chat_prefix + ConfigManager.language.Sell_FullStorage);
player.getInventory().setItemInHand(itemStack);
return;
}
Float price = (itemStack.getAmount() / item.getUnitAmount() ) * item.getBuy();
if (region.getItemStorage().isServershop() || VaultBridge.has(item.getOwner(), price)) {
String dataName = ItemName.getDataName(itemStack);
String niceItemName;
if(dataName.endsWith(" ")) {
niceItemName = dataName + ItemName.nicer(itemStack.getType().toString());
} else if(!dataName.equals("")) {
niceItemName = dataName;
} else {
niceItemName = ItemName.nicer(itemStack.getType().toString());
}
if(!region.getItemStorage().isServershop()) {
OfflinePlayer owner = Plugin.getInstance().getServer().getOfflinePlayer(item.getOwner());
if (owner != null) {
TransactionRepository.generateTransaction(owner,
Transaction.TransactionType.BUY,
region.getName(),
player.getWorld().getName(),
player.getName(),
item.getMeta().getItemID(),
itemStack.getAmount(),
item.getBuy().doubleValue(),
0.0,
item.getUnitAmount());
}
VaultBridge.withdrawPlayer(item.getOwner(), price);
}
VaultBridge.depositPlayer(player.getName(), price);
player.sendMessage(ConfigManager.main.Chat_prefix + ConfigManager.language.Sell_PlayerHint.
replace("%player", player.getDisplayName()).
replace("%amount", ((Integer) itemStack.getAmount()).toString()).
replace("%item", niceItemName).
replace("%shop", region.getName()).
- replace("%price", price.toString().
- replace("%owner", item.getOwner())));
+ replace("%price", price.toString()).
+ replace("%owner", item.getOwner()));
item.setCurrentAmount(item.getCurrentAmount() + itemStack.getAmount());
item.setBought(item.getBought() + itemStack.getAmount());
ItemStorage itemStorage = region.getItemStorage();
itemStorage.setItemAmount(itemStorage.getItemAmount() + itemStack.getAmount());
try {
Database.getDAO(ItemStorage.class).update(itemStorage);
Database.getDAO(Items.class).update(item);
} catch (SQLException e) {
Logger.error("Could not update Items/ItemStorage", e);
}
TransactionRepository.generateTransaction(player,
Transaction.TransactionType.SELL,
region.getName(),
player.getWorld().getName(),
item.getOwner(),
item.getMeta().getItemID(),
itemStack.getAmount(),
0.0,
item.getBuy().doubleValue(),
item.getUnitAmount());
} else {
player.sendMessage(ConfigManager.main.Chat_prefix + ConfigManager.language.Sell_OwnerHasNotEnoughMoney);
player.getInventory().setItemInHand(itemStack);
}
}
}
| true | true | public static void sell(final ItemStack itemStack, final Items item, Player player, final ItemStorageHolder region) {
player.getInventory().removeItem(itemStack);
ForeignCollection<PlayerOwns> playerList = region.getOwners();
boolean isOwner = false;
for(PlayerOwns player1 : playerList) {
if(player1.getPlayer().getName().equals(player.getName().toLowerCase())) {
isOwner = true;
}
}
if(isOwner) {
player.sendMessage(ConfigManager.main.Chat_prefix + ConfigManager.language.Sell_NotYourItem);
player.getInventory().setItemInHand(itemStack);
return;
}
if(item.getBuy() <= 0.0) {
player.sendMessage(ConfigManager.main.Chat_prefix + ConfigManager.language.Sell_DoesNotBuy);
player.getInventory().setItemInHand(itemStack);
return;
}
Group group = ConfigManager.groups.getGroup(region.getItemStorage().getSetting());
if(region.getItemStorage().getItemAmount() + itemStack.getAmount() >= group.Storage) {
player.sendMessage(ConfigManager.main.Chat_prefix + ConfigManager.language.Sell_FullStorage);
player.getInventory().setItemInHand(itemStack);
return;
}
Float price = (itemStack.getAmount() / item.getUnitAmount() ) * item.getBuy();
if (region.getItemStorage().isServershop() || VaultBridge.has(item.getOwner(), price)) {
String dataName = ItemName.getDataName(itemStack);
String niceItemName;
if(dataName.endsWith(" ")) {
niceItemName = dataName + ItemName.nicer(itemStack.getType().toString());
} else if(!dataName.equals("")) {
niceItemName = dataName;
} else {
niceItemName = ItemName.nicer(itemStack.getType().toString());
}
if(!region.getItemStorage().isServershop()) {
OfflinePlayer owner = Plugin.getInstance().getServer().getOfflinePlayer(item.getOwner());
if (owner != null) {
TransactionRepository.generateTransaction(owner,
Transaction.TransactionType.BUY,
region.getName(),
player.getWorld().getName(),
player.getName(),
item.getMeta().getItemID(),
itemStack.getAmount(),
item.getBuy().doubleValue(),
0.0,
item.getUnitAmount());
}
VaultBridge.withdrawPlayer(item.getOwner(), price);
}
VaultBridge.depositPlayer(player.getName(), price);
player.sendMessage(ConfigManager.main.Chat_prefix + ConfigManager.language.Sell_PlayerHint.
replace("%player", player.getDisplayName()).
replace("%amount", ((Integer) itemStack.getAmount()).toString()).
replace("%item", niceItemName).
replace("%shop", region.getName()).
replace("%price", price.toString().
replace("%owner", item.getOwner())));
item.setCurrentAmount(item.getCurrentAmount() + itemStack.getAmount());
item.setBought(item.getBought() + itemStack.getAmount());
ItemStorage itemStorage = region.getItemStorage();
itemStorage.setItemAmount(itemStorage.getItemAmount() + itemStack.getAmount());
try {
Database.getDAO(ItemStorage.class).update(itemStorage);
Database.getDAO(Items.class).update(item);
} catch (SQLException e) {
Logger.error("Could not update Items/ItemStorage", e);
}
TransactionRepository.generateTransaction(player,
Transaction.TransactionType.SELL,
region.getName(),
player.getWorld().getName(),
item.getOwner(),
item.getMeta().getItemID(),
itemStack.getAmount(),
0.0,
item.getBuy().doubleValue(),
item.getUnitAmount());
} else {
player.sendMessage(ConfigManager.main.Chat_prefix + ConfigManager.language.Sell_OwnerHasNotEnoughMoney);
player.getInventory().setItemInHand(itemStack);
}
}
| public static void sell(final ItemStack itemStack, final Items item, Player player, final ItemStorageHolder region) {
player.getInventory().removeItem(itemStack);
ForeignCollection<PlayerOwns> playerList = region.getOwners();
boolean isOwner = false;
for(PlayerOwns player1 : playerList) {
if(player1.getPlayer().getName().equals(player.getName().toLowerCase())) {
isOwner = true;
}
}
if(isOwner) {
player.sendMessage(ConfigManager.main.Chat_prefix + ConfigManager.language.Sell_NotYourItem);
player.getInventory().setItemInHand(itemStack);
return;
}
if(item.getBuy() <= 0.0) {
player.sendMessage(ConfigManager.main.Chat_prefix + ConfigManager.language.Sell_DoesNotBuy);
player.getInventory().setItemInHand(itemStack);
return;
}
Group group = ConfigManager.groups.getGroup(region.getItemStorage().getSetting());
if(region.getItemStorage().getItemAmount() + itemStack.getAmount() >= group.Storage) {
player.sendMessage(ConfigManager.main.Chat_prefix + ConfigManager.language.Sell_FullStorage);
player.getInventory().setItemInHand(itemStack);
return;
}
Float price = (itemStack.getAmount() / item.getUnitAmount() ) * item.getBuy();
if (region.getItemStorage().isServershop() || VaultBridge.has(item.getOwner(), price)) {
String dataName = ItemName.getDataName(itemStack);
String niceItemName;
if(dataName.endsWith(" ")) {
niceItemName = dataName + ItemName.nicer(itemStack.getType().toString());
} else if(!dataName.equals("")) {
niceItemName = dataName;
} else {
niceItemName = ItemName.nicer(itemStack.getType().toString());
}
if(!region.getItemStorage().isServershop()) {
OfflinePlayer owner = Plugin.getInstance().getServer().getOfflinePlayer(item.getOwner());
if (owner != null) {
TransactionRepository.generateTransaction(owner,
Transaction.TransactionType.BUY,
region.getName(),
player.getWorld().getName(),
player.getName(),
item.getMeta().getItemID(),
itemStack.getAmount(),
item.getBuy().doubleValue(),
0.0,
item.getUnitAmount());
}
VaultBridge.withdrawPlayer(item.getOwner(), price);
}
VaultBridge.depositPlayer(player.getName(), price);
player.sendMessage(ConfigManager.main.Chat_prefix + ConfigManager.language.Sell_PlayerHint.
replace("%player", player.getDisplayName()).
replace("%amount", ((Integer) itemStack.getAmount()).toString()).
replace("%item", niceItemName).
replace("%shop", region.getName()).
replace("%price", price.toString()).
replace("%owner", item.getOwner()));
item.setCurrentAmount(item.getCurrentAmount() + itemStack.getAmount());
item.setBought(item.getBought() + itemStack.getAmount());
ItemStorage itemStorage = region.getItemStorage();
itemStorage.setItemAmount(itemStorage.getItemAmount() + itemStack.getAmount());
try {
Database.getDAO(ItemStorage.class).update(itemStorage);
Database.getDAO(Items.class).update(item);
} catch (SQLException e) {
Logger.error("Could not update Items/ItemStorage", e);
}
TransactionRepository.generateTransaction(player,
Transaction.TransactionType.SELL,
region.getName(),
player.getWorld().getName(),
item.getOwner(),
item.getMeta().getItemID(),
itemStack.getAmount(),
0.0,
item.getBuy().doubleValue(),
item.getUnitAmount());
} else {
player.sendMessage(ConfigManager.main.Chat_prefix + ConfigManager.language.Sell_OwnerHasNotEnoughMoney);
player.getInventory().setItemInHand(itemStack);
}
}
|
diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/internal/editors/ReviewTaskEditorPageFactory.java b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/internal/editors/ReviewTaskEditorPageFactory.java
index c1d99ce4..22267617 100644
--- a/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/internal/editors/ReviewTaskEditorPageFactory.java
+++ b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/internal/editors/ReviewTaskEditorPageFactory.java
@@ -1,56 +1,58 @@
/*******************************************************************************
* Copyright (c) 2010 Research Group for Industrial Software (INSO), Vienna University of Technology
* 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:
* Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
*******************************************************************************/
package org.eclipse.mylyn.reviews.tasks.ui.internal.editors;
import org.eclipse.mylyn.reviews.tasks.ui.internal.Images;
import org.eclipse.mylyn.reviews.tasks.ui.internal.Messages;
+import org.eclipse.mylyn.tasks.core.AbstractRepositoryConnector;
+import org.eclipse.mylyn.tasks.ui.TasksUi;
import org.eclipse.mylyn.tasks.ui.editors.AbstractTaskEditorPageFactory;
import org.eclipse.mylyn.tasks.ui.editors.TaskEditor;
import org.eclipse.mylyn.tasks.ui.editors.TaskEditorInput;
import org.eclipse.swt.graphics.Image;
import org.eclipse.ui.forms.editor.IFormPage;
-/*
+/**
* @author Kilian Matt
*/
public class ReviewTaskEditorPageFactory extends AbstractTaskEditorPageFactory {
@Override
public boolean canCreatePageFor(TaskEditorInput input) {
- // TODO restrict reviews to non-new and non-local tasks
- return true;
+ AbstractRepositoryConnector connector = TasksUi.getRepositoryConnector(input.getTask().getConnectorKind());
+ return connector != null && connector.isUserManaged();
}
@Override
public IFormPage createPage(TaskEditor parentEditor) {
return new ReviewTaskEditorPage(parentEditor);
}
@Override
public Image getPageImage() {
return Images.SMALL_ICON.createImage();
}
@Override
public String getPageText() {
return Messages.ReviewTaskEditorPageFactory_PageTitle;
}
@Override
public int getPriority() {
return PRIORITY_ADDITIONS;
}
@Override
public String[] getConflictingIds(TaskEditorInput input) {
return new String[0];
}
}
diff --git a/versions/org.eclipse.mylyn.versions.tasks.ui/src/org/eclipse/mylyn/versions/tasks/ui/ChangeSetPageFactory.java b/versions/org.eclipse.mylyn.versions.tasks.ui/src/org/eclipse/mylyn/versions/tasks/ui/ChangeSetPageFactory.java
index d5a530d0..5945a5f6 100644
--- a/versions/org.eclipse.mylyn.versions.tasks.ui/src/org/eclipse/mylyn/versions/tasks/ui/ChangeSetPageFactory.java
+++ b/versions/org.eclipse.mylyn.versions.tasks.ui/src/org/eclipse/mylyn/versions/tasks/ui/ChangeSetPageFactory.java
@@ -1,49 +1,52 @@
/*******************************************************************************
* Copyright (c) 2011 Research Group for Industrial Software (INSO), Vienna University of Technology.
* 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:
* Research Group for Industrial Software (INSO), Vienna University of Technology - initial API and implementation
*******************************************************************************/
package org.eclipse.mylyn.versions.tasks.ui;
+import org.eclipse.mylyn.tasks.core.AbstractRepositoryConnector;
+import org.eclipse.mylyn.tasks.ui.TasksUi;
import org.eclipse.mylyn.tasks.ui.editors.AbstractTaskEditorPageFactory;
import org.eclipse.mylyn.tasks.ui.editors.TaskEditor;
import org.eclipse.mylyn.tasks.ui.editors.TaskEditorInput;
import org.eclipse.swt.graphics.Image;
import org.eclipse.ui.forms.editor.IFormPage;
/**
*
* @author Kilian Matt
*
*/
public class ChangeSetPageFactory extends AbstractTaskEditorPageFactory {
public ChangeSetPageFactory() {
}
@Override
public boolean canCreatePageFor(TaskEditorInput input) {
- return true;
+ AbstractRepositoryConnector connector = TasksUi.getRepositoryConnector(input.getTask().getConnectorKind());
+ return connector != null && connector.isUserManaged();
}
@Override
public IFormPage createPage(TaskEditor parentEditor) {
return new ChangeSetPage(parentEditor);
}
@Override
public Image getPageImage() {
return null;
}
@Override
public String getPageText() {
return "Changeset";
}
}
| false | false | null | null |
diff --git a/fr/upmc/aladyn/dyn_generics/metaobjects/MyMetaObject.java b/fr/upmc/aladyn/dyn_generics/metaobjects/MyMetaObject.java
index 2cc4bc6..91b00d3 100644
--- a/fr/upmc/aladyn/dyn_generics/metaobjects/MyMetaObject.java
+++ b/fr/upmc/aladyn/dyn_generics/metaobjects/MyMetaObject.java
@@ -1,42 +1,42 @@
package fr.upmc.aladyn.dyn_generics.metaobjects;
import fr.upmc.aladyn.dyn_generics.tests.Generics2;
import fr.upmc.aladyn.reflection.Metaobject;
public class MyMetaObject extends Metaobject {
/**
*
*/
private static final long serialVersionUID = 967068947015262702L;
private Class<?>[] types;
public MyMetaObject(Object self, Object[] args) {
super(self, args);
this.types = (Class<?>[]) args[0];
}
@Override
public Object trapFieldRead(String name){
System.out.println("[trapFieldRead]FieldName: "+name);
Generics2.checkTypeField(getObject().getClass(), name, types);
return super.trapFieldRead(name);
}
@Override
public void trapFieldWrite(String name, Object value){
System.out.println("[trapFieldWrite]FieldName: "+name);
Generics2.checkTypeField(getObject().getClass(), name, types);
super.trapFieldWrite(name, value);
}
@Override
public Object trapMethodcall(int identifier, Object[] args) throws Throwable{
System.out.println("[trapMethodcall]FieldName: "+Thread.currentThread().getStackTrace()[3].getMethodName());
- Generics2.checkTypesParams(getObject().getClass(), types);
+ Generics2.checkTypesParams(getObject().getClass(), types, args);
Generics2.checkTypeReturn(getObject().getClass(), types);
//Generics2.checkTypeReturn(this.getClass(), this.first.getClass(), types);
return super.trapMethodcall(identifier, args);
}
}
diff --git a/fr/upmc/aladyn/dyn_generics/tests/Generics2.java b/fr/upmc/aladyn/dyn_generics/tests/Generics2.java
index 449d046..86b74b7 100644
--- a/fr/upmc/aladyn/dyn_generics/tests/Generics2.java
+++ b/fr/upmc/aladyn/dyn_generics/tests/Generics2.java
@@ -1,119 +1,117 @@
package fr.upmc.aladyn.dyn_generics.tests;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import fr.upmc.aladyn.dyn_generics.annotations.DynamicGenericType;
import fr.upmc.aladyn.dyn_generics.annotations.DynamicGenericTypeParameters;
import fr.upmc.aladyn.dyn_generics.exceptions.LatentTypeCheckException;
public class Generics2 {
- public static void checkTypesParams(Class<?> classinfo, Class<?>[] types) throws LatentTypeCheckException
+ public static void checkTypesParams(Class<?> classinfo, Class<?>[] types, Object[] args) throws LatentTypeCheckException
{
try {
String methodName = Thread.currentThread().getStackTrace()[4].getMethodName();
System.out.println("[checkTypesParams]methodName: "+methodName);
Method methlist[] = classinfo.getMethods();
int num = 0, num2 = 0;
while ((!methlist[num].getName().contains(methodName)) || methodName.equals(methlist[num].getName())){
num++;
}
while ((methodName.equals(methlist[num].getName()))){
num2++;
}
System.out.println("[checkTypesParams]methodfound: "+methlist[num].getName());
String[] typeParams = classinfo.getAnnotation(DynamicGenericTypeParameters.class).typeParams();
- Class<?>[] params = methlist[num].getParameterTypes();
Annotation[][] listannot = methlist[num].getParameterAnnotations();
- System.out.println("[checkTypesParams]paramslength: "+params.length);
if(listannot.length > 0)
{
for (int j=0; j < listannot.length; j++)
{
for (int i = 0; i < typeParams.length; i++) {
if ( ((DynamicGenericType)listannot[j][0]).value().equals(typeParams[i]) )
{
- if (!params[i].equals(types[i]))
+ if (!args[i].getClass().equals(types[i]))
{
- throw new LatentTypeCheckException("["+methodName+"(parameter "+(i+1)+")]bad type "+params[i].getSimpleName()+", waiting "+types[i].getSimpleName());
+ throw new LatentTypeCheckException("["+methodName+"(parameter "+(i+1)+")]bad type "+args[i].getClass().getSimpleName()+", waiting "+types[i].getSimpleName());
}
}
}
}
}
} catch (LatentTypeCheckException e){
e.printStackTrace();
System.exit(0);
}
}
public static void checkTypeReturn(Class<?> classinfo, Class<?>[] types) throws LatentTypeCheckException
{
String methodName = Thread.currentThread().getStackTrace()[4].getMethodName();
System.out.println("[checkTypeReturn]methodName: "+methodName);
Method methlist[] = classinfo.getMethods();
int num = 0;
while ((!methlist[num].getName().contains(methodName)) || methodName.equals(methlist[num].getName())){
num++;
}
System.out.println("[checkTypeReturn]methodNameFound: "+methlist[num].getName());
String type;
String[] typeParams = classinfo.getAnnotation(DynamicGenericTypeParameters.class).typeParams();
Class<?> returntype = methlist[num].getReturnType();
if (!methlist[num].getGenericReturnType().toString().equals("void"))
{
System.out.println("[checkTypeReturn]methodAnnot: "+methlist[num].getAnnotation(DynamicGenericType.class));
type = methlist[num].getAnnotation(DynamicGenericType.class).value();
for (int i = 0; i < typeParams.length; i++) {
if ( type.equals(typeParams[i]) )
{
if (!(returntype.equals(types[i])))
{
throw new LatentTypeCheckException("["+methodName+"]bad returntype "+returntype+", waiting "+types[i].getSimpleName());
}
}
}
}
}
public static void checkTypeField(Class<?> classinfo, String name, Class<?>[] types)
{
String[] typeParams = classinfo.getAnnotation(DynamicGenericTypeParameters.class).typeParams();
Field[] fields = classinfo.getFields();
boolean found = false;
int num = 0;
System.out.println("[checkTypeField]FieldName: "+name);
for(num=0;num<fields.length;num++)
{
if (fields[num].getName().equals(name))
{
found = true;
break;
}
}
if (!found)
return;
String annotation = fields[num].getAnnotation(DynamicGenericType.class).value();
for (int i = 0; i < typeParams.length; i++) {
if ( annotation.equals(typeParams[i]) )
{
if (!(fields[num].getType().equals(types[i])))
{
throw new LatentTypeCheckException("bad type for field "+fields[num].getName()+", waiting "+types[i].getSimpleName());
}
}
}
}
}
diff --git a/fr/upmc/aladyn/dyn_generics/tests/MainUser.java b/fr/upmc/aladyn/dyn_generics/tests/MainUser.java
index 88b5e27..b7734a7 100755
--- a/fr/upmc/aladyn/dyn_generics/tests/MainUser.java
+++ b/fr/upmc/aladyn/dyn_generics/tests/MainUser.java
@@ -1,15 +1,15 @@
package fr.upmc.aladyn.dyn_generics.tests;
public class MainUser {
/**
* @param args
*/
public static void main(String[] args)
{
Pair p = new Pair(new Class<?>[]{Integer.class, Integer.class}, 10, 20);
//p.getFirst();
- p.update((Integer)1, (Integer)2);
+ p.update((Integer)1, (Integer)1);
}
}
| false | false | null | null |
diff --git a/src/org/eclipse/jface/dialogs/Dialog.java b/src/org/eclipse/jface/dialogs/Dialog.java
index 6c123e34..b575778f 100644
--- a/src/org/eclipse/jface/dialogs/Dialog.java
+++ b/src/org/eclipse/jface/dialogs/Dialog.java
@@ -1,1272 +1,1304 @@
/*******************************************************************************
* 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 - initial API and implementation
*******************************************************************************/
package org.eclipse.jface.dialogs;
import java.util.Arrays;
import java.util.HashMap;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.jface.util.Policy;
import org.eclipse.jface.window.IShellProvider;
import org.eclipse.jface.window.SameShellProvider;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.FontData;
import org.eclipse.swt.graphics.FontMetrics;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
/**
* A dialog is a specialized window used for narrow-focused communication with
* the user.
* <p>
* Dialogs are usually modal. Consequently, it is generally bad practice to open
* a dialog without a parent. A modal dialog without a parent is not prevented
* from disappearing behind the application's other windows, making it very
* confusing for the user.
* </p>
* <p>
* If there is more than one modal dialog is open the second one should be
* parented off of the shell of the first one otherwise it is possible that the
* OS will give focus to the first dialog potentially blocking the UI.
* </p>
*/
public abstract class Dialog extends Window {
/**
* Image registry key for error image (value
* <code>"dialog_error_image"</code>).
*
* @deprecated use
* org.eclipse.swt.widgets.Display.getSystemImage(SWT.ICON_ERROR)
*/
public static final String DLG_IMG_ERROR = "dialog_error_image"; //$NON-NLS-1$
/**
* Image registry key for info image (value <code>"dialog_info_image"</code>).
*
* @deprecated use
* org.eclipse.swt.widgets.Display.getSystemImage(SWT.ICON_INFORMATION)
*/
public static final String DLG_IMG_INFO = "dialog_info_imageg"; //$NON-NLS-1$
/**
* Image registry key for question image (value
* <code>"dialog_question_image"</code>).
*
* @deprecated org.eclipse.swt.widgets.Display.getSystemImage(SWT.ICON_QUESTION)
*/
public static final String DLG_IMG_QUESTION = "dialog_question_image"; //$NON-NLS-1$
/**
* Image registry key for warning image (value
* <code>"dialog_warning_image"</code>).
*
* @deprecated use
* org.eclipse.swt.widgets.Display.getSystemImage(SWT.ICON_WARNING)
*/
public static final String DLG_IMG_WARNING = "dialog_warning_image"; //$NON-NLS-1$
/**
* Image registry key for info message image (value
* <code>"dialog_messasge_info_image"</code>).
*
* @since 2.0
*/
public static final String DLG_IMG_MESSAGE_INFO = "dialog_messasge_info_image"; //$NON-NLS-1$
/**
* Image registry key for info message image (value
* <code>"dialog_messasge_warning_image"</code>).
*
* @since 2.0
*/
public static final String DLG_IMG_MESSAGE_WARNING = "dialog_messasge_warning_image"; //$NON-NLS-1$
/**
* Image registry key for info message image (value
* <code>"dialog_message_error_image"</code>).
*
* @since 2.0
*/
public static final String DLG_IMG_MESSAGE_ERROR = "dialog_message_error_image"; //$NON-NLS-1$
/**
* Image registry key for help image (value
* <code>"dialog_help_image"</code>).
*
* @since 3.2
*/
public static final String DLG_IMG_HELP = "dialog_help_image"; //$NON-NLS-1$
/**
* The ellipsis is the string that is used to represent shortened text.
*
* @since 3.0
*/
public static final String ELLIPSIS = "..."; //$NON-NLS-1$
/**
* The dialog settings key name for stored dialog x location.
*
* @since 3.2
*/
private static final String DIALOG_ORIGIN_X = "DIALOG_X_ORIGIN"; //$NON-NLS-1$
/**
* The dialog settings key name for stored dialog y location.
*
* @since 3.2
*/
private static final String DIALOG_ORIGIN_Y = "DIALOG_Y_ORIGIN"; //$NON-NLS-1$
/**
* The dialog settings key name for stored dialog width.
*
* @since 3.2
*/
private static final String DIALOG_WIDTH = "DIALOG_WIDTH"; //$NON-NLS-1$
/**
* The dialog settings key name for stored dialog height.
*
* @since 3.2
*/
private static final String DIALOG_HEIGHT = "DIALOG_HEIGHT"; //$NON-NLS-1$
/**
* The dialog settings key name for the font used when the dialog
* height and width was stored.
*
*@since 3.2
*/
private static final String DIALOG_FONT_DATA = "DIALOG_FONT_NAME"; //$NON-NLS-1$
/**
* A value that can be used for stored dialog width or height that
* indicates that the default bounds should be used.
*
* @since 3.2
*/
public static final int DIALOG_DEFAULT_BOUNDS = -1;
/**
* Constants that can be used for specifying the strategy for persisting
* dialog bounds. These constants represent bit masks that can be used
* together.
*
*@since 3.2
*/
/**
* Persist the last location of the dialog.
* @since 3.2
*/
public static final int DIALOG_PERSISTLOCATION = 0x0001;
/**
* Persist the last known size of the dialog.
* @since 3.2
*/
public static final int DIALOG_PERSISTSIZE = 0x0002;
/**
* The dialog area; <code>null</code> until dialog is layed out.
*/
protected Control dialogArea;
/**
* The button bar; <code>null</code> until dialog is layed out.
*/
public Control buttonBar;
/**
* Collection of buttons created by the <code>createButton</code> method.
*/
private HashMap buttons = new HashMap();
/**
* Font metrics to use for determining pixel sizes.
*/
private FontMetrics fontMetrics;
/**
* Number of horizontal dialog units per character, value <code>4</code>.
*/
private static final int HORIZONTAL_DIALOG_UNIT_PER_CHAR = 4;
/**
* Number of vertical dialog units per character, value <code>8</code>.
*/
private static final int VERTICAL_DIALOG_UNITS_PER_CHAR = 8;
/**
* Returns the number of pixels corresponding to the height of the given
* number of characters.
* <p>
* The required <code>FontMetrics</code> parameter may be created in the
* following way: <code>
* GC gc = new GC(control);
* gc.setFont(control.getFont());
* fontMetrics = gc.getFontMetrics();
* gc.dispose();
* </code>
* </p>
*
* @param fontMetrics
* used in performing the conversion
* @param chars
* the number of characters
* @return the number of pixels
* @since 2.0
*/
public static int convertHeightInCharsToPixels(FontMetrics fontMetrics,
int chars) {
return fontMetrics.getHeight() * chars;
}
/**
* Returns the number of pixels corresponding to the given number of
* horizontal dialog units.
* <p>
* The required <code>FontMetrics</code> parameter may be created in the
* following way: <code>
* GC gc = new GC(control);
* gc.setFont(control.getFont());
* fontMetrics = gc.getFontMetrics();
* gc.dispose();
* </code>
* </p>
*
* @param fontMetrics
* used in performing the conversion
* @param dlus
* the number of horizontal dialog units
* @return the number of pixels
* @since 2.0
*/
public static int convertHorizontalDLUsToPixels(FontMetrics fontMetrics,
int dlus) {
// round to the nearest pixel
return (fontMetrics.getAverageCharWidth() * dlus + HORIZONTAL_DIALOG_UNIT_PER_CHAR / 2)
/ HORIZONTAL_DIALOG_UNIT_PER_CHAR;
}
/**
* Returns the number of pixels corresponding to the given number of
* vertical dialog units.
* <p>
* The required <code>FontMetrics</code> parameter may be created in the
* following way: <code>
* GC gc = new GC(control);
* gc.setFont(control.getFont());
* fontMetrics = gc.getFontMetrics();
* gc.dispose();
* </code>
* </p>
*
* @param fontMetrics
* used in performing the conversion
* @param dlus
* the number of vertical dialog units
* @return the number of pixels
* @since 2.0
*/
public static int convertVerticalDLUsToPixels(FontMetrics fontMetrics,
int dlus) {
// round to the nearest pixel
return (fontMetrics.getHeight() * dlus + VERTICAL_DIALOG_UNITS_PER_CHAR / 2)
/ VERTICAL_DIALOG_UNITS_PER_CHAR;
}
/**
* Returns the number of pixels corresponding to the width of the given
* number of characters.
* <p>
* The required <code>FontMetrics</code> parameter may be created in the
* following way: <code>
* GC gc = new GC(control);
* gc.setFont(control.getFont());
* fontMetrics = gc.getFontMetrics();
* gc.dispose();
* </code>
* </p>
*
* @param fontMetrics
* used in performing the conversion
* @param chars
* the number of characters
* @return the number of pixels
* @since 2.0
*/
public static int convertWidthInCharsToPixels(FontMetrics fontMetrics,
int chars) {
return fontMetrics.getAverageCharWidth() * chars;
}
/**
* Shortens the given text <code>textValue</code> so that its width in
* pixels does not exceed the width of the given control. Overrides
* characters in the center of the original string with an ellipsis ("...")
* if necessary. If a <code>null</code> value is given, <code>null</code>
* is returned.
*
* @param textValue
* the original string or <code>null</code>
* @param control
* the control the string will be displayed on
* @return the string to display, or <code>null</code> if null was passed
* in
*
* @since 3.0
*/
public static String shortenText(String textValue, Control control) {
if (textValue == null) {
return null;
}
GC gc = new GC(control);
int maxWidth = control.getBounds().width - 5;
if (gc.textExtent(textValue).x < maxWidth) {
gc.dispose();
return textValue;
}
int length = textValue.length();
int pivot = length / 2;
int start = pivot;
int end = pivot + 1;
while (start >= 0 && end < length) {
String s1 = textValue.substring(0, start);
String s2 = textValue.substring(end, length);
String s = s1 + ELLIPSIS + s2;
int l = gc.textExtent(s).x;
if (l < maxWidth) {
gc.dispose();
return s;
}
start--;
end++;
}
gc.dispose();
return textValue;
}
/**
* Create a default instance of the blocked handler which does not do
* anything.
*/
public static IDialogBlockedHandler blockedHandler = new IDialogBlockedHandler() {
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.dialogs.IDialogBlockedHandler#clearBlocked()
*/
public void clearBlocked() {
// No default behaviour
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.dialogs.IDialogBlockedHandler#showBlocked(org.eclipse.core.runtime.IProgressMonitor,
* org.eclipse.core.runtime.IStatus, java.lang.String)
*/
public void showBlocked(IProgressMonitor blocking,
IStatus blockingStatus, String blockedName) {
// No default behaviour
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.dialogs.IDialogBlockedHandler#showBlocked(org.eclipse.swt.widgets.Shell,
* org.eclipse.core.runtime.IProgressMonitor,
* org.eclipse.core.runtime.IStatus, java.lang.String)
*/
public void showBlocked(Shell parentShell, IProgressMonitor blocking,
IStatus blockingStatus, String blockedName) {
// No default behaviour
}
};
/**
* Creates a dialog instance. Note that the window will have no visual
* representation (no widgets) until it is told to open. By default,
* <code>open</code> blocks for dialogs.
*
* @param parentShell
* the parent shell, or <code>null</code> to create a top-level
* shell
*/
protected Dialog(Shell parentShell) {
this(new SameShellProvider(parentShell));
if (parentShell == null && Policy.DEBUG_DIALOG_NO_PARENT) {
Policy.getLog().log(
new Status(IStatus.INFO, Policy.JFACE, IStatus.INFO, this
.getClass()
+ " created with no shell",//$NON-NLS-1$
new Exception()));
}
}
/**
* Creates a dialog with the given parent.
*
* @param parentShell
* object that returns the current parent shell
*
* @since 3.1
*/
protected Dialog(IShellProvider parentShell) {
super(parentShell);
- setShellStyle(SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL
- | getDefaultOrientation());
+ if (isResizable()) {
+ setShellStyle(SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL | SWT.MAX | SWT.RESIZE
+ | getDefaultOrientation());
+ } else {
+ setShellStyle(SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL
+ | getDefaultOrientation());
+ }
setBlockOnOpen(true);
}
/**
* Notifies that this dialog's button with the given id has been pressed.
* <p>
* The <code>Dialog</code> implementation of this framework method calls
* <code>okPressed</code> if the ok button is the pressed, and
* <code>cancelPressed</code> if the cancel button is the pressed. All
* other button presses are ignored. Subclasses may override to handle other
* buttons, but should call <code>super.buttonPressed</code> if the
* default handling of the ok and cancel buttons is desired.
* </p>
*
* @param buttonId
* the id of the button that was pressed (see
* <code>IDialogConstants.*_ID</code> constants)
*/
protected void buttonPressed(int buttonId) {
if (IDialogConstants.OK_ID == buttonId) {
okPressed();
} else if (IDialogConstants.CANCEL_ID == buttonId) {
cancelPressed();
}
}
/**
* Notifies that the cancel button of this dialog has been pressed.
* <p>
* The <code>Dialog</code> implementation of this framework method sets
* this dialog's return code to <code>Window.CANCEL</code> and closes the
* dialog. Subclasses may override if desired.
* </p>
*/
protected void cancelPressed() {
setReturnCode(CANCEL);
close();
}
/**
* Returns the number of pixels corresponding to the height of the given
* number of characters.
* <p>
* This method may only be called after <code>initializeDialogUnits</code>
* has been called.
* </p>
* <p>
* Clients may call this framework method, but should not override it.
* </p>
*
* @param chars
* the number of characters
* @return the number of pixels
*/
protected int convertHeightInCharsToPixels(int chars) {
// test for failure to initialize for backward compatibility
if (fontMetrics == null) {
return 0;
}
return convertHeightInCharsToPixels(fontMetrics, chars);
}
/**
* Returns the number of pixels corresponding to the given number of
* horizontal dialog units.
* <p>
* This method may only be called after <code>initializeDialogUnits</code>
* has been called.
* </p>
* <p>
* Clients may call this framework method, but should not override it.
* </p>
*
* @param dlus
* the number of horizontal dialog units
* @return the number of pixels
*/
protected int convertHorizontalDLUsToPixels(int dlus) {
// test for failure to initialize for backward compatibility
if (fontMetrics == null) {
return 0;
}
return convertHorizontalDLUsToPixels(fontMetrics, dlus);
}
/**
* Returns the number of pixels corresponding to the given number of
* vertical dialog units.
* <p>
* This method may only be called after <code>initializeDialogUnits</code>
* has been called.
* </p>
* <p>
* Clients may call this framework method, but should not override it.
* </p>
*
* @param dlus
* the number of vertical dialog units
* @return the number of pixels
*/
protected int convertVerticalDLUsToPixels(int dlus) {
// test for failure to initialize for backward compatibility
if (fontMetrics == null) {
return 0;
}
return convertVerticalDLUsToPixels(fontMetrics, dlus);
}
/**
* Returns the number of pixels corresponding to the width of the given
* number of characters.
* <p>
* This method may only be called after <code>initializeDialogUnits</code>
* has been called.
* </p>
* <p>
* Clients may call this framework method, but should not override it.
* </p>
*
* @param chars
* the number of characters
* @return the number of pixels
*/
protected int convertWidthInCharsToPixels(int chars) {
// test for failure to initialize for backward compatibility
if (fontMetrics == null) {
return 0;
}
return convertWidthInCharsToPixels(fontMetrics, chars);
}
/**
* Creates a new button with the given id.
* <p>
* The <code>Dialog</code> implementation of this framework method creates
* a standard push button, registers it for selection events including
* button presses, and registers default buttons with its shell. The button
* id is stored as the button's client data. If the button id is
* <code>IDialogConstants.CANCEL_ID</code>, the new button will be
* accessible from <code>getCancelButton()</code>. If the button id is
* <code>IDialogConstants.OK_ID</code>, the new button will be accesible
* from <code>getOKButton()</code>. Note that the parent's layout is
* assumed to be a <code>GridLayout</code> and the number of columns in
* this layout is incremented. Subclasses may override.
* </p>
*
* @param parent
* the parent composite
* @param id
* the id of the button (see <code>IDialogConstants.*_ID</code>
* constants for standard dialog button ids)
* @param label
* the label from the button
* @param defaultButton
* <code>true</code> if the button is to be the default button,
* and <code>false</code> otherwise
*
* @return the new button
*
* @see #getCancelButton
* @see #getOKButton()
*/
protected Button createButton(Composite parent, int id, String label,
boolean defaultButton) {
// increment the number of columns in the button bar
((GridLayout) parent.getLayout()).numColumns++;
Button button = new Button(parent, SWT.PUSH);
button.setText(label);
button.setFont(JFaceResources.getDialogFont());
button.setData(new Integer(id));
button.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
buttonPressed(((Integer) event.widget.getData()).intValue());
}
});
if (defaultButton) {
Shell shell = parent.getShell();
if (shell != null) {
shell.setDefaultButton(button);
}
}
buttons.put(new Integer(id), button);
setButtonLayoutData(button);
return button;
}
/**
* Creates and returns the contents of this dialog's button bar.
* <p>
* The <code>Dialog</code> implementation of this framework method lays
* out a button bar and calls the <code>createButtonsForButtonBar</code>
* framework method to populate it. Subclasses may override.
* </p>
* <p>
* The returned control's layout data must be an instance of
* <code>GridData</code>.
* </p>
*
* @param parent
* the parent composite to contain the button bar
* @return the button bar control
*/
protected Control createButtonBar(Composite parent) {
Composite composite = new Composite(parent, SWT.NONE);
// create a layout with spacing and margins appropriate for the font
// size.
GridLayout layout = new GridLayout();
layout.numColumns = 0; // this is incremented by createButton
layout.makeColumnsEqualWidth = true;
layout.marginWidth = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN);
layout.marginHeight = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN);
layout.horizontalSpacing = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING);
layout.verticalSpacing = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING);
composite.setLayout(layout);
GridData data = new GridData(GridData.HORIZONTAL_ALIGN_END
| GridData.VERTICAL_ALIGN_CENTER);
composite.setLayoutData(data);
composite.setFont(parent.getFont());
// Add the buttons to the button bar.
createButtonsForButtonBar(composite);
return composite;
}
/**
* Adds buttons to this dialog's button bar.
* <p>
* The <code>Dialog</code> implementation of this framework method adds
* standard ok and cancel buttons using the <code>createButton</code>
* framework method. These standard buttons will be accessible from
* <code>getCancelButton</code>, and <code>getOKButton</code>.
* Subclasses may override.
* </p>
*
* @param parent
* the button bar composite
*/
protected void createButtonsForButtonBar(Composite parent) {
// create OK and Cancel buttons by default
createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL,
true);
createButton(parent, IDialogConstants.CANCEL_ID,
IDialogConstants.CANCEL_LABEL, false);
}
/*
* @see Window.initializeBounds()
*/
protected void initializeBounds() {
String platform = SWT.getPlatform();
if ("carbon".equals(platform)) { //$NON-NLS-1$
// On Mac OS X the default button must be the right-most button
Shell shell = getShell();
if (shell != null) {
Button defaultButton = shell.getDefaultButton();
if (defaultButton != null
&& isContained(buttonBar, defaultButton)) {
defaultButton.moveBelow(null);
}
}
}
super.initializeBounds();
}
/**
* Returns true if the given Control is a direct or indirect child of
* container.
*
* @param container
* the potential parent
* @param control
* @return boolean <code>true</code> if control is a child of container
*/
private boolean isContained(Control container, Control control) {
Composite parent;
while ((parent = control.getParent()) != null) {
if (parent == container) {
return true;
}
control = parent;
}
return false;
}
/**
* The <code>Dialog</code> implementation of this <code>Window</code>
* method creates and lays out the top level composite for the dialog, and
* determines the appropriate horizontal and vertical dialog units based on
* the font size. It then calls the <code>createDialogArea</code> and
* <code>createButtonBar</code> methods to create the dialog area and
* button bar, respectively. Overriding <code>createDialogArea</code> and
* <code>createButtonBar</code> are recommended rather than overriding
* this method.
*/
protected Control createContents(Composite parent) {
// create the top level composite for the dialog
Composite composite = new Composite(parent, 0);
GridLayout layout = new GridLayout();
layout.marginHeight = 0;
layout.marginWidth = 0;
layout.verticalSpacing = 0;
composite.setLayout(layout);
composite.setLayoutData(new GridData(GridData.FILL_BOTH));
applyDialogFont(composite);
// initialize the dialog units
initializeDialogUnits(composite);
// create the dialog area and button bar
dialogArea = createDialogArea(composite);
buttonBar = createButtonBar(composite);
return composite;
}
/**
* Creates and returns the contents of the upper part of this dialog (above
* the button bar).
* <p>
* The <code>Dialog</code> implementation of this framework method creates
* and returns a new <code>Composite</code> with standard margins and
* spacing.
* </p>
* <p>
* The returned control's layout data must be an instance of
* <code>GridData</code>. This method must not modify the parent's
* layout.
* </p>
* <p>
* Subclasses must override this method but may call <code>super</code> as
* in the following example:
* </p>
*
* <pre>
* Composite composite = (Composite) super.createDialogArea(parent);
* //add controls to composite as necessary
* return composite;
* </pre>
*
* @param parent
* the parent composite to contain the dialog area
* @return the dialog area control
*/
protected Control createDialogArea(Composite parent) {
// create a composite with standard margins and spacing
Composite composite = new Composite(parent, SWT.NONE);
GridLayout layout = new GridLayout();
layout.marginHeight = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN);
layout.marginWidth = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN);
layout.verticalSpacing = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING);
layout.horizontalSpacing = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING);
composite.setLayout(layout);
composite.setLayoutData(new GridData(GridData.FILL_BOTH));
applyDialogFont(composite);
return composite;
}
/**
* Returns the button created by the method <code>createButton</code> for
* the specified ID as defined on <code>IDialogConstants</code>. If
* <code>createButton</code> was never called with this ID, or if
* <code>createButton</code> is overridden, this method will return
* <code>null</code>.
*
* @param id
* the id of the button to look for
*
* @return the button for the ID or <code>null</code>
*
* @see #createButton(Composite, int, String, boolean)
* @since 2.0
*/
protected Button getButton(int id) {
return (Button) buttons.get(new Integer(id));
}
/**
* Returns the button bar control.
* <p>
* Clients may call this framework method, but should not override it.
* </p>
*
* @return the button bar, or <code>null</code> if the button bar has not
* been created yet
*/
protected Control getButtonBar() {
return buttonBar;
}
/**
* Returns the button created when <code>createButton</code> is called
* with an ID of <code>IDialogConstants.CANCEL_ID</code>. If
* <code>createButton</code> was never called with this parameter, or if
* <code>createButton</code> is overridden, <code>getCancelButton</code>
* will return <code>null</code>.
*
* @return the cancel button or <code>null</code>
*
* @see #createButton(Composite, int, String, boolean)
* @since 2.0
* @deprecated Use <code>getButton(IDialogConstants.CANCEL_ID)</code>
* instead. This method will be removed soon.
*/
protected Button getCancelButton() {
return getButton(IDialogConstants.CANCEL_ID);
}
/**
* Returns the dialog area control.
* <p>
* Clients may call this framework method, but should not override it.
* </p>
*
* @return the dialog area, or <code>null</code> if the dialog area has
* not been created yet
*/
protected Control getDialogArea() {
return dialogArea;
}
/**
* Returns the standard dialog image with the given key. Note that these
* images are managed by the dialog framework, and must not be disposed by
* another party.
*
* @param key
* one of the <code>Dialog.DLG_IMG_* </code> constants
* @return the standard dialog image
*
* NOTE: Dialog does not use the following images in the registry
* DLG_IMG_ERROR DLG_IMG_INFO DLG_IMG_QUESTION DLG_IMG_WARNING
*
* They are now coming directly from SWT, see ImageRegistry. For backwards
* compatibility they are still supported, however new code should use SWT
* for these.
*
* @see Display#getSystemImage(int)
*/
public static Image getImage(String key) {
return JFaceResources.getImageRegistry().get(key);
}
/**
* Returns the button created when <code>createButton</code> is called
* with an ID of <code>IDialogConstants.OK_ID</code>. If
* <code>createButton</code> was never called with this parameter, or if
* <code>createButton</code> is overridden, <code>getOKButton</code>
* will return <code>null</code>.
*
* @return the OK button or <code>null</code>
*
* @see #createButton(Composite, int, String, boolean)
* @since 2.0
* @deprecated Use <code>getButton(IDialogConstants.OK_ID)</code> instead.
* This method will be removed soon.
*/
protected Button getOKButton() {
return getButton(IDialogConstants.OK_ID);
}
/**
* Initializes the computation of horizontal and vertical dialog units based
* on the size of current font.
* <p>
* This method must be called before any of the dialog unit based conversion
* methods are called.
* </p>
*
* @param control
* a control from which to obtain the current font
*/
protected void initializeDialogUnits(Control control) {
// Compute and store a font metric
GC gc = new GC(control);
gc.setFont(JFaceResources.getDialogFont());
fontMetrics = gc.getFontMetrics();
gc.dispose();
}
/**
* Notifies that the ok button of this dialog has been pressed.
* <p>
* The <code>Dialog</code> implementation of this framework method sets
* this dialog's return code to <code>Window.OK</code> and closes the
* dialog. Subclasses may override.
* </p>
*/
protected void okPressed() {
setReturnCode(OK);
close();
}
/**
* Set the layout data of the button to a GridData with appropriate heights
* and widths.
*
* @param button
*/
protected void setButtonLayoutData(Button button) {
GridData data = new GridData(GridData.HORIZONTAL_ALIGN_FILL);
int widthHint = convertHorizontalDLUsToPixels(IDialogConstants.BUTTON_WIDTH);
Point minSize = button.computeSize(SWT.DEFAULT, SWT.DEFAULT, true);
data.widthHint = Math.max(widthHint, minSize.x);
button.setLayoutData(data);
}
/**
* Set the layout data of the button to a FormData with appropriate heights
* and widths.
*
* @param button
*/
protected void setButtonLayoutFormData(Button button) {
FormData data = new FormData();
int widthHint = convertHorizontalDLUsToPixels(IDialogConstants.BUTTON_WIDTH);
Point minSize = button.computeSize(SWT.DEFAULT, SWT.DEFAULT, true);
data.width = Math.max(widthHint, minSize.x);
button.setLayoutData(data);
}
/**
* @see org.eclipse.jface.window.Window#close()
*/
public boolean close() {
if (getShell() != null && !getShell().isDisposed()) {
saveDialogBounds(getShell());
}
boolean returnValue = super.close();
if (returnValue) {
buttons = new HashMap();
buttonBar = null;
dialogArea = null;
}
return returnValue;
}
/**
* Applies the dialog font to all controls that currently have the default
* font.
*
* @param control
* the control to apply the font to. Font will also be applied to
* its children. If the control is <code>null</code> nothing
* happens.
*/
public static void applyDialogFont(Control control) {
if (control == null || dialogFontIsDefault()) {
return;
}
Font dialogFont = JFaceResources.getDialogFont();
applyDialogFont(control, dialogFont);
}
/**
* Sets the dialog font on the control and any of its children if thier font
* is not otherwise set.
*
* @param control
* the control to apply the font to. Font will also be applied to
* its children.
* @param dialogFont
* the dialog font to set
*/
private static void applyDialogFont(Control control, Font dialogFont) {
if (hasDefaultFont(control)) {
control.setFont(dialogFont);
}
if (control instanceof Composite) {
Control[] children = ((Composite) control).getChildren();
for (int i = 0; i < children.length; i++) {
applyDialogFont(children[i], dialogFont);
}
}
}
/**
* Return whether or not this control has the same font as it's default.
*
* @param control
* Control
* @return boolean
*/
private static boolean hasDefaultFont(Control control) {
FontData[] controlFontData = control.getFont().getFontData();
FontData[] defaultFontData = getDefaultFont(control).getFontData();
if (controlFontData.length == defaultFontData.length) {
for (int i = 0; i < controlFontData.length; i++) {
if (controlFontData[i].equals(defaultFontData[i])) {
continue;
}
return false;
}
return true;
}
return false;
}
/**
* Get the default font for this type of control.
*
* @param control
* @return the default font
*/
private static Font getDefaultFont(Control control) {
String fontName = "DEFAULT_FONT_" + control.getClass().getName(); //$NON-NLS-1$
if (JFaceResources.getFontRegistry().hasValueFor(fontName)) {
return JFaceResources.getFontRegistry().get(fontName);
}
Font cached = control.getFont();
control.setFont(null);
Font defaultFont = control.getFont();
control.setFont(cached);
JFaceResources.getFontRegistry().put(fontName,
defaultFont.getFontData());
return defaultFont;
}
/**
* Return whether or not the dialog font is currently the same as the
* default font.
*
* @return boolean if the two are the same
*/
protected static boolean dialogFontIsDefault() {
FontData[] dialogFontData = JFaceResources.getFontRegistry()
.getFontData(JFaceResources.DIALOG_FONT);
FontData[] defaultFontData = JFaceResources.getFontRegistry()
.getFontData(JFaceResources.DEFAULT_FONT);
return Arrays.equals(dialogFontData, defaultFontData);
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.window.Window#create()
*/
public void create() {
super.create();
applyDialogFont(buttonBar);
}
/**
* Get the IDialogBlockedHandler to be used by WizardDialogs and
* ModalContexts.
*
* @return Returns the blockedHandler.
*/
public static IDialogBlockedHandler getBlockedHandler() {
return blockedHandler;
}
/**
* Set the IDialogBlockedHandler to be used by WizardDialogs and
* ModalContexts.
*
* @param blockedHandler
* The blockedHandler for the dialogs.
*/
public static void setBlockedHandler(IDialogBlockedHandler blockedHandler) {
Dialog.blockedHandler = blockedHandler;
}
/**
* Gets the dialog settings that should be used for remembering the bounds of
* of the dialog, according to the dialog bounds strategy.
*
* @return settings the dialog settings used to store the dialog's location
* and/or size, or <code>null</code> if the dialog's bounds should
* never be stored.
*
* @since 3.2
* @see Dialog#getDialogBoundsStrategy()
*/
protected IDialogSettings getDialogBoundsSettings() {
return null;
}
/**
* Get the integer constant that describes the strategy for persisting the
* dialog bounds. This strategy is ignored if the implementer does not also
* specify the dialog settings for storing the bounds in
* Dialog.getDialogBoundsSettings().
*
* @return the constant describing the strategy for persisting the dialog
* bounds.
*
* @since 3.2
* @see Dialog#DIALOG_PERSISTLOCATION
* @see Dialog#DIALOG_PERSISTSIZE
* @see Dialog#getDialogBoundsSettings()
*/
protected int getDialogBoundsStrategy() {
return DIALOG_PERSISTLOCATION | DIALOG_PERSISTSIZE;
}
/**
* Saves the bounds of the shell in the appropriate dialog settings. The
* bounds are recorded relative to the parent shell, if there is one, or
* display coordinates if there is no parent shell.
*
* @param shell
* The shell whose bounds are to be stored
*
* @since 3.2
*/
private void saveDialogBounds(Shell shell) {
IDialogSettings settings = getDialogBoundsSettings();
if (settings != null) {
Point shellLocation = shell.getLocation();
Point shellSize = shell.getSize();
Shell parent = getParentShell();
if (parent != null) {
Point parentLocation = parent.getLocation();
shellLocation.x -= parentLocation.x;
shellLocation.y -= parentLocation.y;
}
int strategy = getDialogBoundsStrategy();
if ((strategy & DIALOG_PERSISTLOCATION) != 0) {
settings.put(DIALOG_ORIGIN_X, shellLocation.x);
settings.put(DIALOG_ORIGIN_Y, shellLocation.y);
}
if ((strategy & DIALOG_PERSISTSIZE) != 0) {
settings.put(DIALOG_WIDTH, shellSize.x);
settings.put(DIALOG_HEIGHT, shellSize.y);
FontData [] fontDatas = JFaceResources.getDialogFont().getFontData();
if (fontDatas.length > 0) {
settings.put(DIALOG_FONT_DATA, fontDatas[0].toString());
}
}
}
}
/**
* Returns the initial size to use for the shell. Overridden
* to check whether a size has been stored in dialog settings.
* If a size has been stored, it is returned.
*
* @return the initial size of the shell
*
* @since 3.2
* @see #getDialogBoundsSettings()
* @see #getDialogBoundsStrategy()
*/
protected Point getInitialSize() {
Point result = super.getInitialSize();
// Check the dialog settings for a stored size.
if ((getDialogBoundsStrategy() & DIALOG_PERSISTSIZE)!= 0) {
IDialogSettings settings = getDialogBoundsSettings();
if (settings != null) {
// Check that the dialog font matches the font used
// when the bounds was stored. If the font has changed,
// we do not honor the stored settings.
// See https://bugs.eclipse.org/bugs/show_bug.cgi?id=132821
boolean useStoredBounds = true;
String previousDialogFontData = settings.get(DIALOG_FONT_DATA);
// There is a previously stored font, so we will check it.
// Note that if we haven't stored the font before, then we will
// use the stored bounds. This allows restoring of dialog bounds
// that were stored before we started storing the fontdata.
if (previousDialogFontData != null && previousDialogFontData.length() > 0) {
FontData [] fontDatas = JFaceResources.getDialogFont().getFontData();
if (fontDatas.length > 0) {
String currentDialogFontData = fontDatas[0].toString();
useStoredBounds = currentDialogFontData.equalsIgnoreCase(previousDialogFontData);
}
}
if (useStoredBounds) {
try {
// Get the stored width and height.
int width = settings.getInt(DIALOG_WIDTH);
if (width != DIALOG_DEFAULT_BOUNDS) {
result.x = width;
}
int height = settings.getInt(DIALOG_HEIGHT);
if (height != DIALOG_DEFAULT_BOUNDS) {
result.y = height;
}
} catch (NumberFormatException e) {
}
}
}
}
// No attempt is made to constrain the bounds. The default
// constraining behavior in Window will be used.
return result;
}
/**
* Returns the initial location to use for the shell. Overridden
* to check whether the bounds of the dialog have been stored in
* dialog settings. If a location has been stored, it is returned.
*
* @param initialSize
* the initial size of the shell, as returned by
* <code>getInitialSize</code>.
* @return the initial location of the shell
*
* @since 3.2
* @see #getDialogBoundsSettings()
* @see #getDialogBoundsStrategy()
*/
protected Point getInitialLocation(Point initialSize) {
Point result = super.getInitialLocation(initialSize);
if ((getDialogBoundsStrategy() & DIALOG_PERSISTLOCATION)!= 0) {
IDialogSettings settings = getDialogBoundsSettings();
if (settings != null) {
try {
int x = settings.getInt(DIALOG_ORIGIN_X);
int y = settings.getInt(DIALOG_ORIGIN_Y);
result = new Point(x, y);
// The coordinates were stored relative to the parent shell.
// Convert to display coordinates.
Shell parent = getParentShell();
if (parent != null) {
Point parentLocation = parent.getLocation();
result.x += parentLocation.x;
result.y += parentLocation.y;
}
} catch (NumberFormatException e) {
}
}
}
// No attempt is made to constrain the bounds. The default
// constraining behavior in Window will be used.
return result;
}
+
+ /**
+ * Returns a boolean indicating whether the dialog should be
+ * considered resizable when the shell style is initially
+ * set.
+ *
+ * This method is used to ensure that all style
+ * bits appropriate for resizable dialogs are added to the
+ * shell style. Individual dialogs may always set the shell
+ * style to ensure that a dialog is resizable, but using this
+ * method ensures that resizable dialogs will be created with
+ * the same set of style bits.
+ *
+ * Style bits will never be removed based on the return value
+ * of this method. For example, if a dialog returns
+ * <code>false</code>, but also sets a style bit for a
+ * SWT.RESIZE border, the style bit will be honored.
+ *
+ * @return a boolean indicating whether the dialog is
+ * resizable and should have the default style bits for
+ * resizable dialogs
+ *
+ * @since 3.4
+ */
+ protected boolean isResizable() {
+ return false;
+ }
}
| false | false | null | null |
diff --git a/core/src/main/java/org/apache/mahout/clustering/VectorModelClassifier.java b/core/src/main/java/org/apache/mahout/clustering/VectorModelClassifier.java
index f2fcc5c92..0e3ed37b7 100644
--- a/core/src/main/java/org/apache/mahout/clustering/VectorModelClassifier.java
+++ b/core/src/main/java/org/apache/mahout/clustering/VectorModelClassifier.java
@@ -1,57 +1,86 @@
+/* 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.mahout.clustering;
import java.util.ArrayList;
import java.util.List;
import org.apache.mahout.classifier.AbstractVectorClassifier;
import org.apache.mahout.clustering.fuzzykmeans.FuzzyKMeansClusterer;
import org.apache.mahout.clustering.fuzzykmeans.SoftCluster;
import org.apache.mahout.math.DenseVector;
import org.apache.mahout.math.Vector;
import org.apache.mahout.math.VectorWritable;
import org.apache.mahout.math.function.TimesFunction;
+/**
+ * This classifier works with any of the clustering Models. It is initialized with
+ * a list of compatible Models and thereafter it can classify any new Vector into
+ * one or more of the Models based upon the pdf() function which each Model supports.
+ */
public class VectorModelClassifier extends AbstractVectorClassifier {
private final List<Model<VectorWritable>> models;
public VectorModelClassifier(List<Model<VectorWritable>> models) {
this.models = models;
}
+ /* (non-Javadoc)
+ * @see org.apache.mahout.classifier.AbstractVectorClassifier#classify(org.apache.mahout.math.Vector)
+ */
@Override
public Vector classify(Vector instance) {
Vector pdfs = new DenseVector(models.size());
if (models.get(0) instanceof SoftCluster) {
List<SoftCluster> clusters = new ArrayList<SoftCluster>();
List<Double> distances = new ArrayList<Double>();
for (Model<VectorWritable> model : models) {
SoftCluster sc = (SoftCluster) model;
clusters.add(sc);
distances.add(sc.getMeasure().distance(instance, sc.getCenter()));
}
return new FuzzyKMeansClusterer().computePi(clusters, distances);
} else {
int i = 0;
for (Model<VectorWritable> model : models) {
pdfs.set(i++, model.pdf(new VectorWritable(instance)));
}
return pdfs.assign(new TimesFunction(), 1.0 / pdfs.zSum());
}
}
+ /* (non-Javadoc)
+ * @see org.apache.mahout.classifier.AbstractVectorClassifier#classifyScalar(org.apache.mahout.math.Vector)
+ */
@Override
public double classifyScalar(Vector instance) {
if (models.size() == 2) {
double pdf0 = models.get(0).pdf(new VectorWritable(instance));
double pdf1 = models.get(1).pdf(new VectorWritable(instance));
return pdf0 / (pdf0 + pdf1);
}
throw new IllegalStateException();
}
+ /* (non-Javadoc)
+ * @see org.apache.mahout.classifier.AbstractVectorClassifier#numCategories()
+ */
@Override
public int numCategories() {
return models.size();
}
}
diff --git a/core/src/main/java/org/apache/mahout/clustering/kmeans/KMeansMapper.java b/core/src/main/java/org/apache/mahout/clustering/kmeans/KMeansMapper.java
index 22b6f8a18..c1bab8c3a 100644
--- a/core/src/main/java/org/apache/mahout/clustering/kmeans/KMeansMapper.java
+++ b/core/src/main/java/org/apache/mahout/clustering/kmeans/KMeansMapper.java
@@ -1,85 +1,85 @@
/**
* 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.mahout.clustering.kmeans;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.WritableComparable;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.mahout.clustering.ClusterObservations;
import org.apache.mahout.common.distance.DistanceMeasure;
import org.apache.mahout.math.VectorWritable;
public class KMeansMapper extends Mapper<WritableComparable<?>, VectorWritable, Text, ClusterObservations> {
private KMeansClusterer clusterer;
private final List<Cluster> clusters = new ArrayList<Cluster>();
@Override
protected void map(WritableComparable<?> key, VectorWritable point, Context context)
throws IOException, InterruptedException {
this.clusterer.emitPointToNearestCluster(point.get(), this.clusters, context);
}
@Override
protected void setup(Context context) throws IOException, InterruptedException {
super.setup(context);
Configuration conf = context.getConfiguration();
try {
ClassLoader ccl = Thread.currentThread().getContextClassLoader();
DistanceMeasure measure = ccl.loadClass(conf.get(KMeansConfigKeys.DISTANCE_MEASURE_KEY))
.asSubclass(DistanceMeasure.class).newInstance();
measure.configure(conf);
this.clusterer = new KMeansClusterer(measure);
String clusterPath = conf.get(KMeansConfigKeys.CLUSTER_PATH_KEY);
if ((clusterPath != null) && (clusterPath.length() > 0)) {
KMeansUtil.configureWithClusterInfo(new Path(clusterPath), clusters);
if (clusters.isEmpty()) {
- throw new IllegalStateException("Cluster is empty!");
+ throw new IllegalStateException("No clusters found. Check your -c path.");
}
}
} catch (ClassNotFoundException e) {
throw new IllegalStateException(e);
} catch (IllegalAccessException e) {
throw new IllegalStateException(e);
} catch (InstantiationException e) {
throw new IllegalStateException(e);
}
}
/**
* Configure the mapper by providing its clusters. Used by unit tests.
*
* @param clusters
* a List<Cluster>
* @param measure TODO
*/
void setup(Collection<Cluster> clusters, DistanceMeasure measure) {
this.clusters.clear();
this.clusters.addAll(clusters);
this.clusterer = new KMeansClusterer(measure);
}
}
| false | false | null | null |
diff --git a/org.jrebirth/analyzer/src/main/java/org/jrebirth/analyzer/command/DisplayInfoPropertiesCommand.java b/org.jrebirth/analyzer/src/main/java/org/jrebirth/analyzer/command/DisplayInfoPropertiesCommand.java
index 4afdf793..9e790ab4 100644
--- a/org.jrebirth/analyzer/src/main/java/org/jrebirth/analyzer/command/DisplayInfoPropertiesCommand.java
+++ b/org.jrebirth/analyzer/src/main/java/org/jrebirth/analyzer/command/DisplayInfoPropertiesCommand.java
@@ -1,49 +1,52 @@
/**
* Get more info at : www.jrebirth.org .
* Copyright JRebirth.org © 2011-2013
* Contact : [email protected]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.jrebirth.analyzer.command;
-import org.jrebirth.core.command.AbstractUICommand;
+import org.jrebirth.core.command.AbstractSingleCommand;
+import org.jrebirth.core.concurrent.RunInto;
+import org.jrebirth.core.concurrent.RunType;
import org.jrebirth.core.exception.CoreException;
import org.jrebirth.core.wave.Wave;
/**
* The class <strong>DisplayInfoPropertiesCommand</strong>.
*
* @author Sébastien Bordes
*/
-public class DisplayInfoPropertiesCommand extends AbstractUICommand {
+@RunInto(RunType.JAT)
+public class DisplayInfoPropertiesCommand extends AbstractSingleCommand {
@Override
public void ready() throws CoreException {
// TODO Auto-generated method stub
}
@Override
protected void execute(final Wave wave) {
// TODO Auto-generated method stub
}
@Override
protected void processAction(final Wave wave) {
// TODO Auto-generated method stub
}
}
| false | false | null | null |
diff --git a/src/core/data/SvgFormat.java b/src/core/data/SvgFormat.java
index 2eb8ad0f..70d51b4e 100644
--- a/src/core/data/SvgFormat.java
+++ b/src/core/data/SvgFormat.java
@@ -1,341 +1,345 @@
package data;
import java.util.HashSet;
import java.util.Set;
import org.eclipse.swt.graphics.RGB;
import org.jdom.DocType;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.Namespace;
public class SvgFormat
{
static final Namespace nsSVG = Namespace.getNamespace("http://www.w3.org/2000/svg");
static Element defs;
static Set<String> markers;
static Document createJdom (GmmlData data) throws ConverterException
{
Document doc = new Document();
defs = new Element("defs", nsSVG);
markers = new HashSet<String>();
Element root = new Element("svg");
root.setNamespace(nsSVG);
doc.setRootElement(root);
DocType dt = new DocType("svg", "-//W3C//DTD SVG 1.1//EN", "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd");
doc.setDocType(dt);
root.addContent(defs);
for (GmmlDataObject o : data.getDataObjects())
{
addElement(root, o);
}
return doc;
}
static public void addElement (Element root, GmmlDataObject o) throws ConverterException
{
switch (o.getObjectType())
{
case ObjectType.SHAPE:
mapShape(root, o);
break;
case ObjectType.DATANODE:
mapDataNode(root, o);
break;
case ObjectType.LINE:
mapLine(root, o);
break;
case ObjectType.LABEL:
mapLabel(root, o);
break;
case ObjectType.MAPPINFO:
mapInfo(root, o);
break;
}
}
static void mapInfo(Element root, GmmlDataObject o) {
root.setAttribute("width", "" + toPixel(o.getMBoardWidth()));
root.setAttribute("height", "" + toPixel(o.getMBoardHeight()));
String[][] text = new String[][] {
{"Name: ", o.getMapInfoName()},
{"Maintained by: ", o.getMaintainer()},
{"Email: ", o.getEmail()},
{"Availability: ", o.getCopyright()},
{"Last modified: ", o.getLastModified()},
{"Organism: ", o.getOrganism()},
{"Data Source: ", o.getDataSource()}};
double fsize = toPixel(o.getMFontSize()) + 2;//TODO: find out why smaller in SVG
Element e = new Element("text", nsSVG);
e.setAttribute("x", "" + toPixel(o.getMLeft()));
e.setAttribute("y", "" + toPixel(o.getMTop()));
e.setAttribute("font-size", "" + fsize);
e.setAttribute("font-family", "times new roman");
for(int i = 0; i < text.length; i++) {
if(text[i][1] == null || text[i][1].equals("")) continue;
Element l = new Element("tspan", nsSVG);
l.setAttribute("x", "" + toPixel(o.getMLeft()));
l.setAttribute("dy", fsize + "pt");
l.setAttribute("font-weight", "bold");
l.addContent(text[i][0]);
Element v = new Element("tspan", nsSVG);
v.addContent(text[i][1]);
e.addContent(l);
e.addContent(v);
}
root.addContent(e);
}
static void mapLine(Element parent, GmmlDataObject o) {
Element e = new Element("line", nsSVG);
e.setAttribute("x1", "" + toPixel(o.getMStartX()));
e.setAttribute("y1", "" + toPixel(o.getMStartY()));
e.setAttribute("x2", "" + toPixel(o.getMEndX()));
e.setAttribute("y2", "" + toPixel(o.getMEndY()));
e.setAttribute("stroke", rgb2String(o.getColor()));
if(o.getLineStyle() == LineStyle.DASHED) {
e.setAttribute("stroke-dasharray", "5,2");
}
LineType type = o.getLineType();
String id = getColordMarker(type, o.getColor(), markers, defs);
if(type != LineType.LINE) {
e.setAttribute("marker-end", "url(#" + id + ")");
}
parent.addContent(e);
}
static void mapDataNode(Element parent, GmmlDataObject o) {
Element e = new Element("rect", nsSVG);
e.setAttribute("x", "" + toPixel(o.getMLeft()));
e.setAttribute("y", "" + toPixel(o.getMTop()));
e.setAttribute("width", "" + toPixel(o.getMWidth()));
e.setAttribute("height", "" + toPixel(o.getMHeight()));
mapColor(e, o);
parent.addContent(e);
e = createTextElement(o);
e.addContent(o.getTextLabel());
parent.addContent(e);
}
static void mapLabel(Element parent, GmmlDataObject o) {
Element e = createTextElement(o);
e.addContent(o.getTextLabel());
parent.addContent(e);
}
static void mapShape(Element parent, GmmlDataObject o) {
double cx = toPixel(o.getMCenterX());
double cy = toPixel(o.getMCenterY());
double w = toPixel(o.getMWidth());
double h = toPixel(o.getMHeight());
double r = o.getRotation() * 180.0/Math.PI;
Element tr = new Element("g", nsSVG);
tr.setAttribute("transform", "translate(" + cx + ", " + cy + ")");
Element rot = new Element("g", nsSVG);
rot.setAttribute("transform", "rotate(" + r + ")");
Element e = null;
switch (o.getShapeType())
{
case OVAL:
e = new Element("ellipse", nsSVG);
e.setAttribute("cx", "0");
e.setAttribute("cy", "0");
e.setAttribute("rx", "" + toPixel(o.getMWidth()/2));
e.setAttribute("ry", "" + toPixel(o.getMHeight()/2));
break;
case ARC:
e = new Element("path", nsSVG);
e.setAttribute("d", "M " + -w/2 + " 0 " + " a " + w/2 + " " + h/2 + " 0 0 0 " + w + " 0");
break;
case BRACE:
e = new Element("path", nsSVG);
e.setAttribute(
"d", "M " + -w/2 + " " + h/2 + " q 0 " + -h/2 + " " + h/2 + " " + -h/2 + " " +
"L " + -h/2 + " 0 " +
"Q 0 0 0 " + -h/2 + " " +
"Q 0 0 " + h/2 + " 0 " +
"L " + (w/2 - h/2) + " 0 " +
"q " + h/2 + " 0 " + h/2 + " " + h/2
);
break;
default:
e = new Element("rect", nsSVG);
e.setAttribute("x", "" + -w/2);
e.setAttribute("y", "" + -h/2);
e.setAttribute("width", "" + toPixel(o.getMWidth()));
e.setAttribute("height", "" + toPixel(o.getMHeight()));
break;
}
mapColor(e, o);
rot.addContent(e);
tr.addContent(rot);
parent.addContent(tr);
}
static void mapColor(Element e, GmmlDataObject o) {
e.setAttribute("stroke", rgb2String(o.getColor()));
if(o.isTransparent()) {
e.setAttribute("fill", "none");
} else {
//Ignoring fill-color for now, not supported in PathVisio
//TODO: support fill in PathVisio
//e.setAttribute("fill", rgb2String(o.getFillColor()));
- e.setAttribute("fill", "none");
+ if(o.getObjectType() == ObjectType.DATANODE) {
+ e.setAttribute("fill", "white");
+ } else {
+ e.setAttribute("fill", "none");
+ }
}
}
static String rgb2String(RGB rgb) {
return "rgb(" + rgb.red + "," + rgb.green + "," + rgb.blue + ")";
}
static int toPixel(double coordinate) {
return (int)(coordinate * 1/15);
}
static Element createTextElement(GmmlDataObject o) {
Element e = new Element("text", nsSVG);
e.setAttribute("x", "" + toPixel(o.getMCenterX()));
e.setAttribute("y", "" + (toPixel(o.getMCenterY()) + toPixel(o.getMFontSize())));
e.setAttribute("font-family", o.getFontName() + ".ttf");
e.setAttribute("font-size",toPixel(o.getMFontSize()) + "pt");
e.setAttribute("text-anchor", "middle");
//e.setAttribute("alignment-baseline", "middle"); //Not supported by firefox
e.setAttribute("dy", "-" + toPixel((1.0/3) * o.getMFontSize()) + "pt"); //Instead of alignment-baseline
if(o.isBold()) e.setAttribute("font-weight", "bold");
if(o.isItalic()) e.setAttribute("font-style", "italic");
if(o.isStrikethru()) e.setAttribute("text-decoration", "line-through");
if(o.isUnderline()) e.setAttribute("text-decoration", "underline");
e.setAttribute("fill", rgb2String(o.getColor()));
return e;
}
static String getColordMarker(LineType type, RGB color, Set markers, Element defs) {
Element marker = null;
String id = type.getGpmlName() + color.toString().hashCode();
if(markers.contains(id)) return id;
String c = rgb2String(color);
switch(type) {
case ARROW:
marker = new Element("marker", nsSVG);
marker.setAttribute("id", id);
marker.setAttribute("viewBox", "0 0 10 10");
marker.setAttribute("orient", "auto");
marker.setAttribute("refX", "10");
marker.setAttribute("refY", "5");
marker.setAttribute("markerWidth", "10");
marker.setAttribute("markerHeight", "15");
Element e = new Element("path", nsSVG);
e.setAttribute("d", "M 0 0 L 10 5 L 0 10 z");
e.setAttribute("stroke", c);
e.setAttribute("fill", c);
marker.addContent(e);
break;
case TBAR:
marker = new Element("marker", nsSVG);
marker.setAttribute("id", id);
marker.setAttribute("viewBox", "0 0 1 15");
marker.setAttribute("orient", "auto");
marker.setAttribute("refX", "1");
marker.setAttribute("refY", "8");
marker.setAttribute("markerWidth", "5");
marker.setAttribute("markerHeight", "20");
e = new Element("rect", nsSVG);
e.setAttribute("x", "1");
e.setAttribute("y", "1");
e.setAttribute("width", "1");
e.setAttribute("height", "15");
e.setAttribute("stroke", c);
e.setAttribute("fill", c);
marker.addContent(e);
break;
case LIGAND_ROUND:
marker = new Element("marker", nsSVG);
marker.setAttribute("id", id);
marker.setAttribute("viewBox", "0 0 10 10");
marker.setAttribute("orient", "auto");
marker.setAttribute("refX", "10");
marker.setAttribute("refY", "5");
marker.setAttribute("markerWidth", "10");
marker.setAttribute("markerHeight", "10");
e = new Element("ellipse", nsSVG);
e.setAttribute("cx", "5");
e.setAttribute("cy", "5");
e.setAttribute("rx", "5");
e.setAttribute("ry", "5");
e.setAttribute("stroke", c);
e.setAttribute("fill", c);
marker.addContent(e);
break;
case RECEPTOR_ROUND:
marker = new Element("marker", nsSVG);
marker.setAttribute("id", id);
marker.setAttribute("viewBox", "0 0 10 10");
marker.setAttribute("orient", "auto");
marker.setAttribute("refX", "5");
marker.setAttribute("refY", "5");
marker.setAttribute("markerWidth", "15");
marker.setAttribute("markerHeight", "15");
e = new Element("path", nsSVG);
e.setAttribute("d", "M 10 0 A 5 5 0 0 0 10 10");
e.setAttribute("stroke", c);
e.setAttribute("fill", "none");
marker.addContent(e);
break;
case RECEPTOR_SQUARE:
marker = new Element("marker", nsSVG);
marker.setAttribute("id", id);
marker.setAttribute("viewBox", "0 0 10 15");
marker.setAttribute("orient", "auto");
marker.setAttribute("refX", "1");
marker.setAttribute("refY", "7.5");
marker.setAttribute("markerWidth", "15");
marker.setAttribute("markerHeight", "15");
e = new Element("path", nsSVG);
e.setAttribute("d", "M 10 0 L 0 0 L 0 15 L 10 15");
e.setAttribute("stroke", c);
e.setAttribute("fill", "none");
marker.addContent(e);
break;
case LIGAND_SQUARE:
marker = new Element("marker", nsSVG);
marker.setAttribute("id", id);
marker.setAttribute("viewBox", "0 0 10 15");
marker.setAttribute("orient", "auto");
marker.setAttribute("refX", "10");
marker.setAttribute("refY", "7.5");
marker.setAttribute("markerWidth", "10");
marker.setAttribute("markerHeight", "10");
e = new Element("rect", nsSVG);
e.setAttribute("x", "1");
e.setAttribute("y", "1");
e.setAttribute("width", "10");
e.setAttribute("height", "15");
e.setAttribute("stroke", c);
e.setAttribute("fill", c);
marker.addContent(e);
break;
}
if(marker != null) {
defs.addContent(marker);
markers.add(id);
return id;
} else {
return null;
}
}
}
diff --git a/src/test/data/Test.java b/src/test/data/Test.java
index fce1f0ce..c84f61e2 100644
--- a/src/test/data/Test.java
+++ b/src/test/data/Test.java
@@ -1,369 +1,369 @@
// PathVisio,
// a tool for data visualization and analysis using Biological Pathways
// Copyright 2006-2007 BiGCaT Bioinformatics
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
package data;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import junit.framework.TestCase;
public class Test extends TestCase implements GmmlListener {
GmmlData data;
GmmlDataObject o;
List<GmmlEvent> received;
GmmlDataObject l;
public void setUp()
{
data = new GmmlData();
data.addListener(this);
o = new GmmlDataObject(ObjectType.DATANODE);
received = new ArrayList<GmmlEvent>();
o.addListener(this);
data.add (o);
l = new GmmlDataObject(ObjectType.LINE);
data.add(l);
received.clear();
}
public void testFields ()
{
o.setMCenterX(1.0);
assertEquals ("test set/get CenterX", 1.0, o.getMCenterX(), 0.0001);
assertEquals ("Setting CenterX should generate single event", received.size(), 1);
assertEquals ("test getProperty()", 1.0, (Double)o.getProperty(PropertyType.CENTERX), 0.0001);
try
{
o.setProperty(PropertyType.CENTERX, null);
fail("Setting centerx property to null should generate exception");
}
catch (Exception e) {}
// however, you should be able to set graphRef to null
assertNull ("graphref null by default", l.getStartGraphRef());
l.setStartGraphRef(null);
assertNull ("can set graphRef to null", l.getStartGraphRef());
}
public void testProperties()
{
try
{
o.setProperty(null, new Object());
fail("Setting null property should generate exception");
}
catch (Exception e) {}
}
public void testColor()
{
try
{
o.setColor(null);
fail("Shouldn't be able to set color null");
}
catch (Exception e) {}
}
public void testObjectType()
{
assertEquals ("getObjectType() test", o.getObjectType(), ObjectType.DATANODE);
try
{
new GmmlDataObject (-1);
fail ("Shouldn't be able to set invalid object type");
}
catch (IllegalArgumentException e)
{
}
try
{
new GmmlDataObject (100);
fail ("Shouldn't be able to set invalid object type");
}
catch (IllegalArgumentException e)
{
}
}
public void testParent()
{
// remove
data.remove (o);
assertNull ("removing object set parents null", o.getParent());
assertEquals (received.size(), 1);
assertEquals ("Event type should be DELETED", received.get(0).getType(), GmmlEvent.DELETED);
// re-add
data.add(o);
assertEquals ("adding sets parent", o.getParent(), data);
assertEquals (received.size(), 2);
assertEquals ("Event type should be ADDED", received.get(1).getType(), GmmlEvent.ADDED);
}
/**
* Test graphRef's and graphId's
*
*/
public void testRef()
{
assertNull ("query non-existing list of ref", data.getReferringObjects("abcde"));
// create link
o.setGraphId("1");
l.setStartGraphRef("1");
- assertTrue ("reference created", data.getReferringObjects("1").contains(l));
+ assertTrue ("reference created", data.getReferringObjects("1").contains(l.getMStart()));
l.setStartGraphRef("2");
assertNull ("reference removed", data.getReferringObjects("1"));
GmmlDataObject o2 = new GmmlDataObject(ObjectType.DATANODE);
data.add (o2);
// create link in opposite order
o.setGraphId("2");
l.setEndGraphRef("2");
- assertTrue ("reference created (2)", data.getReferringObjects("2").contains(l));
+ assertTrue ("reference created (2)", data.getReferringObjects("2").contains(l.getMEnd()));
}
/**
* Test for maintaining list of unique id's per GmmlData.
*
*/
public void testRefUniq()
{
// test for uniqueness
o.setGraphId("1");
GmmlDataObject o2 = new GmmlDataObject(ObjectType.DATANODE);
data.add (o2);
try
{
// try setting the same id again
o2.setGraphId("1");
fail("shouldn't be able to set the same id twice");
}
catch (IllegalArgumentException e) {}
// test random id
String x = data.getUniqueId();
try
{
// test that we can use it as unique id
o.setGraphId(x);
assertEquals (x, o.getGraphId());
// test that we can't use the same id twice
o2.setGraphId(x);
fail("shouldn't be able to set the same id twice");
}
catch (IllegalArgumentException e) {}
// test that a second random id is unique again
x = data.getUniqueId();
o2.setGraphId(x);
assertEquals (x, o2.getGraphId());
// test setting id first, then parent
GmmlDataObject o3 = new GmmlDataObject(ObjectType.DATANODE);
x = data.getUniqueId();
o3.setGraphId(x);
data.add (o3);
assertEquals (o3.getGraphId(), x);
try
{
GmmlDataObject o4 = new GmmlDataObject(ObjectType.DATANODE);
// try setting the same id again
o4.setGraphId(x);
data.add (o4);
fail("shouldn't be able to set the same id twice");
}
catch (IllegalArgumentException e) {}
}
public void testRef2()
{
o.setGraphId("1");
GmmlDataObject o2 = new GmmlDataObject(ObjectType.DATANODE);
// note: parent not set yet!
o2.setGraphId ("3");
data.add(o2); // reference should now be created
assertNull ("default endGraphRef is null", l.getEndGraphRef());
l.setEndGraphRef("3");
- assertTrue ("reference created through adding", data.getReferringObjects("3").contains(l));
+ assertTrue ("reference created through adding", data.getReferringObjects("3").contains(l.getMEnd()));
}
public void testXml() throws IOException, ConverterException
{
data.readFromXml(new File("testData/test.gpml"), false);
assertTrue ("Loaded a bunch of objects from xml", data.getDataObjects().size() > 20);
File temp = File.createTempFile ("data.test", ".gpml");
temp.deleteOnExit();
data.writeToXml(temp, false);
try {
data.readFromXml(new File ("testData/test.mapp"), false);
fail ("Loading wrong format, Exception expected");
} catch (Exception e) {}
}
/**
* test exporting of .mapp (genmapp format)
* Note: this test is only run whenever os.name starts with Windows
*/
public void testMapp() throws IOException, ConverterException
{
if (System.getProperty("os.name").startsWith("Windows"))
{
data.readFromMapp(new File("testData/test.mapp"));
assertTrue ("Loaded a bunch of objects from mapp", data.getDataObjects().size() > 20);
File temp = File.createTempFile ("data.test", ".mapp");
temp.deleteOnExit();
data.writeToMapp(temp);
try {
data.readFromMapp(new File ("testData/test.gpml"));
fail ("Loading wrong format, Exception expected");
} catch (Exception e) {}
}
}
/**
* test exporting of .svg
*/
public void testSvg() throws IOException, ConverterException
{
data.readFromXml(new File("testData/test.gpml"), false);
assertTrue ("Loaded a bunch of objects from xml", data.getDataObjects().size() > 20);
File temp = File.createTempFile ("data.test", ".svg");
temp.deleteOnExit();
data.writeToSvg(temp);
}
/**
* Test that there is one and only one MAPPINFO object
*
*/
public void testMappInfo()
{
GmmlDataObject mi;
mi = data.getMappInfo();
assertEquals (mi.getObjectType(), ObjectType.MAPPINFO);
assertTrue (data.getDataObjects().contains(mi));
assertNotNull (mi);
try
{
mi = new GmmlDataObject(ObjectType.MAPPINFO);
data.add (mi);
fail("data should already have a MAPPINFO and shouldn't accept more");
}
catch (IllegalArgumentException e) {}
mi = data.getMappInfo();
try
{
data.remove(mi);
fail ("Shouldn't be able to remove mappinfo object!");
}
catch (IllegalArgumentException e) {}
}
/**
* Test that there is one and only one MAPPINFO object
*
*/
public void testInfoBox()
{
GmmlDataObject ib;
ib = data.getInfoBox();
assertTrue (data.getDataObjects().contains(ib));
assertNotNull (ib);
assertEquals (ib.getObjectType(), ObjectType.INFOBOX);
try
{
ib = new GmmlDataObject(ObjectType.INFOBOX);
data.add (ib);
fail("data should already have a MAPPINFO and shouldn't accept more");
}
catch (IllegalArgumentException e) {}
ib = data.getMappInfo();
try
{
data.remove(ib);
fail ("Shouldn't be able to remove mappinfo object!");
}
catch (IllegalArgumentException e) {}
}
public void testValidator() throws IOException
{
File tmp = File.createTempFile("test", ".gpml");
o.setMCenterX(50.0);
o.setMCenterY(50.0);
o.setInitialSize();
o.setGraphId(data.getUniqueId());
GmmlDataObject o2 = new GmmlDataObject (ObjectType.LINE);
o2.setMStartX(10.0);
o2.setMStartY(10.0);
o2.setInitialSize();
data.add(o2);
GmmlDataObject o3 = new GmmlDataObject (ObjectType.LABEL);
o3.setMCenterX(100.0);
o3.setMCenterY(50);
o3.setGraphId(data.getUniqueId());
data.add(o3);
GmmlDataObject mi;
mi = data.getMappInfo();
try
{
data.writeToXml(tmp, false);
} catch (ConverterException e)
{
e.printStackTrace();
fail ("Exception while writing newly created pathway");
}
}
// event listener
// receives events generated on objects o and data
public void gmmlObjectModified(GmmlEvent e)
{
// store all received events
received.add(e);
}
}
| false | false | null | null |
diff --git a/org.eclipse.mylyn.monitor.core/src/org/eclipse/mylyn/monitor/core/DateUtil.java b/org.eclipse.mylyn.monitor.core/src/org/eclipse/mylyn/monitor/core/DateUtil.java
index fde35919..c004df4a 100644
--- a/org.eclipse.mylyn.monitor.core/src/org/eclipse/mylyn/monitor/core/DateUtil.java
+++ b/org.eclipse.mylyn.monitor.core/src/org/eclipse/mylyn/monitor/core/DateUtil.java
@@ -1,167 +1,169 @@
/*******************************************************************************
* Copyright (c) 2004, 2007 Mylyn project committers 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
*******************************************************************************/
package org.eclipse.mylyn.monitor.core;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
/**
* Used for formatting dates.
*
* @author Mik Kersten
* @since 2.0
*/
public class DateUtil {
- private static final SimpleDateFormat formatter = new SimpleDateFormat();
-
public static String getFormattedDate() {
return getFormattedDate(Calendar.getInstance());
}
public static String getFormattedDate(Calendar calendar) {
try {
int monthInt = (calendar.get(Calendar.MONTH) + 1);
String month = "" + monthInt;
if (monthInt < 10)
month = "0" + month;
int dateInt = (calendar.get(Calendar.DATE));
String date = "" + dateInt;
if (dateInt < 10)
date = "0" + date;
return calendar.get(Calendar.YEAR) + "-" + month + "-" + date;
} catch (Exception e) {
return "<unresolved date>";
}
}
public static String getFormattedTime() {
return Calendar.getInstance().get(Calendar.HOUR_OF_DAY) + ":" + Calendar.getInstance().get(Calendar.MINUTE)
+ ":" + Calendar.getInstance().get(Calendar.SECOND);
}
public static String getFormattedDateTime(long time) {
// XXX: need to get UTC times
Calendar c = Calendar.getInstance();
c.setTimeInMillis(time);
return getFormattedDate() + "-" + c.get(Calendar.HOUR) + "-" + c.get(Calendar.MINUTE) + "-"
+ c.get(Calendar.SECOND);
}
/** Returns the time in the format: HHH:MM */
public static String getFormattedDurationShort(long duration) {
if (duration <= 0) {
return "00:00";
}
long totalMinutes = duration / 1000 / 60;
long remainderMinutes = totalMinutes % 60;
long totalHours = totalMinutes / 60;
String hourString = "" + totalHours;
String minuteString = "" + remainderMinutes;
if (totalHours < 10) {
hourString = "0" + hourString;
}
if (remainderMinutes < 10) {
minuteString = "0" + remainderMinutes;
}
return hourString + ":" + minuteString;
}
public static String getFormattedDuration(long duration, boolean includeSeconds) {
long seconds = duration / 1000;
long minutes = 0;
long hours = 0;
// final long SECOND = 1000;
final long MIN = 60;
final long HOUR = MIN * 60;
String formatted = "";
String hour = "";
String min = "";
String sec = "";
if (seconds >= HOUR) {
hours = seconds / HOUR;
if (hours == 1) {
hour = hours + " hour ";
} else if (hours > 1) {
hour = hours + " hours ";
}
seconds -= hours * HOUR;
minutes = seconds / MIN;
if (minutes == 1) {
min = minutes + " minute ";
} else if (minutes != 1) {
min = minutes + " minutes ";
}
seconds -= minutes * MIN;
if (seconds == 1) {
sec = seconds + " second";
} else if (seconds > 1) {
sec = seconds + " seconds";
}
formatted += hour + min;
if (includeSeconds)
formatted += sec;
} else if (seconds >= MIN) {
minutes = seconds / MIN;
if (minutes == 1) {
min = minutes + " minute ";
} else if (minutes != 1) {
min = minutes + " minutes ";
}
seconds -= minutes * MIN;
if (seconds == 1) {
sec = seconds + " second";
} else if (seconds > 1) {
sec = seconds + " seconds";
}
formatted += min;
if (includeSeconds)
formatted += sec;
} else {
if (seconds == 1) {
sec = seconds + " second";
} else if (seconds > 1) {
sec = seconds + " seconds";
}
if (includeSeconds)
formatted += sec;
}
return formatted;
}
public static String getZoneFormattedDate(TimeZone zone, Date date, String dateFormat) {
+ SimpleDateFormat formatter = new SimpleDateFormat();
+
formatter.setTimeZone(zone);
formatter.applyPattern(dateFormat);
return formatter.format(date);
}
public static String getFormattedDate(Date date, String format) {
+ SimpleDateFormat formatter = new SimpleDateFormat();
+
formatter.setTimeZone(TimeZone.getDefault());
formatter.applyPattern(format);
return formatter.format(date);
}
public static TimeZone getTimeZone(String zoneId) {
TimeZone timeZone = TimeZone.getTimeZone(zoneId);
if (!timeZone.getID().equals(zoneId)) {
StatusHandler.log("Specified time zone not available, using " + timeZone.getDisplayName()
+ ". Check repository settings.", DateUtil.class);
}
return timeZone;
}
}
| false | false | null | null |