diff
stringlengths 262
553k
| is_single_chunk
bool 2
classes | is_single_function
bool 1
class | buggy_function
stringlengths 20
391k
| fixed_function
stringlengths 0
392k
|
---|---|---|---|---|
diff --git a/gremlin/gremlin-test/src/main/java/com/tinkerpop/gremlin/test/ComplianceTest.java b/gremlin/gremlin-test/src/main/java/com/tinkerpop/gremlin/test/ComplianceTest.java
index a9599724b..bb4e21c4d 100644
--- a/gremlin/gremlin-test/src/main/java/com/tinkerpop/gremlin/test/ComplianceTest.java
+++ b/gremlin/gremlin-test/src/main/java/com/tinkerpop/gremlin/test/ComplianceTest.java
@@ -1,41 +1,41 @@
package com.tinkerpop.gremlin.test;
import org.junit.Test;
import java.util.stream.Stream;
import static junit.framework.TestCase.fail;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
/**
* @author Marko A. Rodriguez (http://markorodriguez.com)
* @author Stephen Mallette (http://stephen.genoprime.com)
*/
public class ComplianceTest {
@Test
public void testCompliance() {
assertTrue(true);
}
public static void testCompliance(final Class testClass) {
// get the base class from gremlin-test
final Class gremlinTestBaseClass = testClass.getSuperclass();
assertNotNull(gremlinTestBaseClass);
// get the test methods from base and validate that they are somehow implemented in the parent class
// and have a junit @Test annotation.
- assertTrue(Stream.of(gremlinTestBaseClass.getDeclaredMethods())
+ Stream.of(gremlinTestBaseClass.getDeclaredMethods())
.map(m -> {
try {
assertNotNull(testClass.getDeclaredMethod(m.getName()).getAnnotation(Test.class));
return true;
} catch (final NoSuchMethodException e) {
fail(String.format("Base test method from gremlin-test [%s] not found in test implementation %s",
m.getName(), testClass));
return false;
}
- }).reduce(true, (a, b) -> a && b));
+ }).count();
}
}
| false | true | public static void testCompliance(final Class testClass) {
// get the base class from gremlin-test
final Class gremlinTestBaseClass = testClass.getSuperclass();
assertNotNull(gremlinTestBaseClass);
// get the test methods from base and validate that they are somehow implemented in the parent class
// and have a junit @Test annotation.
assertTrue(Stream.of(gremlinTestBaseClass.getDeclaredMethods())
.map(m -> {
try {
assertNotNull(testClass.getDeclaredMethod(m.getName()).getAnnotation(Test.class));
return true;
} catch (final NoSuchMethodException e) {
fail(String.format("Base test method from gremlin-test [%s] not found in test implementation %s",
m.getName(), testClass));
return false;
}
}).reduce(true, (a, b) -> a && b));
}
| public static void testCompliance(final Class testClass) {
// get the base class from gremlin-test
final Class gremlinTestBaseClass = testClass.getSuperclass();
assertNotNull(gremlinTestBaseClass);
// get the test methods from base and validate that they are somehow implemented in the parent class
// and have a junit @Test annotation.
Stream.of(gremlinTestBaseClass.getDeclaredMethods())
.map(m -> {
try {
assertNotNull(testClass.getDeclaredMethod(m.getName()).getAnnotation(Test.class));
return true;
} catch (final NoSuchMethodException e) {
fail(String.format("Base test method from gremlin-test [%s] not found in test implementation %s",
m.getName(), testClass));
return false;
}
}).count();
}
|
diff --git a/emailsync/src/com/android/emailsync/SyncManager.java b/emailsync/src/com/android/emailsync/SyncManager.java
index e4e155e91..0500837fd 100644
--- a/emailsync/src/com/android/emailsync/SyncManager.java
+++ b/emailsync/src/com/android/emailsync/SyncManager.java
@@ -1,2269 +1,2271 @@
/*
* Copyright (C) 2008-2009 Marc Blank
* Licensed to 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.emailsync;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.NetworkInfo.State;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.os.Process;
import android.os.RemoteException;
import android.provider.CalendarContract;
import android.provider.CalendarContract.Calendars;
import android.provider.CalendarContract.Events;
import android.provider.ContactsContract;
import android.util.Log;
import com.android.emailcommon.TempDirectory;
import com.android.emailcommon.provider.Account;
import com.android.emailcommon.provider.EmailContent;
import com.android.emailcommon.provider.EmailContent.Body;
import com.android.emailcommon.provider.EmailContent.BodyColumns;
import com.android.emailcommon.provider.EmailContent.MailboxColumns;
import com.android.emailcommon.provider.EmailContent.Message;
import com.android.emailcommon.provider.EmailContent.MessageColumns;
import com.android.emailcommon.provider.EmailContent.SyncColumns;
import com.android.emailcommon.provider.HostAuth;
import com.android.emailcommon.provider.Mailbox;
import com.android.emailcommon.provider.Policy;
import com.android.emailcommon.provider.ProviderUnavailableException;
import com.android.emailcommon.service.AccountServiceProxy;
import com.android.emailcommon.service.EmailServiceProxy;
import com.android.emailcommon.service.EmailServiceStatus;
import com.android.emailcommon.service.IEmailServiceCallback.Stub;
import com.android.emailcommon.service.PolicyServiceProxy;
import com.android.emailcommon.utility.EmailAsyncTask;
import com.android.emailcommon.utility.EmailClientConnectionManager;
import com.android.emailcommon.utility.Utility;
import org.apache.http.conn.params.ConnManagerPNames;
import org.apache.http.conn.params.ConnPerRoute;
import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
/**
* The SyncServiceManager handles the lifecycle of various sync adapters used by services that
* cannot rely on the system SyncManager
*
* SyncServiceManager uses ContentObservers to detect changes to accounts, mailboxes, & messages in
* order to maintain proper 2-way syncing of data. (More documentation to follow)
*
*/
public abstract class SyncManager extends Service implements Runnable {
private static final String TAG = "SyncServiceManager";
// The SyncServiceManager's mailbox "id"
public static final int EXTRA_MAILBOX_ID = -1;
public static final int SYNC_SERVICE_MAILBOX_ID = 0;
private static final int SECONDS = 1000;
private static final int MINUTES = 60*SECONDS;
private static final int ONE_DAY_MINUTES = 1440;
private static final int SYNC_SERVICE_HEARTBEAT_TIME = 15*MINUTES;
private static final int CONNECTIVITY_WAIT_TIME = 10*MINUTES;
// Sync hold constants for services with transient errors
private static final int HOLD_DELAY_MAXIMUM = 4*MINUTES;
// Reason codes when SyncServiceManager.kick is called (mainly for debugging)
// UI has changed data, requiring an upsync of changes
public static final int SYNC_UPSYNC = 0;
// A scheduled sync (when not using push)
public static final int SYNC_SCHEDULED = 1;
// Mailbox was marked push
public static final int SYNC_PUSH = 2;
// A ping (EAS push signal) was received
public static final int SYNC_PING = 3;
// Misc.
public static final int SYNC_KICK = 4;
// A part request (attachment load, for now) was sent to SyncServiceManager
public static final int SYNC_SERVICE_PART_REQUEST = 5;
// Requests >= SYNC_CALLBACK_START generate callbacks to the UI
public static final int SYNC_CALLBACK_START = 6;
// startSync was requested of SyncServiceManager (other than due to user request)
public static final int SYNC_SERVICE_START_SYNC = SYNC_CALLBACK_START + 0;
// startSync was requested of SyncServiceManager (due to user request)
public static final int SYNC_UI_REQUEST = SYNC_CALLBACK_START + 1;
protected static final String WHERE_IN_ACCOUNT_AND_PUSHABLE =
MailboxColumns.ACCOUNT_KEY + "=? and type in (" + Mailbox.TYPE_INBOX + ','
+ Mailbox.TYPE_EAS_ACCOUNT_MAILBOX + ',' + Mailbox.TYPE_CONTACTS + ','
+ Mailbox.TYPE_CALENDAR + ')';
protected static final String WHERE_IN_ACCOUNT_AND_TYPE_INBOX =
MailboxColumns.ACCOUNT_KEY + "=? and type = " + Mailbox.TYPE_INBOX ;
private static final String WHERE_MAILBOX_KEY = Message.MAILBOX_KEY + "=?";
private static final String WHERE_NOT_INTERVAL_NEVER_AND_ACCOUNT_KEY_IN =
"(" + MailboxColumns.TYPE + '=' + Mailbox.TYPE_OUTBOX
+ " or " + MailboxColumns.SYNC_INTERVAL + "!=" + Mailbox.CHECK_INTERVAL_NEVER + ')'
+ " and " + MailboxColumns.ACCOUNT_KEY + " in (";
public static final int SEND_FAILED = 1;
public static final String MAILBOX_KEY_AND_NOT_SEND_FAILED =
MessageColumns.MAILBOX_KEY + "=? and (" + SyncColumns.SERVER_ID + " is null or " +
SyncColumns.SERVER_ID + "!=" + SEND_FAILED + ')';
public static final String CALENDAR_SELECTION =
Calendars.ACCOUNT_NAME + "=? AND " + Calendars.ACCOUNT_TYPE + "=?";
private static final String WHERE_CALENDAR_ID = Events.CALENDAR_ID + "=?";
// Offsets into the syncStatus data for EAS that indicate type, exit status, and change count
// The format is S<type_char>:<exit_char>:<change_count>
public static final int STATUS_TYPE_CHAR = 1;
public static final int STATUS_EXIT_CHAR = 3;
public static final int STATUS_CHANGE_COUNT_OFFSET = 5;
// Ready for ping
public static final int PING_STATUS_OK = 0;
// Service already running (can't ping)
public static final int PING_STATUS_RUNNING = 1;
// Service waiting after I/O error (can't ping)
public static final int PING_STATUS_WAITING = 2;
// Service had a fatal error; can't run
public static final int PING_STATUS_UNABLE = 3;
// Service is disabled by user (checkbox)
public static final int PING_STATUS_DISABLED = 4;
private static final int MAX_CLIENT_CONNECTION_MANAGER_SHUTDOWNS = 1;
// We synchronize on this for all actions affecting the service and error maps
private static final Object sSyncLock = new Object();
// All threads can use this lock to wait for connectivity
public static final Object sConnectivityLock = new Object();
public static boolean sConnectivityHold = false;
// Keeps track of running services (by mailbox id)
public final HashMap<Long, AbstractSyncService> mServiceMap =
new HashMap<Long, AbstractSyncService>();
// Keeps track of services whose last sync ended with an error (by mailbox id)
/*package*/ public ConcurrentHashMap<Long, SyncError> mSyncErrorMap =
new ConcurrentHashMap<Long, SyncError>();
// Keeps track of which services require a wake lock (by mailbox id)
private final HashMap<Long, Boolean> mWakeLocks = new HashMap<Long, Boolean>();
// Keeps track of PendingIntents for mailbox alarms (by mailbox id)
private final HashMap<Long, PendingIntent> mPendingIntents = new HashMap<Long, PendingIntent>();
// The actual WakeLock obtained by SyncServiceManager
private WakeLock mWakeLock = null;
// Keep our cached list of active Accounts here
public final AccountList mAccountList = new AccountList();
// Observers that we use to look for changed mail-related data
private final Handler mHandler = new Handler();
private AccountObserver mAccountObserver;
private MailboxObserver mMailboxObserver;
private SyncedMessageObserver mSyncedMessageObserver;
// Concurrent because CalendarSyncAdapter can modify the map during a wipe
private final ConcurrentHashMap<Long, CalendarObserver> mCalendarObservers =
new ConcurrentHashMap<Long, CalendarObserver>();
public ContentResolver mResolver;
// The singleton SyncServiceManager object, with its thread and stop flag
protected static SyncManager INSTANCE;
protected static Thread sServiceThread = null;
// Cached unique device id
protected static String sDeviceId = null;
// HashMap of ConnectionManagers that all EAS threads can use (by HostAuth id)
private static HashMap<Long, EmailClientConnectionManager> sClientConnectionManagers =
new HashMap<Long, EmailClientConnectionManager>();
// Count of ClientConnectionManager shutdowns
private static volatile int sClientConnectionManagerShutdownCount = 0;
private static volatile boolean sStartingUp = false;
private static volatile boolean sStop = false;
// The reason for SyncServiceManager's next wakeup call
private String mNextWaitReason;
// Whether we have an unsatisfied "kick" pending
private boolean mKicked = false;
// Receiver of connectivity broadcasts
private ConnectivityReceiver mConnectivityReceiver = null;
private ConnectivityReceiver mBackgroundDataSettingReceiver = null;
private volatile boolean mBackgroundData = true;
// The most current NetworkInfo (from ConnectivityManager)
private NetworkInfo mNetworkInfo;
// For sync logging
protected static boolean sUserLog = false;
protected static boolean sFileLog = false;
/**
* Return an AccountObserver for this manager; the subclass must implement the newAccount()
* method, which is called whenever the observer discovers that a new account has been created.
* The subclass should do any housekeeping necessary
* @param handler a Handler
* @return the AccountObserver
*/
public abstract AccountObserver getAccountObserver(Handler handler);
/**
* Perform any housekeeping necessary upon startup of the manager
*/
public abstract void onStartup();
/**
* Returns a String that can be used as a WHERE clause in SQLite that selects accounts whose
* syncs are managed by this manager
* @return the account selector String
*/
public abstract String getAccountsSelector();
/**
* Returns an appropriate sync service for the passed in mailbox
* @param context the caller's context
* @param mailbox the Mailbox to be synced
* @return a service that will sync the Mailbox
*/
public abstract AbstractSyncService getServiceForMailbox(Context context, Mailbox mailbox);
/**
* Return a list of all Accounts in EmailProvider. Because the result of this call may be used
* in account reconciliation, an exception is thrown if the result cannot be guaranteed accurate
* @param context the caller's context
* @param accounts a list that Accounts will be added into
* @return the list of Accounts
* @throws ProviderUnavailableException if the list of Accounts cannot be guaranteed valid
*/
public abstract AccountList collectAccounts(Context context, AccountList accounts);
/**
* Returns the AccountManager type (e.g. com.android.exchange) for this sync service
*/
public abstract String getAccountManagerType();
/**
* Returns the intent action used for this sync service
*/
public abstract String getServiceIntentAction();
/**
* Returns the callback proxy used for communicating back with the Email app
*/
public abstract Stub getCallbackProxy();
public class AccountList extends ArrayList<Account> {
private static final long serialVersionUID = 1L;
@Override
public boolean add(Account account) {
// Cache the account manager account
account.mAmAccount = new android.accounts.Account(
account.mEmailAddress, getAccountManagerType());
super.add(account);
return true;
}
public boolean contains(long id) {
for (Account account : this) {
if (account.mId == id) {
return true;
}
}
return false;
}
public Account getById(long id) {
for (Account account : this) {
if (account.mId == id) {
return account;
}
}
return null;
}
public Account getByName(String accountName) {
for (Account account : this) {
if (account.mEmailAddress.equalsIgnoreCase(accountName)) {
return account;
}
}
return null;
}
}
public static void setUserDebug(int state) {
sUserLog = (state & EmailServiceProxy.DEBUG_BIT) != 0;
sFileLog = (state & EmailServiceProxy.DEBUG_FILE_BIT) != 0;
if (sFileLog) {
sUserLog = true;
}
Log.d("Sync Debug", "Logging: " + (sUserLog ? "User " : "") + (sFileLog ? "File" : ""));
}
private boolean onSecurityHold(Account account) {
return (account.mFlags & Account.FLAGS_SECURITY_HOLD) != 0;
}
public static String getAccountSelector() {
SyncManager ssm = INSTANCE;
if (ssm == null) return "";
return ssm.getAccountsSelector();
}
public abstract class AccountObserver extends ContentObserver {
String mSyncableMailboxSelector = null;
String mAccountSelector = null;
// Runs when SyncServiceManager first starts
@SuppressWarnings("deprecation")
public AccountObserver(Handler handler) {
super(handler);
// At startup, we want to see what EAS accounts exist and cache them
// TODO: Move database work out of UI thread
Context context = getContext();
synchronized (mAccountList) {
try {
collectAccounts(context, mAccountList);
} catch (ProviderUnavailableException e) {
// Just leave if EmailProvider is unavailable
return;
}
// Create an account mailbox for any account without one
for (Account account : mAccountList) {
int cnt = Mailbox.count(context, Mailbox.CONTENT_URI, "accountKey="
+ account.mId, null);
if (cnt == 0) {
// This case handles a newly created account
newAccount(account.mId);
}
}
}
// Run through accounts and update account hold information
Utility.runAsync(new Runnable() {
@Override
public void run() {
synchronized (mAccountList) {
for (Account account : mAccountList) {
if (onSecurityHold(account)) {
// If we're in a security hold, and our policies are active, release
// the hold
if (PolicyServiceProxy.isActive(SyncManager.this, null)) {
PolicyServiceProxy.setAccountHoldFlag(SyncManager.this,
account, false);
log("isActive true; release hold for " + account.mDisplayName);
}
}
}
}
}});
}
/**
* Returns a String suitable for appending to a where clause that selects for all syncable
* mailboxes in all eas accounts
* @return a complex selection string that is not to be cached
*/
public String getSyncableMailboxWhere() {
if (mSyncableMailboxSelector == null) {
StringBuilder sb = new StringBuilder(WHERE_NOT_INTERVAL_NEVER_AND_ACCOUNT_KEY_IN);
boolean first = true;
synchronized (mAccountList) {
for (Account account : mAccountList) {
if (!first) {
sb.append(',');
} else {
first = false;
}
sb.append(account.mId);
}
}
sb.append(')');
mSyncableMailboxSelector = sb.toString();
}
return mSyncableMailboxSelector;
}
private void onAccountChanged() {
try {
maybeStartSyncServiceManagerThread();
Context context = getContext();
// A change to the list requires us to scan for deletions (stop running syncs)
// At startup, we want to see what accounts exist and cache them
AccountList currentAccounts = new AccountList();
try {
collectAccounts(context, currentAccounts);
} catch (ProviderUnavailableException e) {
// Just leave if EmailProvider is unavailable
return;
}
synchronized (mAccountList) {
for (Account account : mAccountList) {
boolean accountIncomplete =
(account.mFlags & Account.FLAGS_INCOMPLETE) != 0;
// If the current list doesn't include this account and the account wasn't
// incomplete, then this is a deletion
if (!currentAccounts.contains(account.mId) && !accountIncomplete) {
// The implication is that the account has been deleted; let's find out
alwaysLog("Observer found deleted account: " + account.mDisplayName);
// Run the reconciler (the reconciliation itself runs in the Email app)
runAccountReconcilerSync(SyncManager.this);
// See if the account is still around
Account deletedAccount =
Account.restoreAccountWithId(context, account.mId);
if (deletedAccount != null) {
// It is; add it to our account list
alwaysLog("Account still in provider: " + account.mDisplayName);
currentAccounts.add(account);
} else {
// It isn't; stop syncs and clear our selectors
alwaysLog("Account deletion confirmed: " + account.mDisplayName);
stopAccountSyncs(account.mId, true);
mSyncableMailboxSelector = null;
mAccountSelector = null;
}
} else {
// Get the newest version of this account
Account updatedAccount =
Account.restoreAccountWithId(context, account.mId);
if (updatedAccount == null) continue;
if (account.mSyncInterval != updatedAccount.mSyncInterval
|| account.mSyncLookback != updatedAccount.mSyncLookback) {
// Set the inbox interval to the interval of the Account
// This setting should NOT affect other boxes
ContentValues cv = new ContentValues();
cv.put(MailboxColumns.SYNC_INTERVAL, updatedAccount.mSyncInterval);
getContentResolver().update(Mailbox.CONTENT_URI, cv,
WHERE_IN_ACCOUNT_AND_TYPE_INBOX, new String[] {
Long.toString(account.mId)
});
// Stop all current syncs; the appropriate ones will restart
log("Account " + account.mDisplayName + " changed; stop syncs");
stopAccountSyncs(account.mId, true);
}
// See if this account is no longer on security hold
if (onSecurityHold(account) && !onSecurityHold(updatedAccount)) {
releaseSyncHolds(SyncManager.this,
AbstractSyncService.EXIT_SECURITY_FAILURE, account);
}
// Put current values into our cached account
account.mSyncInterval = updatedAccount.mSyncInterval;
account.mSyncLookback = updatedAccount.mSyncLookback;
account.mFlags = updatedAccount.mFlags;
}
}
// Look for new accounts
for (Account account : currentAccounts) {
if (!mAccountList.contains(account.mId)) {
// Don't forget to cache the HostAuth
HostAuth ha = HostAuth.restoreHostAuthWithId(getContext(),
account.mHostAuthKeyRecv);
if (ha == null) continue;
account.mHostAuthRecv = ha;
// This is an addition; create our magic hidden mailbox...
log("Account observer found new account: " + account.mDisplayName);
newAccount(account.mId);
mAccountList.add(account);
mSyncableMailboxSelector = null;
mAccountSelector = null;
}
}
// Finally, make sure our account list is up to date
mAccountList.clear();
mAccountList.addAll(currentAccounts);
}
// See if there's anything to do...
kick("account changed");
} catch (ProviderUnavailableException e) {
alwaysLog("Observer failed; provider unavailable");
}
}
@Override
public void onChange(boolean selfChange) {
new Thread(new Runnable() {
@Override
public void run() {
onAccountChanged();
}}, "Account Observer").start();
}
public abstract void newAccount(long acctId);
}
/**
* Register a specific Calendar's data observer; we need to recognize when the SYNC_EVENTS
* column has changed (when sync has turned off or on)
* @param account the Account whose Calendar we're observing
*/
private void registerCalendarObserver(Account account) {
// Get a new observer
CalendarObserver observer = new CalendarObserver(mHandler, account);
if (observer.mCalendarId != 0) {
// If we find the Calendar (and we'd better) register it and store it in the map
mCalendarObservers.put(account.mId, observer);
mResolver.registerContentObserver(
ContentUris.withAppendedId(Calendars.CONTENT_URI, observer.mCalendarId), false,
observer);
}
}
/**
* Unregister all CalendarObserver's
*/
static public void unregisterCalendarObservers() {
SyncManager ssm = INSTANCE;
if (ssm == null) return;
ContentResolver resolver = ssm.mResolver;
for (CalendarObserver observer: ssm.mCalendarObservers.values()) {
resolver.unregisterContentObserver(observer);
}
ssm.mCalendarObservers.clear();
}
public static Uri asSyncAdapter(Uri uri, String account, String accountType) {
return uri.buildUpon().appendQueryParameter(CalendarContract.CALLER_IS_SYNCADAPTER, "true")
.appendQueryParameter(Calendars.ACCOUNT_NAME, account)
.appendQueryParameter(Calendars.ACCOUNT_TYPE, accountType).build();
}
/**
* Return the syncable state of an account's calendar, as determined by the sync_events column
* of our Calendar (from CalendarProvider2)
* Note that the current state of sync_events is cached in our CalendarObserver
* @param accountId the id of the account whose calendar we are checking
* @return whether or not syncing of events is enabled
*/
private boolean isCalendarEnabled(long accountId) {
CalendarObserver observer = mCalendarObservers.get(accountId);
if (observer != null) {
return (observer.mSyncEvents == 1);
}
// If there's no observer, there's no Calendar in CalendarProvider2, so we return true
// to allow Calendar creation
return true;
}
private class CalendarObserver extends ContentObserver {
final long mAccountId;
final String mAccountName;
long mCalendarId;
long mSyncEvents;
public CalendarObserver(Handler handler, Account account) {
super(handler);
mAccountId = account.mId;
mAccountName = account.mEmailAddress;
// Find the Calendar for this account
Cursor c = mResolver.query(Calendars.CONTENT_URI,
new String[] {Calendars._ID, Calendars.SYNC_EVENTS},
CALENDAR_SELECTION,
new String[] {account.mEmailAddress, getAccountManagerType()},
null);
if (c != null) {
// Save its id and its sync events status
try {
if (c.moveToFirst()) {
mCalendarId = c.getLong(0);
mSyncEvents = c.getLong(1);
}
} finally {
c.close();
}
}
}
@Override
public synchronized void onChange(boolean selfChange) {
// See if the user has changed syncing of our calendar
if (!selfChange) {
new Thread(new Runnable() {
@Override
public void run() {
try {
Cursor c = mResolver.query(Calendars.CONTENT_URI,
new String[] {Calendars.SYNC_EVENTS}, Calendars._ID + "=?",
new String[] {Long.toString(mCalendarId)}, null);
if (c == null) return;
// Get its sync events; if it's changed, we've got work to do
try {
if (c.moveToFirst()) {
long newSyncEvents = c.getLong(0);
if (newSyncEvents != mSyncEvents) {
log("_sync_events changed for calendar in " + mAccountName);
Mailbox mailbox = Mailbox.restoreMailboxOfType(INSTANCE,
mAccountId, Mailbox.TYPE_CALENDAR);
// Sanity check for mailbox deletion
if (mailbox == null) return;
ContentValues cv = new ContentValues();
if (newSyncEvents == 0) {
// When sync is disabled, we're supposed to delete
// all events in the calendar
log("Deleting events and setting syncKey to 0 for " +
mAccountName);
// First, stop any sync that's ongoing
stopManualSync(mailbox.mId);
// Set the syncKey to 0 (reset)
AbstractSyncService service = getServiceForMailbox(
INSTANCE, mailbox);
service.resetCalendarSyncKey();
// Reset the sync key locally and stop syncing
cv.put(Mailbox.SYNC_KEY, "0");
cv.put(Mailbox.SYNC_INTERVAL,
Mailbox.CHECK_INTERVAL_NEVER);
mResolver.update(ContentUris.withAppendedId(
Mailbox.CONTENT_URI, mailbox.mId), cv, null,
null);
// Delete all events using the sync adapter
// parameter so that the deletion is only local
Uri eventsAsSyncAdapter =
asSyncAdapter(
Events.CONTENT_URI,
mAccountName,
getAccountManagerType());
mResolver.delete(eventsAsSyncAdapter, WHERE_CALENDAR_ID,
new String[] {Long.toString(mCalendarId)});
} else {
// Make this a push mailbox and kick; this will start
// a resync of the Calendar; the account mailbox will
// ping on this during the next cycle of the ping loop
cv.put(Mailbox.SYNC_INTERVAL,
Mailbox.CHECK_INTERVAL_PUSH);
mResolver.update(ContentUris.withAppendedId(
Mailbox.CONTENT_URI, mailbox.mId), cv, null,
null);
kick("calendar sync changed");
}
// Save away the new value
mSyncEvents = newSyncEvents;
}
}
} finally {
c.close();
}
} catch (ProviderUnavailableException e) {
Log.w(TAG, "Observer failed; provider unavailable");
}
}}, "Calendar Observer").start();
}
}
}
private class MailboxObserver extends ContentObserver {
public MailboxObserver(Handler handler) {
super(handler);
}
@Override
public void onChange(boolean selfChange) {
// See if there's anything to do...
if (!selfChange) {
kick("mailbox changed");
}
}
}
private class SyncedMessageObserver extends ContentObserver {
Intent syncAlarmIntent = new Intent(INSTANCE, EmailSyncAlarmReceiver.class);
PendingIntent syncAlarmPendingIntent =
PendingIntent.getBroadcast(INSTANCE, 0, syncAlarmIntent, 0);
AlarmManager alarmManager = (AlarmManager)INSTANCE.getSystemService(Context.ALARM_SERVICE);
public SyncedMessageObserver(Handler handler) {
super(handler);
}
@Override
public void onChange(boolean selfChange) {
alarmManager.set(AlarmManager.RTC_WAKEUP,
System.currentTimeMillis() + 10*SECONDS, syncAlarmPendingIntent);
}
}
static public Account getAccountById(long accountId) {
SyncManager ssm = INSTANCE;
if (ssm != null) {
AccountList accountList = ssm.mAccountList;
synchronized (accountList) {
return accountList.getById(accountId);
}
}
return null;
}
static public Account getAccountByName(String accountName) {
SyncManager ssm = INSTANCE;
if (ssm != null) {
AccountList accountList = ssm.mAccountList;
synchronized (accountList) {
return accountList.getByName(accountName);
}
}
return null;
}
public class SyncStatus {
static public final int NOT_RUNNING = 0;
static public final int DIED = 1;
static public final int SYNC = 2;
static public final int IDLE = 3;
}
/*package*/ public class SyncError {
int reason;
public boolean fatal = false;
long holdDelay = 15*SECONDS;
public long holdEndTime = System.currentTimeMillis() + holdDelay;
public SyncError(int _reason, boolean _fatal) {
reason = _reason;
fatal = _fatal;
}
/**
* We double the holdDelay from 15 seconds through 8 mins
*/
void escalate() {
if (holdDelay <= HOLD_DELAY_MAXIMUM) {
holdDelay *= 2;
}
holdEndTime = System.currentTimeMillis() + holdDelay;
}
}
private void logSyncHolds() {
if (sUserLog) {
log("Sync holds:");
long time = System.currentTimeMillis();
for (long mailboxId : mSyncErrorMap.keySet()) {
Mailbox m = Mailbox.restoreMailboxWithId(this, mailboxId);
if (m == null) {
log("Mailbox " + mailboxId + " no longer exists");
} else {
SyncError error = mSyncErrorMap.get(mailboxId);
if (error != null) {
log("Mailbox " + m.mDisplayName + ", error = " + error.reason
+ ", fatal = " + error.fatal);
if (error.holdEndTime > 0) {
log("Hold ends in " + ((error.holdEndTime - time) / 1000) + "s");
}
}
}
}
}
}
/**
* Release security holds for the specified account
* @param account the account whose Mailboxes should be released from security hold
*/
static public void releaseSecurityHold(Account account) {
SyncManager ssm = INSTANCE;
if (ssm != null) {
ssm.releaseSyncHolds(INSTANCE, AbstractSyncService.EXIT_SECURITY_FAILURE,
account);
}
}
/**
* Release a specific type of hold (the reason) for the specified Account; if the account
* is null, mailboxes from all accounts with the specified hold will be released
* @param reason the reason for the SyncError (AbstractSyncService.EXIT_XXX)
* @param account an Account whose mailboxes should be released (or all if null)
* @return whether or not any mailboxes were released
*/
public /*package*/ boolean releaseSyncHolds(Context context, int reason, Account account) {
boolean holdWasReleased = releaseSyncHoldsImpl(context, reason, account);
kick("security release");
return holdWasReleased;
}
private boolean releaseSyncHoldsImpl(Context context, int reason, Account account) {
boolean holdWasReleased = false;
for (long mailboxId: mSyncErrorMap.keySet()) {
if (account != null) {
Mailbox m = Mailbox.restoreMailboxWithId(context, mailboxId);
if (m == null) {
mSyncErrorMap.remove(mailboxId);
} else if (m.mAccountKey != account.mId) {
continue;
}
}
SyncError error = mSyncErrorMap.get(mailboxId);
if (error != null && error.reason == reason) {
mSyncErrorMap.remove(mailboxId);
holdWasReleased = true;
}
}
return holdWasReleased;
}
public static void log(String str) {
log(TAG, str);
}
public static void log(String tag, String str) {
if (sUserLog) {
Log.d(tag, str);
if (sFileLog) {
FileLogger.log(tag, str);
}
}
}
public static void alwaysLog(String str) {
if (!sUserLog) {
Log.d(TAG, str);
} else {
log(str);
}
}
/**
* EAS requires a unique device id, so that sync is possible from a variety of different
* devices (e.g. the syncKey is specific to a device) If we're on an emulator or some other
* device that doesn't provide one, we can create it as "device".
* This would work on a real device as well, but it would be better to use the "real" id if
* it's available
*/
static public String getDeviceId(Context context) throws IOException {
if (sDeviceId == null) {
sDeviceId = new AccountServiceProxy(context).getDeviceId();
alwaysLog("Received deviceId from Email app: " + sDeviceId);
}
return sDeviceId;
}
static public ConnPerRoute sConnPerRoute = new ConnPerRoute() {
@Override
public int getMaxForRoute(HttpRoute route) {
return 8;
}
};
static public synchronized EmailClientConnectionManager getClientConnectionManager(
Context context, HostAuth hostAuth) {
// We'll use a different connection manager for each HostAuth
EmailClientConnectionManager mgr = null;
// We don't save managers for validation/autodiscover
if (hostAuth.mId != HostAuth.NOT_SAVED) {
mgr = sClientConnectionManagers.get(hostAuth.mId);
}
if (mgr == null) {
// After two tries, kill the process. Most likely, this will happen in the background
// The service will restart itself after about 5 seconds
if (sClientConnectionManagerShutdownCount > MAX_CLIENT_CONNECTION_MANAGER_SHUTDOWNS) {
alwaysLog("Shutting down process to unblock threads");
Process.killProcess(Process.myPid());
}
HttpParams params = new BasicHttpParams();
params.setIntParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 25);
params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, sConnPerRoute);
boolean ssl = hostAuth.shouldUseSsl();
int port = hostAuth.mPort;
mgr = EmailClientConnectionManager.newInstance(context, params, hostAuth);
log("Creating connection manager for port " + port + ", ssl: " + ssl);
sClientConnectionManagers.put(hostAuth.mId, mgr);
}
// Null is a valid return result if we get an exception
return mgr;
}
static private synchronized void shutdownConnectionManager() {
log("Shutting down ClientConnectionManagers");
for (EmailClientConnectionManager mgr: sClientConnectionManagers.values()) {
mgr.shutdown();
}
sClientConnectionManagers.clear();
}
public static void stopAccountSyncs(long acctId) {
SyncManager ssm = INSTANCE;
if (ssm != null) {
ssm.stopAccountSyncs(acctId, true);
}
}
public void stopAccountSyncs(long acctId, boolean includeAccountMailbox) {
synchronized (sSyncLock) {
List<Long> deletedBoxes = new ArrayList<Long>();
for (Long mid : mServiceMap.keySet()) {
Mailbox box = Mailbox.restoreMailboxWithId(this, mid);
if (box != null) {
if (box.mAccountKey == acctId) {
if (!includeAccountMailbox &&
box.mType == Mailbox.TYPE_EAS_ACCOUNT_MAILBOX) {
AbstractSyncService svc = mServiceMap.get(mid);
if (svc != null) {
svc.stop();
}
continue;
}
AbstractSyncService svc = mServiceMap.get(mid);
if (svc != null) {
svc.stop();
Thread t = svc.mThread;
if (t != null) {
t.interrupt();
}
}
deletedBoxes.add(mid);
}
}
}
for (Long mid : deletedBoxes) {
releaseMailbox(mid);
}
}
}
/**
* Informs SyncServiceManager that an account has a new folder list; as a result, any existing
* folder might have become invalid. Therefore, we act as if the account has been deleted, and
* then we reinitialize it.
*
* @param acctId
*/
static public void stopNonAccountMailboxSyncsForAccount(long acctId) {
SyncManager ssm = INSTANCE;
if (ssm != null) {
ssm.stopAccountSyncs(acctId, false);
kick("reload folder list");
}
}
private void acquireWakeLock(long id) {
synchronized (mWakeLocks) {
Boolean lock = mWakeLocks.get(id);
if (lock == null) {
if (mWakeLock == null) {
PowerManager pm = (PowerManager)getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MAIL_SERVICE");
mWakeLock.acquire();
//log("+WAKE LOCK ACQUIRED");
}
mWakeLocks.put(id, true);
}
}
}
private void releaseWakeLock(long id) {
synchronized (mWakeLocks) {
Boolean lock = mWakeLocks.get(id);
if (lock != null) {
mWakeLocks.remove(id);
if (mWakeLocks.isEmpty()) {
if (mWakeLock != null) {
mWakeLock.release();
}
mWakeLock = null;
//log("+WAKE LOCK RELEASED");
} else {
}
}
}
}
static public String alarmOwner(long id) {
if (id == EXTRA_MAILBOX_ID) {
return TAG;
} else {
String name = Long.toString(id);
if (sUserLog && INSTANCE != null) {
Mailbox m = Mailbox.restoreMailboxWithId(INSTANCE, id);
if (m != null) {
name = m.mDisplayName + '(' + m.mAccountKey + ')';
}
}
return "Mailbox " + name;
}
}
private void clearAlarm(long id) {
synchronized (mPendingIntents) {
PendingIntent pi = mPendingIntents.get(id);
if (pi != null) {
AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(pi);
//log("+Alarm cleared for " + alarmOwner(id));
mPendingIntents.remove(id);
}
}
}
private void setAlarm(long id, long millis) {
synchronized (mPendingIntents) {
PendingIntent pi = mPendingIntents.get(id);
if (pi == null) {
Intent i = new Intent(this, MailboxAlarmReceiver.class);
i.putExtra("mailbox", id);
i.setData(Uri.parse("Box" + id));
pi = PendingIntent.getBroadcast(this, 0, i, 0);
mPendingIntents.put(id, pi);
AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + millis, pi);
//log("+Alarm set for " + alarmOwner(id) + ", " + millis/1000 + "s");
}
}
}
private void clearAlarms() {
AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
synchronized (mPendingIntents) {
for (PendingIntent pi : mPendingIntents.values()) {
alarmManager.cancel(pi);
}
mPendingIntents.clear();
}
}
static public void runAwake(long id) {
SyncManager ssm = INSTANCE;
if (ssm != null) {
ssm.acquireWakeLock(id);
ssm.clearAlarm(id);
}
}
static public void runAsleep(long id, long millis) {
SyncManager ssm = INSTANCE;
if (ssm != null) {
ssm.setAlarm(id, millis);
ssm.releaseWakeLock(id);
}
}
static public void clearWatchdogAlarm(long id) {
SyncManager ssm = INSTANCE;
if (ssm != null) {
ssm.clearAlarm(id);
}
}
static public void setWatchdogAlarm(long id, long millis) {
SyncManager ssm = INSTANCE;
if (ssm != null) {
ssm.setAlarm(id, millis);
}
}
static public void alert(Context context, final long id) {
final SyncManager ssm = INSTANCE;
checkSyncServiceManagerServiceRunning();
if (id < 0) {
log("SyncServiceManager alert");
kick("ping SyncServiceManager");
} else if (ssm == null) {
context.startService(new Intent(context, SyncManager.class));
} else {
final AbstractSyncService service = ssm.mServiceMap.get(id);
if (service != null) {
// Handle alerts in a background thread, as we are typically called from a
// broadcast receiver, and are therefore running in the UI thread
String threadName = "SyncServiceManager Alert: ";
if (service.mMailbox != null) {
threadName += service.mMailbox.mDisplayName;
}
new Thread(new Runnable() {
@Override
public void run() {
Mailbox m = Mailbox.restoreMailboxWithId(ssm, id);
if (m != null) {
// We ignore drafts completely (doesn't sync). Changes in Outbox are
// handled in the checkMailboxes loop, so we can ignore these pings.
if (sUserLog) {
Log.d(TAG, "Alert for mailbox " + id + " (" + m.mDisplayName + ")");
}
if (m.mType == Mailbox.TYPE_DRAFTS || m.mType == Mailbox.TYPE_OUTBOX) {
String[] args = new String[] {Long.toString(m.mId)};
ContentResolver resolver = INSTANCE.mResolver;
resolver.delete(Message.DELETED_CONTENT_URI, WHERE_MAILBOX_KEY,
args);
resolver.delete(Message.UPDATED_CONTENT_URI, WHERE_MAILBOX_KEY,
args);
return;
}
service.mAccount = Account.restoreAccountWithId(INSTANCE, m.mAccountKey);
service.mMailbox = m;
// Send the alarm to the sync service
if (!service.alarm()) {
// A false return means that we were forced to interrupt the thread
// In this case, we release the mailbox so that we can start another
// thread to do the work
log("Alarm failed; releasing mailbox");
synchronized(sSyncLock) {
ssm.releaseMailbox(id);
}
// Shutdown the connection manager; this should close all of our
// sockets and generate IOExceptions all around.
SyncManager.shutdownConnectionManager();
}
}
}}, threadName).start();
}
}
}
public class ConnectivityReceiver extends BroadcastReceiver {
@SuppressWarnings("deprecation")
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
Bundle b = intent.getExtras();
if (b != null) {
NetworkInfo a = (NetworkInfo)b.get(ConnectivityManager.EXTRA_NETWORK_INFO);
String info = "Connectivity alert for " + a.getTypeName();
State state = a.getState();
if (state == State.CONNECTED) {
info += " CONNECTED";
log(info);
synchronized (sConnectivityLock) {
sConnectivityLock.notifyAll();
}
kick("connected");
} else if (state == State.DISCONNECTED) {
info += " DISCONNECTED";
log(info);
kick("disconnected");
}
}
} else if (intent.getAction().equals(
ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED)) {
ConnectivityManager cm =
(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
mBackgroundData = cm.getBackgroundDataSetting();
// If background data is now on, we want to kick SyncServiceManager
if (mBackgroundData) {
kick("background data on");
log("Background data on; restart syncs");
// Otherwise, stop all syncs
} else {
log("Background data off: stop all syncs");
EmailAsyncTask.runAsyncParallel(new Runnable() {
@Override
public void run() {
synchronized (mAccountList) {
for (Account account : mAccountList)
SyncManager.stopAccountSyncs(account.mId);
}
}});
}
}
}
}
/**
* Starts a service thread and enters it into the service map
* This is the point of instantiation of all sync threads
* @param service the service to start
* @param m the Mailbox on which the service will operate
*/
private void startServiceThread(AbstractSyncService service) {
synchronized (sSyncLock) {
Mailbox mailbox = service.mMailbox;
String mailboxName = mailbox.mDisplayName;
String accountName = service.mAccount.mDisplayName;
Thread thread = new Thread(service, mailboxName + "[" + accountName + "]");
log("Starting thread for " + mailboxName + " in account " + accountName);
thread.start();
mServiceMap.put(mailbox.mId, service);
runAwake(mailbox.mId);
if (mailbox.mServerId != null && mailbox.mType != Mailbox.TYPE_EAS_ACCOUNT_MAILBOX) {
stopPing(mailbox.mAccountKey);
}
}
}
/**
* Stop any ping in progress for the given account
* @param accountId
*/
private void stopPing(long accountId) {
// Go through our active mailboxes looking for the right one
synchronized (sSyncLock) {
AbstractSyncService serviceToReset = null;
for (long mailboxId: mServiceMap.keySet()) {
Mailbox m = Mailbox.restoreMailboxWithId(this, mailboxId);
if (m != null) {
String serverId = m.mServerId;
if (m.mAccountKey == accountId && serverId != null &&
m.mType == Mailbox.TYPE_EAS_ACCOUNT_MAILBOX) {
// Here's our account mailbox; reset him (stopping pings)
serviceToReset = mServiceMap.get(mailboxId);
break;
}
}
}
if (serviceToReset != null) {
serviceToReset.reset();
}
}
}
private void requestSync(Mailbox m, int reason, Request req) {
int syncStatus = EmailContent.SYNC_STATUS_BACKGROUND;
// Don't sync if there's no connectivity
if (sConnectivityHold || (m == null) || sStop) {
if (reason >= SYNC_CALLBACK_START) {
try {
Stub proxy = getCallbackProxy();
if (proxy != null) {
proxy.syncMailboxStatus(m.mId, EmailServiceStatus.CONNECTION_ERROR, 0);
}
} catch (RemoteException e) {
// We tried...
}
}
return;
}
synchronized (sSyncLock) {
Account acct = Account.restoreAccountWithId(this, m.mAccountKey);
if (acct != null) {
// Always make sure there's not a running instance of this service
AbstractSyncService service = mServiceMap.get(m.mId);
if (service == null) {
service = getServiceForMailbox(this, m);
if (!service.mIsValid) return;
service.mSyncReason = reason;
if (req != null) {
service.addRequest(req);
}
startServiceThread(service);
if (reason >= SYNC_CALLBACK_START) {
syncStatus = EmailContent.SYNC_STATUS_USER;
}
setMailboxSyncStatus(m.mId, syncStatus);
}
}
}
}
public void setMailboxSyncStatus(long id, int status) {
ContentValues values = new ContentValues();
values.put(Mailbox.UI_SYNC_STATUS, status);
mResolver.update(ContentUris.withAppendedId(Mailbox.CONTENT_URI, id), values, null, null);
}
public void setMailboxLastSyncResult(long id, int result) {
ContentValues values = new ContentValues();
values.put(Mailbox.UI_LAST_SYNC_RESULT, result);
mResolver.update(ContentUris.withAppendedId(Mailbox.CONTENT_URI, id), values, null, null);
}
private void stopServiceThreads() {
synchronized (sSyncLock) {
ArrayList<Long> toStop = new ArrayList<Long>();
// Keep track of which services to stop
for (Long mailboxId : mServiceMap.keySet()) {
toStop.add(mailboxId);
}
// Shut down all of those running services
for (Long mailboxId : toStop) {
AbstractSyncService svc = mServiceMap.get(mailboxId);
if (svc != null) {
log("Stopping " + svc.mAccount.mDisplayName + '/' + svc.mMailbox.mDisplayName);
svc.stop();
if (svc.mThread != null) {
svc.mThread.interrupt();
}
}
releaseWakeLock(mailboxId);
}
}
}
private void waitForConnectivity() {
boolean waiting = false;
ConnectivityManager cm =
(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
while (!sStop) {
NetworkInfo info = cm.getActiveNetworkInfo();
if (info != null) {
mNetworkInfo = info;
// We're done if there's an active network
if (waiting) {
// If we've been waiting, release any I/O error holds
releaseSyncHolds(this, AbstractSyncService.EXIT_IO_ERROR, null);
// And log what's still being held
logSyncHolds();
}
return;
} else {
// If this is our first time through the loop, shut down running service threads
if (!waiting) {
waiting = true;
stopServiceThreads();
}
// Wait until a network is connected (or 10 mins), but let the device sleep
// We'll set an alarm just in case we don't get notified (bugs happen)
synchronized (sConnectivityLock) {
runAsleep(EXTRA_MAILBOX_ID, CONNECTIVITY_WAIT_TIME+5*SECONDS);
try {
log("Connectivity lock...");
sConnectivityHold = true;
sConnectivityLock.wait(CONNECTIVITY_WAIT_TIME);
log("Connectivity lock released...");
} catch (InterruptedException e) {
// This is fine; we just go around the loop again
} finally {
sConnectivityHold = false;
}
runAwake(EXTRA_MAILBOX_ID);
}
}
}
}
/**
* Note that there are two ways the EAS SyncServiceManager service can be created:
*
* 1) as a background service instantiated via startService (which happens on boot, when the
* first EAS account is created, etc), in which case the service thread is spun up, mailboxes
* sync, etc. and
* 2) to execute an RPC call from the UI, in which case the background service will already be
* running most of the time (unless we're creating a first EAS account)
*
* If the running background service detects that there are no EAS accounts (on boot, if none
* were created, or afterward if the last remaining EAS account is deleted), it will call
* stopSelf() to terminate operation.
*
* The goal is to ensure that the background service is running at all times when there is at
* least one EAS account in existence
*
* Because there are edge cases in which our process can crash (typically, this has been seen
* in UI crashes, ANR's, etc.), it's possible for the UI to start up again without the
* background service having been started. We explicitly try to start the service in Welcome
* (to handle the case of the app having been reloaded). We also start the service on any
* startSync call (if it isn't already running)
*/
@SuppressWarnings("deprecation")
@Override
public void onCreate() {
Utility.runAsync(new Runnable() {
@Override
public void run() {
// Quick checks first, before getting the lock
if (sStartingUp) return;
synchronized (sSyncLock) {
alwaysLog("!!! EAS SyncServiceManager, onCreate");
// Try to start up properly; we might be coming back from a crash that the Email
// application isn't aware of.
startService(new Intent(getServiceIntentAction()));
if (sStop) {
return;
}
}
}});
}
@SuppressWarnings("deprecation")
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
alwaysLog("!!! EAS SyncServiceManager, onStartCommand, startingUp = " + sStartingUp +
", running = " + (INSTANCE != null));
if (!sStartingUp && INSTANCE == null) {
sStartingUp = true;
Utility.runAsync(new Runnable() {
@Override
public void run() {
try {
synchronized (sSyncLock) {
// SyncServiceManager cannot start unless we connect to AccountService
if (!new AccountServiceProxy(SyncManager.this).test()) {
alwaysLog("!!! Email application not found; stopping self");
stopSelf();
}
if (sDeviceId == null) {
try {
String deviceId = getDeviceId(SyncManager.this);
if (deviceId != null) {
sDeviceId = deviceId;
}
} catch (IOException e) {
}
if (sDeviceId == null) {
alwaysLog("!!! deviceId unknown; stopping self and retrying");
stopSelf();
// Try to restart ourselves in a few seconds
Utility.runAsync(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
}
startService(new Intent(getServiceIntentAction()));
}});
return;
}
}
// Run the reconciler and clean up mismatched accounts - if we weren't
// running when accounts were deleted, it won't have been called.
runAccountReconcilerSync(SyncManager.this);
// Update other services depending on final account configuration
maybeStartSyncServiceManagerThread();
if (sServiceThread == null) {
log("!!! EAS SyncServiceManager, stopping self");
stopSelf();
} else if (sStop) {
// If we were trying to stop, attempt a restart in 5 secs
setAlarm(SYNC_SERVICE_MAILBOX_ID, 5*SECONDS);
}
}
} finally {
sStartingUp = false;
}
}});
}
return Service.START_STICKY;
}
public static void reconcileAccounts(Context context) {
SyncManager ssm = INSTANCE;
if (ssm != null) {
ssm.runAccountReconcilerSync(context);
}
}
protected abstract void runAccountReconcilerSync(Context context);
@SuppressWarnings("deprecation")
@Override
public void onDestroy() {
log("!!! EAS SyncServiceManager, onDestroy");
// Handle shutting down off the UI thread
Utility.runAsync(new Runnable() {
@Override
public void run() {
// Quick checks first, before getting the lock
if (INSTANCE == null || sServiceThread == null) return;
synchronized(sSyncLock) {
// Stop the sync manager thread and return
if (sServiceThread != null) {
sStop = true;
sServiceThread.interrupt();
}
}
}});
}
void maybeStartSyncServiceManagerThread() {
// Start our thread...
// See if there are any EAS accounts; otherwise, just go away
if (sServiceThread == null || !sServiceThread.isAlive()) {
AccountList currentAccounts = new AccountList();
try {
collectAccounts(this, currentAccounts);
} catch (ProviderUnavailableException e) {
// Just leave if EmailProvider is unavailable
return;
}
if (!currentAccounts.isEmpty()) {
log(sServiceThread == null ? "Starting thread..." : "Restarting thread...");
sServiceThread = new Thread(this, TAG);
INSTANCE = this;
sServiceThread.start();
}
}
}
/**
* Start up the SyncServiceManager service if it's not already running
* This is a stopgap for cases in which SyncServiceManager died (due to a crash somewhere in
* com.android.email) and hasn't been restarted. See the comment for onCreate for details
*/
static void checkSyncServiceManagerServiceRunning() {
SyncManager ssm = INSTANCE;
if (ssm == null) return;
if (sServiceThread == null) {
log("!!! checkSyncServiceManagerServiceRunning; starting service...");
ssm.startService(new Intent(ssm, SyncManager.class));
}
}
@SuppressWarnings("deprecation")
@Override
public void run() {
sStop = false;
alwaysLog("SyncServiceManager thread running");
TempDirectory.setTempDirectory(this);
// Synchronize here to prevent a shutdown from happening while we initialize our observers
// and receivers
synchronized (sSyncLock) {
if (INSTANCE != null) {
mResolver = getContentResolver();
// Set up our observers; we need them to know when to start/stop various syncs based
// on the insert/delete/update of mailboxes and accounts
// We also observe synced messages to trigger upsyncs at the appropriate time
mAccountObserver = getAccountObserver(mHandler);
mResolver.registerContentObserver(Account.NOTIFIER_URI, true, mAccountObserver);
mMailboxObserver = new MailboxObserver(mHandler);
mResolver.registerContentObserver(Mailbox.CONTENT_URI, false, mMailboxObserver);
mSyncedMessageObserver = new SyncedMessageObserver(mHandler);
mResolver.registerContentObserver(Message.SYNCED_CONTENT_URI, true,
mSyncedMessageObserver);
// Set up receivers for connectivity and background data setting
mConnectivityReceiver = new ConnectivityReceiver();
registerReceiver(mConnectivityReceiver, new IntentFilter(
ConnectivityManager.CONNECTIVITY_ACTION));
mBackgroundDataSettingReceiver = new ConnectivityReceiver();
registerReceiver(mBackgroundDataSettingReceiver, new IntentFilter(
ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED));
// Save away the current background data setting; we'll keep track of it with the
// receiver we just registered
ConnectivityManager cm = (ConnectivityManager)getSystemService(
Context.CONNECTIVITY_SERVICE);
mBackgroundData = cm.getBackgroundDataSetting();
onStartup();
}
}
try {
// Loop indefinitely until we're shut down
while (!sStop) {
runAwake(EXTRA_MAILBOX_ID);
waitForConnectivity();
mNextWaitReason = null;
long nextWait = checkMailboxes();
try {
synchronized (this) {
if (!mKicked) {
if (nextWait < 0) {
log("Negative wait? Setting to 1s");
nextWait = 1*SECONDS;
}
if (nextWait > 10*SECONDS) {
if (mNextWaitReason != null) {
log("Next awake " + nextWait / 1000 + "s: " + mNextWaitReason);
}
runAsleep(EXTRA_MAILBOX_ID, nextWait + (3*SECONDS));
}
wait(nextWait);
}
}
} catch (InterruptedException e) {
// Needs to be caught, but causes no problem
log("SyncServiceManager interrupted");
} finally {
synchronized (this) {
if (mKicked) {
//log("Wait deferred due to kick");
mKicked = false;
}
}
}
}
log("Shutdown requested");
} catch (ProviderUnavailableException pue) {
// Shutdown cleanly in this case
// NOTE: Sync adapters will also crash with this error, but that is already handled
// in the adapters themselves, i.e. they return cleanly via done(). When the Email
// process starts running again, remote processes will be started again in due course
Log.e(TAG, "EmailProvider unavailable; shutting down");
// Ask for our service to be restarted; this should kick-start the Email process as well
startService(new Intent(this, SyncManager.class));
} catch (RuntimeException e) {
// Crash; this is a completely unexpected runtime error
Log.e(TAG, "RuntimeException in SyncServiceManager", e);
throw e;
} finally {
shutdown();
}
}
private void shutdown() {
synchronized (sSyncLock) {
// If INSTANCE is null, we've already been shut down
if (INSTANCE != null) {
log("SyncServiceManager shutting down...");
// Stop our running syncs
stopServiceThreads();
// Stop receivers
if (mConnectivityReceiver != null) {
unregisterReceiver(mConnectivityReceiver);
}
if (mBackgroundDataSettingReceiver != null) {
unregisterReceiver(mBackgroundDataSettingReceiver);
}
// Unregister observers
ContentResolver resolver = getContentResolver();
if (mSyncedMessageObserver != null) {
resolver.unregisterContentObserver(mSyncedMessageObserver);
mSyncedMessageObserver = null;
}
if (mAccountObserver != null) {
resolver.unregisterContentObserver(mAccountObserver);
mAccountObserver = null;
}
if (mMailboxObserver != null) {
resolver.unregisterContentObserver(mMailboxObserver);
mMailboxObserver = null;
}
unregisterCalendarObservers();
// Clear pending alarms and associated Intents
clearAlarms();
// Release our wake lock, if we have one
synchronized (mWakeLocks) {
if (mWakeLock != null) {
mWakeLock.release();
mWakeLock = null;
}
}
INSTANCE = null;
sServiceThread = null;
sStop = false;
log("Goodbye");
}
}
}
/**
* Release a mailbox from the service map and release its wake lock.
* NOTE: This method MUST be called while holding sSyncLock!
*
* @param mailboxId the id of the mailbox to be released
*/
public void releaseMailbox(long mailboxId) {
mServiceMap.remove(mailboxId);
releaseWakeLock(mailboxId);
}
/**
* Check whether an Outbox (referenced by a Cursor) has any messages that can be sent
* @param c the cursor to an Outbox
* @return true if there is mail to be sent
*/
private boolean hasSendableMessages(Cursor outboxCursor) {
Cursor c = mResolver.query(Message.CONTENT_URI, Message.ID_COLUMN_PROJECTION,
MAILBOX_KEY_AND_NOT_SEND_FAILED,
new String[] {Long.toString(outboxCursor.getLong(Mailbox.CONTENT_ID_COLUMN))},
null);
try {
while (c.moveToNext()) {
if (!Utility.hasUnloadedAttachments(this, c.getLong(Message.CONTENT_ID_COLUMN))) {
return true;
}
}
} finally {
if (c != null) {
c.close();
}
}
return false;
}
/**
* Taken from ConnectivityManager using public constants
*/
public static boolean isNetworkTypeMobile(int networkType) {
switch (networkType) {
case ConnectivityManager.TYPE_MOBILE:
case ConnectivityManager.TYPE_MOBILE_MMS:
case ConnectivityManager.TYPE_MOBILE_SUPL:
case ConnectivityManager.TYPE_MOBILE_DUN:
case ConnectivityManager.TYPE_MOBILE_HIPRI:
return true;
default:
return false;
}
}
/**
* Determine whether the account is allowed to sync automatically, as opposed to manually, based
* on whether the "require manual sync when roaming" policy is in force and applicable
* @param account the account
* @return whether or not the account can sync automatically
*/
/*package*/ public static boolean canAutoSync(Account account) {
SyncManager ssm = INSTANCE;
if (ssm == null) {
return false;
}
NetworkInfo networkInfo = ssm.mNetworkInfo;
// Enforce manual sync only while roaming here
long policyKey = account.mPolicyKey;
// Quick exit from this check
if ((policyKey != 0) && (networkInfo != null) &&
isNetworkTypeMobile(networkInfo.getType())) {
// We'll cache the Policy data here
Policy policy = account.mPolicy;
if (policy == null) {
policy = Policy.restorePolicyWithId(INSTANCE, policyKey);
account.mPolicy = policy;
if (!PolicyServiceProxy.isActive(ssm, policy)) return false;
}
if (policy != null && policy.mRequireManualSyncWhenRoaming && networkInfo.isRoaming()) {
return false;
}
}
return true;
}
/**
* Convenience method to determine whether Email sync is enabled for a given account
* @param account the Account in question
* @return whether Email sync is enabled
*/
private boolean canSyncEmail(android.accounts.Account account) {
return ContentResolver.getSyncAutomatically(account, EmailContent.AUTHORITY);
}
/**
* Determine whether a mailbox of a given type in a given account can be synced automatically
* by SyncServiceManager. This is an increasingly complex determination, taking into account
* security policies and user settings (both within the Email application and in the Settings
* application)
*
* @param account the Account that the mailbox is in
* @param type the type of the Mailbox
* @return whether or not to start a sync
*/
private boolean isMailboxSyncable(Account account, int type) {
// This 'if' statement performs checks to see whether or not a mailbox is a
// candidate for syncing based on policies, user settings, & other restrictions
if (type == Mailbox.TYPE_OUTBOX) {
// Outbox is always syncable
return true;
} else if (type == Mailbox.TYPE_EAS_ACCOUNT_MAILBOX) {
// Always sync EAS mailbox unless master sync is off
return ContentResolver.getMasterSyncAutomatically();
} else if (type == Mailbox.TYPE_CONTACTS || type == Mailbox.TYPE_CALENDAR) {
// Contacts/Calendar obey this setting from ContentResolver
if (!ContentResolver.getMasterSyncAutomatically()) {
return false;
}
// Get the right authority for the mailbox
String authority;
if (type == Mailbox.TYPE_CONTACTS) {
authority = ContactsContract.AUTHORITY;
} else {
authority = CalendarContract.AUTHORITY;
if (!mCalendarObservers.containsKey(account.mId)){
// Make sure we have an observer for this Calendar, as
// we need to be able to detect sync state changes, sigh
registerCalendarObserver(account);
}
}
// See if "sync automatically" is set; if not, punt
if (!ContentResolver.getSyncAutomatically(account.mAmAccount, authority)) {
return false;
// See if the calendar is enabled from the Calendar app UI; if not, punt
} else if ((type == Mailbox.TYPE_CALENDAR) && !isCalendarEnabled(account.mId)) {
return false;
}
// Never automatically sync trash
} else if (type == Mailbox.TYPE_TRASH) {
return false;
// For non-outbox, non-account mail, we do three checks:
// 1) are we restricted by policy (i.e. manual sync only),
// 2) has the user checked the "Sync Email" box in Account Settings, and
// 3) does the user have the master "background data" box checked in Settings
} else if (!canAutoSync(account) || !canSyncEmail(account.mAmAccount) || !mBackgroundData) {
return false;
}
return true;
}
private long checkMailboxes () {
// First, see if any running mailboxes have been deleted
ArrayList<Long> deletedMailboxes = new ArrayList<Long>();
synchronized (sSyncLock) {
for (long mailboxId: mServiceMap.keySet()) {
Mailbox m = Mailbox.restoreMailboxWithId(this, mailboxId);
if (m == null) {
deletedMailboxes.add(mailboxId);
}
}
// If so, stop them or remove them from the map
for (Long mailboxId: deletedMailboxes) {
AbstractSyncService svc = mServiceMap.get(mailboxId);
if (svc == null || svc.mThread == null) {
releaseMailbox(mailboxId);
continue;
} else {
boolean alive = svc.mThread.isAlive();
log("Deleted mailbox: " + svc.mMailboxName);
if (alive) {
stopManualSync(mailboxId);
} else {
log("Removing from serviceMap");
releaseMailbox(mailboxId);
}
}
}
}
long nextWait = SYNC_SERVICE_HEARTBEAT_TIME;
long now = System.currentTimeMillis();
// Start up threads that need it; use a query which finds eas mailboxes where the
// the sync interval is not "never". This is the set of mailboxes that we control
if (mAccountObserver == null) {
log("mAccountObserver null; service died??");
return nextWait;
}
Cursor c = getContentResolver().query(Mailbox.CONTENT_URI, Mailbox.CONTENT_PROJECTION,
mAccountObserver.getSyncableMailboxWhere(), null, null);
if (c == null) throw new ProviderUnavailableException();
try {
while (c.moveToNext()) {
long mailboxId = c.getLong(Mailbox.CONTENT_ID_COLUMN);
AbstractSyncService service = null;
synchronized (sSyncLock) {
service = mServiceMap.get(mailboxId);
}
if (service == null) {
// Get the cached account
Account account = getAccountById(c.getInt(Mailbox.CONTENT_ACCOUNT_KEY_COLUMN));
if (account == null) continue;
// We handle a few types of mailboxes specially
int mailboxType = c.getInt(Mailbox.CONTENT_TYPE_COLUMN);
if (!isMailboxSyncable(account, mailboxType)) {
continue;
}
// Check whether we're in a hold (temporary or permanent)
SyncError syncError = mSyncErrorMap.get(mailboxId);
if (syncError != null) {
// Nothing we can do about fatal errors
if (syncError.fatal) continue;
if (now < syncError.holdEndTime) {
// If release time is earlier than next wait time,
// move next wait time up to the release time
if (syncError.holdEndTime < now + nextWait) {
nextWait = syncError.holdEndTime - now;
mNextWaitReason = "Release hold";
}
continue;
} else {
// Keep the error around, but clear the end time
syncError.holdEndTime = 0;
}
}
// Otherwise, we use the sync interval
long syncInterval = c.getInt(Mailbox.CONTENT_SYNC_INTERVAL_COLUMN);
if (syncInterval == Mailbox.CHECK_INTERVAL_PUSH) {
Mailbox m = EmailContent.getContent(c, Mailbox.class);
requestSync(m, SYNC_PUSH, null);
} else if (mailboxType == Mailbox.TYPE_OUTBOX) {
if (hasSendableMessages(c)) {
Mailbox m = EmailContent.getContent(c, Mailbox.class);
startServiceThread(getServiceForMailbox(this, m));
}
} else if (syncInterval > 0 && syncInterval <= ONE_DAY_MINUTES) {
long lastSync = c.getLong(Mailbox.CONTENT_SYNC_TIME_COLUMN);
long sinceLastSync = now - lastSync;
long toNextSync = syncInterval*MINUTES - sinceLastSync;
String name = c.getString(Mailbox.CONTENT_DISPLAY_NAME_COLUMN);
if (toNextSync <= 0) {
Mailbox m = EmailContent.getContent(c, Mailbox.class);
requestSync(m, SYNC_SCHEDULED, null);
} else if (toNextSync < nextWait) {
nextWait = toNextSync;
if (sUserLog) {
log("Next sync for " + name + " in " + nextWait/1000 + "s");
}
mNextWaitReason = "Scheduled sync, " + name;
} else if (sUserLog) {
log("Next sync for " + name + " in " + toNextSync/1000 + "s");
}
}
} else {
Thread thread = service.mThread;
// Look for threads that have died and remove them from the map
if (thread != null && !thread.isAlive()) {
if (sUserLog) {
log("Dead thread, mailbox released: " +
c.getString(Mailbox.CONTENT_DISPLAY_NAME_COLUMN));
}
- releaseMailbox(mailboxId);
+ synchronized (sSyncLock) {
+ releaseMailbox(mailboxId);
+ }
// Restart this if necessary
if (nextWait > 3*SECONDS) {
nextWait = 3*SECONDS;
mNextWaitReason = "Clean up dead thread(s)";
}
} else {
long requestTime = service.mRequestTime;
if (requestTime > 0) {
long timeToRequest = requestTime - now;
if (timeToRequest <= 0) {
service.mRequestTime = 0;
service.alarm();
} else if (requestTime > 0 && timeToRequest < nextWait) {
if (timeToRequest < 11*MINUTES) {
nextWait = timeToRequest < 250 ? 250 : timeToRequest;
mNextWaitReason = "Sync data change";
} else {
log("Illegal timeToRequest: " + timeToRequest);
}
}
}
}
}
}
} finally {
c.close();
}
return nextWait;
}
static public void serviceRequest(long mailboxId, int reason) {
serviceRequest(mailboxId, 5*SECONDS, reason);
}
/**
* Return a boolean indicating whether the mailbox can be synced
* @param m the mailbox
* @return whether or not the mailbox can be synced
*/
public static boolean isSyncable(Mailbox m) {
return m.mType != Mailbox.TYPE_DRAFTS
&& m.mType != Mailbox.TYPE_OUTBOX
&& m.mType != Mailbox.TYPE_SEARCH
&& m.mType < Mailbox.TYPE_NOT_SYNCABLE;
}
static public void serviceRequest(long mailboxId, long ms, int reason) {
SyncManager ssm = INSTANCE;
if (ssm == null) return;
Mailbox m = Mailbox.restoreMailboxWithId(ssm, mailboxId);
if (m == null || !isSyncable(m)) return;
try {
AbstractSyncService service = ssm.mServiceMap.get(mailboxId);
if (service != null) {
service.mRequestTime = System.currentTimeMillis() + ms;
kick("service request");
} else {
startManualSync(mailboxId, reason, null);
}
} catch (Exception e) {
e.printStackTrace();
}
}
static public void serviceRequestImmediate(long mailboxId) {
SyncManager ssm = INSTANCE;
if (ssm == null) return;
AbstractSyncService service = ssm.mServiceMap.get(mailboxId);
if (service != null) {
service.mRequestTime = System.currentTimeMillis();
Mailbox m = Mailbox.restoreMailboxWithId(ssm, mailboxId);
if (m != null) {
service.mAccount = Account.restoreAccountWithId(ssm, m.mAccountKey);
service.mMailbox = m;
kick("service request immediate");
}
}
}
static public void sendMessageRequest(Request req) {
SyncManager ssm = INSTANCE;
if (ssm == null) return;
Message msg = Message.restoreMessageWithId(ssm, req.mMessageId);
if (msg == null) return;
long mailboxId = msg.mMailboxKey;
Mailbox mailbox = Mailbox.restoreMailboxWithId(ssm, mailboxId);
if (mailbox == null) return;
// If we're loading an attachment for Outbox, we want to look at the source message
// to find the loading mailbox
if (mailbox.mType == Mailbox.TYPE_OUTBOX) {
long sourceId = Utility.getFirstRowLong(ssm, Body.CONTENT_URI,
new String[] {BodyColumns.SOURCE_MESSAGE_KEY},
BodyColumns.MESSAGE_KEY + "=?",
new String[] {Long.toString(msg.mId)}, null, 0, -1L);
if (sourceId != -1L) {
EmailContent.Message sourceMsg =
EmailContent.Message.restoreMessageWithId(ssm, sourceId);
if (sourceMsg != null) {
mailboxId = sourceMsg.mMailboxKey;
}
}
}
sendRequest(mailboxId, req);
}
static public void sendRequest(long mailboxId, Request req) {
SyncManager ssm = INSTANCE;
if (ssm == null) return;
AbstractSyncService service = ssm.mServiceMap.get(mailboxId);
if (service == null) {
startManualSync(mailboxId, SYNC_SERVICE_PART_REQUEST, req);
kick("part request");
} else {
service.addRequest(req);
}
}
/**
* Determine whether a given Mailbox can be synced, i.e. is not already syncing and is not in
* an error state
*
* @param mailboxId
* @return whether or not the Mailbox is available for syncing (i.e. is a valid push target)
*/
static public int pingStatus(long mailboxId) {
SyncManager ssm = INSTANCE;
if (ssm == null) return PING_STATUS_OK;
// Already syncing...
if (ssm.mServiceMap.get(mailboxId) != null) {
return PING_STATUS_RUNNING;
}
// No errors or a transient error, don't ping...
SyncError error = ssm.mSyncErrorMap.get(mailboxId);
if (error != null) {
if (error.fatal) {
return PING_STATUS_UNABLE;
} else if (error.holdEndTime > 0) {
return PING_STATUS_WAITING;
}
}
return PING_STATUS_OK;
}
static public void startManualSync(long mailboxId, int reason, Request req) {
SyncManager ssm = INSTANCE;
if (ssm == null) return;
synchronized (sSyncLock) {
AbstractSyncService svc = ssm.mServiceMap.get(mailboxId);
if (svc == null) {
ssm.mSyncErrorMap.remove(mailboxId);
Mailbox m = Mailbox.restoreMailboxWithId(ssm, mailboxId);
if (m != null) {
log("Starting sync for " + m.mDisplayName);
ssm.requestSync(m, reason, req);
}
} else {
// If this is a ui request, set the sync reason for the service
if (reason >= SYNC_CALLBACK_START) {
svc.mSyncReason = reason;
}
}
}
}
// DO NOT CALL THIS IN A LOOP ON THE SERVICEMAP
static public void stopManualSync(long mailboxId) {
SyncManager ssm = INSTANCE;
if (ssm == null) return;
synchronized (sSyncLock) {
AbstractSyncService svc = ssm.mServiceMap.get(mailboxId);
if (svc != null) {
log("Stopping sync for " + svc.mMailboxName);
svc.stop();
svc.mThread.interrupt();
ssm.releaseWakeLock(mailboxId);
}
}
}
/**
* Wake up SyncServiceManager to check for mailboxes needing service
*/
static public void kick(String reason) {
SyncManager ssm = INSTANCE;
if (ssm != null) {
synchronized (ssm) {
//INSTANCE.log("Kick: " + reason);
ssm.mKicked = true;
ssm.notify();
}
}
if (sConnectivityLock != null) {
synchronized (sConnectivityLock) {
sConnectivityLock.notify();
}
}
}
/**
* Tell SyncServiceManager to remove the mailbox from the map of mailboxes with sync errors
* @param mailboxId the id of the mailbox
*/
static public void removeFromSyncErrorMap(long mailboxId) {
SyncManager ssm = INSTANCE;
if (ssm != null) {
ssm.mSyncErrorMap.remove(mailboxId);
}
}
private boolean isRunningInServiceThread(long mailboxId) {
AbstractSyncService syncService = mServiceMap.get(mailboxId);
Thread thisThread = Thread.currentThread();
return syncService != null && syncService.mThread != null &&
thisThread == syncService.mThread;
}
/**
* Sent by services indicating that their thread is finished; action depends on the exitStatus
* of the service.
*
* @param svc the service that is finished
*/
static public void done(AbstractSyncService svc) {
SyncManager ssm = INSTANCE;
if (ssm == null) return;
synchronized(sSyncLock) {
long mailboxId = svc.mMailboxId;
// If we're no longer the syncing thread for the mailbox, just return
if (!ssm.isRunningInServiceThread(mailboxId)) {
return;
}
ssm.releaseMailbox(mailboxId);
ssm.setMailboxSyncStatus(mailboxId, EmailContent.SYNC_STATUS_NONE);
ConcurrentHashMap<Long, SyncError> errorMap = ssm.mSyncErrorMap;
SyncError syncError = errorMap.get(mailboxId);
int exitStatus = svc.mExitStatus;
Mailbox m = Mailbox.restoreMailboxWithId(ssm, mailboxId);
if (m == null) return;
if (exitStatus != AbstractSyncService.EXIT_LOGIN_FAILURE) {
long accountId = m.mAccountKey;
Account account = Account.restoreAccountWithId(ssm, accountId);
if (account == null) return;
if (ssm.releaseSyncHolds(ssm,
AbstractSyncService.EXIT_LOGIN_FAILURE, account)) {
new AccountServiceProxy(ssm).notifyLoginSucceeded(accountId);
}
}
int lastResult = EmailContent.LAST_SYNC_RESULT_SUCCESS;
// For error states, whether the error is fatal (won't automatically be retried)
boolean errorIsFatal = true;
try {
switch (exitStatus) {
case AbstractSyncService.EXIT_DONE:
if (svc.hasPendingRequests()) {
// TODO Handle this case
}
errorMap.remove(mailboxId);
// If we've had a successful sync, clear the shutdown count
synchronized (SyncManager.class) {
sClientConnectionManagerShutdownCount = 0;
}
// Leave now; other statuses are errors
return;
// I/O errors get retried at increasing intervals
case AbstractSyncService.EXIT_IO_ERROR:
if (syncError != null) {
syncError.escalate();
log(m.mDisplayName + " held for " + syncError.holdDelay + "ms");
return;
} else {
log(m.mDisplayName + " added to syncErrorMap, hold for 15s");
}
lastResult = EmailContent.LAST_SYNC_RESULT_CONNECTION_ERROR;
errorIsFatal = false;
break;
// These errors are not retried automatically
case AbstractSyncService.EXIT_LOGIN_FAILURE:
new AccountServiceProxy(ssm).notifyLoginFailed(m.mAccountKey, svc.mExitReason);
lastResult = EmailContent.LAST_SYNC_RESULT_AUTH_ERROR;
break;
case AbstractSyncService.EXIT_SECURITY_FAILURE:
case AbstractSyncService.EXIT_ACCESS_DENIED:
lastResult = EmailContent.LAST_SYNC_RESULT_SECURITY_ERROR;
break;
case AbstractSyncService.EXIT_EXCEPTION:
lastResult = EmailContent.LAST_SYNC_RESULT_INTERNAL_ERROR;
break;
}
// Add this box to the error map
errorMap.put(mailboxId, ssm.new SyncError(exitStatus, errorIsFatal));
} finally {
// Always set the last result
ssm.setMailboxLastSyncResult(mailboxId, lastResult);
kick("sync completed");
}
}
}
/**
* Given the status string from a Mailbox, return the type code for the last sync
* @param status the syncStatus column of a Mailbox
* @return
*/
static public int getStatusType(String status) {
if (status == null) {
return -1;
} else {
return status.charAt(STATUS_TYPE_CHAR) - '0';
}
}
/**
* Given the status string from a Mailbox, return the change count for the last sync
* The change count is the number of adds + deletes + changes in the last sync
* @param status the syncStatus column of a Mailbox
* @return
*/
static public int getStatusChangeCount(String status) {
try {
String s = status.substring(STATUS_CHANGE_COUNT_OFFSET);
return Integer.parseInt(s);
} catch (RuntimeException e) {
return -1;
}
}
static public Context getContext() {
return INSTANCE;
}
}
| true | true | private long checkMailboxes () {
// First, see if any running mailboxes have been deleted
ArrayList<Long> deletedMailboxes = new ArrayList<Long>();
synchronized (sSyncLock) {
for (long mailboxId: mServiceMap.keySet()) {
Mailbox m = Mailbox.restoreMailboxWithId(this, mailboxId);
if (m == null) {
deletedMailboxes.add(mailboxId);
}
}
// If so, stop them or remove them from the map
for (Long mailboxId: deletedMailboxes) {
AbstractSyncService svc = mServiceMap.get(mailboxId);
if (svc == null || svc.mThread == null) {
releaseMailbox(mailboxId);
continue;
} else {
boolean alive = svc.mThread.isAlive();
log("Deleted mailbox: " + svc.mMailboxName);
if (alive) {
stopManualSync(mailboxId);
} else {
log("Removing from serviceMap");
releaseMailbox(mailboxId);
}
}
}
}
long nextWait = SYNC_SERVICE_HEARTBEAT_TIME;
long now = System.currentTimeMillis();
// Start up threads that need it; use a query which finds eas mailboxes where the
// the sync interval is not "never". This is the set of mailboxes that we control
if (mAccountObserver == null) {
log("mAccountObserver null; service died??");
return nextWait;
}
Cursor c = getContentResolver().query(Mailbox.CONTENT_URI, Mailbox.CONTENT_PROJECTION,
mAccountObserver.getSyncableMailboxWhere(), null, null);
if (c == null) throw new ProviderUnavailableException();
try {
while (c.moveToNext()) {
long mailboxId = c.getLong(Mailbox.CONTENT_ID_COLUMN);
AbstractSyncService service = null;
synchronized (sSyncLock) {
service = mServiceMap.get(mailboxId);
}
if (service == null) {
// Get the cached account
Account account = getAccountById(c.getInt(Mailbox.CONTENT_ACCOUNT_KEY_COLUMN));
if (account == null) continue;
// We handle a few types of mailboxes specially
int mailboxType = c.getInt(Mailbox.CONTENT_TYPE_COLUMN);
if (!isMailboxSyncable(account, mailboxType)) {
continue;
}
// Check whether we're in a hold (temporary or permanent)
SyncError syncError = mSyncErrorMap.get(mailboxId);
if (syncError != null) {
// Nothing we can do about fatal errors
if (syncError.fatal) continue;
if (now < syncError.holdEndTime) {
// If release time is earlier than next wait time,
// move next wait time up to the release time
if (syncError.holdEndTime < now + nextWait) {
nextWait = syncError.holdEndTime - now;
mNextWaitReason = "Release hold";
}
continue;
} else {
// Keep the error around, but clear the end time
syncError.holdEndTime = 0;
}
}
// Otherwise, we use the sync interval
long syncInterval = c.getInt(Mailbox.CONTENT_SYNC_INTERVAL_COLUMN);
if (syncInterval == Mailbox.CHECK_INTERVAL_PUSH) {
Mailbox m = EmailContent.getContent(c, Mailbox.class);
requestSync(m, SYNC_PUSH, null);
} else if (mailboxType == Mailbox.TYPE_OUTBOX) {
if (hasSendableMessages(c)) {
Mailbox m = EmailContent.getContent(c, Mailbox.class);
startServiceThread(getServiceForMailbox(this, m));
}
} else if (syncInterval > 0 && syncInterval <= ONE_DAY_MINUTES) {
long lastSync = c.getLong(Mailbox.CONTENT_SYNC_TIME_COLUMN);
long sinceLastSync = now - lastSync;
long toNextSync = syncInterval*MINUTES - sinceLastSync;
String name = c.getString(Mailbox.CONTENT_DISPLAY_NAME_COLUMN);
if (toNextSync <= 0) {
Mailbox m = EmailContent.getContent(c, Mailbox.class);
requestSync(m, SYNC_SCHEDULED, null);
} else if (toNextSync < nextWait) {
nextWait = toNextSync;
if (sUserLog) {
log("Next sync for " + name + " in " + nextWait/1000 + "s");
}
mNextWaitReason = "Scheduled sync, " + name;
} else if (sUserLog) {
log("Next sync for " + name + " in " + toNextSync/1000 + "s");
}
}
} else {
Thread thread = service.mThread;
// Look for threads that have died and remove them from the map
if (thread != null && !thread.isAlive()) {
if (sUserLog) {
log("Dead thread, mailbox released: " +
c.getString(Mailbox.CONTENT_DISPLAY_NAME_COLUMN));
}
releaseMailbox(mailboxId);
// Restart this if necessary
if (nextWait > 3*SECONDS) {
nextWait = 3*SECONDS;
mNextWaitReason = "Clean up dead thread(s)";
}
} else {
long requestTime = service.mRequestTime;
if (requestTime > 0) {
long timeToRequest = requestTime - now;
if (timeToRequest <= 0) {
service.mRequestTime = 0;
service.alarm();
} else if (requestTime > 0 && timeToRequest < nextWait) {
if (timeToRequest < 11*MINUTES) {
nextWait = timeToRequest < 250 ? 250 : timeToRequest;
mNextWaitReason = "Sync data change";
} else {
log("Illegal timeToRequest: " + timeToRequest);
}
}
}
}
}
}
} finally {
c.close();
}
return nextWait;
}
| private long checkMailboxes () {
// First, see if any running mailboxes have been deleted
ArrayList<Long> deletedMailboxes = new ArrayList<Long>();
synchronized (sSyncLock) {
for (long mailboxId: mServiceMap.keySet()) {
Mailbox m = Mailbox.restoreMailboxWithId(this, mailboxId);
if (m == null) {
deletedMailboxes.add(mailboxId);
}
}
// If so, stop them or remove them from the map
for (Long mailboxId: deletedMailboxes) {
AbstractSyncService svc = mServiceMap.get(mailboxId);
if (svc == null || svc.mThread == null) {
releaseMailbox(mailboxId);
continue;
} else {
boolean alive = svc.mThread.isAlive();
log("Deleted mailbox: " + svc.mMailboxName);
if (alive) {
stopManualSync(mailboxId);
} else {
log("Removing from serviceMap");
releaseMailbox(mailboxId);
}
}
}
}
long nextWait = SYNC_SERVICE_HEARTBEAT_TIME;
long now = System.currentTimeMillis();
// Start up threads that need it; use a query which finds eas mailboxes where the
// the sync interval is not "never". This is the set of mailboxes that we control
if (mAccountObserver == null) {
log("mAccountObserver null; service died??");
return nextWait;
}
Cursor c = getContentResolver().query(Mailbox.CONTENT_URI, Mailbox.CONTENT_PROJECTION,
mAccountObserver.getSyncableMailboxWhere(), null, null);
if (c == null) throw new ProviderUnavailableException();
try {
while (c.moveToNext()) {
long mailboxId = c.getLong(Mailbox.CONTENT_ID_COLUMN);
AbstractSyncService service = null;
synchronized (sSyncLock) {
service = mServiceMap.get(mailboxId);
}
if (service == null) {
// Get the cached account
Account account = getAccountById(c.getInt(Mailbox.CONTENT_ACCOUNT_KEY_COLUMN));
if (account == null) continue;
// We handle a few types of mailboxes specially
int mailboxType = c.getInt(Mailbox.CONTENT_TYPE_COLUMN);
if (!isMailboxSyncable(account, mailboxType)) {
continue;
}
// Check whether we're in a hold (temporary or permanent)
SyncError syncError = mSyncErrorMap.get(mailboxId);
if (syncError != null) {
// Nothing we can do about fatal errors
if (syncError.fatal) continue;
if (now < syncError.holdEndTime) {
// If release time is earlier than next wait time,
// move next wait time up to the release time
if (syncError.holdEndTime < now + nextWait) {
nextWait = syncError.holdEndTime - now;
mNextWaitReason = "Release hold";
}
continue;
} else {
// Keep the error around, but clear the end time
syncError.holdEndTime = 0;
}
}
// Otherwise, we use the sync interval
long syncInterval = c.getInt(Mailbox.CONTENT_SYNC_INTERVAL_COLUMN);
if (syncInterval == Mailbox.CHECK_INTERVAL_PUSH) {
Mailbox m = EmailContent.getContent(c, Mailbox.class);
requestSync(m, SYNC_PUSH, null);
} else if (mailboxType == Mailbox.TYPE_OUTBOX) {
if (hasSendableMessages(c)) {
Mailbox m = EmailContent.getContent(c, Mailbox.class);
startServiceThread(getServiceForMailbox(this, m));
}
} else if (syncInterval > 0 && syncInterval <= ONE_DAY_MINUTES) {
long lastSync = c.getLong(Mailbox.CONTENT_SYNC_TIME_COLUMN);
long sinceLastSync = now - lastSync;
long toNextSync = syncInterval*MINUTES - sinceLastSync;
String name = c.getString(Mailbox.CONTENT_DISPLAY_NAME_COLUMN);
if (toNextSync <= 0) {
Mailbox m = EmailContent.getContent(c, Mailbox.class);
requestSync(m, SYNC_SCHEDULED, null);
} else if (toNextSync < nextWait) {
nextWait = toNextSync;
if (sUserLog) {
log("Next sync for " + name + " in " + nextWait/1000 + "s");
}
mNextWaitReason = "Scheduled sync, " + name;
} else if (sUserLog) {
log("Next sync for " + name + " in " + toNextSync/1000 + "s");
}
}
} else {
Thread thread = service.mThread;
// Look for threads that have died and remove them from the map
if (thread != null && !thread.isAlive()) {
if (sUserLog) {
log("Dead thread, mailbox released: " +
c.getString(Mailbox.CONTENT_DISPLAY_NAME_COLUMN));
}
synchronized (sSyncLock) {
releaseMailbox(mailboxId);
}
// Restart this if necessary
if (nextWait > 3*SECONDS) {
nextWait = 3*SECONDS;
mNextWaitReason = "Clean up dead thread(s)";
}
} else {
long requestTime = service.mRequestTime;
if (requestTime > 0) {
long timeToRequest = requestTime - now;
if (timeToRequest <= 0) {
service.mRequestTime = 0;
service.alarm();
} else if (requestTime > 0 && timeToRequest < nextWait) {
if (timeToRequest < 11*MINUTES) {
nextWait = timeToRequest < 250 ? 250 : timeToRequest;
mNextWaitReason = "Sync data change";
} else {
log("Illegal timeToRequest: " + timeToRequest);
}
}
}
}
}
}
} finally {
c.close();
}
return nextWait;
}
|
diff --git a/src/no/digipost/android/gui/adapters/ContentArrayAdapter.java b/src/no/digipost/android/gui/adapters/ContentArrayAdapter.java
index b773c535..1ebdddaf 100644
--- a/src/no/digipost/android/gui/adapters/ContentArrayAdapter.java
+++ b/src/no/digipost/android/gui/adapters/ContentArrayAdapter.java
@@ -1,222 +1,223 @@
/**
* Copyright (C) Posten Norge AS
*
* 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 no.digipost.android.gui.adapters;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import no.digipost.android.R;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Typeface;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.BackgroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.Filter;
import android.widget.ImageView;
import android.widget.TextView;
public abstract class ContentArrayAdapter<T> extends ArrayAdapter<T> {
public static final String TEXT_HIGHLIGHT_COLOR = "#EBEB86";
protected Context context;
protected ArrayList<T> objects;
protected ArrayList<T> filtered;
protected boolean[] checked;
protected boolean checkboxVisible;
protected TextView title;
protected TextView subTitle;
protected TextView metaTop;
protected TextView metaMiddle;
protected ImageView metaBottom;
protected Filter contentFilter;
protected String titleFilterText;
protected String subTitleFilterText;
protected String metaTopFilterText;
public ContentArrayAdapter(final Context context, final int resource, final ArrayList<T> objects) {
super(context, resource, objects);
this.context = context;
this.filtered = objects;
this.objects = this.filtered;
this.checked = new boolean[this.filtered.size()];
this.titleFilterText = null;
this.subTitleFilterText = null;
this.metaTopFilterText = null;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.content_list_item, parent, false);
this.title = (TextView) row.findViewById(R.id.content_title);
this.subTitle = (TextView) row.findViewById(R.id.content_subTitle);
this.metaTop = (TextView) row.findViewById(R.id.content_meta_top);
this.metaMiddle = (TextView) row.findViewById(R.id.content_meta_middle);
this.metaBottom = (ImageView) row.findViewById(R.id.content_meta_bottom);
CheckBox checkBox = (CheckBox) row.findViewById(R.id.content_checkbox);
checkBox.setFocusable(false);
+ checkBox.setClickable(false);
if (checkboxVisible) {
if (checked[position]) {
checkBox.setChecked(true);
}
checkBox.setVisibility(View.VISIBLE);
} else {
checkBox.setVisibility(View.GONE);
}
return row;
}
protected void setTitleAndSubTitleBold() {
title.setTypeface(null, Typeface.BOLD);
subTitle.setTypeface(null, Typeface.BOLD);
}
public void replaceAll(Collection<? extends T> collection) {
this.filtered.clear();
this.filtered.addAll(collection);
this.objects = this.filtered;
initializeChecked();
notifyDataSetChanged();
}
@Override
public void add(final T object) {
filtered.add(object);
initializeChecked();
notifyDataSetChanged();
}
@Override
public T getItem(final int position) {
return filtered.get(position);
}
@Override
public int getCount() {
return filtered.size();
}
@Override
public void remove(final T object) {
filtered.remove(object);
initializeChecked();
notifyDataSetChanged();
}
@Override
public void addAll(Collection<? extends T> collection) {
filtered.addAll(collection);
initializeChecked();
notifyDataSetChanged();
}
@Override
public abstract Filter getFilter();
protected void setFilterTextColor() {
if (titleFilterText != null) {
setTextViewFilterTextColor(title, titleFilterText);
}
if (subTitleFilterText != null) {
setTextViewFilterTextColor(subTitle, subTitleFilterText);
}
if (metaTopFilterText != null) {
setTextViewFilterTextColor(metaTop, metaTopFilterText);
}
}
private void setTextViewFilterTextColor(final TextView v, final String filterText) {
int l = filterText.length();
int i = v.getText().toString().toLowerCase().indexOf(filterText.toLowerCase());
if (i < 0) {
return;
}
Spannable sb = new SpannableString(v.getText().toString());
sb.setSpan(new BackgroundColorSpan(Color.parseColor(TEXT_HIGHLIGHT_COLOR)), i, i + l, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
v.setText(sb);
}
private void initializeChecked() {
checked = new boolean[filtered.size()];
}
public void setCheckboxVisible(boolean state) {
checkboxVisible = state;
initializeChecked();
notifyDataSetChanged();
}
public void clearChecked() {
initializeChecked();
notifyDataSetChanged();
}
public void setChecked(int position) {
checked[position] = !checked[position];
}
public int getCheckedCount() {
int count = 0;
for (boolean state : checked) {
if (state) {
count++;
}
}
return count;
}
public ArrayList<T> getCheckedItems() {
ArrayList<T> checkedItems = new ArrayList<T>();
for (int i = 0; i < checked.length; i++) {
if (checked[i]) {
checkedItems.add(filtered.get(i));
}
}
return checkedItems;
}
public void clearFilter() {
getFilter().filter("");
}
}
| true | true | public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.content_list_item, parent, false);
this.title = (TextView) row.findViewById(R.id.content_title);
this.subTitle = (TextView) row.findViewById(R.id.content_subTitle);
this.metaTop = (TextView) row.findViewById(R.id.content_meta_top);
this.metaMiddle = (TextView) row.findViewById(R.id.content_meta_middle);
this.metaBottom = (ImageView) row.findViewById(R.id.content_meta_bottom);
CheckBox checkBox = (CheckBox) row.findViewById(R.id.content_checkbox);
checkBox.setFocusable(false);
if (checkboxVisible) {
if (checked[position]) {
checkBox.setChecked(true);
}
checkBox.setVisibility(View.VISIBLE);
} else {
checkBox.setVisibility(View.GONE);
}
return row;
}
| public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.content_list_item, parent, false);
this.title = (TextView) row.findViewById(R.id.content_title);
this.subTitle = (TextView) row.findViewById(R.id.content_subTitle);
this.metaTop = (TextView) row.findViewById(R.id.content_meta_top);
this.metaMiddle = (TextView) row.findViewById(R.id.content_meta_middle);
this.metaBottom = (ImageView) row.findViewById(R.id.content_meta_bottom);
CheckBox checkBox = (CheckBox) row.findViewById(R.id.content_checkbox);
checkBox.setFocusable(false);
checkBox.setClickable(false);
if (checkboxVisible) {
if (checked[position]) {
checkBox.setChecked(true);
}
checkBox.setVisibility(View.VISIBLE);
} else {
checkBox.setVisibility(View.GONE);
}
return row;
}
|
diff --git a/src/org/ssgwt/client/ui/menu/TopMenuBar.java b/src/org/ssgwt/client/ui/menu/TopMenuBar.java
index b547357..d713069 100644
--- a/src/org/ssgwt/client/ui/menu/TopMenuBar.java
+++ b/src/org/ssgwt/client/ui/menu/TopMenuBar.java
@@ -1,232 +1,233 @@
/**
* Copyright 2012 A24Group
*
* 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.ssgwt.client.ui.menu;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.ssgwt.client.ui.datagrid.SSDataGrid.Resources;
import org.ssgwt.client.ui.datagrid.SSDataGrid.Style;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.MouseUpEvent;
import com.google.gwt.event.dom.client.MouseUpHandler;
import com.google.gwt.resources.client.ClientBundle;
import com.google.gwt.resources.client.CssResource;
import com.google.gwt.resources.client.ClientBundle.Source;
import com.google.gwt.resources.client.CssResource.ClassName;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.Widget;
/**
* This class will render a top menu based on a list
* of menu items that is passed in to it
*
* @author Michael Barnard
* @since 9 July 2012
*/
public class TopMenuBar extends Composite {
/**
* Instance of the UiBinder
*/
private static Binder uiBinder = GWT.create(Binder.class);
/**
* The default resources holder for the top menu
*/
private static TopMenuResources DEFAULT_RESOURCES;
/**
* The holder for the custom resources
*/
private TopMenuResources resources;
/**
* The holder for the selected menu item
*/
private Button selectedItem = null;
/**
* A list of the menu item
*/
private List<MenuItem> menuItems;
/**
* The flow panel used for the menu item list
*/
@UiField
FlowPanel topMenu;
/**
* UiBinder interface for the composite
*
* @author Michael Barnard
* @since 9 July 2012
*/
interface Binder extends UiBinder<Widget, TopMenuBar> {
}
/**
* A ClientBundle that provides images for this widget.
*/
public interface TopMenuResources extends ClientBundle {
/**
* The styles used in this widget.
*/
@Source("TopMenuBar.css")
Style topMenuStyle();
}
/**
* The css resource standards that that should be followed
*
* @author Michael Barnard
* @since 9 July 2012
*/
public interface Style extends CssResource {
/**
* The style for a non selected button
*
* @return The name of the compiled style
*/
String buttonStyle();
/**
* The style for the selected button
*
* @return The name of the compiled style
*/
String buttonSelectedStyle();
/**
* The style for the panel that contains all the menu items
*
* @return The name of the compiled style
*/
String containerStyle();
}
/**
* The class constructor
*
* @param menuItems - The list of menu items that needs to be added to the menu bar
*/
public TopMenuBar(List<MenuItem> menuItems) {
this(menuItems, getDefaultResources());
}
/**
* The class constructor
*
* @param menuItems - The list of menu items that needs to be added to the menu bar
* @param resources - The resources that needs to be used on the menu bar
*/
public TopMenuBar(List<MenuItem> menuItems, TopMenuResources resources) {
this.resources = resources;
this.resources.topMenuStyle().ensureInjected();
this.initWidget(uiBinder.createAndBindUi(this));
this.setTopMenuBar(menuItems);
}
/**
* Setter for the menu Items
*
* @param menuItems - The list of menu items that needs to be added to the menu bar
*/
public void setTopMenuBar(List<MenuItem> menuItems) {
topMenu.clear();
if (menuItems != null) {
List<MenuItem> sorted = new ArrayList<MenuItem>();
int max = 0;
for (int x = 0; x < menuItems.size(); x++) {
int current = menuItems.get(x).getOrder();
if (current > max) {
max = current;
}
}
for(int x = 0; x <= max; x++) {
for (MenuItem menuItem : menuItems) {
int current = menuItem.getOrder();
if (current == x) {
sorted.add(menuItem);
}
}
}
menuItems = sorted;
boolean containsDefault = false;
for (MenuItem menuItem : sorted) {
containsDefault = containsDefault || menuItem.isDefaultSelected();
}
for (MenuItem menuItem : menuItems) {
final Button button = new Button();
final MenuItem currentMenuItem = menuItem;
button.setText(currentMenuItem.getLabel());
button.addMouseUpHandler(new MouseUpHandler() {
/**
* Triggered when the mouse button is released
* while the pointer is over the menu item
*
* @param event - The event that will be triggered
*/
@Override
public void onMouseUp(MouseUpEvent event) {
selectedItem.setStyleName(TopMenuBar.this.resources.topMenuStyle().buttonStyle());
button.setStyleName(TopMenuBar.this.resources.topMenuStyle().buttonSelectedStyle());
selectedItem = button;
currentMenuItem.getCommand().execute();
}
});
if (!containsDefault) {
selectedItem = button;
button.setStyleName(resources.topMenuStyle().buttonSelectedStyle());
containsDefault = true;
+ currentMenuItem.getCommand().execute();
} else {
if (menuItem.isDefaultSelected()) {
selectedItem = button;
button.setStyleName(resources.topMenuStyle().buttonSelectedStyle());
menuItem.getCommand().execute();
} else {
button.setStyleName(resources.topMenuStyle().buttonStyle());
}
}
topMenu.setStyleName(resources.topMenuStyle().containerStyle());
topMenu.add(button);
}
}
}
/**
* Gets the default menu bar resources
*
* @return The default resources that should be used for the menu bar
*/
private static TopMenuResources getDefaultResources() {
if (DEFAULT_RESOURCES == null) {
DEFAULT_RESOURCES = GWT.create(TopMenuResources.class);
}
return DEFAULT_RESOURCES;
}
}
| true | true | public void setTopMenuBar(List<MenuItem> menuItems) {
topMenu.clear();
if (menuItems != null) {
List<MenuItem> sorted = new ArrayList<MenuItem>();
int max = 0;
for (int x = 0; x < menuItems.size(); x++) {
int current = menuItems.get(x).getOrder();
if (current > max) {
max = current;
}
}
for(int x = 0; x <= max; x++) {
for (MenuItem menuItem : menuItems) {
int current = menuItem.getOrder();
if (current == x) {
sorted.add(menuItem);
}
}
}
menuItems = sorted;
boolean containsDefault = false;
for (MenuItem menuItem : sorted) {
containsDefault = containsDefault || menuItem.isDefaultSelected();
}
for (MenuItem menuItem : menuItems) {
final Button button = new Button();
final MenuItem currentMenuItem = menuItem;
button.setText(currentMenuItem.getLabel());
button.addMouseUpHandler(new MouseUpHandler() {
/**
* Triggered when the mouse button is released
* while the pointer is over the menu item
*
* @param event - The event that will be triggered
*/
@Override
public void onMouseUp(MouseUpEvent event) {
selectedItem.setStyleName(TopMenuBar.this.resources.topMenuStyle().buttonStyle());
button.setStyleName(TopMenuBar.this.resources.topMenuStyle().buttonSelectedStyle());
selectedItem = button;
currentMenuItem.getCommand().execute();
}
});
if (!containsDefault) {
selectedItem = button;
button.setStyleName(resources.topMenuStyle().buttonSelectedStyle());
containsDefault = true;
} else {
if (menuItem.isDefaultSelected()) {
selectedItem = button;
button.setStyleName(resources.topMenuStyle().buttonSelectedStyle());
menuItem.getCommand().execute();
} else {
button.setStyleName(resources.topMenuStyle().buttonStyle());
}
}
topMenu.setStyleName(resources.topMenuStyle().containerStyle());
topMenu.add(button);
}
}
}
| public void setTopMenuBar(List<MenuItem> menuItems) {
topMenu.clear();
if (menuItems != null) {
List<MenuItem> sorted = new ArrayList<MenuItem>();
int max = 0;
for (int x = 0; x < menuItems.size(); x++) {
int current = menuItems.get(x).getOrder();
if (current > max) {
max = current;
}
}
for(int x = 0; x <= max; x++) {
for (MenuItem menuItem : menuItems) {
int current = menuItem.getOrder();
if (current == x) {
sorted.add(menuItem);
}
}
}
menuItems = sorted;
boolean containsDefault = false;
for (MenuItem menuItem : sorted) {
containsDefault = containsDefault || menuItem.isDefaultSelected();
}
for (MenuItem menuItem : menuItems) {
final Button button = new Button();
final MenuItem currentMenuItem = menuItem;
button.setText(currentMenuItem.getLabel());
button.addMouseUpHandler(new MouseUpHandler() {
/**
* Triggered when the mouse button is released
* while the pointer is over the menu item
*
* @param event - The event that will be triggered
*/
@Override
public void onMouseUp(MouseUpEvent event) {
selectedItem.setStyleName(TopMenuBar.this.resources.topMenuStyle().buttonStyle());
button.setStyleName(TopMenuBar.this.resources.topMenuStyle().buttonSelectedStyle());
selectedItem = button;
currentMenuItem.getCommand().execute();
}
});
if (!containsDefault) {
selectedItem = button;
button.setStyleName(resources.topMenuStyle().buttonSelectedStyle());
containsDefault = true;
currentMenuItem.getCommand().execute();
} else {
if (menuItem.isDefaultSelected()) {
selectedItem = button;
button.setStyleName(resources.topMenuStyle().buttonSelectedStyle());
menuItem.getCommand().execute();
} else {
button.setStyleName(resources.topMenuStyle().buttonStyle());
}
}
topMenu.setStyleName(resources.topMenuStyle().containerStyle());
topMenu.add(button);
}
}
}
|
diff --git a/src/me/guillaumin/android/osmtracker/gpx/ExportTrackTask.java b/src/me/guillaumin/android/osmtracker/gpx/ExportTrackTask.java
index c2abe51..804fad9 100644
--- a/src/me/guillaumin/android/osmtracker/gpx/ExportTrackTask.java
+++ b/src/me/guillaumin/android/osmtracker/gpx/ExportTrackTask.java
@@ -1,306 +1,310 @@
package me.guillaumin.android.osmtracker.gpx;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import me.guillaumin.android.osmtracker.OSMTracker;
import me.guillaumin.android.osmtracker.R;
import me.guillaumin.android.osmtracker.db.DataHelper;
import me.guillaumin.android.osmtracker.db.TrackContentProvider;
import me.guillaumin.android.osmtracker.db.TrackContentProvider.Schema;
import me.guillaumin.android.osmtracker.exception.ExportTrackException;
import android.app.ProgressDialog;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.widget.Toast;
/**
* Writes a GPX file.
*
* @author Nicolas Guillaumin
*
*/
public class ExportTrackTask extends AsyncTask<Void, Integer, Boolean> {
/**
* XML header.
*/
private static final String XML_HEADER = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>";
private static final String CDATA_START = "<![CDATA[";
private static final String CDATA_END = "]]>";
/**
* GPX opening tag
*/
private static final String TAG_GPX = "<gpx"
+ " xmlns=\"http://www.topografix.com/GPX/1/1\""
+ " version=\"1.1\""
+ " creator=\"osmtracker-android\"" // TODO: Get name in resources ?
+ " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""
+ " xsi:schemaLocation=\"http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd \">";
/**
* Date format for a point timestamp.
*/
private static SimpleDateFormat POINT_DATE_FORMATTER = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
static {
POINT_DATE_FORMATTER.setTimeZone(TimeZone.getTimeZone("UTC"));
}
/**
* {@link Context} to get resources
*/
private Context context;
/**
* Track ID to export
*/
private long trackId;
/**
* Dialog to display while exporting
*/
private ProgressDialog dialog;
/**
* Message in case of an error
*/
private String errorMsg = null;
public ExportTrackTask(Context context, long trackId) {
this.context = context;
this.trackId = trackId;
}
@Override
protected void onPreExecute() {
// Display dialog
dialog = new ProgressDialog(context);
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.setIndeterminate(true);
dialog.setTitle(
context.getResources().getString(R.string.trackmgr_exporting)
.replace("{0}", Long.toString(trackId)));
dialog.setCancelable(false);
dialog.show();
}
@Override
protected Boolean doInBackground(Void... params) {
try {
exportTrackAsGpx(trackId);
} catch (ExportTrackException ete) {
errorMsg = ete.getMessage();
return false;
}
return true;
}
@Override
protected void onProgressUpdate(Integer... values) {
dialog.setProgress(values[0]);
}
@Override
protected void onPostExecute(Boolean success) {
dialog.dismiss();
if (!success) {
Toast.makeText(context, context.getResources()
.getString(R.string.trackmgr_export_error)
.replace("{0}", errorMsg),
Toast.LENGTH_LONG).show();
}
}
private void exportTrackAsGpx(long trackId) throws ExportTrackException {
File sdRoot = Environment.getExternalStorageDirectory();
if (sdRoot.canWrite()) {
Cursor c = context.getContentResolver()
.query(ContentUris.withAppendedId(TrackContentProvider.CONTENT_URI_TRACK, trackId), null, null,
null, null);
c.moveToFirst();
File trackDir = new File(c.getString(c.getColumnIndex(Schema.COL_DIR)));
long startDate = c.getLong(c.getColumnIndex(Schema.COL_START_DATE));
c.close();
if (trackDir != null) {
File trackFile = new File(trackDir, DataHelper.FILENAME_FORMATTER.format(new Date(startDate))
+ DataHelper.EXTENSION_GPX);
Cursor cTrackPoints = context.getContentResolver().query(TrackContentProvider.trackPointsUri(trackId), null,
null, null, Schema.COL_TIMESTAMP + " asc");
Cursor cWayPoints = context.getContentResolver().query(TrackContentProvider.waypointsUri(trackId), null, null,
null, Schema.COL_TIMESTAMP + " asc");
dialog.setIndeterminate(false);
dialog.setProgress(0);
dialog.setMax(cTrackPoints.getCount() + cWayPoints.getCount());
try {
writeGpxFile(cTrackPoints, cWayPoints, trackFile);
DataHelper.setTrackExportDate(trackId, System.currentTimeMillis(), context.getContentResolver());
} catch (IOException ioe) {
throw new ExportTrackException(ioe.getMessage());
} finally {
cTrackPoints.close();
cWayPoints.close();
}
}
} else {
throw new ExportTrackException(context.getResources().getString(R.string.error_externalstorage_not_writable));
}
}
/**
* Writes the GPX file
* @param cTrackPoints Cursor to track points.
* @param cWayPoints Cursor to way points.
* @param target Target GPX file
* @throws IOException
*/
private void writeGpxFile(Cursor cTrackPoints, Cursor cWayPoints, File target) throws IOException {
String accuracyOutput = PreferenceManager.getDefaultSharedPreferences(context).getString(
OSMTracker.Preferences.KEY_OUTPUT_ACCURACY,
OSMTracker.Preferences.VAL_OUTPUT_ACCURACY);
boolean fillHDOP = PreferenceManager.getDefaultSharedPreferences(context).getBoolean(
OSMTracker.Preferences.KEY_OUTPUT_GPX_HDOP_APPROXIMATION,
OSMTracker.Preferences.VAL_OUTPUT_GPX_HDOP_APPROXIMATION);
FileWriter fw = new FileWriter(target);
fw.write(XML_HEADER + "\n");
fw.write(TAG_GPX + "\n");
writeTrackPoints(context.getResources().getString(R.string.gpx_track_name), fw, cTrackPoints, fillHDOP);
writeWayPoints(fw, cWayPoints, accuracyOutput, fillHDOP);
fw.write("</gpx>");
fw.close();
}
/**
* Iterates on track points and write them.
* @param trackName Name of the track (metadata).
* @param fw Writer to the target file.
* @param c Cursor to track points.
* @param fillHDOP Indicates whether fill <hdop> tag with approximation from location accuracy.
* @throws IOException
*/
private void writeTrackPoints(String trackName, FileWriter fw, Cursor c, boolean fillHDOP) throws IOException {
fw.write("\t" + "<trk>" + "\n");
fw.write("\t\t" + "<name>" + CDATA_START + trackName + CDATA_END + "</name>" + "\n");
if (fillHDOP) {
fw.write("\t\t" + "<cmt>"
+ CDATA_START
+ context.getResources().getString(R.string.gpx_hdop_approximation_cmt)
+ CDATA_END
+ "</cmt>" + "\n");
}
fw.write("\t\t" + "<trkseg>" + "\n");
for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
StringBuffer out = new StringBuffer();
out.append("\t\t\t" + "<trkpt lat=\""
+ c.getDouble(c.getColumnIndex(Schema.COL_LATITUDE)) + "\" "
+ "lon=\"" + c.getDouble(c.getColumnIndex(Schema.COL_LONGITUDE)) + "\">" + "\n");
if (! c.isNull(c.getColumnIndex(Schema.COL_ELEVATION))) {
out.append("\t\t\t\t" + "<ele>" + c.getDouble(c.getColumnIndex(Schema.COL_ELEVATION)) + "</ele>" + "\n");
}
out.append("\t\t\t\t" + "<time>" + POINT_DATE_FORMATTER.format(new Date(c.getLong(c.getColumnIndex(Schema.COL_TIMESTAMP)))) + "</time>" + "\n");
if(fillHDOP && ! c.isNull(c.getColumnIndex(Schema.COL_ACCURACY))) {
out.append("\t\t\t\t" + "<hdop>" + (c.getDouble(c.getColumnIndex(Schema.COL_ACCURACY)) / OSMTracker.HDOP_APPROXIMATION_FACTOR) + "</hdop>" + "\n");
}
out.append("\t\t\t" + "</trkpt>" + "\n");
fw.write(out.toString());
dialog.incrementProgressBy(1);
}
fw.write("\t\t" + "</trkseg>" + "\n");
fw.write("\t" + "</trk>" + "\n");
}
/**
* Iterates on way points and write them.
* @param fw Writer to the target file.
* @param c Cursor to way points.
* @param accuracyInfo Constant describing how to include (or not) accuracy info for way points.
* @param fillHDOP Indicates whether fill <hdop> tag with approximation from location accuracy.
* @throws IOException
*/
private void writeWayPoints(FileWriter fw, Cursor c, String accuracyInfo, boolean fillHDOP) throws IOException {
// Label for meter unit
String meterUnit = context.getResources().getString(R.string.various_unit_meters);
// Word "accuracy"
String accuracy = context.getResources().getString(R.string.various_accuracy);
for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
StringBuffer out = new StringBuffer();
out.append("\t" + "<wpt lat=\""
+ c.getDouble(c.getColumnIndex(Schema.COL_LATITUDE)) + "\" "
+ "lon=\"" + c.getDouble(c.getColumnIndex(Schema.COL_LONGITUDE)) + "\">" + "\n");
if (! c.isNull(c.getColumnIndex(Schema.COL_ELEVATION))) {
out.append("\t\t" + "<ele>" + c.getDouble(c.getColumnIndex(Schema.COL_ELEVATION)) + "</ele>" + "\n");
}
out.append("\t\t" + "<time>" + POINT_DATE_FORMATTER.format(new Date(c.getLong(c.getColumnIndex(Schema.COL_TIMESTAMP)))) + "</time>" + "\n");
if(fillHDOP && ! c.isNull(c.getColumnIndex(Schema.COL_ACCURACY))) {
out.append("\t\t" + "<hdop>" + (c.getDouble(c.getColumnIndex(Schema.COL_ACCURACY)) / OSMTracker.HDOP_APPROXIMATION_FACTOR) + "</hdop>" + "\n");
}
String name = c.getString(c.getColumnIndex(Schema.COL_NAME));
if (! OSMTracker.Preferences.VAL_OUTPUT_ACCURACY_NONE.equals(accuracyInfo) && ! c.isNull(c.getColumnIndex(Schema.COL_ACCURACY))) {
// Outputs accuracy info for way point
if (OSMTracker.Preferences.VAL_OUTPUT_ACCURACY_WPT_NAME.equals(accuracyInfo)) {
// Output accuracy with name
out.append("\t\t" + "<name>"
+ CDATA_START
+ name
+ " (" + c.getDouble(c.getColumnIndex(Schema.COL_ACCURACY)) + meterUnit + ")"
+ CDATA_END
+ "</name>" + "\n");
} else if (OSMTracker.Preferences.VAL_OUTPUT_ACCURACY_WPT_CMT.equals(accuracyInfo)) {
// Output accuracy in separate tag
out.append("\t\t" + "<name>" + CDATA_START + name + CDATA_END + "</name>" + "\n");
out.append("\t\t" + "<cmt>" + CDATA_START + accuracy + ": " + c.getDouble(c.getColumnIndex(Schema.COL_ACCURACY)) + meterUnit + CDATA_END + "</cmt>" + "\n");
+ } else {
+ // Unknown value for accuracy info, shouldn't occur but who knows ?
+ // See issue #68. Output at least the name just in case.
+ out.append("\t\t" + "<name>" + CDATA_START + name + CDATA_END + "</name>" + "\n");
}
} else {
// No accuracy info requested, or available
out.append("\t\t" + "<name>" + CDATA_START + name + CDATA_END + "</name>" + "\n");
}
String link = c.getString(c.getColumnIndex(Schema.COL_LINK));
if (link != null) {
out.append("\t\t" + "<link>" + link + "</link>" + "\n");
}
if (! c.isNull(c.getColumnIndex(Schema.COL_NBSATELLITES))) {
out.append("\t\t" + "<sat>" + c.getInt(c.getColumnIndex(Schema.COL_NBSATELLITES)) + "</sat>" + "\n");
}
out.append("\t" + "</wpt>" + "\n");
fw.write(out.toString());
dialog.incrementProgressBy(1);
}
}
}
| true | true | private void writeWayPoints(FileWriter fw, Cursor c, String accuracyInfo, boolean fillHDOP) throws IOException {
// Label for meter unit
String meterUnit = context.getResources().getString(R.string.various_unit_meters);
// Word "accuracy"
String accuracy = context.getResources().getString(R.string.various_accuracy);
for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
StringBuffer out = new StringBuffer();
out.append("\t" + "<wpt lat=\""
+ c.getDouble(c.getColumnIndex(Schema.COL_LATITUDE)) + "\" "
+ "lon=\"" + c.getDouble(c.getColumnIndex(Schema.COL_LONGITUDE)) + "\">" + "\n");
if (! c.isNull(c.getColumnIndex(Schema.COL_ELEVATION))) {
out.append("\t\t" + "<ele>" + c.getDouble(c.getColumnIndex(Schema.COL_ELEVATION)) + "</ele>" + "\n");
}
out.append("\t\t" + "<time>" + POINT_DATE_FORMATTER.format(new Date(c.getLong(c.getColumnIndex(Schema.COL_TIMESTAMP)))) + "</time>" + "\n");
if(fillHDOP && ! c.isNull(c.getColumnIndex(Schema.COL_ACCURACY))) {
out.append("\t\t" + "<hdop>" + (c.getDouble(c.getColumnIndex(Schema.COL_ACCURACY)) / OSMTracker.HDOP_APPROXIMATION_FACTOR) + "</hdop>" + "\n");
}
String name = c.getString(c.getColumnIndex(Schema.COL_NAME));
if (! OSMTracker.Preferences.VAL_OUTPUT_ACCURACY_NONE.equals(accuracyInfo) && ! c.isNull(c.getColumnIndex(Schema.COL_ACCURACY))) {
// Outputs accuracy info for way point
if (OSMTracker.Preferences.VAL_OUTPUT_ACCURACY_WPT_NAME.equals(accuracyInfo)) {
// Output accuracy with name
out.append("\t\t" + "<name>"
+ CDATA_START
+ name
+ " (" + c.getDouble(c.getColumnIndex(Schema.COL_ACCURACY)) + meterUnit + ")"
+ CDATA_END
+ "</name>" + "\n");
} else if (OSMTracker.Preferences.VAL_OUTPUT_ACCURACY_WPT_CMT.equals(accuracyInfo)) {
// Output accuracy in separate tag
out.append("\t\t" + "<name>" + CDATA_START + name + CDATA_END + "</name>" + "\n");
out.append("\t\t" + "<cmt>" + CDATA_START + accuracy + ": " + c.getDouble(c.getColumnIndex(Schema.COL_ACCURACY)) + meterUnit + CDATA_END + "</cmt>" + "\n");
}
} else {
// No accuracy info requested, or available
out.append("\t\t" + "<name>" + CDATA_START + name + CDATA_END + "</name>" + "\n");
}
String link = c.getString(c.getColumnIndex(Schema.COL_LINK));
if (link != null) {
out.append("\t\t" + "<link>" + link + "</link>" + "\n");
}
if (! c.isNull(c.getColumnIndex(Schema.COL_NBSATELLITES))) {
out.append("\t\t" + "<sat>" + c.getInt(c.getColumnIndex(Schema.COL_NBSATELLITES)) + "</sat>" + "\n");
}
out.append("\t" + "</wpt>" + "\n");
fw.write(out.toString());
dialog.incrementProgressBy(1);
}
}
| private void writeWayPoints(FileWriter fw, Cursor c, String accuracyInfo, boolean fillHDOP) throws IOException {
// Label for meter unit
String meterUnit = context.getResources().getString(R.string.various_unit_meters);
// Word "accuracy"
String accuracy = context.getResources().getString(R.string.various_accuracy);
for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
StringBuffer out = new StringBuffer();
out.append("\t" + "<wpt lat=\""
+ c.getDouble(c.getColumnIndex(Schema.COL_LATITUDE)) + "\" "
+ "lon=\"" + c.getDouble(c.getColumnIndex(Schema.COL_LONGITUDE)) + "\">" + "\n");
if (! c.isNull(c.getColumnIndex(Schema.COL_ELEVATION))) {
out.append("\t\t" + "<ele>" + c.getDouble(c.getColumnIndex(Schema.COL_ELEVATION)) + "</ele>" + "\n");
}
out.append("\t\t" + "<time>" + POINT_DATE_FORMATTER.format(new Date(c.getLong(c.getColumnIndex(Schema.COL_TIMESTAMP)))) + "</time>" + "\n");
if(fillHDOP && ! c.isNull(c.getColumnIndex(Schema.COL_ACCURACY))) {
out.append("\t\t" + "<hdop>" + (c.getDouble(c.getColumnIndex(Schema.COL_ACCURACY)) / OSMTracker.HDOP_APPROXIMATION_FACTOR) + "</hdop>" + "\n");
}
String name = c.getString(c.getColumnIndex(Schema.COL_NAME));
if (! OSMTracker.Preferences.VAL_OUTPUT_ACCURACY_NONE.equals(accuracyInfo) && ! c.isNull(c.getColumnIndex(Schema.COL_ACCURACY))) {
// Outputs accuracy info for way point
if (OSMTracker.Preferences.VAL_OUTPUT_ACCURACY_WPT_NAME.equals(accuracyInfo)) {
// Output accuracy with name
out.append("\t\t" + "<name>"
+ CDATA_START
+ name
+ " (" + c.getDouble(c.getColumnIndex(Schema.COL_ACCURACY)) + meterUnit + ")"
+ CDATA_END
+ "</name>" + "\n");
} else if (OSMTracker.Preferences.VAL_OUTPUT_ACCURACY_WPT_CMT.equals(accuracyInfo)) {
// Output accuracy in separate tag
out.append("\t\t" + "<name>" + CDATA_START + name + CDATA_END + "</name>" + "\n");
out.append("\t\t" + "<cmt>" + CDATA_START + accuracy + ": " + c.getDouble(c.getColumnIndex(Schema.COL_ACCURACY)) + meterUnit + CDATA_END + "</cmt>" + "\n");
} else {
// Unknown value for accuracy info, shouldn't occur but who knows ?
// See issue #68. Output at least the name just in case.
out.append("\t\t" + "<name>" + CDATA_START + name + CDATA_END + "</name>" + "\n");
}
} else {
// No accuracy info requested, or available
out.append("\t\t" + "<name>" + CDATA_START + name + CDATA_END + "</name>" + "\n");
}
String link = c.getString(c.getColumnIndex(Schema.COL_LINK));
if (link != null) {
out.append("\t\t" + "<link>" + link + "</link>" + "\n");
}
if (! c.isNull(c.getColumnIndex(Schema.COL_NBSATELLITES))) {
out.append("\t\t" + "<sat>" + c.getInt(c.getColumnIndex(Schema.COL_NBSATELLITES)) + "</sat>" + "\n");
}
out.append("\t" + "</wpt>" + "\n");
fw.write(out.toString());
dialog.incrementProgressBy(1);
}
}
|
diff --git a/plugins/org.eclipse.m2m.atl.adt.debug/src/org/eclipse/m2m/atl/adt/launching/AtlRegularVM.java b/plugins/org.eclipse.m2m.atl.adt.debug/src/org/eclipse/m2m/atl/adt/launching/AtlRegularVM.java
index 6a30e763..094d870c 100644
--- a/plugins/org.eclipse.m2m.atl.adt.debug/src/org/eclipse/m2m/atl/adt/launching/AtlRegularVM.java
+++ b/plugins/org.eclipse.m2m.atl.adt.debug/src/org/eclipse/m2m/atl/adt/launching/AtlRegularVM.java
@@ -1,471 +1,471 @@
/*******************************************************************************
* Copyright (c) 2004 INRIA.
* 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:
* Freddy Allilaire (INRIA) - initial API and implementation
*******************************************************************************/
package org.eclipse.m2m.atl.adt.launching;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.debug.core.ILaunch;
import org.eclipse.debug.core.ILaunchConfiguration;
import org.eclipse.debug.core.ILaunchManager;
import org.eclipse.emf.common.util.URI;
import org.eclipse.m2m.atl.adt.debug.core.AtlDebugTarget;
import org.eclipse.m2m.atl.adt.debug.core.AtlRunTarget;
import org.eclipse.m2m.atl.adt.launching.sourcelookup.AtlSourceLocator;
import org.eclipse.m2m.atl.drivers.emf4atl.ASMEMFModel;
import org.eclipse.m2m.atl.engine.AtlEMFModelHandler;
import org.eclipse.m2m.atl.engine.AtlLauncher;
import org.eclipse.m2m.atl.engine.AtlModelHandler;
import org.eclipse.m2m.atl.engine.vm.nativelib.ASMModel;
/**
* The ATL Regular VM launcher class.
*
* @author <a href="mailto:[email protected]">Freddy Allilaire</a>
*/
public class AtlRegularVM extends AtlVM {
private static final boolean USE_EMF_URIS = true;
/**
* With the path of a file, the input stream of the file is returned.
*
* @param filePath
* @return the input stream corresponding to the file
* @throws FileNotFoundException
*/
private static InputStream fileNameToInputStream(String filePath) throws FileNotFoundException,
CoreException {
String usedFilePath = filePath;
if (usedFilePath.startsWith("ext:")) { //$NON-NLS-1$
File f = new File(usedFilePath.substring(4));
return new FileInputStream(f);
} else {
IWorkspaceRoot iwr = ResourcesPlugin.getWorkspace().getRoot();
usedFilePath = usedFilePath.replace('#', '/');
return iwr.getFile(new Path(usedFilePath)).getContents();
}
}
private static URI fileNameToURI(String filePath) throws IllegalArgumentException {
if (filePath.startsWith("ext:")) { //$NON-NLS-1$
File f = new File(filePath.substring(4));
return URI.createFileURI(f.getPath());
} else {
return URI.createPlatformResourceURI(filePath, true);
}
}
private static URL fileNameToURL(String filePath) throws MalformedURLException {
if (filePath.startsWith("ext:")) { //$NON-NLS-1$
File f = new File(filePath.substring(4));
return f.toURI().toURL();
} else {
IWorkspace wks = ResourcesPlugin.getWorkspace();
IWorkspaceRoot wksroot = wks.getRoot();
IFile currentLib = wksroot.getFile(new Path(filePath));
return currentLib.getLocation().toFile().toURI().toURL();
}
}
/**
* From the path of an ATL File, this method returns the ASM File corresponding to the ATL File.
*
* @param atlFilePath
* name of the ATL File
* @return ASM File corresponding to the ATL File
*/
private static IFile getASMFile(String atlFilePath) {
// TODO Get properties of the project
// know where bin files are, then choose good ASM File for ATL File
IFile currentAtlFile = ResourcesPlugin.getWorkspace().getRoot().getFile(
Path.fromOSString(atlFilePath));
String extension = currentAtlFile.getFileExtension().toLowerCase();
if (AtlLauncherTools.getExtensions().contains(extension)) {
String currentAsmPath = currentAtlFile.getFullPath().toString().substring(0,
currentAtlFile.getFullPath().toString().length() - extension.length())
+ "asm"; //$NON-NLS-1$
return ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(currentAsmPath));
} else {
return null;
}
}
/**
* Returns the input stream from a path for metamodel.
*
* @param metamodelPath
* @return
* @throws CoreException
*/
private static Map getSourceModels(Map arg, Map path, Map modelHandler, Map atlModelHandler,
boolean checkSameModel, Collection toDispose) throws CoreException {
Map toReturn = new HashMap();
try {
for (Iterator i = arg.keySet().iterator(); i.hasNext();) {
String mName = (String)i.next();
String mmName = (String)arg.get(mName);
AtlModelHandler amh = (AtlModelHandler)atlModelHandler.get(modelHandler.get(mmName));
ASMModel mofmm = amh.getMof();
toReturn.put("%" + modelHandler.get(mmName), mofmm); //$NON-NLS-1$
mofmm.setIsTarget(false);
ASMModel inputModel;
if (((String)path.get(mmName)).startsWith("#")) { //$NON-NLS-1$
toReturn.put(mmName, mofmm);
inputModel = (ASMModel)toReturn.get(mName);
if (inputModel == null) {
inputModel = loadModel(amh, mName, mofmm, (String)path.get(mName), toDispose);
}
} else {
ASMModel inputMetaModel = (ASMModel)toReturn.get(mmName);
if (inputMetaModel == null) {
inputMetaModel = loadModel(amh, mmName, mofmm, (String)path.get(mmName), toDispose);
toReturn.put(mmName, inputMetaModel);
}
inputMetaModel.setIsTarget(false);
inputModel = loadModel(amh, mName, inputMetaModel, (String)path.get(mName), toDispose);
}
inputModel.setIsTarget(false);
if (inputModel instanceof ASMEMFModel) {
((ASMEMFModel)inputModel).setCheckSameModel(checkSameModel);
}
toReturn.put(mName, inputModel);
}
} catch (IOException e) {
logger.log(Level.SEVERE, e.getLocalizedMessage(), e);
}
return toReturn;
}
/**
* Returns the input stream from a path for metamodel.
*
* @param metamodelPath
* @return
* @throws CoreException
*/
private static Map getTargetModels(Map arg, Map path, Map modelHandler, Map atlModelHandler, Map input,
boolean checkSameModel, Collection toDispose) throws CoreException {
Map toReturn = new HashMap();
try {
for (Iterator i = arg.keySet().iterator(); i.hasNext();) {
String mName = (String)i.next();
String mmName = (String)arg.get(mName);
AtlModelHandler amh = (AtlModelHandler)atlModelHandler.get(modelHandler.get(mmName));
ASMModel mofmm = amh.getMof();
mofmm.setIsTarget(false);
ASMModel outputModel;
if (((String)path.get(mmName)).startsWith("#")) { //$NON-NLS-1$
if (input.get(mmName) == null) {
toReturn.put(mmName, mofmm);
}
outputModel = (ASMModel)toReturn.get(mName);
if (outputModel == null) {
outputModel = newModel(amh, mName, mofmm, (String)path.get(mName), toDispose);
}
} else {
ASMModel outputMetaModel = (ASMModel)input.get(mmName);
if (outputMetaModel == null) {
outputMetaModel = (ASMModel)toReturn.get(mmName);
}
if (outputMetaModel == null) {
outputMetaModel = loadModel(amh, mmName, mofmm, (String)path.get(mmName), toDispose);
toReturn.put(mmName, outputMetaModel);
}
outputMetaModel.setIsTarget(false);
outputModel = newModel(amh, mName, outputMetaModel, (String)path.get(mName), toDispose);
}
outputModel.setIsTarget(true);
if (outputModel instanceof ASMEMFModel) {
((ASMEMFModel)outputModel).setCheckSameModel(checkSameModel);
}
toReturn.put(mName, outputModel);
}
} catch (IOException e) {
logger.log(Level.SEVERE, e.getLocalizedMessage(), e);
}
return toReturn;
}
private static ASMModel loadModel(AtlModelHandler amh, String mName, ASMModel metamodel, String path,
Collection toDispose) throws CoreException, FileNotFoundException {
ASMModel ret = null;
if (USE_EMF_URIS && (amh instanceof AtlEMFModelHandler)) {
if (path.startsWith("uri:")) { //$NON-NLS-1$
ret = ((AtlEMFModelHandler)amh).loadModel(mName, metamodel, path);
// this model should not be disposed of because we did not load it
} else {
ret = ((AtlEMFModelHandler)amh).loadModel(mName, metamodel, fileNameToURI(path));
toDispose.add(ret);
}
} else {
ret = amh.loadModel(mName, metamodel, fileNameToInputStream(path));
toDispose.add(ret);
}
return ret;
}
/**
* Returns a new ASMModel.
*
* @param amh
* @param mName
* @param metamodel
* @param path
* Project file path. Used to derive a platform:/... URI.
* @param toDispose
* @return A new ASMModel.
* @author <a href="mailto:[email protected]">Dennis Wagelaar</a>
*/
private static ASMModel newModel(AtlModelHandler amh, String mName, ASMModel metamodel, String path,
Collection toDispose) {
ASMModel ret = amh.newModel(mName, fileNameToURI(path).toString(), metamodel);
toDispose.add(ret);
return ret;
}
/**
* Runs an ATL transformation.
*
* @param filePath
* path of the ATL Transformation
* @param libsFromConfig
* Map {lib_name --> URI}
* @param input
* Map {model_input --> metamodel_input}
* @param output
* Map {model_output --> metamodel_output}
* @param path
* Map {model_name --> URI}
* @param modelType
* Map {model_name --> type if the model(mIn, mmIn, ...)}
* @param modelHandler
* modelHandler (MDR or EMF)
* @param mode
* (DEBUG or RUN)
* @param superimpose
* list of module URIs to superimpose
* @param options
* transformation options
* @return unused (TODO)
*/
public static Map runAtlLauncher(String filePath, Map libsFromConfig, Map input, Map output, Map path,
Map modelType, Map modelHandler, String mode, /* Map linkWithNextTransformation, Map inModel, */
List superimpose, Map options) {
boolean checkSameModel = "true".equals(options.get("checkSameModel")); //$NON-NLS-1$//$NON-NLS-2$
Map toReturn = new HashMap();
try {
// asmUrl
IFile asmFile = getASMFile(filePath);
URL asmUrl;
asmUrl = asmFile.getLocation().toFile().toURI().toURL();
// model handler
Map atlModelHandler = new HashMap();
for (Iterator i = modelHandler.keySet().iterator(); i.hasNext();) {
String currentModelHandler = (String)modelHandler.get(i.next());
if (!atlModelHandler.containsKey(currentModelHandler) && !currentModelHandler.equals("")) { //$NON-NLS-1$
atlModelHandler.put(currentModelHandler, AtlModelHandler.getDefault(currentModelHandler));
}
}
// libs
Map libs = new HashMap();
for (Iterator i = libsFromConfig.keySet().iterator(); i.hasNext();) {
String libName = (String)i.next();
URL stringsUrl = fileNameToURL((String)libsFromConfig.get(libName));
libs.put(libName, stringsUrl);
}
// superimpose
List superimposeURLs = new ArrayList();
for (Iterator i = superimpose.iterator(); i.hasNext();) {
URL moduleUrl = fileNameToURL((String)i.next());
superimposeURLs.add(moduleUrl);
}
Collection toDispose = new HashSet();
// models
// if (inModel.isEmpty())
Map inModel = getSourceModels(input, path, modelHandler, atlModelHandler, checkSameModel,
toDispose);
Map outModel = getTargetModels(output, path, modelHandler, atlModelHandler, inModel,
checkSameModel, toDispose);
Map models = new HashMap();
for (Iterator i = inModel.keySet().iterator(); i.hasNext();) {
String mName = (String)i.next();
models.put(mName, inModel.get(mName));
}
for (Iterator i = outModel.keySet().iterator(); i.hasNext();) {
String mName = (String)i.next();
models.put(mName, outModel.get(mName));
}
// models.put("ATL", amh.getAtl());
// models.put("MOF", amh.getMof());
// params
Map params = Collections.EMPTY_MAP;
AtlLauncher myLauncher = AtlLauncher.getDefault();
if (mode.equals(ILaunchManager.DEBUG_MODE)) {
myLauncher.debug(asmUrl, libs, models, params, superimposeURLs, options);
} else {
myLauncher.launch(asmUrl, libs, models, params, superimposeURLs, options);
}
for (Iterator i = outModel.keySet().iterator(); i.hasNext();) {
String mName = (String)i.next();
ASMModel currentOutModel = (ASMModel)outModel.get(mName);
// if (linkWithNextTransformation.containsKey(mName))
// toReturn.put(linkWithNextTransformation.get(mName), currentOutModel);
if ((modelType.get(mName) != null)
&& ((String)modelType.get(mName)).equals(ModelChoiceTab.MODEL_OUTPUT)) {
- // TODO mettre un boolean peut g�rer la non sauvegarde
+ // TODO a boolean may manage the saving
String mmName = (String)output.get(mName);
((AtlModelHandler)atlModelHandler.get(modelHandler.get(mmName))).saveModel(
currentOutModel, (String)path.get(mName));
}
}
for (Iterator i = toDispose.iterator(); i.hasNext();) {
ASMModel model = (ASMModel)i.next();
AtlModelHandler.getHandler(model).disposeOfModel(model);
}
} catch (MalformedURLException e) {
logger.log(Level.SEVERE, e.getLocalizedMessage(), e);
// e.printStackTrace();
} catch (CoreException e1) {
logger.log(Level.SEVERE, e1.getLocalizedMessage(), e1);
}
return toReturn;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.debug.core.model.ILaunchConfigurationDelegate#launch(org.eclipse.debug.core.ILaunchConfiguration,
* java.lang.String, org.eclipse.debug.core.ILaunch, org.eclipse.core.runtime.IProgressMonitor)
*/
public void launch(ILaunchConfiguration configurationParam, String mode, ILaunch launchParam,
IProgressMonitor monitor) throws CoreException {
final String currentMode = mode;
final ILaunchConfiguration configuration = configurationParam;
final ILaunch launch = launchParam;
/*
* If the mode choosen was Debug, an ATLDebugTarget was created
*/
if (mode.equals(ILaunchManager.DEBUG_MODE)) {
// link between the debug target and the source locator
launch.setSourceLocator(new AtlSourceLocator());
AtlDebugTarget mTarget = new AtlDebugTarget(launchParam);
Thread th = new Thread() {
public void run() {
runAtlLauncher(configuration, launch, currentMode);
}
};
th.start();
mTarget.start();
launchParam.addDebugTarget(mTarget);
} else {
// Run mode
launchParam.setSourceLocator(new AtlSourceLocator());
AtlRunTarget mTarget = new AtlRunTarget(launchParam);
launchParam.addDebugTarget(mTarget);
runAtlLauncher(configurationParam, launchParam, currentMode);
mTarget.terminate();
}
}
/**
* Launcher of the debuggee with AtlLauncher.
*
* @param configuration
* the launch configuration
* @param launch
* the launch interface
*/
private void runAtlLauncher(ILaunchConfiguration configuration, ILaunch launch, String mode) {
try {
String fileName = configuration.getAttribute(AtlLauncherTools.ATLFILENAME,
AtlLauncherTools.NULLPARAMETER);
Map input = configuration.getAttribute(AtlLauncherTools.INPUT, new HashMap());
Map output = configuration.getAttribute(AtlLauncherTools.OUTPUT, new HashMap());
Map path = configuration.getAttribute(AtlLauncherTools.PATH, new HashMap());
Map modelType = configuration.getAttribute(AtlLauncherTools.MODELTYPE, new HashMap());
Map libsFromConfig = configuration.getAttribute(AtlLauncherTools.LIBS, new HashMap());
Map modelHandler = configuration.getAttribute(AtlLauncherTools.MODELHANDLER, new HashMap());
List superimpose = configuration.getAttribute(AtlLauncherTools.SUPERIMPOSE, new ArrayList());
Map options = new HashMap();
for (int i = 0; i < AtlLauncherTools.ADDITIONAL_PARAM_IDS.length; i++) {
boolean value = configuration.getAttribute(AtlLauncherTools.ADDITIONAL_PARAM_IDS[i], false);
options.put(AtlLauncherTools.ADDITIONAL_PARAM_IDS[i], value ? "true" : "false"); //$NON-NLS-1$//$NON-NLS-2$
}
runAtlLauncher(fileName, libsFromConfig, input, output, path, modelType, modelHandler, mode,
superimpose, options);
} catch (CoreException e1) {
logger.log(Level.SEVERE, e1.getLocalizedMessage(), e1);
}
}
/**
* {@inheritDoc}
*
* @see org.eclipse.m2m.atl.adt.launching.AtlVM#launch(java.net.URL, java.util.Map, java.util.Map,
* java.util.Map, java.util.List, java.util.Map)
*/
public Object launch(URL asmUrl, Map libs, Map models, Map params, List superimps, Map options) {
return AtlLauncher.getDefault().launch(asmUrl, libs, models, params, superimps, options);
}
}
| true | true | public static Map runAtlLauncher(String filePath, Map libsFromConfig, Map input, Map output, Map path,
Map modelType, Map modelHandler, String mode, /* Map linkWithNextTransformation, Map inModel, */
List superimpose, Map options) {
boolean checkSameModel = "true".equals(options.get("checkSameModel")); //$NON-NLS-1$//$NON-NLS-2$
Map toReturn = new HashMap();
try {
// asmUrl
IFile asmFile = getASMFile(filePath);
URL asmUrl;
asmUrl = asmFile.getLocation().toFile().toURI().toURL();
// model handler
Map atlModelHandler = new HashMap();
for (Iterator i = modelHandler.keySet().iterator(); i.hasNext();) {
String currentModelHandler = (String)modelHandler.get(i.next());
if (!atlModelHandler.containsKey(currentModelHandler) && !currentModelHandler.equals("")) { //$NON-NLS-1$
atlModelHandler.put(currentModelHandler, AtlModelHandler.getDefault(currentModelHandler));
}
}
// libs
Map libs = new HashMap();
for (Iterator i = libsFromConfig.keySet().iterator(); i.hasNext();) {
String libName = (String)i.next();
URL stringsUrl = fileNameToURL((String)libsFromConfig.get(libName));
libs.put(libName, stringsUrl);
}
// superimpose
List superimposeURLs = new ArrayList();
for (Iterator i = superimpose.iterator(); i.hasNext();) {
URL moduleUrl = fileNameToURL((String)i.next());
superimposeURLs.add(moduleUrl);
}
Collection toDispose = new HashSet();
// models
// if (inModel.isEmpty())
Map inModel = getSourceModels(input, path, modelHandler, atlModelHandler, checkSameModel,
toDispose);
Map outModel = getTargetModels(output, path, modelHandler, atlModelHandler, inModel,
checkSameModel, toDispose);
Map models = new HashMap();
for (Iterator i = inModel.keySet().iterator(); i.hasNext();) {
String mName = (String)i.next();
models.put(mName, inModel.get(mName));
}
for (Iterator i = outModel.keySet().iterator(); i.hasNext();) {
String mName = (String)i.next();
models.put(mName, outModel.get(mName));
}
// models.put("ATL", amh.getAtl());
// models.put("MOF", amh.getMof());
// params
Map params = Collections.EMPTY_MAP;
AtlLauncher myLauncher = AtlLauncher.getDefault();
if (mode.equals(ILaunchManager.DEBUG_MODE)) {
myLauncher.debug(asmUrl, libs, models, params, superimposeURLs, options);
} else {
myLauncher.launch(asmUrl, libs, models, params, superimposeURLs, options);
}
for (Iterator i = outModel.keySet().iterator(); i.hasNext();) {
String mName = (String)i.next();
ASMModel currentOutModel = (ASMModel)outModel.get(mName);
// if (linkWithNextTransformation.containsKey(mName))
// toReturn.put(linkWithNextTransformation.get(mName), currentOutModel);
if ((modelType.get(mName) != null)
&& ((String)modelType.get(mName)).equals(ModelChoiceTab.MODEL_OUTPUT)) {
// TODO mettre un boolean peut g�rer la non sauvegarde
String mmName = (String)output.get(mName);
((AtlModelHandler)atlModelHandler.get(modelHandler.get(mmName))).saveModel(
currentOutModel, (String)path.get(mName));
}
}
for (Iterator i = toDispose.iterator(); i.hasNext();) {
ASMModel model = (ASMModel)i.next();
AtlModelHandler.getHandler(model).disposeOfModel(model);
}
} catch (MalformedURLException e) {
logger.log(Level.SEVERE, e.getLocalizedMessage(), e);
// e.printStackTrace();
} catch (CoreException e1) {
logger.log(Level.SEVERE, e1.getLocalizedMessage(), e1);
}
return toReturn;
}
| public static Map runAtlLauncher(String filePath, Map libsFromConfig, Map input, Map output, Map path,
Map modelType, Map modelHandler, String mode, /* Map linkWithNextTransformation, Map inModel, */
List superimpose, Map options) {
boolean checkSameModel = "true".equals(options.get("checkSameModel")); //$NON-NLS-1$//$NON-NLS-2$
Map toReturn = new HashMap();
try {
// asmUrl
IFile asmFile = getASMFile(filePath);
URL asmUrl;
asmUrl = asmFile.getLocation().toFile().toURI().toURL();
// model handler
Map atlModelHandler = new HashMap();
for (Iterator i = modelHandler.keySet().iterator(); i.hasNext();) {
String currentModelHandler = (String)modelHandler.get(i.next());
if (!atlModelHandler.containsKey(currentModelHandler) && !currentModelHandler.equals("")) { //$NON-NLS-1$
atlModelHandler.put(currentModelHandler, AtlModelHandler.getDefault(currentModelHandler));
}
}
// libs
Map libs = new HashMap();
for (Iterator i = libsFromConfig.keySet().iterator(); i.hasNext();) {
String libName = (String)i.next();
URL stringsUrl = fileNameToURL((String)libsFromConfig.get(libName));
libs.put(libName, stringsUrl);
}
// superimpose
List superimposeURLs = new ArrayList();
for (Iterator i = superimpose.iterator(); i.hasNext();) {
URL moduleUrl = fileNameToURL((String)i.next());
superimposeURLs.add(moduleUrl);
}
Collection toDispose = new HashSet();
// models
// if (inModel.isEmpty())
Map inModel = getSourceModels(input, path, modelHandler, atlModelHandler, checkSameModel,
toDispose);
Map outModel = getTargetModels(output, path, modelHandler, atlModelHandler, inModel,
checkSameModel, toDispose);
Map models = new HashMap();
for (Iterator i = inModel.keySet().iterator(); i.hasNext();) {
String mName = (String)i.next();
models.put(mName, inModel.get(mName));
}
for (Iterator i = outModel.keySet().iterator(); i.hasNext();) {
String mName = (String)i.next();
models.put(mName, outModel.get(mName));
}
// models.put("ATL", amh.getAtl());
// models.put("MOF", amh.getMof());
// params
Map params = Collections.EMPTY_MAP;
AtlLauncher myLauncher = AtlLauncher.getDefault();
if (mode.equals(ILaunchManager.DEBUG_MODE)) {
myLauncher.debug(asmUrl, libs, models, params, superimposeURLs, options);
} else {
myLauncher.launch(asmUrl, libs, models, params, superimposeURLs, options);
}
for (Iterator i = outModel.keySet().iterator(); i.hasNext();) {
String mName = (String)i.next();
ASMModel currentOutModel = (ASMModel)outModel.get(mName);
// if (linkWithNextTransformation.containsKey(mName))
// toReturn.put(linkWithNextTransformation.get(mName), currentOutModel);
if ((modelType.get(mName) != null)
&& ((String)modelType.get(mName)).equals(ModelChoiceTab.MODEL_OUTPUT)) {
// TODO a boolean may manage the saving
String mmName = (String)output.get(mName);
((AtlModelHandler)atlModelHandler.get(modelHandler.get(mmName))).saveModel(
currentOutModel, (String)path.get(mName));
}
}
for (Iterator i = toDispose.iterator(); i.hasNext();) {
ASMModel model = (ASMModel)i.next();
AtlModelHandler.getHandler(model).disposeOfModel(model);
}
} catch (MalformedURLException e) {
logger.log(Level.SEVERE, e.getLocalizedMessage(), e);
// e.printStackTrace();
} catch (CoreException e1) {
logger.log(Level.SEVERE, e1.getLocalizedMessage(), e1);
}
return toReturn;
}
|
diff --git a/source/ru/peppers/MainListActivity.java b/source/ru/peppers/MainListActivity.java
index 07eff4a..f6f01cd 100644
--- a/source/ru/peppers/MainListActivity.java
+++ b/source/ru/peppers/MainListActivity.java
@@ -1,244 +1,243 @@
package ru.peppers;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import model.Driver;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
public class MainListActivity extends Activity {
private ListView lv;
public SimpleAdapter simpleAdpt;
public List<Map<String, String>> itemsList;
private static final String MY_TAG = "My_tag";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//init();
}
@Override
protected void onResume() {
super.onResume();
init();
}
private void init() {
// Bundle bundle = getIntent().getExtras();
// int id = bundle.getInt("id");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
nameValuePairs.add(new BasicNameValuePair("action", "get"));
nameValuePairs.add(new BasicNameValuePair("module", "mobile"));
nameValuePairs.add(new BasicNameValuePair("mode", "status"));
nameValuePairs.add(new BasicNameValuePair("object", "driver"));
Document doc = PhpData.postData(this, nameValuePairs,PhpData.newURL);
if (doc != null) {
Node responseNode = doc.getElementsByTagName("response").item(0);
Node errorNode = doc.getElementsByTagName("message").item(0);
if (responseNode.getTextContent().equalsIgnoreCase("failure"))
PhpData.errorFromServer(this, errorNode);
else {
try {
parseMainList(doc);
} catch (Exception e) {
Log.d("My_tag", e.toString());
errorHandler();
}
}
}
else{
initMainList();
}
}
private void errorHandler() {
new AlertDialog.Builder(this).setTitle(this.getString(R.string.error_title))
.setMessage(this.getString(R.string.error_message))
.setNeutralButton(this.getString(R.string.close), null).show();
}
private void parseMainList(Document doc) {
int ordersCount = Integer.valueOf(doc.getElementsByTagName("ordercount").item(0).getTextContent());
// int carClass = Integer.valueOf(doc.getElementsByTagName("carClass").item(0).getTextContent());
int status = 2;
Node statusNode = doc.getElementsByTagName("status").item(1);
if(!statusNode.getTextContent().equalsIgnoreCase(""))
status = Integer.valueOf(statusNode.getTextContent());
String district = doc.getElementsByTagName("districttitle").item(0).getTextContent();
String subdistrict = doc.getElementsByTagName("subdistricttitle").item(0).getTextContent();
// Bundle bundle = getIntent().getExtras();
// int id = bundle.getInt("id");
Driver driver = TaxiApplication.getDriver();
driver.setStatus(status);
//driver.setClassAuto(0);
driver.setOrdersCount(ordersCount);
driver.setDistrict(district);
driver.setSubdistrict(subdistrict);
initMainList();
}
private void initMainList() {
final Driver driver = TaxiApplication.getDriver();
if (driver != null) {
itemsList = new ArrayList<Map<String, String>>();
itemsList.add(createItem("item", this.getString(R.string.my_orders)+" " + driver.getOrdersCount()));
itemsList.add(createItem("item", this.getString(R.string.status)+" " + driver.getStatusString()));
itemsList.add(createItem("item", this.getString(R.string.free_orders)));
if (driver.getStatus() != 1) {
itemsList.add(createItem("item", this.getString(R.string.region)+" " + driver.getFullDisctrict()));
}
itemsList.add(createItem("item", this.getString(R.string.call_office)));
itemsList.add(createItem("item", this.getString(R.string.settings)));
itemsList.add(createItem("item", this.getString(R.string.messages)));
itemsList.add(createItem("item", this.getString(R.string.exit)));
lv = (ListView) findViewById(R.id.mainListView);
simpleAdpt = new SimpleAdapter(this, itemsList, android.R.layout.simple_list_item_1,
new String[] { "item" }, new int[] { android.R.id.text1 });
lv.setAdapter(simpleAdpt);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parentAdapter, View view, int position, long index) {
Bundle extras = getIntent().getExtras();
// //int id = extras.getInt("id");
Intent intent;
switch (position) {
case 0:
intent = new Intent(MainListActivity.this, MyOrderActivity.class);
startActivity(intent);
break;
case 1:
if (driver.getStatus() != 3) {
intent = new Intent(MainListActivity.this, ReportActivity.class);
startActivity(intent);
} else {
intent = new Intent(MainListActivity.this, MyOrderActivity.class);
startActivity(intent);
}
break;
case 2:
intent = new Intent(MainListActivity.this, FreeOrderActivity.class);
startActivity(intent);
break;
case 3:
- //TODO:�������
- //if (driver.getStatus() != 1) {
+ if (driver.getStatus() != 1) {
intent = new Intent(MainListActivity.this, DistrictActivity.class);
startActivity(intent);
return;
- //}
+ }
default:
break;
}
if (driver.getStatus() != 1)
position--;
if (position == 3) {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("action", "calloffice"));
// nameValuePairs.add(new BasicNameValuePair("id", String.valueOf(id)));
Document doc = PhpData.postData(MainListActivity.this, nameValuePairs);
if (doc != null) {
Node errorNode = doc.getElementsByTagName("error").item(0);
if (Integer.parseInt(errorNode.getTextContent()) == 1)
//TODO:fix
errorHandler();
else {
errorHandler();
}
}
}
if (position == 4) {
intent = new Intent(MainListActivity.this, SettingsActivity.class);
startActivity(intent);
}
if (position == 5) {
intent = new Intent(MainListActivity.this, MessageActivity.class);
startActivity(intent);
}
if (position == 6) {
Driver driver = TaxiApplication.getDriver();
if (driver.getOrdersCount() != 0) {
exitDialog();
}
else{
Intent service = new Intent(MainListActivity.this, PhpService.class);
stopService(service);
finish();
}
}
}
});
}
}
private void exitDialog() {
new AlertDialog.Builder(MainListActivity.this).setTitle(this.getString(R.string.orders))
.setMessage(this.getString(R.string.sorry_exit))
.setPositiveButton(this.getString(R.string.exit_action), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(MainListActivity.this, PhpService.class);
stopService(intent);
finish();
}
}).setNegativeButton(this.getString(R.string.cancel), null).show();
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// Handle the back button
if (keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_HOME) {
// Ask the user if they want to quit
Driver driver = TaxiApplication.getDriver();
if (driver.getOrdersCount() != 0) {
exitDialog();
}
return true;
} else {
return super.onKeyDown(keyCode, event);
}
}
public HashMap<String, String> createItem(String key, String name) {
HashMap<String, String> item = new HashMap<String, String>();
item.put(key, name);
return item;
}
}
| false | true | private void initMainList() {
final Driver driver = TaxiApplication.getDriver();
if (driver != null) {
itemsList = new ArrayList<Map<String, String>>();
itemsList.add(createItem("item", this.getString(R.string.my_orders)+" " + driver.getOrdersCount()));
itemsList.add(createItem("item", this.getString(R.string.status)+" " + driver.getStatusString()));
itemsList.add(createItem("item", this.getString(R.string.free_orders)));
if (driver.getStatus() != 1) {
itemsList.add(createItem("item", this.getString(R.string.region)+" " + driver.getFullDisctrict()));
}
itemsList.add(createItem("item", this.getString(R.string.call_office)));
itemsList.add(createItem("item", this.getString(R.string.settings)));
itemsList.add(createItem("item", this.getString(R.string.messages)));
itemsList.add(createItem("item", this.getString(R.string.exit)));
lv = (ListView) findViewById(R.id.mainListView);
simpleAdpt = new SimpleAdapter(this, itemsList, android.R.layout.simple_list_item_1,
new String[] { "item" }, new int[] { android.R.id.text1 });
lv.setAdapter(simpleAdpt);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parentAdapter, View view, int position, long index) {
Bundle extras = getIntent().getExtras();
// //int id = extras.getInt("id");
Intent intent;
switch (position) {
case 0:
intent = new Intent(MainListActivity.this, MyOrderActivity.class);
startActivity(intent);
break;
case 1:
if (driver.getStatus() != 3) {
intent = new Intent(MainListActivity.this, ReportActivity.class);
startActivity(intent);
} else {
intent = new Intent(MainListActivity.this, MyOrderActivity.class);
startActivity(intent);
}
break;
case 2:
intent = new Intent(MainListActivity.this, FreeOrderActivity.class);
startActivity(intent);
break;
case 3:
//TODO:�������
//if (driver.getStatus() != 1) {
intent = new Intent(MainListActivity.this, DistrictActivity.class);
startActivity(intent);
return;
//}
default:
break;
}
if (driver.getStatus() != 1)
position--;
if (position == 3) {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("action", "calloffice"));
// nameValuePairs.add(new BasicNameValuePair("id", String.valueOf(id)));
Document doc = PhpData.postData(MainListActivity.this, nameValuePairs);
if (doc != null) {
Node errorNode = doc.getElementsByTagName("error").item(0);
if (Integer.parseInt(errorNode.getTextContent()) == 1)
//TODO:fix
errorHandler();
else {
errorHandler();
}
}
}
if (position == 4) {
intent = new Intent(MainListActivity.this, SettingsActivity.class);
startActivity(intent);
}
if (position == 5) {
intent = new Intent(MainListActivity.this, MessageActivity.class);
startActivity(intent);
}
if (position == 6) {
Driver driver = TaxiApplication.getDriver();
if (driver.getOrdersCount() != 0) {
exitDialog();
}
else{
Intent service = new Intent(MainListActivity.this, PhpService.class);
stopService(service);
finish();
}
}
}
});
}
}
| private void initMainList() {
final Driver driver = TaxiApplication.getDriver();
if (driver != null) {
itemsList = new ArrayList<Map<String, String>>();
itemsList.add(createItem("item", this.getString(R.string.my_orders)+" " + driver.getOrdersCount()));
itemsList.add(createItem("item", this.getString(R.string.status)+" " + driver.getStatusString()));
itemsList.add(createItem("item", this.getString(R.string.free_orders)));
if (driver.getStatus() != 1) {
itemsList.add(createItem("item", this.getString(R.string.region)+" " + driver.getFullDisctrict()));
}
itemsList.add(createItem("item", this.getString(R.string.call_office)));
itemsList.add(createItem("item", this.getString(R.string.settings)));
itemsList.add(createItem("item", this.getString(R.string.messages)));
itemsList.add(createItem("item", this.getString(R.string.exit)));
lv = (ListView) findViewById(R.id.mainListView);
simpleAdpt = new SimpleAdapter(this, itemsList, android.R.layout.simple_list_item_1,
new String[] { "item" }, new int[] { android.R.id.text1 });
lv.setAdapter(simpleAdpt);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parentAdapter, View view, int position, long index) {
Bundle extras = getIntent().getExtras();
// //int id = extras.getInt("id");
Intent intent;
switch (position) {
case 0:
intent = new Intent(MainListActivity.this, MyOrderActivity.class);
startActivity(intent);
break;
case 1:
if (driver.getStatus() != 3) {
intent = new Intent(MainListActivity.this, ReportActivity.class);
startActivity(intent);
} else {
intent = new Intent(MainListActivity.this, MyOrderActivity.class);
startActivity(intent);
}
break;
case 2:
intent = new Intent(MainListActivity.this, FreeOrderActivity.class);
startActivity(intent);
break;
case 3:
if (driver.getStatus() != 1) {
intent = new Intent(MainListActivity.this, DistrictActivity.class);
startActivity(intent);
return;
}
default:
break;
}
if (driver.getStatus() != 1)
position--;
if (position == 3) {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("action", "calloffice"));
// nameValuePairs.add(new BasicNameValuePair("id", String.valueOf(id)));
Document doc = PhpData.postData(MainListActivity.this, nameValuePairs);
if (doc != null) {
Node errorNode = doc.getElementsByTagName("error").item(0);
if (Integer.parseInt(errorNode.getTextContent()) == 1)
//TODO:fix
errorHandler();
else {
errorHandler();
}
}
}
if (position == 4) {
intent = new Intent(MainListActivity.this, SettingsActivity.class);
startActivity(intent);
}
if (position == 5) {
intent = new Intent(MainListActivity.this, MessageActivity.class);
startActivity(intent);
}
if (position == 6) {
Driver driver = TaxiApplication.getDriver();
if (driver.getOrdersCount() != 0) {
exitDialog();
}
else{
Intent service = new Intent(MainListActivity.this, PhpService.class);
stopService(service);
finish();
}
}
}
});
}
}
|
diff --git a/src/org/timadorus/webapp/client/character/ui/selectrace/SelectRaceWidget.java b/src/org/timadorus/webapp/client/character/ui/selectrace/SelectRaceWidget.java
index f36b352..b82332a 100644
--- a/src/org/timadorus/webapp/client/character/ui/selectrace/SelectRaceWidget.java
+++ b/src/org/timadorus/webapp/client/character/ui/selectrace/SelectRaceWidget.java
@@ -1,233 +1,234 @@
package org.timadorus.webapp.client.character.ui.selectrace;
import java.util.List;
import org.timadorus.webapp.beans.Character;
import org.timadorus.webapp.beans.User;
import org.timadorus.webapp.client.DefaultTimadorusWebApp;
import org.timadorus.webapp.client.character.ui.DefaultActionHandler;
import org.timadorus.webapp.client.character.ui.createcharacter.CreateDialog;
import org.timadorus.webapp.client.character.ui.selectclass.SelectClassDialog;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.FormPanel;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.RadioButton;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.VerticalPanel;
/**
* FormPanel for selecting Race of a Character-Object
*
* @author aaz210
*
*/
public class SelectRaceWidget extends FormPanel implements SelectRaceDialog.Display {
private Button nextButton;
private Button prevButton;
private VerticalPanel panel;
private RadioButton selectMale;
private RadioButton selectFemale;
private FlexTable selectGenderGrid;
private FlexTable buttonGrid;
private FlexTable selectRaceGrid;
private ListBox raceListBox;
public SelectRaceWidget(List<String> racenames) {
super();
// init controls
nextButton = new Button("weiter");
prevButton = new Button("zurück");
panel = new VerticalPanel();
selectMale = new RadioButton("selectGender", "männlich");
selectFemale = new RadioButton("selectGender", "weiblich");
selectGenderGrid = new FlexTable();
+ selectRaceGrid = new FlexTable();
buttonGrid = new FlexTable();
raceListBox = new ListBox();
// arrange controls
Image progressBar = new Image("media/images/progressbar_1.png");
selectGenderGrid.setBorderWidth(0);
selectGenderGrid.setStylePrimaryName("selectGrid");
Label genderLabel = new Label("Geschlecht wählen:");
selectGenderGrid.setWidget(0, 0, genderLabel);
selectGenderGrid.setWidget(0, 1, selectMale);
selectGenderGrid.setWidget(0, 2, selectFemale);
selectMale.setValue(true);
selectRaceGrid.setBorderWidth(0);
selectRaceGrid.setStylePrimaryName("selectGrid");
for (String racename : racenames) {
raceListBox.addItem(racename);
}
Label raceLabel = new Label("Rasse wählen: ");
selectRaceGrid.setWidget(0, 0, raceLabel);
selectRaceGrid.setWidget(0, 1, raceListBox);
raceListBox.setVisibleItemCount(raceListBox.getItemCount());
buttonGrid.getCellFormatter().setHorizontalAlignment(0, 1, HasHorizontalAlignment.ALIGN_RIGHT);
buttonGrid.setWidth("350px");
buttonGrid.setWidget(0, 0, prevButton);
buttonGrid.setWidget(0, 1, nextButton);
// Add it to the root panel.
HTML headline = new HTML("<h1>Geschlecht und Rasse wählen</h1>");
panel.setStyleName("panel");
panel.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
panel.setWidth("100%");
panel.add(progressBar);
panel.add(new Label("Schritt 1 von 9"));
panel.add(headline);
panel.add(selectGenderGrid);
panel.add(selectRaceGrid);
panel.add(buttonGrid);
RootPanel.get("information").clear();
RootPanel.get("information").add(getInformation());
RootPanel.get("content").clear();
RootPanel.get("content").add(panel);
}
public void loadCharacterPanel(User user, DefaultTimadorusWebApp entry) {
RootPanel.get("content").clear();
RootPanel.get("content").add(CreateDialog.getCreateDialog(entry, user).getFormPanel());
}
public void loadSelectClassPanel(DefaultTimadorusWebApp entry, User user, Character character) {
RootPanel.get("content").clear();
RootPanel.get("content").add(SelectClassDialog.getSelecteddDialog(entry, character, user)
.getFormPanel());
}
public String getSelectedRace() {
return raceListBox.getValue(raceListBox.getSelectedIndex());
}
public String getSelectedGender() {
String gender = "männlich";
if (selectMale.getValue()) {
gender = "männlich";
} else if (selectFemale.getValue()) {
gender = "weiblich";
}
return gender;
}
private static final HTML getInformation() {
HTML information = new HTML(
"<h1>Rasse und Geschlecht wählen</h1><p>Wählen sie hier das Geschlecht "
+ "und die Rasse ihres Charakteres. Beachten sie, dass bestimmte"
+ " Rassen nur bestimmte Klassen sowie "
+ "Fraktionen wählen können.</p>");
return information;
}
@Override
public FormPanel getFormPanel() {
return this;
}
@Override
public void addRaceSelectionHandler(final DefaultActionHandler handler) {
raceListBox.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
handler.onAction();
}
});
}
@Override
public void addPrevButtonHandler(final DefaultActionHandler handler) {
prevButton.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
handler.onAction();
}
});
}
@Override
public void addNextButtonHandler(final DefaultActionHandler handler) {
nextButton.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
handler.onAction();
}
});
}
@Override
public void showRaceSelection(String raceName, String raceDescription,
List<String> availableClasses, List<String> availableFactions) {
RootPanel.get("information").clear();
RootPanel.get("information").add(new HTML("<h1>" + raceName + "</h1><p>" + raceDescription
+ "</p>"));
// Show available Classes
RootPanel.get("information").add(new HTML("<h2>Wählbare Klassen</h2>"));
StringBuilder sb = new StringBuilder("<ul>");
for (String classname : availableClasses) {
sb.append("<li>");
sb.append(classname);
sb.append("</li>");
}
sb.append("</ul>");
RootPanel.get("information").add(new HTML(sb.toString()));
// Show available Factions
RootPanel.get("information").add(new HTML("<h2>Wählbare Fraktionen</h2>"));
sb = new StringBuilder("<ul>");
for (String factionname : availableFactions) {
sb.append("<li>");
sb.append(factionname);
sb.append("</li>");
}
sb.append("</ul>");
RootPanel.get("information").add(new HTML(sb.toString()));
}
}
| true | true | public SelectRaceWidget(List<String> racenames) {
super();
// init controls
nextButton = new Button("weiter");
prevButton = new Button("zurück");
panel = new VerticalPanel();
selectMale = new RadioButton("selectGender", "männlich");
selectFemale = new RadioButton("selectGender", "weiblich");
selectGenderGrid = new FlexTable();
buttonGrid = new FlexTable();
raceListBox = new ListBox();
// arrange controls
Image progressBar = new Image("media/images/progressbar_1.png");
selectGenderGrid.setBorderWidth(0);
selectGenderGrid.setStylePrimaryName("selectGrid");
Label genderLabel = new Label("Geschlecht wählen:");
selectGenderGrid.setWidget(0, 0, genderLabel);
selectGenderGrid.setWidget(0, 1, selectMale);
selectGenderGrid.setWidget(0, 2, selectFemale);
selectMale.setValue(true);
selectRaceGrid.setBorderWidth(0);
selectRaceGrid.setStylePrimaryName("selectGrid");
for (String racename : racenames) {
raceListBox.addItem(racename);
}
Label raceLabel = new Label("Rasse wählen: ");
selectRaceGrid.setWidget(0, 0, raceLabel);
selectRaceGrid.setWidget(0, 1, raceListBox);
raceListBox.setVisibleItemCount(raceListBox.getItemCount());
buttonGrid.getCellFormatter().setHorizontalAlignment(0, 1, HasHorizontalAlignment.ALIGN_RIGHT);
buttonGrid.setWidth("350px");
buttonGrid.setWidget(0, 0, prevButton);
buttonGrid.setWidget(0, 1, nextButton);
// Add it to the root panel.
HTML headline = new HTML("<h1>Geschlecht und Rasse wählen</h1>");
panel.setStyleName("panel");
panel.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
panel.setWidth("100%");
panel.add(progressBar);
panel.add(new Label("Schritt 1 von 9"));
panel.add(headline);
panel.add(selectGenderGrid);
panel.add(selectRaceGrid);
panel.add(buttonGrid);
RootPanel.get("information").clear();
RootPanel.get("information").add(getInformation());
RootPanel.get("content").clear();
RootPanel.get("content").add(panel);
}
| public SelectRaceWidget(List<String> racenames) {
super();
// init controls
nextButton = new Button("weiter");
prevButton = new Button("zurück");
panel = new VerticalPanel();
selectMale = new RadioButton("selectGender", "männlich");
selectFemale = new RadioButton("selectGender", "weiblich");
selectGenderGrid = new FlexTable();
selectRaceGrid = new FlexTable();
buttonGrid = new FlexTable();
raceListBox = new ListBox();
// arrange controls
Image progressBar = new Image("media/images/progressbar_1.png");
selectGenderGrid.setBorderWidth(0);
selectGenderGrid.setStylePrimaryName("selectGrid");
Label genderLabel = new Label("Geschlecht wählen:");
selectGenderGrid.setWidget(0, 0, genderLabel);
selectGenderGrid.setWidget(0, 1, selectMale);
selectGenderGrid.setWidget(0, 2, selectFemale);
selectMale.setValue(true);
selectRaceGrid.setBorderWidth(0);
selectRaceGrid.setStylePrimaryName("selectGrid");
for (String racename : racenames) {
raceListBox.addItem(racename);
}
Label raceLabel = new Label("Rasse wählen: ");
selectRaceGrid.setWidget(0, 0, raceLabel);
selectRaceGrid.setWidget(0, 1, raceListBox);
raceListBox.setVisibleItemCount(raceListBox.getItemCount());
buttonGrid.getCellFormatter().setHorizontalAlignment(0, 1, HasHorizontalAlignment.ALIGN_RIGHT);
buttonGrid.setWidth("350px");
buttonGrid.setWidget(0, 0, prevButton);
buttonGrid.setWidget(0, 1, nextButton);
// Add it to the root panel.
HTML headline = new HTML("<h1>Geschlecht und Rasse wählen</h1>");
panel.setStyleName("panel");
panel.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
panel.setWidth("100%");
panel.add(progressBar);
panel.add(new Label("Schritt 1 von 9"));
panel.add(headline);
panel.add(selectGenderGrid);
panel.add(selectRaceGrid);
panel.add(buttonGrid);
RootPanel.get("information").clear();
RootPanel.get("information").add(getInformation());
RootPanel.get("content").clear();
RootPanel.get("content").add(panel);
}
|
diff --git a/fabric/fabric-openshift/src/main/java/org/fusesource/fabric/openshift/commands/ContainerCreateOpenshift.java b/fabric/fabric-openshift/src/main/java/org/fusesource/fabric/openshift/commands/ContainerCreateOpenshift.java
index f2d2d45ea..d0ed9363d 100644
--- a/fabric/fabric-openshift/src/main/java/org/fusesource/fabric/openshift/commands/ContainerCreateOpenshift.java
+++ b/fabric/fabric-openshift/src/main/java/org/fusesource/fabric/openshift/commands/ContainerCreateOpenshift.java
@@ -1,87 +1,86 @@
package org.fusesource.fabric.openshift.commands;
import org.apache.felix.gogo.commands.Argument;
import org.apache.felix.gogo.commands.Command;
import org.apache.felix.gogo.commands.Option;
import org.fusesource.fabric.api.CreateContainerMetadata;
import org.fusesource.fabric.boot.commands.support.ContainerCreateSupport;
import org.fusesource.fabric.openshift.CreateOpenshiftContainerOptions;
import org.fusesource.fabric.utils.shell.ShellUtils;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import static org.fusesource.fabric.utils.FabricValidations.validateProfileName;
@Command(name = "container-create-openshift", scope = "fabric", description = "Creates one or more new containers on Openshift")
public class ContainerCreateOpenshift extends ContainerCreateSupport {
@Option(name = "--server-url", required = false, description = "The url to the openshift server.")
String serverUrl;
@Option(name = "--login", required = false, description = "The login name to use.")
String login;
@Option(name = "--password", required = false, description = "The password to use.")
String password;
@Option(name = "--proxy-uri", description = "The Maven proxy URL to use")
private URI proxyUri;
@Argument(index = 0, required = true, description = "The name of the container to be created. When creating multiple containers it serves as a prefix")
protected String name;
@Argument(index = 1, required = false, description = "The number of containers that should be created")
protected int number = 0;
@Override
protected Object doExecute() throws Exception {
// validate input before creating containers
preCreateContainer(name);
validateProfileName(profiles);
CreateOpenshiftContainerOptions.Builder builder = CreateOpenshiftContainerOptions.builder()
.name(name)
.serverUrl(serverUrl)
.login(login)
.password(password)
- .application(name)
.version(version)
.ensembleServer(isEnsembleServer)
.zookeeperUrl(fabricService.getZookeeperUrl())
.zookeeperPassword(isEnsembleServer && zookeeperPassword != null ? zookeeperPassword : fabricService.getZookeeperPassword())
.proxyUri(proxyUri != null ? proxyUri : fabricService.getMavenRepoURI())
.profiles(getProfileNames());
CreateContainerMetadata[] metadatas = fabricService.createContainers(builder.build());
if (isEnsembleServer && metadatas != null && metadatas.length > 0 && metadatas[0].isSuccess()) {
ShellUtils.storeZookeeperPassword(session, metadatas[0].getCreateOptions().getZookeeperPassword());
}
// display containers
displayContainers(metadatas);
return null;
}
protected void displayContainers(CreateContainerMetadata[] metadatas) {
List<CreateContainerMetadata> success = new ArrayList<CreateContainerMetadata>();
List<CreateContainerMetadata> failures = new ArrayList<CreateContainerMetadata>();
for (CreateContainerMetadata metadata : metadatas) {
(metadata.isSuccess() ? success : failures).add(metadata);
}
if (success.size() > 0) {
System.out.println("The following containers have been created successfully:");
for (CreateContainerMetadata m : success) {
System.out.println("\t" + m.toString());
}
}
if (failures.size() > 0) {
System.out.println("The following containers have failed:");
for (CreateContainerMetadata m : failures) {
System.out.println("\t" + m.getContainerName() + ": " + m.getFailure().getMessage());
}
}
}
}
| true | true | protected Object doExecute() throws Exception {
// validate input before creating containers
preCreateContainer(name);
validateProfileName(profiles);
CreateOpenshiftContainerOptions.Builder builder = CreateOpenshiftContainerOptions.builder()
.name(name)
.serverUrl(serverUrl)
.login(login)
.password(password)
.application(name)
.version(version)
.ensembleServer(isEnsembleServer)
.zookeeperUrl(fabricService.getZookeeperUrl())
.zookeeperPassword(isEnsembleServer && zookeeperPassword != null ? zookeeperPassword : fabricService.getZookeeperPassword())
.proxyUri(proxyUri != null ? proxyUri : fabricService.getMavenRepoURI())
.profiles(getProfileNames());
CreateContainerMetadata[] metadatas = fabricService.createContainers(builder.build());
if (isEnsembleServer && metadatas != null && metadatas.length > 0 && metadatas[0].isSuccess()) {
ShellUtils.storeZookeeperPassword(session, metadatas[0].getCreateOptions().getZookeeperPassword());
}
// display containers
displayContainers(metadatas);
return null;
}
| protected Object doExecute() throws Exception {
// validate input before creating containers
preCreateContainer(name);
validateProfileName(profiles);
CreateOpenshiftContainerOptions.Builder builder = CreateOpenshiftContainerOptions.builder()
.name(name)
.serverUrl(serverUrl)
.login(login)
.password(password)
.version(version)
.ensembleServer(isEnsembleServer)
.zookeeperUrl(fabricService.getZookeeperUrl())
.zookeeperPassword(isEnsembleServer && zookeeperPassword != null ? zookeeperPassword : fabricService.getZookeeperPassword())
.proxyUri(proxyUri != null ? proxyUri : fabricService.getMavenRepoURI())
.profiles(getProfileNames());
CreateContainerMetadata[] metadatas = fabricService.createContainers(builder.build());
if (isEnsembleServer && metadatas != null && metadatas.length > 0 && metadatas[0].isSuccess()) {
ShellUtils.storeZookeeperPassword(session, metadatas[0].getCreateOptions().getZookeeperPassword());
}
// display containers
displayContainers(metadatas);
return null;
}
|
diff --git a/src/uk/ac/gla/dcs/tp3/w/algorithm/Graph.java b/src/uk/ac/gla/dcs/tp3/w/algorithm/Graph.java
index 6feaf21..474e968 100644
--- a/src/uk/ac/gla/dcs/tp3/w/algorithm/Graph.java
+++ b/src/uk/ac/gla/dcs/tp3/w/algorithm/Graph.java
@@ -1,146 +1,147 @@
package uk.ac.gla.dcs.tp3.w.algorithm;
import java.util.LinkedList;
import uk.ac.gla.dcs.tp3.w.league.League;
import uk.ac.gla.dcs.tp3.w.league.Team;
public class Graph {
private Vertex[] vertices;
private int[][] matrix;
private Vertex source;
private Vertex sink;
public Graph() {
this(null, null);
}
public Graph(League l, Team t) {
if (l == null || t == null)
return;
// Number of team nodes is one less than total number of teams.
// The team nodes do not include the team being tested for elimination.
int teamTotal = l.getTeams().length;
// The r-combination of teamTotal for length 2 is the number of possible
// combinations for matches between the list of Teams-{t}.
int gameTotal = comb(teamTotal - 1, 2);
// Total number of vertices is the number of teams-1 + number of match
// pairs + source + sink.
vertices = new Vertex[teamTotal + gameTotal + 1];
// Set first vertex to be source, and last vertex to be sink.
// Create blank vertices for source and sink.
source = new Vertex(0);
sink = new Vertex(vertices.length - 1);
vertices[0] = source;
vertices[vertices.length - 1] = sink;
+ // Create vertices for each team node, and make them adjacent to
+ // the sink.
Team[] teams = l.getTeams();
- int pos = vertices.length -1;
- for(int i = 0;i<teams.length;i++){
- if (teams[i] != t){
- vertices[pos] = new TeamVertex(teams[i],i);
- vertices[vertices.length-1].getAdjList().add(new AdjListNode(0,vertices[pos]));
+ int pos = vertices.length - 1;
+ for (int i = 0; i < teams.length; i++) {
+ if (teams[i] != t) {
+ vertices[pos] = new TeamVertex(teams[i], i);
+ vertices[pos].getAdjList().add(
+ new AdjListNode(0, vertices[vertices.length - 1]));
pos--;
}
}
- // TODO Create vertices for each team node, and make them adjacent to
- // the sink.
// Create vertex for each team pair and make it adjacent from the
// source.
// TODO Also make the team pairs adjacent to the relevant Teams
pos = 1;
for (int i = 0; i < teamTotal + 1; i++) {
if (teams[i] == t)
continue;
for (int j = 1; j < teamTotal; j++) {
if (teams[j] == t)
continue;
vertices[pos] = new PairVertex(teams[i], teams[j], pos);
vertices[0].getAdjList().add(new AdjListNode(0, vertices[pos]));
pos++;
}
}
// TODO Iterate over every match, if the match hasn't been played and
// doesn't involve the Team t, increment the appropriate capacity of the
// edges.
// TODO Create the adjacency matrix representation of the graph.
}
public Vertex[] getV() {
return vertices;
}
public void setV(Vertex[] v) {
this.vertices = v;
}
public int[][] getMatrix() {
return matrix;
}
public int getSize() {
return vertices.length;
}
public void setMatrix(int[][] matrix) {
this.matrix = matrix;
}
public Vertex getSource() {
return source;
}
public void setSource(Vertex source) {
this.source = source;
}
public Vertex getSink() {
return sink;
}
public void setSink(Vertex sink) {
this.sink = sink;
}
private static int fact(int s) {
// For s < 2, the factorial is 1. Otherwise, multiply s by fact(s-1)
return (s < 2) ? 1 : s * fact(s - 1);
}
private static int comb(int n, int r) {
// r-combination of size n is n!/r!(n-r)!
return (fact(n) / (fact(r) * fact(n - r)));
}
/**
* carry out a breadth first search/traversal of the graph
*/
public void bfs() {
// TODO Read over this code, I (GR) just dropped this in here from
// bfs-example.
for (Vertex v : vertices)
v.setVisited(false);
LinkedList<Vertex> queue = new LinkedList<Vertex>();
for (Vertex v : vertices) {
if (!v.getVisited()) {
v.setVisited(true);
v.setPredecessor(v.getIndex());
queue.add(v);
while (!queue.isEmpty()) {
Vertex u = queue.removeFirst();
LinkedList<AdjListNode> list = u.getAdjList();
for (AdjListNode node : list) {
Vertex w = node.getVertex();
if (!w.getVisited()) {
w.setVisited(true);
w.setPredecessor(u.getIndex());
queue.add(w);
}
}
}
}
}
}
}
| false | true | public Graph(League l, Team t) {
if (l == null || t == null)
return;
// Number of team nodes is one less than total number of teams.
// The team nodes do not include the team being tested for elimination.
int teamTotal = l.getTeams().length;
// The r-combination of teamTotal for length 2 is the number of possible
// combinations for matches between the list of Teams-{t}.
int gameTotal = comb(teamTotal - 1, 2);
// Total number of vertices is the number of teams-1 + number of match
// pairs + source + sink.
vertices = new Vertex[teamTotal + gameTotal + 1];
// Set first vertex to be source, and last vertex to be sink.
// Create blank vertices for source and sink.
source = new Vertex(0);
sink = new Vertex(vertices.length - 1);
vertices[0] = source;
vertices[vertices.length - 1] = sink;
Team[] teams = l.getTeams();
int pos = vertices.length -1;
for(int i = 0;i<teams.length;i++){
if (teams[i] != t){
vertices[pos] = new TeamVertex(teams[i],i);
vertices[vertices.length-1].getAdjList().add(new AdjListNode(0,vertices[pos]));
pos--;
}
}
// TODO Create vertices for each team node, and make them adjacent to
// the sink.
// Create vertex for each team pair and make it adjacent from the
// source.
// TODO Also make the team pairs adjacent to the relevant Teams
pos = 1;
for (int i = 0; i < teamTotal + 1; i++) {
if (teams[i] == t)
continue;
for (int j = 1; j < teamTotal; j++) {
if (teams[j] == t)
continue;
vertices[pos] = new PairVertex(teams[i], teams[j], pos);
vertices[0].getAdjList().add(new AdjListNode(0, vertices[pos]));
pos++;
}
}
// TODO Iterate over every match, if the match hasn't been played and
// doesn't involve the Team t, increment the appropriate capacity of the
// edges.
// TODO Create the adjacency matrix representation of the graph.
}
| public Graph(League l, Team t) {
if (l == null || t == null)
return;
// Number of team nodes is one less than total number of teams.
// The team nodes do not include the team being tested for elimination.
int teamTotal = l.getTeams().length;
// The r-combination of teamTotal for length 2 is the number of possible
// combinations for matches between the list of Teams-{t}.
int gameTotal = comb(teamTotal - 1, 2);
// Total number of vertices is the number of teams-1 + number of match
// pairs + source + sink.
vertices = new Vertex[teamTotal + gameTotal + 1];
// Set first vertex to be source, and last vertex to be sink.
// Create blank vertices for source and sink.
source = new Vertex(0);
sink = new Vertex(vertices.length - 1);
vertices[0] = source;
vertices[vertices.length - 1] = sink;
// Create vertices for each team node, and make them adjacent to
// the sink.
Team[] teams = l.getTeams();
int pos = vertices.length - 1;
for (int i = 0; i < teams.length; i++) {
if (teams[i] != t) {
vertices[pos] = new TeamVertex(teams[i], i);
vertices[pos].getAdjList().add(
new AdjListNode(0, vertices[vertices.length - 1]));
pos--;
}
}
// Create vertex for each team pair and make it adjacent from the
// source.
// TODO Also make the team pairs adjacent to the relevant Teams
pos = 1;
for (int i = 0; i < teamTotal + 1; i++) {
if (teams[i] == t)
continue;
for (int j = 1; j < teamTotal; j++) {
if (teams[j] == t)
continue;
vertices[pos] = new PairVertex(teams[i], teams[j], pos);
vertices[0].getAdjList().add(new AdjListNode(0, vertices[pos]));
pos++;
}
}
// TODO Iterate over every match, if the match hasn't been played and
// doesn't involve the Team t, increment the appropriate capacity of the
// edges.
// TODO Create the adjacency matrix representation of the graph.
}
|
diff --git a/proxy/src/main/java/org/fedoraproject/candlepin/resource/ContentResource.java b/proxy/src/main/java/org/fedoraproject/candlepin/resource/ContentResource.java
index 4e1149bbd..629fca9fb 100644
--- a/proxy/src/main/java/org/fedoraproject/candlepin/resource/ContentResource.java
+++ b/proxy/src/main/java/org/fedoraproject/candlepin/resource/ContentResource.java
@@ -1,90 +1,90 @@
/**
* Copyright (c) 2009 Red Hat, Inc.
*
* This software is licensed to you under the GNU General Public License,
* version 2 (GPLv2). There is NO WARRANTY for this software, express or
* implied, including the implied warranties of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
* along with this software; if not, see
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
*
* Red Hat trademarks are not licensed under GPLv2. No permission is
* granted to use or replicate Red Hat trademarks that are incorporated
* in this software or its documentation.
*/
package org.fedoraproject.candlepin.resource;
import java.util.List;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.fedoraproject.candlepin.auth.Role;
import org.fedoraproject.candlepin.auth.interceptor.AllowRoles;
import org.fedoraproject.candlepin.exceptions.BadRequestException;
import org.fedoraproject.candlepin.model.Content;
import org.fedoraproject.candlepin.model.ContentCurator;
import org.xnap.commons.i18n.I18n;
import com.google.inject.Inject;
/**
* ContentResource
*/
@Path("/content")
public class ContentResource {
private ContentCurator contentCurator;
private I18n i18n;
/**
* default ctor
*
* Product Adapter used to interact with multiple services.
*/
@Inject
public ContentResource(ContentCurator contentCurator,
I18n i18n) {
this.i18n = i18n;
this.contentCurator = contentCurator;
}
@GET
@Produces(MediaType.APPLICATION_JSON)
public List<Content> list() {
return contentCurator.listAll();
}
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/id/{content_id}")
- public Content getContent(@PathParam("contend_id") String contentId) {
+ public Content getContent(@PathParam("content_id") String contentId) {
Content content = contentCurator.find(contentId);
if (content == null) {
throw new BadRequestException(
i18n.tr("Content with id {0} could not be found", contentId));
}
return content;
}
@POST
@Produces(MediaType.APPLICATION_JSON)
@AllowRoles(roles = {Role.SUPER_ADMIN})
public Content createContent(Content content) {
Content lookedUp = contentCurator.find(content.getId());
if (lookedUp != null) {
return lookedUp;
}
return contentCurator.create(content);
}
}
| true | true | public Content getContent(@PathParam("contend_id") String contentId) {
Content content = contentCurator.find(contentId);
if (content == null) {
throw new BadRequestException(
i18n.tr("Content with id {0} could not be found", contentId));
}
return content;
}
| public Content getContent(@PathParam("content_id") String contentId) {
Content content = contentCurator.find(contentId);
if (content == null) {
throw new BadRequestException(
i18n.tr("Content with id {0} could not be found", contentId));
}
return content;
}
|
diff --git a/plugins/org.eclipse.birt.report.engine/src/org/eclipse/birt/report/engine/layout/pdf/util/PropertyUtil.java b/plugins/org.eclipse.birt.report.engine/src/org/eclipse/birt/report/engine/layout/pdf/util/PropertyUtil.java
index 4e7b4f646..1e7e461d9 100644
--- a/plugins/org.eclipse.birt.report.engine/src/org/eclipse/birt/report/engine/layout/pdf/util/PropertyUtil.java
+++ b/plugins/org.eclipse.birt.report.engine/src/org/eclipse/birt/report/engine/layout/pdf/util/PropertyUtil.java
@@ -1,262 +1,262 @@
/***********************************************************************
* Copyright (c) 2004 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.report.engine.layout.pdf.util;
import java.awt.Color;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.eclipse.birt.report.engine.content.IContent;
import org.eclipse.birt.report.engine.content.IStyle;
import org.eclipse.birt.report.engine.css.engine.StyleConstants;
import org.eclipse.birt.report.engine.css.engine.value.FloatValue;
import org.eclipse.birt.report.engine.css.engine.value.RGBColorValue;
import org.eclipse.birt.report.engine.css.engine.value.StringValue;
import org.eclipse.birt.report.engine.css.engine.value.css.CSSConstants;
import org.eclipse.birt.report.engine.ir.DimensionType;
import org.w3c.dom.Element;
import org.w3c.dom.css.CSSPrimitiveValue;
import org.w3c.dom.css.CSSValue;
import com.lowagie.text.Font;
public class PropertyUtil
{
private static Logger logger = Logger.getLogger( PropertyUtil.class.getName() );
/**
* Checks if the font is bold
* @param value the CSSValue
* @return true if the font is bold
* false if not
*/
public static boolean isBoldFont(CSSValue value)
{
if(value!=null)
{
if ( IStyle.BOLD_VALUE.equals( value )
|| IStyle.BOLDER_VALUE.equals( value )
|| IStyle.NUMBER_600.equals( value )
|| IStyle.NUMBER_700.equals( value )
|| IStyle.NUMBER_800.equals( value )
|| IStyle.NUMBER_900.equals( value ) )
{
return true;
}
}
return false;
}
public static boolean isInlineElement(IContent content)
{
IStyle style = content.getStyle();
if(style!=null)
{
return IStyle.INLINE_VALUE.equals(style.getProperty( IStyle.STYLE_DISPLAY ));
}
return false;
}
public static int getLineHeight(String lineHeight)
{
try
{
if( lineHeight.equalsIgnoreCase( "normal" )) //$NON-NLS-1$
{
//BUG 147861: we return *0* as the default value of the *lineLight*
return 0;
}
return (int)Float.parseFloat( lineHeight );
}
catch(NumberFormatException ex)
{
logger.log(Level.WARNING, "invalid line height: {0}", lineHeight ); //$NON-NLS-1$
return 0;
}
}
public static Color getColor( CSSValue value )
{
if ( value != null && value instanceof RGBColorValue )
{
RGBColorValue color = (RGBColorValue) value;
try
{
return new Color( color.getRed( ).getFloatValue(
CSSPrimitiveValue.CSS_NUMBER ) / 255.0f, color
.getGreen( ).getFloatValue(
CSSPrimitiveValue.CSS_NUMBER ) / 255.0f, color
.getBlue( )
.getFloatValue( CSSPrimitiveValue.CSS_NUMBER ) / 255.0f );
}
catch ( RuntimeException ex )
{
logger.log( Level.WARNING, "invalid color: {0}", value ); //$NON-NLS-1$
}
}
return null;
}
/**
* Gets the color from a CSSValue converted string.
*
* @param color CSSValue converted string.
* @return java.awt.Color
*/
public static Color getColor( String color )
{
if ( color == null )
{
logger.log( Level.WARNING, "invalid color" ); //$NON-NLS-1$
return null;
}
Pattern p = Pattern.compile( "rgb\\(.+,.+,.+\\)" );
Matcher m = p.matcher( color );
if ( m.find( ) )
{
String[] rgb = color.substring( m.start( ) + 4, m.end( ) - 1 )
.split( "," );
if ( rgb.length == 3 )
{
- int red = Integer.parseInt( rgb[0].trim( ) );
- int green = Integer.parseInt( rgb[1].trim( ) );
- int blue = Integer.parseInt( rgb[2].trim( ) );
try
{
+ int red = Integer.parseInt( rgb[0].trim( ) );
+ int green = Integer.parseInt( rgb[1].trim( ) );
+ int blue = Integer.parseInt( rgb[2].trim( ) );
return new Color( red, green, blue );
}
catch ( RuntimeException ex )
{
logger.log( Level.WARNING, "invalid color" ); //$NON-NLS-1$
return null;
}
}
}
logger.log( Level.WARNING, "invalid color" ); //$NON-NLS-1$
return null;
}
public static int getFontStyle(String fontStyle, String fontWeight )
{
int styleValue = Font.NORMAL;
if ( CSSConstants.CSS_OBLIQUE_VALUE.equals( fontStyle )
|| CSSConstants.CSS_ITALIC_VALUE.equals( fontStyle ) )
{
styleValue |= Font.ITALIC;
}
if ( CSSConstants.CSS_BOLD_VALUE.equals( fontWeight )
|| CSSConstants.CSS_BOLDER_VALUE.equals( fontWeight )
|| CSSConstants.CSS_600_VALUE.equals( fontWeight )
|| CSSConstants.CSS_700_VALUE.equals( fontWeight )
|| CSSConstants.CSS_800_VALUE.equals( fontWeight )
|| CSSConstants.CSS_900_VALUE.equals( fontWeight ) )
{
styleValue |= Font.BOLD;
}
return styleValue;
}
public static String getBackgroundImage( CSSValue value )
{
if ( value != null && value instanceof StringValue )
{
String strValue = ( (StringValue) value ).getStringValue( );
if ( strValue != null
&& ( !CSSConstants.CSS_NONE_VALUE.equals( strValue ) ) )
{
return strValue;
}
}
return null;
}
public static int getDimensionValue( CSSValue value )
{
return getDimensionValue( value, 0 );
}
public static int getDimensionValue( CSSValue value, int referenceLength )
{
if ( value != null && ( value instanceof FloatValue ) )
{
FloatValue fv = (FloatValue) value;
float v = fv.getFloatValue( );
switch ( fv.getPrimitiveType( ) )
{
case CSSPrimitiveValue.CSS_CM :
return (int) ( v * 72000 / 2.54 );
case CSSPrimitiveValue.CSS_IN :
return (int) ( v * 72000 );
case CSSPrimitiveValue.CSS_MM :
return (int) ( v * 7200 / 2.54 );
case CSSPrimitiveValue.CSS_PT :
return (int) ( v * 1000 );
case CSSPrimitiveValue.CSS_NUMBER :
return (int) v;
case CSSPrimitiveValue.CSS_PERCENTAGE :
return (int) ( referenceLength * v/100.0 );
}
}
return 0;
}
public static int getIntAttribute( Element element, String attribute )
{
String value = element.getAttribute( attribute );
int result = 1;
if ( value != null && value.length( ) != 0 )
{
result = Integer.parseInt( value );
}
return result;
}
public static DimensionType getDimensionAttribute( Element ele,
String attribute )
{
String value = ele.getAttribute( attribute );
if ( value == null || 0 == value.length( ) )
{
return null;
}
return DimensionType.parserUnit( value, DimensionType.UNITS_PX );
}
public static float getPercentageValue(CSSValue value)
{
if(value!=null && (value instanceof FloatValue))
{
FloatValue fv = (FloatValue)value;
float v = fv.getFloatValue();
if (CSSPrimitiveValue.CSS_PERCENTAGE == fv.getPrimitiveType())
{
return v/100.0f;
}
}
return 0.0f;
}
}
| false | true | public static Color getColor( String color )
{
if ( color == null )
{
logger.log( Level.WARNING, "invalid color" ); //$NON-NLS-1$
return null;
}
Pattern p = Pattern.compile( "rgb\\(.+,.+,.+\\)" );
Matcher m = p.matcher( color );
if ( m.find( ) )
{
String[] rgb = color.substring( m.start( ) + 4, m.end( ) - 1 )
.split( "," );
if ( rgb.length == 3 )
{
int red = Integer.parseInt( rgb[0].trim( ) );
int green = Integer.parseInt( rgb[1].trim( ) );
int blue = Integer.parseInt( rgb[2].trim( ) );
try
{
return new Color( red, green, blue );
}
catch ( RuntimeException ex )
{
logger.log( Level.WARNING, "invalid color" ); //$NON-NLS-1$
return null;
}
}
}
logger.log( Level.WARNING, "invalid color" ); //$NON-NLS-1$
return null;
}
| public static Color getColor( String color )
{
if ( color == null )
{
logger.log( Level.WARNING, "invalid color" ); //$NON-NLS-1$
return null;
}
Pattern p = Pattern.compile( "rgb\\(.+,.+,.+\\)" );
Matcher m = p.matcher( color );
if ( m.find( ) )
{
String[] rgb = color.substring( m.start( ) + 4, m.end( ) - 1 )
.split( "," );
if ( rgb.length == 3 )
{
try
{
int red = Integer.parseInt( rgb[0].trim( ) );
int green = Integer.parseInt( rgb[1].trim( ) );
int blue = Integer.parseInt( rgb[2].trim( ) );
return new Color( red, green, blue );
}
catch ( RuntimeException ex )
{
logger.log( Level.WARNING, "invalid color" ); //$NON-NLS-1$
return null;
}
}
}
logger.log( Level.WARNING, "invalid color" ); //$NON-NLS-1$
return null;
}
|
diff --git a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/views/TaskElementLabelProvider.java b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/views/TaskElementLabelProvider.java
index 90e067e01..cafb6a050 100644
--- a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/views/TaskElementLabelProvider.java
+++ b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/views/TaskElementLabelProvider.java
@@ -1,367 +1,367 @@
/*******************************************************************************
* 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.internal.tasks.ui.views;
import java.util.regex.Pattern;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.viewers.IColorProvider;
import org.eclipse.jface.viewers.IFontProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.mylyn.internal.tasks.core.Person;
import org.eclipse.mylyn.internal.tasks.core.ScheduledTaskContainer;
import org.eclipse.mylyn.internal.tasks.core.TaskActivityManager;
import org.eclipse.mylyn.internal.tasks.core.TaskArchive;
import org.eclipse.mylyn.internal.tasks.core.TaskCategory;
import org.eclipse.mylyn.internal.tasks.core.TaskGroup;
import org.eclipse.mylyn.internal.tasks.core.UnfiledCategory;
import org.eclipse.mylyn.internal.tasks.ui.ITaskHighlighter;
import org.eclipse.mylyn.internal.tasks.ui.TaskListColorsAndFonts;
import org.eclipse.mylyn.internal.tasks.ui.TasksUiImages;
import org.eclipse.mylyn.internal.tasks.ui.TasksUiPreferenceConstants;
import org.eclipse.mylyn.tasks.core.AbstractRepositoryQuery;
import org.eclipse.mylyn.tasks.core.AbstractTask;
import org.eclipse.mylyn.tasks.core.AbstractTaskContainer;
import org.eclipse.mylyn.tasks.core.TaskRepository;
import org.eclipse.mylyn.tasks.core.AbstractTask.PriorityLevel;
import org.eclipse.mylyn.tasks.core.AbstractTask.RepositoryTaskSyncState;
import org.eclipse.mylyn.tasks.ui.AbstractRepositoryConnectorUi;
import org.eclipse.mylyn.tasks.ui.TasksUiPlugin;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.Image;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.themes.IThemeManager;
/**
* @author Mik Kersten
*/
public class TaskElementLabelProvider extends LabelProvider implements IColorProvider, IFontProvider {
private static final String NO_SUMMARY_AVAILABLE = ": <no summary available>";
private IThemeManager themeManager = PlatformUI.getWorkbench().getThemeManager();
private static final Pattern pattern = Pattern.compile("\\d*: .*");
private boolean wideImages = false;
private class CompositeImageDescriptor {
ImageDescriptor icon;
ImageDescriptor overlayKind;
};
// public TaskElementLabelProvider() {
// super();
// }
public TaskElementLabelProvider(boolean wideImages) {
super();
this.wideImages = wideImages;
}
@Override
public Image getImage(Object element) {
CompositeImageDescriptor compositeDescriptor = getImageDescriptor(element);
if (element instanceof AbstractTask) {
if (compositeDescriptor.overlayKind == null) {
compositeDescriptor.overlayKind = TasksUiImages.OVERLAY_BLANK;
}
return TasksUiImages.getCompositeTaskImage(compositeDescriptor.icon, compositeDescriptor.overlayKind,
wideImages);
} else if (element instanceof AbstractTaskContainer) {
return TasksUiImages.getCompositeTaskImage(compositeDescriptor.icon, TasksUiImages.OVERLAY_BLANK,
wideImages);
} else {
return TasksUiImages.getCompositeTaskImage(compositeDescriptor.icon, null, wideImages);
}
}
private CompositeImageDescriptor getImageDescriptor(Object object) {
CompositeImageDescriptor compositeDescriptor = new CompositeImageDescriptor();
if (object instanceof TaskArchive || object instanceof UnfiledCategory) {
compositeDescriptor.icon = TasksUiImages.CATEGORY_ARCHIVE;
return compositeDescriptor;
} else if (object instanceof TaskCategory || object instanceof UnfiledCategory) {
compositeDescriptor.icon = TasksUiImages.CATEGORY;
} else if (object instanceof TaskGroup) {
compositeDescriptor.icon = TasksUiImages.TASKLIST_MODE;
}
if (object instanceof AbstractTaskContainer) {
AbstractTaskContainer element = (AbstractTaskContainer) object;
AbstractRepositoryConnectorUi connectorUi = null;
if (element instanceof AbstractTask) {
AbstractTask repositoryTask = (AbstractTask) element;
connectorUi = TasksUiPlugin.getConnectorUi(((AbstractTask) element).getConnectorKind());
if (connectorUi != null) {
compositeDescriptor.overlayKind = connectorUi.getTaskKindOverlay(repositoryTask);
}
} else if (element instanceof AbstractRepositoryQuery) {
connectorUi = TasksUiPlugin.getConnectorUi(((AbstractRepositoryQuery) element).getRepositoryKind());
}
if (connectorUi != null) {
compositeDescriptor.icon = connectorUi.getTaskListElementIcon(element);
return compositeDescriptor;
} else {
if (element instanceof AbstractRepositoryQuery) {
compositeDescriptor.icon = TasksUiImages.QUERY;
} else if (element instanceof AbstractTask) {
compositeDescriptor.icon = TasksUiImages.TASK;
} else if (element instanceof ScheduledTaskContainer) {
compositeDescriptor.icon = TasksUiImages.CALENDAR;
} else if (element instanceof Person) {
compositeDescriptor.icon = TasksUiImages.PERSON;
for (TaskRepository repository : TasksUiPlugin.getRepositoryManager().getAllRepositories()) {
- if (!repository.isAnonymous()
- && repository.getUserName().equalsIgnoreCase(element.getHandleIdentifier())) {
+ if (!repository.isAnonymous() && (repository.getUserName() == null || repository.getUserName().equalsIgnoreCase(
+ element.getHandleIdentifier()))) {
compositeDescriptor.icon = TasksUiImages.PERSON_ME;
break;
}
}
}
return compositeDescriptor;
}
}
return compositeDescriptor;
}
public static ImageDescriptor getSynchronizationImageDescriptor(Object element, boolean synchViewStyle) {
AbstractTask repositoryTask = null;
ImageDescriptor imageDescriptor = null;
if (element instanceof AbstractTask) {
repositoryTask = (AbstractTask) element;
}
if (repositoryTask != null) {
if (repositoryTask.getSynchronizationState() == RepositoryTaskSyncState.INCOMING
&& repositoryTask.getLastReadTimeStamp() == null) {
if (synchViewStyle) {
return TasksUiImages.OVERLAY_SYNCH_INCOMMING_NEW;
} else {
return TasksUiImages.OVERLAY_INCOMMING_NEW;
}
}
if (repositoryTask.getSynchronizationState() == RepositoryTaskSyncState.OUTGOING) {
if (synchViewStyle) {
imageDescriptor = TasksUiImages.OVERLAY_SYNCH_OUTGOING;
} else {
imageDescriptor = TasksUiImages.OVERLAY_OUTGOING;
}
} else if (repositoryTask.getSynchronizationState() == RepositoryTaskSyncState.INCOMING) {
if (synchViewStyle) {
imageDescriptor = TasksUiImages.OVERLAY_SYNCH_INCOMMING;
} else {
imageDescriptor = TasksUiImages.OVERLAY_INCOMMING;
}
} else if (repositoryTask.getSynchronizationState() == RepositoryTaskSyncState.CONFLICT) {
imageDescriptor = TasksUiImages.OVERLAY_CONFLICT;
}
if (imageDescriptor == null && repositoryTask.getSynchronizationStatus() != null) {
return TasksUiImages.OVERLAY_WARNING;
} else if (imageDescriptor != null) {
return imageDescriptor;
}
} else if (element instanceof AbstractTaskContainer) {
AbstractTaskContainer container = (AbstractTaskContainer) element;
if (container instanceof AbstractRepositoryQuery) {
AbstractRepositoryQuery query = (AbstractRepositoryQuery) container;
if (query.getSynchronizationStatus() != null) {
return TasksUiImages.OVERLAY_WARNING;
}
}
}
// HACK: need a proper blank image
return TasksUiImages.OVERLAY_BLANK;
}
public static ImageDescriptor getPriorityImageDescriptor(Object element) {
AbstractRepositoryConnectorUi connectorUi;
if (element instanceof AbstractTask) {
AbstractTask repositoryTask = (AbstractTask) element;
connectorUi = TasksUiPlugin.getConnectorUi(((AbstractTask) element).getConnectorKind());
if (connectorUi != null) {
return connectorUi.getTaskPriorityOverlay(repositoryTask);
}
}
if (element instanceof AbstractTask) {
AbstractTask task = TaskElementLabelProvider.getCorrespondingTask((AbstractTaskContainer) element);
if (task != null) {
return TasksUiImages.getImageDescriptorForPriority(PriorityLevel.fromString(task.getPriority()));
}
}
return null;
}
@Override
public String getText(Object object) {
if (object instanceof AbstractTask) {
AbstractTask task = (AbstractTask) object;
if (task.getSummary() == null) {
if (task.getTaskKey() != null) {
return task.getTaskKey() + NO_SUMMARY_AVAILABLE;
} else {
return task.getTaskId() + NO_SUMMARY_AVAILABLE;
}
} else if (!pattern.matcher(task.getSummary()).matches()) {
if (task.getTaskKey() != null) {
return task.getTaskKey() + ": " + task.getSummary();
} else {
return task.getSummary();
}
} else {
return task.getSummary();
}
} else if (object instanceof TaskGroup) {
TaskGroup element = (TaskGroup) object;
return element.getSummary();// + " / " + element.getChildren().size();
} else if (object instanceof AbstractTaskContainer) {
AbstractTaskContainer element = (AbstractTaskContainer) object;
return element.getSummary();
} else {
return super.getText(object);
}
}
public Color getForeground(Object object) {
if (object instanceof AbstractTaskContainer && object instanceof AbstractTask) {
AbstractTask task = getCorrespondingTask((AbstractTaskContainer) object);
if (task != null) {
if (TaskActivityManager.getInstance().isCompletedToday(task)) {
return themeManager.getCurrentTheme().getColorRegistry().get(
TaskListColorsAndFonts.THEME_COLOR_TASK_TODAY_COMPLETED);
} else if (task.isCompleted()) {
return themeManager.getCurrentTheme().getColorRegistry().get(
TaskListColorsAndFonts.THEME_COLOR_COMPLETED);
} else if (task.isActive()) {
return TaskListColorsAndFonts.COLOR_TASK_ACTIVE;
} else if (task.isPastReminder()) {
return themeManager.getCurrentTheme().getColorRegistry().get(
TaskListColorsAndFonts.THEME_COLOR_TASK_OVERDUE);
} else if (TaskActivityManager.getInstance().isScheduledForToday(task)) {
return themeManager.getCurrentTheme().getColorRegistry().get(
TaskListColorsAndFonts.THEME_COLOR_TASK_TODAY_SCHEDULED);
} else if (TaskActivityManager.getInstance().isScheduledForThisWeek(task)) {
return themeManager.getCurrentTheme().getColorRegistry().get(
TaskListColorsAndFonts.THEME_COLOR_TASK_THISWEEK_SCHEDULED);
}
}
} else if (object instanceof AbstractTaskContainer) {
for (AbstractTask child : ((AbstractTaskContainer) object).getChildren()) {
if (child.isActive() || showHasActiveChild(child)) {
return TaskListColorsAndFonts.COLOR_TASK_ACTIVE;
} else if ((child.isPastReminder() && !child.isCompleted()) || showHasChildrenPastDue(child)) {
return themeManager.getCurrentTheme().getColorRegistry().get(
TaskListColorsAndFonts.THEME_COLOR_TASK_OVERDUE);
}
}
}
return null;
}
/**
* TODO: move
*/
public static AbstractTask getCorrespondingTask(AbstractTaskContainer element) {
if (element instanceof AbstractTask) {
return (AbstractTask) element;
} else {
return null;
}
}
public Color getBackground(Object element) {
if (element instanceof AbstractTask) {
AbstractTask task = (AbstractTask) element;
ITaskHighlighter highlighter = TasksUiPlugin.getDefault().getHighlighter();
if (highlighter != null) {
return highlighter.getHighlightColor(task);
}
}
return null;
}
public Font getFont(Object element) {
if (!(element instanceof AbstractTaskContainer)) {
return null;
}
AbstractTask task = getCorrespondingTask((AbstractTaskContainer) element);
if (task != null) {
AbstractTask repositoryTask = task;
if (repositoryTask.isSynchronizing()) {
return TaskListColorsAndFonts.ITALIC;
}
}
if (element instanceof AbstractTaskContainer) {
if (element instanceof AbstractRepositoryQuery) {
if (((AbstractRepositoryQuery) element).isSynchronizing()) {
return TaskListColorsAndFonts.ITALIC;
}
}
for (AbstractTask child : ((AbstractTaskContainer) element).getChildren()) {
if (child.isActive() || showHasActiveChild(child)) {
return TaskListColorsAndFonts.BOLD;
}
}
}
if (task != null) {
if (task.isActive()) {
return TaskListColorsAndFonts.BOLD;
} else if (task.isCompleted()) {
return TaskListColorsAndFonts.STRIKETHROUGH;
}
for (AbstractTask child : ((AbstractTaskContainer) element).getChildren()) {
if (child.isActive() || showHasActiveChild(child)) {
return TaskListColorsAndFonts.BOLD;
}
}
}
return null;
}
private boolean showHasActiveChild(AbstractTaskContainer container) {
if (!TasksUiPlugin.getDefault().getPreferenceStore().getBoolean(TasksUiPreferenceConstants.GROUP_SUBTASKS)) {
return false;
}
for (AbstractTaskContainer child : container.getChildren()) {
if (child instanceof AbstractTask && ((AbstractTask) child).isActive()) {
return true;
} else {
if (showHasActiveChild(child)) {
return true;
}
}
}
return false;
}
private boolean showHasChildrenPastDue(AbstractTaskContainer container) {
if (!TasksUiPlugin.getDefault().getPreferenceStore().getBoolean(TasksUiPreferenceConstants.GROUP_SUBTASKS)) {
return false;
}
for (AbstractTaskContainer child : container.getChildren()) {
if (child instanceof AbstractTask && ((AbstractTask) child).isPastReminder()
&& !((AbstractTask) child).isCompleted()) {
return true;
} else {
if (showHasChildrenPastDue(child)) {
return true;
}
}
}
return false;
}
}
| true | true | private CompositeImageDescriptor getImageDescriptor(Object object) {
CompositeImageDescriptor compositeDescriptor = new CompositeImageDescriptor();
if (object instanceof TaskArchive || object instanceof UnfiledCategory) {
compositeDescriptor.icon = TasksUiImages.CATEGORY_ARCHIVE;
return compositeDescriptor;
} else if (object instanceof TaskCategory || object instanceof UnfiledCategory) {
compositeDescriptor.icon = TasksUiImages.CATEGORY;
} else if (object instanceof TaskGroup) {
compositeDescriptor.icon = TasksUiImages.TASKLIST_MODE;
}
if (object instanceof AbstractTaskContainer) {
AbstractTaskContainer element = (AbstractTaskContainer) object;
AbstractRepositoryConnectorUi connectorUi = null;
if (element instanceof AbstractTask) {
AbstractTask repositoryTask = (AbstractTask) element;
connectorUi = TasksUiPlugin.getConnectorUi(((AbstractTask) element).getConnectorKind());
if (connectorUi != null) {
compositeDescriptor.overlayKind = connectorUi.getTaskKindOverlay(repositoryTask);
}
} else if (element instanceof AbstractRepositoryQuery) {
connectorUi = TasksUiPlugin.getConnectorUi(((AbstractRepositoryQuery) element).getRepositoryKind());
}
if (connectorUi != null) {
compositeDescriptor.icon = connectorUi.getTaskListElementIcon(element);
return compositeDescriptor;
} else {
if (element instanceof AbstractRepositoryQuery) {
compositeDescriptor.icon = TasksUiImages.QUERY;
} else if (element instanceof AbstractTask) {
compositeDescriptor.icon = TasksUiImages.TASK;
} else if (element instanceof ScheduledTaskContainer) {
compositeDescriptor.icon = TasksUiImages.CALENDAR;
} else if (element instanceof Person) {
compositeDescriptor.icon = TasksUiImages.PERSON;
for (TaskRepository repository : TasksUiPlugin.getRepositoryManager().getAllRepositories()) {
if (!repository.isAnonymous()
&& repository.getUserName().equalsIgnoreCase(element.getHandleIdentifier())) {
compositeDescriptor.icon = TasksUiImages.PERSON_ME;
break;
}
}
}
return compositeDescriptor;
}
}
return compositeDescriptor;
}
| private CompositeImageDescriptor getImageDescriptor(Object object) {
CompositeImageDescriptor compositeDescriptor = new CompositeImageDescriptor();
if (object instanceof TaskArchive || object instanceof UnfiledCategory) {
compositeDescriptor.icon = TasksUiImages.CATEGORY_ARCHIVE;
return compositeDescriptor;
} else if (object instanceof TaskCategory || object instanceof UnfiledCategory) {
compositeDescriptor.icon = TasksUiImages.CATEGORY;
} else if (object instanceof TaskGroup) {
compositeDescriptor.icon = TasksUiImages.TASKLIST_MODE;
}
if (object instanceof AbstractTaskContainer) {
AbstractTaskContainer element = (AbstractTaskContainer) object;
AbstractRepositoryConnectorUi connectorUi = null;
if (element instanceof AbstractTask) {
AbstractTask repositoryTask = (AbstractTask) element;
connectorUi = TasksUiPlugin.getConnectorUi(((AbstractTask) element).getConnectorKind());
if (connectorUi != null) {
compositeDescriptor.overlayKind = connectorUi.getTaskKindOverlay(repositoryTask);
}
} else if (element instanceof AbstractRepositoryQuery) {
connectorUi = TasksUiPlugin.getConnectorUi(((AbstractRepositoryQuery) element).getRepositoryKind());
}
if (connectorUi != null) {
compositeDescriptor.icon = connectorUi.getTaskListElementIcon(element);
return compositeDescriptor;
} else {
if (element instanceof AbstractRepositoryQuery) {
compositeDescriptor.icon = TasksUiImages.QUERY;
} else if (element instanceof AbstractTask) {
compositeDescriptor.icon = TasksUiImages.TASK;
} else if (element instanceof ScheduledTaskContainer) {
compositeDescriptor.icon = TasksUiImages.CALENDAR;
} else if (element instanceof Person) {
compositeDescriptor.icon = TasksUiImages.PERSON;
for (TaskRepository repository : TasksUiPlugin.getRepositoryManager().getAllRepositories()) {
if (!repository.isAnonymous() && (repository.getUserName() == null || repository.getUserName().equalsIgnoreCase(
element.getHandleIdentifier()))) {
compositeDescriptor.icon = TasksUiImages.PERSON_ME;
break;
}
}
}
return compositeDescriptor;
}
}
return compositeDescriptor;
}
|
diff --git a/src/r/nodes/truffle/FunctionCall.java b/src/r/nodes/truffle/FunctionCall.java
index 2ee0cea..e7bc5ea 100644
--- a/src/r/nodes/truffle/FunctionCall.java
+++ b/src/r/nodes/truffle/FunctionCall.java
@@ -1,124 +1,124 @@
package r.nodes.truffle;
import r.*;
import r.data.*;
import r.nodes.*;
public class FunctionCall extends BaseR {
RNode closureExpr;
final RSymbol[] names; // arguments of the call (not of the function), in order
RNode[] expressions;
private static final boolean DEBUG_MATCHING = false;
public FunctionCall(ASTNode ast, RNode closureExpr, RSymbol[] argNames, RNode[] argExprs) {
super(ast);
this.closureExpr = updateParent(closureExpr);
this.names = argNames;
this.expressions = updateParent(argExprs);
}
@Override
public Object execute(RContext context, RFrame frame) {
RClosure tgt = (RClosure) closureExpr.execute(context, frame);
RFunction func = tgt.function();
RFrame fframe = matchParams(context, func, tgt.environment());
RNode code = func.body();
Object res = code.execute(context, fframe);
return res;
}
private RFrame matchParams(RContext context, RFunction func, RFrame parentFrame) {
RFrame fframe = new RFrame(parentFrame, func);
// FIXME: now only eager evaluation (no promises)
// FIXME: now no support for "..."
RSymbol[] fargs = func.argNames();
RNode[] fdefs = func.argExprs();
Utils.check(fargs.length == fdefs.length);
int j;
for (j = 0; j < fargs.length; j++) { // FIXME: get rid of this to improve performance
fframe.localExtra(j, -1);
}
// exact matching on tags (names)
j = 0;
for (int i = 0; i < names.length; i++) {
RSymbol tag = names[i];
if (tag != null) {
boolean matched = false;
for (j = 0; j < fargs.length; j++) {
RSymbol ftag = fargs[j];
if (tag == ftag) {
fframe.localExtra(j, i); // remember the index of supplied argument that matches
if (DEBUG_MATCHING)
Utils.debug("matched formal at index " + j + " by tag " + tag.pretty() + " to supplied argument at index " + i);
matched = true;
break;
}
}
if (!matched) {
// FIXME: fix error reporting
context.warning(getAST(), "unused argument(s) (" + tag.pretty() + ")"); // FIXME move this string in RError
}
}
}
// FIXME: add partial matching on tags
// positional matching of remaining arguments
j = 0;
for (int i = 0; i < names.length; i++) {
RSymbol tag = names[i];
if (tag == null) {
for (;;) {
if (j == fargs.length) {
// FIXME: fix error reporting
- throw new RuntimeException("Error in " + getAST() + " : unused argument(s) (" + expressions[i].getAST() + ")");
+ context.warning(getAST(), "unused argument(s) (" + expressions[i].getAST() + ")");
}
if (fframe.localExtra(j) == -1) {
fframe.localExtra(j, i); // remember the index of supplied argument that matches
if (DEBUG_MATCHING)
Utils.debug("matched formal at index " + j + " by position at formal index " + i);
j++;
break;
}
j++;
}
}
}
// providing values for the arguments
for (j = 0; j < fargs.length; j++) {
int i = (int) fframe.localExtra(j);
if (i != -1) {
RNode argExp = expressions[i];
if (argExp != null) {
fframe.writeAt(j, (RAny) argExp.execute(context, parentFrame)); // FIXME: premature forcing of a promise
if (DEBUG_MATCHING)
Utils.debug("supplied formal " + fargs[j].pretty() + " with provided value from supplied index " + i);
continue;
}
// note that an argument may be matched, but still have a null expression
}
RNode defExp = fdefs[j];
if (defExp != null) {
fframe.writeAt(j, (RAny) defExp.execute(context, fframe)); // FIXME: premature forcing of a promise
if (DEBUG_MATCHING)
Utils.debug("supplied ` " + fargs[j].pretty() + " with default value");
} else {
// throw new RuntimeException("Error in " + getAST() + " : '" + fargs[j].pretty() + "' is missing");
// This is not an error ! This error will be reported iff some code try to access it. (Which sucks a bit but is the behaviour)
}
}
return fframe;
}
private void displaceArgs(RContext context, int[] positions, RNode[] exprs, RFrame frame) {
for (int i = 0; i < positions.length; i++) {
frame.writeAt(i, (RAny) exprs[i].execute(context, frame)); // FIXME this is wrong ! We have to build a promise at this point and not evaluate
}
}
}
| true | true | private RFrame matchParams(RContext context, RFunction func, RFrame parentFrame) {
RFrame fframe = new RFrame(parentFrame, func);
// FIXME: now only eager evaluation (no promises)
// FIXME: now no support for "..."
RSymbol[] fargs = func.argNames();
RNode[] fdefs = func.argExprs();
Utils.check(fargs.length == fdefs.length);
int j;
for (j = 0; j < fargs.length; j++) { // FIXME: get rid of this to improve performance
fframe.localExtra(j, -1);
}
// exact matching on tags (names)
j = 0;
for (int i = 0; i < names.length; i++) {
RSymbol tag = names[i];
if (tag != null) {
boolean matched = false;
for (j = 0; j < fargs.length; j++) {
RSymbol ftag = fargs[j];
if (tag == ftag) {
fframe.localExtra(j, i); // remember the index of supplied argument that matches
if (DEBUG_MATCHING)
Utils.debug("matched formal at index " + j + " by tag " + tag.pretty() + " to supplied argument at index " + i);
matched = true;
break;
}
}
if (!matched) {
// FIXME: fix error reporting
context.warning(getAST(), "unused argument(s) (" + tag.pretty() + ")"); // FIXME move this string in RError
}
}
}
// FIXME: add partial matching on tags
// positional matching of remaining arguments
j = 0;
for (int i = 0; i < names.length; i++) {
RSymbol tag = names[i];
if (tag == null) {
for (;;) {
if (j == fargs.length) {
// FIXME: fix error reporting
throw new RuntimeException("Error in " + getAST() + " : unused argument(s) (" + expressions[i].getAST() + ")");
}
if (fframe.localExtra(j) == -1) {
fframe.localExtra(j, i); // remember the index of supplied argument that matches
if (DEBUG_MATCHING)
Utils.debug("matched formal at index " + j + " by position at formal index " + i);
j++;
break;
}
j++;
}
}
}
// providing values for the arguments
for (j = 0; j < fargs.length; j++) {
int i = (int) fframe.localExtra(j);
if (i != -1) {
RNode argExp = expressions[i];
if (argExp != null) {
fframe.writeAt(j, (RAny) argExp.execute(context, parentFrame)); // FIXME: premature forcing of a promise
if (DEBUG_MATCHING)
Utils.debug("supplied formal " + fargs[j].pretty() + " with provided value from supplied index " + i);
continue;
}
// note that an argument may be matched, but still have a null expression
}
RNode defExp = fdefs[j];
if (defExp != null) {
fframe.writeAt(j, (RAny) defExp.execute(context, fframe)); // FIXME: premature forcing of a promise
if (DEBUG_MATCHING)
Utils.debug("supplied ` " + fargs[j].pretty() + " with default value");
} else {
// throw new RuntimeException("Error in " + getAST() + " : '" + fargs[j].pretty() + "' is missing");
// This is not an error ! This error will be reported iff some code try to access it. (Which sucks a bit but is the behaviour)
}
}
return fframe;
}
| private RFrame matchParams(RContext context, RFunction func, RFrame parentFrame) {
RFrame fframe = new RFrame(parentFrame, func);
// FIXME: now only eager evaluation (no promises)
// FIXME: now no support for "..."
RSymbol[] fargs = func.argNames();
RNode[] fdefs = func.argExprs();
Utils.check(fargs.length == fdefs.length);
int j;
for (j = 0; j < fargs.length; j++) { // FIXME: get rid of this to improve performance
fframe.localExtra(j, -1);
}
// exact matching on tags (names)
j = 0;
for (int i = 0; i < names.length; i++) {
RSymbol tag = names[i];
if (tag != null) {
boolean matched = false;
for (j = 0; j < fargs.length; j++) {
RSymbol ftag = fargs[j];
if (tag == ftag) {
fframe.localExtra(j, i); // remember the index of supplied argument that matches
if (DEBUG_MATCHING)
Utils.debug("matched formal at index " + j + " by tag " + tag.pretty() + " to supplied argument at index " + i);
matched = true;
break;
}
}
if (!matched) {
// FIXME: fix error reporting
context.warning(getAST(), "unused argument(s) (" + tag.pretty() + ")"); // FIXME move this string in RError
}
}
}
// FIXME: add partial matching on tags
// positional matching of remaining arguments
j = 0;
for (int i = 0; i < names.length; i++) {
RSymbol tag = names[i];
if (tag == null) {
for (;;) {
if (j == fargs.length) {
// FIXME: fix error reporting
context.warning(getAST(), "unused argument(s) (" + expressions[i].getAST() + ")");
}
if (fframe.localExtra(j) == -1) {
fframe.localExtra(j, i); // remember the index of supplied argument that matches
if (DEBUG_MATCHING)
Utils.debug("matched formal at index " + j + " by position at formal index " + i);
j++;
break;
}
j++;
}
}
}
// providing values for the arguments
for (j = 0; j < fargs.length; j++) {
int i = (int) fframe.localExtra(j);
if (i != -1) {
RNode argExp = expressions[i];
if (argExp != null) {
fframe.writeAt(j, (RAny) argExp.execute(context, parentFrame)); // FIXME: premature forcing of a promise
if (DEBUG_MATCHING)
Utils.debug("supplied formal " + fargs[j].pretty() + " with provided value from supplied index " + i);
continue;
}
// note that an argument may be matched, but still have a null expression
}
RNode defExp = fdefs[j];
if (defExp != null) {
fframe.writeAt(j, (RAny) defExp.execute(context, fframe)); // FIXME: premature forcing of a promise
if (DEBUG_MATCHING)
Utils.debug("supplied ` " + fargs[j].pretty() + " with default value");
} else {
// throw new RuntimeException("Error in " + getAST() + " : '" + fargs[j].pretty() + "' is missing");
// This is not an error ! This error will be reported iff some code try to access it. (Which sucks a bit but is the behaviour)
}
}
return fframe;
}
|
diff --git a/src/main/src/test/java/org/geoserver/data/test/MockData.java b/src/main/src/test/java/org/geoserver/data/test/MockData.java
index d1fdf160..11336414 100644
--- a/src/main/src/test/java/org/geoserver/data/test/MockData.java
+++ b/src/main/src/test/java/org/geoserver/data/test/MockData.java
@@ -1,958 +1,959 @@
/* Copyright (c) 2001 - 2007 TOPP - www.openplans.org. All rights reserved.
* This code is licensed under the GPL 2.0 license, availible at the root
* application directory.
*/
package org.geoserver.data.test;
import java.awt.geom.AffineTransform;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.xml.namespace.QName;
import org.apache.commons.io.FileUtils;
import org.geoserver.catalog.ProjectionPolicy;
import org.geoserver.data.CatalogWriter;
import org.geoserver.data.util.CoverageStoreUtils;
import org.geoserver.data.util.CoverageUtils;
import org.geoserver.data.util.IOUtils;
import org.geotools.coverage.Category;
import org.geotools.coverage.GridSampleDimension;
import org.geotools.coverage.grid.GridCoverage2D;
import org.geotools.coverage.grid.GridGeometry2D;
import org.geotools.coverage.grid.io.AbstractGridCoverage2DReader;
import org.geotools.coverage.grid.io.AbstractGridFormat;
import org.geotools.coverage.grid.io.GridFormatFinder;
import org.geotools.data.property.PropertyDataStoreFactory;
import org.geotools.geometry.GeneralEnvelope;
import org.geotools.referencing.CRS;
import org.opengis.coverage.grid.GridGeometry;
import org.opengis.parameter.ParameterValueGroup;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import org.opengis.referencing.cs.CoordinateSystem;
import com.vividsolutions.jts.geom.Envelope;
/**
* Class used to build a mock GeoServer data directory.
* <p>
* Data is based off the wms and wfs "cite" datasets.
* </p>
*
* @author Justin Deoliveira, The Open Planning Project
*
*/
public class MockData implements TestData {
// Extra configuration keys for vector data
/**
* Use FeatureTypeInfo constants for srs handling as values or use {@link ProjectionPolicy}
* values straight
*/
public static final String KEY_SRS_HANDLINGS = "srsHandling";
/**
* The feature type alias, a string
*/
public static final String KEY_ALIAS = "alias";
/**
* The style name
*/
public static final String KEY_STYLE = "style";
/**
* The srs code (a number) for this layer
*/
public static final String KEY_SRS_NUMBER = "srs";
/**
* The lon/lat envelope as a JTS Envelope
*/
public static final String KEY_LL_ENVELOPE = "ll_envelope";
/**
* The native envelope as a JTS Envelope
*/
public static final String KEY_NATIVE_ENVELOPE = "native_envelope";
static final Envelope DEFAULT_ENVELOPE = new Envelope(-180,180,-90,90);
// //// WMS 1.1.1
/**
* WMS 1.1.1 cite namespace + uri
*/
public static String CITE_PREFIX = "cite";
public static String CITE_URI = "http://www.opengis.net/cite";
/** featuretype name for WMS 1.1.1 CITE BasicPolygons features */
public static QName BASIC_POLYGONS = new QName(CITE_URI, "BasicPolygons", CITE_PREFIX);
/** featuretype name for WMS 1.1.1 CITE Bridges features */
public static QName BRIDGES = new QName(CITE_URI, "Bridges", CITE_PREFIX);
/** featuretype name for WMS 1.1.1 CITE Buildings features */
public static QName BUILDINGS = new QName(CITE_URI, "Buildings", CITE_PREFIX);
/** featuretype name for WMS 1.1.1 CITE Divided Routes features */
public static QName DIVIDED_ROUTES = new QName(CITE_URI, "DividedRoutes", CITE_PREFIX);
/** featuretype name for WMS 1.1.1 CITE Forests features */
public static QName FORESTS = new QName(CITE_URI, "Forests", CITE_PREFIX);
/** featuretype name for WMS 1.1.1 CITE Lakes features */
public static QName LAKES = new QName(CITE_URI, "Lakes", CITE_PREFIX);
/** featuretype name for WMS 1.1.1 CITE Map Neatliine features */
public static QName MAP_NEATLINE = new QName(CITE_URI, "MapNeatline", CITE_PREFIX);
/** featuretype name for WMS 1.1.1 CITE Named Places features */
public static QName NAMED_PLACES = new QName(CITE_URI, "NamedPlaces", CITE_PREFIX);
/** featuretype name for WMS 1.1.1 CITE Ponds features */
public static QName PONDS = new QName(CITE_URI, "Ponds", CITE_PREFIX);
/** featuretype name for WMS 1.1.1 CITE Road Segments features */
public static QName ROAD_SEGMENTS = new QName(CITE_URI, "RoadSegments", CITE_PREFIX);
/** featuretype name for WMS 1.1.1 CITE Streams features */
public static QName STREAMS = new QName(CITE_URI, "Streams", CITE_PREFIX);
// /// WFS 1.0
/**
* WFS 1.0 cdf namespace + uri
*/
public static String CDF_PREFIX = "cdf";
public static String CDF_URI = "http://www.opengis.net/cite/data";
/** featuretype name for WFS 1.0 CITE Deletes features */
public static QName DELETES = new QName(CDF_URI, "Deletes", CDF_PREFIX);
/** featuretype name for WFS 1.0 CITE Fifteen features */
public static QName FIFTEEN = new QName(CDF_URI, "Fifteen", CDF_PREFIX);
/** featuretype name for WFS 1.0 CITE Inserts features */
public static QName INSERTS = new QName(CDF_URI, "Inserts", CDF_PREFIX);
/** featuretype name for WFS 1.0 CITE Inserts features */
public static QName LOCKS = new QName(CDF_URI, "Locks", CDF_PREFIX);
/** featuretype name for WFS 1.0 CITE Nulls features */
public static QName NULLS = new QName(CDF_URI, "Nulls", CDF_PREFIX);
/** featuretype name for WFS 1.0 CITE Other features */
public static QName OTHER = new QName(CDF_URI, "Other", CDF_PREFIX);
/** featuretype name for WFS 1.0 CITE Nulls features */
public static QName SEVEN = new QName(CDF_URI, "Seven", CDF_PREFIX);
/** featuretype name for WFS 1.0 CITE Updates features */
public static QName UPDATES = new QName(CDF_URI, "Updates", CDF_PREFIX);
/**
* cgf namespace + uri
*/
public static String CGF_PREFIX = "cgf";
public static String CGF_URI = "http://www.opengis.net/cite/geometry";
/** featuretype name for WFS 1.0 CITE Lines features */
public static QName LINES = new QName(CGF_URI, "Lines", CGF_PREFIX);
/** featuretype name for WFS 1.0 CITE MLines features */
public static QName MLINES = new QName(CGF_URI, "MLines", CGF_PREFIX);
/** featuretype name for WFS 1.0 CITE MPoints features */
public static QName MPOINTS = new QName(CGF_URI, "MPoints", CGF_PREFIX);
/** featuretype name for WFS 1.0 CITE MPolygons features */
public static QName MPOLYGONS = new QName(CGF_URI, "MPolygons", CGF_PREFIX);
/** featuretype name for WFS 1.0 CITE Points features */
public static QName POINTS = new QName(CGF_URI, "Points", CGF_PREFIX);
/** featuretype name for WFS 1.0 CITE Polygons features */
public static QName POLYGONS = new QName(CGF_URI, "Polygons", CGF_PREFIX);
// //// WFS 1.1
/**
* sf namespace + uri
*/
public static String SF_PREFIX = "sf";
public static String SF_URI = "http://cite.opengeospatial.org/gmlsf";
public static QName PRIMITIVEGEOFEATURE = new QName(SF_URI, "PrimitiveGeoFeature", SF_PREFIX);
public static QName AGGREGATEGEOFEATURE = new QName(SF_URI, "AggregateGeoFeature", SF_PREFIX);
public static QName GENERICENTITY = new QName(SF_URI, "GenericEntity", SF_PREFIX);
// WCS 1.0
public static QName GTOPO_DEM = new QName(CDF_URI, "W020N90", CDF_PREFIX);
public static QName USA_WORLDIMG = new QName(CDF_URI, "usa", CDF_PREFIX);
public static String DEM = "dem";
public static String PNG = "png";
// WCS 1.1
public static String WCS_PREFIX = "wcs";
public static String WCS_URI = "http://www.opengis.net/wcs/1.1.1";
public static QName TASMANIA_DEM = new QName(WCS_URI, "DEM", WCS_PREFIX);
public static QName TASMANIA_BM = new QName(WCS_URI, "BlueMarble", WCS_PREFIX);
public static QName ROTATED_CAD = new QName(WCS_URI, "RotatedCad", WCS_PREFIX);
public static QName WORLD = new QName(WCS_URI, "World", WCS_PREFIX);
public static String TIFF = "tiff";
// DEFAULT
public static String DEFAULT_PREFIX = "gs";
public static String DEFAULT_URI = "http://geoserver.org";
// public static QName ENTIT\u00C9G\u00C9N\u00C9RIQUE = new QName( SF_URI,
// "Entit\u00E9G\u00E9n\u00E9rique", SF_PREFIX );
// Extra types
public static QName GEOMETRYLESS = new QName(CITE_URI, "Geometryless", CITE_PREFIX);
/**
* List of all cite types names
*/
public static QName[] TYPENAMES = new QName[] {
// WMS 1.1.1
BASIC_POLYGONS, BRIDGES, BUILDINGS, DIVIDED_ROUTES, FORESTS, LAKES, MAP_NEATLINE,
NAMED_PLACES, PONDS, ROAD_SEGMENTS, STREAMS, // WFS 1.0
DELETES, FIFTEEN, INSERTS, LOCKS, NULLS, OTHER, SEVEN, UPDATES, LINES, MLINES, MPOINTS,
MPOLYGONS, POINTS, POLYGONS, // WFS 1.1
PRIMITIVEGEOFEATURE, AGGREGATEGEOFEATURE, GENERICENTITY, GEOMETRYLESS /* ENTIT\u00C9G\u00C9N\u00C9RIQUE */
};
/**
* List of wms type names.
*/
public static QName[] WMS_TYPENAMES = new QName[] {
BASIC_POLYGONS, BRIDGES, BUILDINGS, DIVIDED_ROUTES, FORESTS, LAKES, MAP_NEATLINE,
NAMED_PLACES, PONDS, ROAD_SEGMENTS, STREAMS
};
/**
* List of wfs 1.0 type names.
*/
public static QName[] WFS10_TYPENAMES = new QName[] {
DELETES, FIFTEEN, INSERTS, LOCKS, NULLS, OTHER, SEVEN, UPDATES, LINES, MLINES, MPOINTS,
MPOLYGONS, POINTS, POLYGONS
};
/**
* List of wfs 1.1 type names.
*/
public static QName[] WFS11_TYPENAMES = new QName[] {
PRIMITIVEGEOFEATURE, AGGREGATEGEOFEATURE, GENERICENTITY /* ENTIT\u00C9G\u00C9N\u00C9RIQUE */
};
/**
* map of qname to srs
*/
public static HashMap<QName,Integer> SRS = new HashMap<QName, Integer>();
static {
for ( int i = 0; i < WFS10_TYPENAMES.length; i++ ) {
SRS.put( WFS10_TYPENAMES[i], 32615);
}
for ( int i = 0; i < WFS11_TYPENAMES.length; i++ ) {
SRS.put( WFS11_TYPENAMES[i], 4326 );
}
}
/** the base of the data directory */
File data;
/** the 'featureTypes' directory, under 'data' */
File featureTypes;
/** the 'coverages' directory, under 'data' */
File coverages;
/** the 'styles' directory, under 'data' */
File styles;
/** the 'plugIns' directory under 'data */
File plugIns;
/** the 'validation' directory under 'data */
File validation;
/** the 'templates' director under 'data' */
File templates;
/** The datastore definition map */
HashMap dataStores = new HashMap();
/** The set of disabled data stores */
Set disabledDataStores = new HashSet();
/** The datastore to namespace map */
private HashMap dataStoreNamepaces = new HashMap();
/** The namespaces map */
private HashMap namespaces = new HashMap();
/** The styles map */
private HashMap layerStyles = new HashMap();
/** The coverage store map */
private HashMap coverageStores = new HashMap();
/** The set of disabled coverage stores */
Set disabledCoverageStores = new HashSet();
/** The coverage store id to namespace map */
private HashMap coverageStoresNamespaces = new HashMap();
public MockData() throws IOException {
// setup the root
data = IOUtils.createRandomDirectory("./target", "mock", "data");
data.delete();
data.mkdir();
// create a featureTypes directory
featureTypes = new File(data, "featureTypes");
featureTypes.mkdir();
// create a coverages directory
coverages = new File(data, "coverages");
coverages.mkdir();
// create the styles directory
styles = new File(data, "styles");
styles.mkdir();
//copy over the minimal style
IOUtils.copy(MockData.class.getResourceAsStream("Default.sld"), new File(styles, "Default.sld"));
//plugins
plugIns = new File(data, "plugIns");
plugIns.mkdir();
//validation
validation = new File(data, "validation");
validation.mkdir();
//templates
templates = new File(data, "templates");
templates.mkdir();
// setup basic map information
namespaces.put(DEFAULT_PREFIX, DEFAULT_URI);
namespaces.put("", DEFAULT_URI);
layerStyles.put("Default", "Default.sld");
}
public void setUp() throws IOException {
setUpCatalog();
copyTo(MockData.class.getResourceAsStream("services.xml"), "services.xml");
}
public boolean isTestDataAvailable() {
return true;
}
/**
* @return The root of the data directory.
*/
public File getDataDirectoryRoot() {
return data;
}
/**
* @return the "featureTypes" directory under the root
*/
public File getFeatureTypesDirectory() {
return featureTypes;
}
/**
* @return the "coverages" directory under the root
*/
public File getCoveragesDirectory() {
return coverages;
}
/**
* Copies some content to a file under the base of the data directory.
* <p>
* The <code>location</code> is considred to be a path relative to the
* data directory root.
* </p>
* <p>
* Note that the resulting file will be deleted when {@link #tearDown()}
* is called.
* </p>
* @param input The content to copy.
* @param location A relative path
*/
public void copyTo(InputStream input, String location)
throws IOException {
IOUtils.copy(input, new File(getDataDirectoryRoot(), location));
}
/**
* Copies some content to a file udner a specific feature type directory
* of the data directory.
* Example:
* <p>
* <code>
* dd.copyToFeautreTypeDirectory(input,MockData.PrimitiveGeoFeature,"info.xml");
* </code>
* </p>
* @param input The content to copy.
* @param featureTypeName The name of the feature type.
* @param location The resulting location to copy to relative to the
* feautre type directory.
*/
public void copyToFeatureTypeDirectory(InputStream input, QName featureTypeName, String location )
throws IOException {
copyTo(input, "featureTypes" + File.separator + featureTypeName.getPrefix()
+ "_" + featureTypeName.getLocalPart() + File.separator + location );
}
/**
* Adds the list of well known types to the data directory. Well known types
* are listed as constants in the MockData class header, and are organized
* as arrays based on the cite test they do come from
*
* @param names
* @throws IOException
*/
public void addWellKnownTypes(QName[] names) throws IOException {
for (int i = 0; i < names.length; i++) {
QName name = names[i];
addWellKnownType(name, null);
}
}
/**
* Adds a single well known type with the custom properties specified
*
* @param name
* @param extraProperties The extra properties to be used
* @throws IOException
*/
public void addWellKnownType(QName name, Map extraProperties) throws IOException {
URL properties = MockData.class.getResource(name.getLocalPart() + ".properties");
URL style = MockData.class.getResource(name.getLocalPart() + ".sld");
String styleName = null;
if(style != null) {
styleName = name.getLocalPart();
addStyle(styleName, style);
}
if(extraProperties == null)
addPropertiesType(name, properties, Collections.singletonMap(KEY_STYLE, styleName));
else {
Map props = new HashMap(extraProperties);
props.put(KEY_STYLE, styleName);
addPropertiesType(name, properties, props);
}
}
public void removeFeatureType(QName typeName) throws IOException {
String prefix = typeName.getPrefix();
String type = typeName.getLocalPart();
File featureTypeDir = new File(featureTypes, prefix + "_" + type);
if (!featureTypeDir.exists()) {
throw new FileNotFoundException("Type directory not found: "
+ featureTypeDir.getAbsolutePath());
}
File info = new File(featureTypeDir, "info.xml");
if (!info.exists()) {
throw new FileNotFoundException("FeatureType file not found: "
+ featureTypeDir.getAbsolutePath());
}
if (!IOUtils.delete(featureTypeDir)) {
throw new IOException("FetureType directory not deleted: "
+ featureTypeDir.getAbsolutePath());
}
}
/**
* Adds the "well known" coverage types to the data directory.
*
* @deprecated use {@link #addWcs11Coverages()}
*/
public void addWellKnownCoverageTypes() throws Exception {
addWcs11Coverages();
}
/**
* Adds the wcs 1.0 coverages.
*/
public void addWcs10Coverages() throws Exception {
URL style = MockData.class.getResource("raster.sld");
String styleName = "raster";
addStyle(styleName, style);
//wcs 1.0
//addCoverage(GTOPO_DEM, TestData.class.getResource("W020N90/W020N90.manifest"),
// "dem", styleName);
addCoverage(USA_WORLDIMG, TestData.class.getResource("usa.zip"), null, styleName);
}
/**
* Adds the wcs 1.1 coverages.
*/
public void addWcs11Coverages() throws Exception {
URL style = MockData.class.getResource("raster.sld");
String styleName = "raster";
addStyle(styleName, style);
//wcs 1.1
addCoverage(TASMANIA_DEM, TestData.class.getResource("tazdem.tiff"),
TIFF, styleName);
addCoverage(TASMANIA_BM, TestData.class.getResource("tazbm.tiff"),
TIFF, styleName);
addCoverage(ROTATED_CAD, TestData.class.getResource("rotated.tiff"),
TIFF, styleName);
addCoverage(WORLD, TestData.class.getResource("world.tiff"),
TIFF, styleName);
}
/**
* Adds the specified style to the data directory
* @param styleId the style id
* @param style an URL pointing to an SLD file to be copied into the data directory
* @throws IOException
*/
public void addStyle(String styleId, URL style) throws IOException {
layerStyles.put(styleId, styleId + ".sld");
InputStream styleContents = style.openStream();
File to = new File(styles, styleId + ".sld");
IOUtils.copy(styleContents, to);
}
/**
* Adds a property file as a feature type in a property datastore.
*
* @param name
* the fully qualified name of the feature type. The prefix and
* namespace URI will be used to create a namespace, the prefix
* will be used as the datastore name, the local name will become
* the feature type name
* @param properties
* a URL to the property file backing the feature type. If null,
* an emtpy property file will be used
* @param extraParams
* a map from extra configurable keys to their values (see for example
* @throws IOException
*/
public void addPropertiesType(QName name, URL properties, Map extraParams) throws IOException {
// sanitize input params
if(extraParams == null)
extraParams = Collections.EMPTY_MAP;
// setup the type directory if needed
File directory = new File(data, name.getPrefix());
if ( !directory.exists() ) {
directory.mkdir();
}
// create the properties file
File f = new File(directory, name.getLocalPart() + ".properties");
// copy over the contents
InputStream propertiesContents;
if(properties == null)
propertiesContents = new ByteArrayInputStream( "-=".getBytes() );
else
propertiesContents = properties.openStream();
IOUtils.copy( propertiesContents, f );
// write the info file
info(name, extraParams);
// setup the meta information to be written in the catalog
namespaces.put(name.getPrefix(), name.getNamespaceURI());
dataStoreNamepaces.put(name.getPrefix(), name.getPrefix());
Map params = new HashMap();
params.put(PropertyDataStoreFactory.DIRECTORY.key, directory);
params.put(PropertyDataStoreFactory.NAMESPACE.key, name.getNamespaceURI());
dataStores.put(name.getPrefix(), params);
}
/**
* Adds a new coverage.
*<p>
* Note that callers of this code should call <code>applicationContext.refresh()</code>
* in order to force the catalog to reload.
* </p>
* <p>
* The <tt>coverage</tt> parameter is an input stream containing a single uncompressed
* file that's supposed to be a coverage (e.g., a GeoTiff).
* </p>
* @param name
* @param coverage
*/
public void addCoverage(QName name, URL coverage, String extension, String styleName) throws Exception {
File directory = new File(data, name.getPrefix());
if ( !directory.exists() ) {
directory.mkdir();
}
// create the coverage file
File f = new File(directory, name.getLocalPart() + (extension != null ? "." + extension : ""));
if (extension == null) {
f.mkdir();
}
// copy over the contents
if (!f.isDirectory())
IOUtils.copy( coverage.openStream(), f );
else {
// assuming compressed file
final File compressedFile = new File(f, name.getLocalPart() + ".zip");
IOUtils.copy( coverage.openStream(), compressedFile );
IOUtils.decompress(compressedFile, f);
final File srcDir = new File(f, name.getLocalPart());
srcDir.mkdir();
FileUtils.copyDirectory(srcDir, f, true);
}
coverageInfo(name, f, styleName);
// setup the meta information to be written in the catalog
AbstractGridFormat format = (AbstractGridFormat) GridFormatFinder.findFormat(f);
namespaces.put(name.getPrefix(), name.getNamespaceURI());
coverageStoresNamespaces.put(name.getLocalPart(), name.getPrefix());
Map params = new HashMap();
params.put(CatalogWriter.COVERAGE_TYPE_KEY, format.getName());
params.put(CatalogWriter.COVERAGE_URL_KEY, "file:" + name.getPrefix() + "/" + name.getLocalPart() + (extension != null ? "." + extension : ""));
coverageStores.put(name.getLocalPart(), params);
}
public void addCoverageFromZip(QName name, URL coverage, String extension, String styleName) throws Exception {
File directory = new File(data, name.getPrefix());
if (!directory.exists()) {
directory.mkdir();
}
File f = new File(directory, name.getLocalPart());
f.mkdir();
File compressedFile = new File(f, name.getLocalPart() + ".zip");
IOUtils.copy(coverage.openStream(), compressedFile);
IOUtils.decompress(compressedFile, f);
final File srcDir = new File(f, name.getLocalPart());
srcDir.mkdir();
FileUtils.copyDirectory(srcDir, f, true);
if (extension != null) {
File coverageFile = new File(srcDir, name.getLocalPart() + "." + extension);
addCoverageFromPath(name, coverageFile,
"file:" + name.getPrefix() + "/" + name.getLocalPart() + "/" + name.getLocalPart() + "." + extension,
styleName);
} else {
addCoverageFromPath(name, f,
"file:" + name.getPrefix() + "/" + name.getLocalPart(),
styleName);
}
}
private void addCoverageFromPath(QName name, File coverage, String relpath, String styleName) throws Exception {
coverageInfo(name, coverage, styleName);
// setup the meta information to be written in the catalog
AbstractGridFormat format = (AbstractGridFormat) GridFormatFinder.findFormat(coverage);
namespaces.put(name.getPrefix(), name.getNamespaceURI());
coverageStoresNamespaces.put(name.getLocalPart(), name.getPrefix());
Map params = new HashMap();
params.put(CatalogWriter.COVERAGE_TYPE_KEY, format.getName());
params.put(CatalogWriter.COVERAGE_URL_KEY, relpath);
coverageStores.put(name.getLocalPart(), params);
}
/**
* Disables the specificed datastore (it's still configured, but with enabled=false)
* @param datastoreId
*/
public void disableDataStore(String datastoreId) {
disabledDataStores.add(datastoreId);
}
/**
* Disables the specificed coveragestore (it's still configured, but with enabled=false)
* @param datastoreId
*/
public void disableCoverageStore(String datastoreId) {
disabledCoverageStores.add(datastoreId);
}
/**
* Populates a map with prefix to namespace uri mappings for all the
* mock data namespaces.
*/
public void registerNamespaces(Map<String,String> namespaces) {
namespaces.put(MockData.CITE_PREFIX, MockData.CITE_URI);
namespaces.put(MockData.CDF_PREFIX, MockData.CDF_URI);
namespaces.put(MockData.CGF_PREFIX, MockData.CGF_URI);
namespaces.put(MockData.SF_PREFIX, MockData.SF_URI);
}
/**
* Sets up the catalog in the data directory
*
* @throws IOException
*/
protected void setUpCatalog() throws IOException {
// create the catalog.xml
CatalogWriter writer = new CatalogWriter();
writer.dataStores(dataStores, dataStoreNamepaces, disabledDataStores);
writer.coverageStores(coverageStores, coverageStoresNamespaces, disabledCoverageStores);
writer.namespaces(namespaces);
writer.styles(layerStyles);
writer.write(new File(data, "catalog.xml"));
}
void properties(QName name) throws IOException {
// copy over the properties file
InputStream from = MockData.class.getResourceAsStream(name.getLocalPart() + ".properties");
File directory = new File(data, name.getPrefix());
directory.mkdir();
File to = new File(directory, name.getLocalPart() + ".properties");
IOUtils.copy(from, to);
}
void info(QName name, Map<String, Object> extraParams) throws IOException {
String type = name.getLocalPart();
String prefix = name.getPrefix();
// prepare extra params default
Map<String, Object> params = new HashMap<String, Object>();
params.put(KEY_STYLE, "Default");
params.put(KEY_ALIAS, null);
Integer srs = SRS.get( name );
if ( srs == null ) {
srs = 4326;
}
params.put(KEY_SRS_NUMBER, srs);
// override with whatever the user provided
params.putAll(extraParams);
File featureTypeDir = new File(featureTypes, prefix + "_" + type);
featureTypeDir.mkdir();
File info = new File(featureTypeDir, "info.xml");
info.delete();
info.createNewFile();
FileWriter writer = new FileWriter(info);
writer.write("<featureType datastore=\"" + prefix + "\">");
writer.write("<name>" + type + "</name>");
if(params.get(KEY_ALIAS) != null)
writer.write("<alias>" + params.get(KEY_ALIAS) + "</alias>");
writer.write("<SRS>" + params.get(KEY_SRS_NUMBER) + "</SRS>");
// this mock type may have wrong SRS compared to the actual one in the property files...
// let's configure SRS handling not to alter the original one, and have 4326 used only
// for capabilities
int srsHandling = 2;
Object handling = params.get(KEY_SRS_HANDLINGS);
if(handling != null) {
if(handling instanceof ProjectionPolicy) {
srsHandling = ((ProjectionPolicy) params.get(KEY_SRS_HANDLINGS)).getCode();
} else if(handling instanceof Number) {
srsHandling = ((Number) params.get(KEY_SRS_HANDLINGS)).intValue();
}
}
writer.write("<SRSHandling>" + srsHandling + "</SRSHandling>");
writer.write("<title>" + type + "</title>");
writer.write("<abstract>abstract about " + type + "</abstract>");
writer.write("<numDecimals value=\"8\"/>");
writer.write("<keywords>" + type + "</keywords>");
Envelope llEnvelope = (Envelope) params.get(KEY_LL_ENVELOPE);
if(llEnvelope == null)
llEnvelope = DEFAULT_ENVELOPE;
writer.write("<latLonBoundingBox dynamic=\"false\" minx=\"" + llEnvelope.getMinX()
+ "\" miny=\"" + llEnvelope.getMinY() + "\" maxx=\"" + llEnvelope.getMaxX()
+ "\" maxy=\"" + llEnvelope.getMaxY() + "\"/>");
Envelope nativeEnvelope = (Envelope) params.get(KEY_NATIVE_ENVELOPE);
if(nativeEnvelope != null)
writer.write("<nativeBBox dynamic=\"false\" minx=\"" + nativeEnvelope.getMinX()
+ "\" miny=\"" + nativeEnvelope.getMinY() + "\" maxx=\"" + nativeEnvelope.getMaxX()
+ "\" maxy=\"" + nativeEnvelope.getMaxY() + "\"/>");
String style = (String) params.get(KEY_STYLE);
if(style == null)
style = "Default";
writer.write("<styles default=\"" + style + "\"/>");
writer.write("</featureType>");
writer.flush();
writer.close();
}
void coverageInfo(QName name, File coverageFile, String styleName) throws Exception {
String coverage = name.getLocalPart();
File coverageDir = new File(coverages, coverage);
coverageDir.mkdir();
File info = new File(coverageDir, "info.xml");
info.createNewFile();
// let's grab the necessary metadata
AbstractGridFormat format = (AbstractGridFormat) GridFormatFinder.findFormat(coverageFile);
+ System.out.println(coverageFile.toString());
AbstractGridCoverage2DReader reader = (AbstractGridCoverage2DReader) format.getReader(coverageFile);
if (reader == null) {
throw new RuntimeException("No reader for " + coverageFile.getCanonicalPath() + " with format " + format.getName());
}
// basic info
FileWriter writer = new FileWriter(info);
writer.write("<coverage format=\"" + coverage + "\">\n");
writer.write("<name>" + coverage + "</name>\n");
writer.write("<label>" + coverage + "</label>\n");
writer.write("<description>" + coverage + " description</description>\n");
writer.write("<metadataLink about = \"http://www.remotesensing.org:16080/websites/geotiff/geotiff.html\" metadataType = \"other\" />");
writer.write("<keywords>WCS," + coverage + " </keywords>\n");
if(styleName == null)
styleName = "raster";
writer.write("<styles default=\"" + styleName + "\"/>\n");
// envelope
CoordinateReferenceSystem crs = reader.getCrs();
GeneralEnvelope envelope = reader.getOriginalEnvelope();
GeneralEnvelope wgs84envelope = CoverageStoreUtils.getWGS84LonLatEnvelope(envelope);
final String nativeCrsName = CRS.lookupIdentifier(crs, false);
writer.write("<envelope crs=\"" + crs.toString().replaceAll("\"", "'") + "\" srsName=\"" + nativeCrsName + "\">\n");
writer.write("<pos>" + wgs84envelope.getMinimum(0) + " " + wgs84envelope.getMinimum(1) + "</pos>\n");
writer.write("<pos>" + wgs84envelope.getMaximum(0) + " " + wgs84envelope.getMaximum(1) + "</pos>\n");
writer.write("</envelope>\n");
/**
* Now reading a fake small GridCoverage just to retrieve meta information:
* - calculating a new envelope which is 1/20 of the original one
* - reading the GridCoverage subset
*/
final ParameterValueGroup readParams = reader.getFormat().getReadParameters();
final Map parameters = CoverageUtils.getParametersKVP(readParams);
double[] minCP = envelope.getLowerCorner().getCoordinate();
double[] maxCP = new double[] {
minCP[0] + (envelope.getSpan(0) / 20.0),
minCP[1] + (envelope.getSpan(1) / 20.0)
};
final GeneralEnvelope subEnvelope = new GeneralEnvelope(minCP, maxCP);
subEnvelope.setCoordinateReferenceSystem(reader.getCrs());
parameters.put(AbstractGridFormat.READ_GRIDGEOMETRY2D.getName().toString(),
new GridGeometry2D(reader.getOriginalGridRange(), subEnvelope));
GridCoverage2D gc = (GridCoverage2D) reader.read(CoverageUtils.getParameters(readParams, parameters,
true));
// grid geometry
final GridGeometry geometry = gc.getGridGeometry();
final int dimensions = geometry.getGridRange().getDimension();
String lower = "";
String upper = "";
for(int i = 0; i < dimensions; i++) {
lower = lower + geometry.getGridRange().getLow(i) + " ";
upper = upper + geometry.getGridRange().getHigh(i) + " ";
}
writer.write("<grid dimension = \"" + dimensions + "\">\n");
writer.write("<low>" + lower + "</low>\n");
writer.write("<high>" + upper + "</high>\n");
final CoordinateSystem cs = crs.getCoordinateSystem();
for (int i=0; i < cs.getDimension(); i++) {
writer.write("<axisName>" + cs.getAxis(i).getName().getCode() + "</axisName>\n");
}
if(geometry.getGridToCRS() instanceof AffineTransform) {
AffineTransform aTX = (AffineTransform) geometry.getGridToCRS();
writer.write("<geoTransform>");
writer.write("<scaleX>" + aTX.getScaleX() + "</scaleX>\n");
writer.write("<scaleY>" + aTX.getScaleY() + "</scaleY>\n");
writer.write("<shearX>" + aTX.getShearX() + "</shearX>\n");
writer.write("<shearY>" + aTX.getShearY() + "</shearY>\n");
writer.write("<translateX>" + aTX.getTranslateX() + "</translateX>\n");
writer.write("<translateY>" + aTX.getTranslateY() + "</translateY>\n");
writer.write("</geoTransform>\n");
}
writer.write("</grid>\n");
// coverage dimensions
final GridSampleDimension[] sd = gc.getSampleDimensions();
for (int i = 0; i < sd.length; i++) {
writer.write("<CoverageDimension>\n");
writer.write("<name>" + sd[i].getDescription().toString() + "</name>\n");
writer.write("<interval>\n");
writer.write("<min>" + sd[i].getMinimumValue() + "</min>\n");
writer.write("<max>" + sd[i].getMaximumValue() + "</max>\n");
writer.write("</interval>\n");
final List<Category> categories = sd[i].getCategories();
if (categories != null && categories.size() >= 1) {
writer.write("<nullValues>\n");
for (Iterator<Category> it = sd[i].getCategories().iterator(); it
.hasNext();) {
Category cat = (Category) it.next();
if ((cat != null)
&& cat.getName().toString().equalsIgnoreCase(
"no data")) {
double min = cat.getRange().getMinimum();
double max = cat.getRange().getMaximum();
writer.write("<value>" + min + "</value>\n");
if (min != max)
writer.write("<value>" + max + "</value>\n");
}
}
writer.write("</nullValues>\n");
}
else
writer.write("<nullValues/>\n");
writer.write("</CoverageDimension>\n");
}
// supported crs
writer.write("<supportedCRSs>\n");
writer.write("<requestCRSs>" + nativeCrsName + "</requestCRSs>\n");
writer.write("<responseCRSs>" + nativeCrsName + "</responseCRSs>\n");
writer.write("</supportedCRSs>\n");
// supported formats
writer.write("<supportedFormats nativeFormat = \"" + format.getName() + "\">\n");
writer.write("<formats>ARCGRID,ARCGRID-GZIP,GEOTIFF,PNG,GIF,TIFF</formats>\n");
writer.write("</supportedFormats>\n");
// supported interpolations
writer.write("<supportedInterpolations default = \"nearest neighbor\">\n");
writer.write("<interpolationMethods>nearest neighbor</interpolationMethods>\n");
writer.write("</supportedInterpolations>\n");
// the end
writer.write("</coverage>\n");
writer.flush();
writer.close();
}
/**
* Kills the data directory, deleting all the files.
*
* @throws IOException
*/
public void tearDown() throws IOException {
// IOUtils.delete(templates);
// IOUtils.delete(validation);
// IOUtils.delete(plugIns);
// IOUtils.delete(styles);
// IOUtils.delete(featureTypes);
// IOUtils.delete(coverages);
IOUtils.delete(data);
styles = null;
featureTypes = null;
data = null;
}
}
| true | true | void coverageInfo(QName name, File coverageFile, String styleName) throws Exception {
String coverage = name.getLocalPart();
File coverageDir = new File(coverages, coverage);
coverageDir.mkdir();
File info = new File(coverageDir, "info.xml");
info.createNewFile();
// let's grab the necessary metadata
AbstractGridFormat format = (AbstractGridFormat) GridFormatFinder.findFormat(coverageFile);
AbstractGridCoverage2DReader reader = (AbstractGridCoverage2DReader) format.getReader(coverageFile);
if (reader == null) {
throw new RuntimeException("No reader for " + coverageFile.getCanonicalPath() + " with format " + format.getName());
}
// basic info
FileWriter writer = new FileWriter(info);
writer.write("<coverage format=\"" + coverage + "\">\n");
writer.write("<name>" + coverage + "</name>\n");
writer.write("<label>" + coverage + "</label>\n");
writer.write("<description>" + coverage + " description</description>\n");
writer.write("<metadataLink about = \"http://www.remotesensing.org:16080/websites/geotiff/geotiff.html\" metadataType = \"other\" />");
writer.write("<keywords>WCS," + coverage + " </keywords>\n");
if(styleName == null)
styleName = "raster";
writer.write("<styles default=\"" + styleName + "\"/>\n");
// envelope
CoordinateReferenceSystem crs = reader.getCrs();
GeneralEnvelope envelope = reader.getOriginalEnvelope();
GeneralEnvelope wgs84envelope = CoverageStoreUtils.getWGS84LonLatEnvelope(envelope);
final String nativeCrsName = CRS.lookupIdentifier(crs, false);
writer.write("<envelope crs=\"" + crs.toString().replaceAll("\"", "'") + "\" srsName=\"" + nativeCrsName + "\">\n");
writer.write("<pos>" + wgs84envelope.getMinimum(0) + " " + wgs84envelope.getMinimum(1) + "</pos>\n");
writer.write("<pos>" + wgs84envelope.getMaximum(0) + " " + wgs84envelope.getMaximum(1) + "</pos>\n");
writer.write("</envelope>\n");
/**
* Now reading a fake small GridCoverage just to retrieve meta information:
* - calculating a new envelope which is 1/20 of the original one
* - reading the GridCoverage subset
*/
final ParameterValueGroup readParams = reader.getFormat().getReadParameters();
final Map parameters = CoverageUtils.getParametersKVP(readParams);
double[] minCP = envelope.getLowerCorner().getCoordinate();
double[] maxCP = new double[] {
minCP[0] + (envelope.getSpan(0) / 20.0),
minCP[1] + (envelope.getSpan(1) / 20.0)
};
final GeneralEnvelope subEnvelope = new GeneralEnvelope(minCP, maxCP);
subEnvelope.setCoordinateReferenceSystem(reader.getCrs());
parameters.put(AbstractGridFormat.READ_GRIDGEOMETRY2D.getName().toString(),
new GridGeometry2D(reader.getOriginalGridRange(), subEnvelope));
GridCoverage2D gc = (GridCoverage2D) reader.read(CoverageUtils.getParameters(readParams, parameters,
true));
// grid geometry
final GridGeometry geometry = gc.getGridGeometry();
final int dimensions = geometry.getGridRange().getDimension();
String lower = "";
String upper = "";
for(int i = 0; i < dimensions; i++) {
lower = lower + geometry.getGridRange().getLow(i) + " ";
upper = upper + geometry.getGridRange().getHigh(i) + " ";
}
writer.write("<grid dimension = \"" + dimensions + "\">\n");
writer.write("<low>" + lower + "</low>\n");
writer.write("<high>" + upper + "</high>\n");
final CoordinateSystem cs = crs.getCoordinateSystem();
for (int i=0; i < cs.getDimension(); i++) {
writer.write("<axisName>" + cs.getAxis(i).getName().getCode() + "</axisName>\n");
}
if(geometry.getGridToCRS() instanceof AffineTransform) {
AffineTransform aTX = (AffineTransform) geometry.getGridToCRS();
writer.write("<geoTransform>");
writer.write("<scaleX>" + aTX.getScaleX() + "</scaleX>\n");
writer.write("<scaleY>" + aTX.getScaleY() + "</scaleY>\n");
writer.write("<shearX>" + aTX.getShearX() + "</shearX>\n");
writer.write("<shearY>" + aTX.getShearY() + "</shearY>\n");
writer.write("<translateX>" + aTX.getTranslateX() + "</translateX>\n");
writer.write("<translateY>" + aTX.getTranslateY() + "</translateY>\n");
writer.write("</geoTransform>\n");
}
writer.write("</grid>\n");
// coverage dimensions
final GridSampleDimension[] sd = gc.getSampleDimensions();
for (int i = 0; i < sd.length; i++) {
writer.write("<CoverageDimension>\n");
writer.write("<name>" + sd[i].getDescription().toString() + "</name>\n");
writer.write("<interval>\n");
writer.write("<min>" + sd[i].getMinimumValue() + "</min>\n");
writer.write("<max>" + sd[i].getMaximumValue() + "</max>\n");
writer.write("</interval>\n");
final List<Category> categories = sd[i].getCategories();
if (categories != null && categories.size() >= 1) {
writer.write("<nullValues>\n");
for (Iterator<Category> it = sd[i].getCategories().iterator(); it
.hasNext();) {
Category cat = (Category) it.next();
if ((cat != null)
&& cat.getName().toString().equalsIgnoreCase(
"no data")) {
double min = cat.getRange().getMinimum();
double max = cat.getRange().getMaximum();
writer.write("<value>" + min + "</value>\n");
if (min != max)
writer.write("<value>" + max + "</value>\n");
}
}
writer.write("</nullValues>\n");
}
else
writer.write("<nullValues/>\n");
writer.write("</CoverageDimension>\n");
}
// supported crs
writer.write("<supportedCRSs>\n");
writer.write("<requestCRSs>" + nativeCrsName + "</requestCRSs>\n");
writer.write("<responseCRSs>" + nativeCrsName + "</responseCRSs>\n");
writer.write("</supportedCRSs>\n");
// supported formats
writer.write("<supportedFormats nativeFormat = \"" + format.getName() + "\">\n");
writer.write("<formats>ARCGRID,ARCGRID-GZIP,GEOTIFF,PNG,GIF,TIFF</formats>\n");
writer.write("</supportedFormats>\n");
// supported interpolations
writer.write("<supportedInterpolations default = \"nearest neighbor\">\n");
writer.write("<interpolationMethods>nearest neighbor</interpolationMethods>\n");
writer.write("</supportedInterpolations>\n");
// the end
writer.write("</coverage>\n");
writer.flush();
writer.close();
}
| void coverageInfo(QName name, File coverageFile, String styleName) throws Exception {
String coverage = name.getLocalPart();
File coverageDir = new File(coverages, coverage);
coverageDir.mkdir();
File info = new File(coverageDir, "info.xml");
info.createNewFile();
// let's grab the necessary metadata
AbstractGridFormat format = (AbstractGridFormat) GridFormatFinder.findFormat(coverageFile);
System.out.println(coverageFile.toString());
AbstractGridCoverage2DReader reader = (AbstractGridCoverage2DReader) format.getReader(coverageFile);
if (reader == null) {
throw new RuntimeException("No reader for " + coverageFile.getCanonicalPath() + " with format " + format.getName());
}
// basic info
FileWriter writer = new FileWriter(info);
writer.write("<coverage format=\"" + coverage + "\">\n");
writer.write("<name>" + coverage + "</name>\n");
writer.write("<label>" + coverage + "</label>\n");
writer.write("<description>" + coverage + " description</description>\n");
writer.write("<metadataLink about = \"http://www.remotesensing.org:16080/websites/geotiff/geotiff.html\" metadataType = \"other\" />");
writer.write("<keywords>WCS," + coverage + " </keywords>\n");
if(styleName == null)
styleName = "raster";
writer.write("<styles default=\"" + styleName + "\"/>\n");
// envelope
CoordinateReferenceSystem crs = reader.getCrs();
GeneralEnvelope envelope = reader.getOriginalEnvelope();
GeneralEnvelope wgs84envelope = CoverageStoreUtils.getWGS84LonLatEnvelope(envelope);
final String nativeCrsName = CRS.lookupIdentifier(crs, false);
writer.write("<envelope crs=\"" + crs.toString().replaceAll("\"", "'") + "\" srsName=\"" + nativeCrsName + "\">\n");
writer.write("<pos>" + wgs84envelope.getMinimum(0) + " " + wgs84envelope.getMinimum(1) + "</pos>\n");
writer.write("<pos>" + wgs84envelope.getMaximum(0) + " " + wgs84envelope.getMaximum(1) + "</pos>\n");
writer.write("</envelope>\n");
/**
* Now reading a fake small GridCoverage just to retrieve meta information:
* - calculating a new envelope which is 1/20 of the original one
* - reading the GridCoverage subset
*/
final ParameterValueGroup readParams = reader.getFormat().getReadParameters();
final Map parameters = CoverageUtils.getParametersKVP(readParams);
double[] minCP = envelope.getLowerCorner().getCoordinate();
double[] maxCP = new double[] {
minCP[0] + (envelope.getSpan(0) / 20.0),
minCP[1] + (envelope.getSpan(1) / 20.0)
};
final GeneralEnvelope subEnvelope = new GeneralEnvelope(minCP, maxCP);
subEnvelope.setCoordinateReferenceSystem(reader.getCrs());
parameters.put(AbstractGridFormat.READ_GRIDGEOMETRY2D.getName().toString(),
new GridGeometry2D(reader.getOriginalGridRange(), subEnvelope));
GridCoverage2D gc = (GridCoverage2D) reader.read(CoverageUtils.getParameters(readParams, parameters,
true));
// grid geometry
final GridGeometry geometry = gc.getGridGeometry();
final int dimensions = geometry.getGridRange().getDimension();
String lower = "";
String upper = "";
for(int i = 0; i < dimensions; i++) {
lower = lower + geometry.getGridRange().getLow(i) + " ";
upper = upper + geometry.getGridRange().getHigh(i) + " ";
}
writer.write("<grid dimension = \"" + dimensions + "\">\n");
writer.write("<low>" + lower + "</low>\n");
writer.write("<high>" + upper + "</high>\n");
final CoordinateSystem cs = crs.getCoordinateSystem();
for (int i=0; i < cs.getDimension(); i++) {
writer.write("<axisName>" + cs.getAxis(i).getName().getCode() + "</axisName>\n");
}
if(geometry.getGridToCRS() instanceof AffineTransform) {
AffineTransform aTX = (AffineTransform) geometry.getGridToCRS();
writer.write("<geoTransform>");
writer.write("<scaleX>" + aTX.getScaleX() + "</scaleX>\n");
writer.write("<scaleY>" + aTX.getScaleY() + "</scaleY>\n");
writer.write("<shearX>" + aTX.getShearX() + "</shearX>\n");
writer.write("<shearY>" + aTX.getShearY() + "</shearY>\n");
writer.write("<translateX>" + aTX.getTranslateX() + "</translateX>\n");
writer.write("<translateY>" + aTX.getTranslateY() + "</translateY>\n");
writer.write("</geoTransform>\n");
}
writer.write("</grid>\n");
// coverage dimensions
final GridSampleDimension[] sd = gc.getSampleDimensions();
for (int i = 0; i < sd.length; i++) {
writer.write("<CoverageDimension>\n");
writer.write("<name>" + sd[i].getDescription().toString() + "</name>\n");
writer.write("<interval>\n");
writer.write("<min>" + sd[i].getMinimumValue() + "</min>\n");
writer.write("<max>" + sd[i].getMaximumValue() + "</max>\n");
writer.write("</interval>\n");
final List<Category> categories = sd[i].getCategories();
if (categories != null && categories.size() >= 1) {
writer.write("<nullValues>\n");
for (Iterator<Category> it = sd[i].getCategories().iterator(); it
.hasNext();) {
Category cat = (Category) it.next();
if ((cat != null)
&& cat.getName().toString().equalsIgnoreCase(
"no data")) {
double min = cat.getRange().getMinimum();
double max = cat.getRange().getMaximum();
writer.write("<value>" + min + "</value>\n");
if (min != max)
writer.write("<value>" + max + "</value>\n");
}
}
writer.write("</nullValues>\n");
}
else
writer.write("<nullValues/>\n");
writer.write("</CoverageDimension>\n");
}
// supported crs
writer.write("<supportedCRSs>\n");
writer.write("<requestCRSs>" + nativeCrsName + "</requestCRSs>\n");
writer.write("<responseCRSs>" + nativeCrsName + "</responseCRSs>\n");
writer.write("</supportedCRSs>\n");
// supported formats
writer.write("<supportedFormats nativeFormat = \"" + format.getName() + "\">\n");
writer.write("<formats>ARCGRID,ARCGRID-GZIP,GEOTIFF,PNG,GIF,TIFF</formats>\n");
writer.write("</supportedFormats>\n");
// supported interpolations
writer.write("<supportedInterpolations default = \"nearest neighbor\">\n");
writer.write("<interpolationMethods>nearest neighbor</interpolationMethods>\n");
writer.write("</supportedInterpolations>\n");
// the end
writer.write("</coverage>\n");
writer.flush();
writer.close();
}
|
diff --git a/src/Main/Client.java b/src/Main/Client.java
index 143b977..a459bc4 100644
--- a/src/Main/Client.java
+++ b/src/Main/Client.java
@@ -1,416 +1,417 @@
package Main;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Socket;
import org.apache.shiro.session.Session;
/**
* Provides an extensible framework to do public and private calculations Can be
* extended to provide degrees within this black or white type casting
*
* @author Cole Christie
*
*/
public class Client {
private Logging mylog;
private Networking ServerNetwork;
private Networking DropOffNetwork;
private Auth subject;
private Crypto crypt;
private Session clientSession;
/**
* s CONSTRUCTOR
*/
public Client(Logging passedLog, Auth passedSubject, Session passedSession) {
mylog = passedLog;
subject = passedSubject;
clientSession = passedSession;
}
/**
* This displays the CLI menu and advertised commands
*/
private void DisplayMenu() {
System.out.println("======================================================================");
System.out.println("Commands are:");
System.out.println("QUIT - Closes connection with the server and quits");
System.out.println("REKEY - Rekeys encryption between the client and the server");
System.out.println("JOB - Requests a job from the server");
System.out.println("HELP - Displays this menu");
System.out.println("* - Anything else is sent to the server and echo'ed back");
System.out.println("======================================================================");
}
/**
* Handles the creation and main thread of client activity
*
* @param passedPort
* @param passedTarget
*/
public void StartClient(int SERVERpassedPort, String SERVERpassedTarget, int DROPOFFpassedPort,
String DROPOFFpassedTarget) {
// Connect to the server
// Start up client networking
ServerNetwork = new Networking(mylog, SERVERpassedPort, SERVERpassedTarget);
// Bring the created socket into this scope
Socket ServerSock = ServerNetwork.PassBackClient();
// Bind I/O to the socket
ServerNetwork.BringUp(ServerSock);
+ System.out.println("Connected to Server [" + SERVERpassedTarget + "] on port [" + SERVERpassedPort + "]");
// Connect to the drop off
// Start up client networking
- DropOffNetwork = new Networking(mylog, SERVERpassedPort, SERVERpassedTarget);
+ DropOffNetwork = new Networking(mylog, DROPOFFpassedPort, DROPOFFpassedTarget);
// Bring the created socket into this scope
Socket DropOffSock = DropOffNetwork.PassBackClient();
// Bind I/O to the socket
DropOffNetwork.BringUp(DropOffSock);
+ System.out.println("Connected to Drop Off [" + DROPOFFpassedTarget + "] on port [" + DROPOFFpassedPort + "]");
// Prepare the interface
String UserInput = null;
String ServerResponse = null;
// Load client identification data
String OS = (String) clientSession.getAttribute("OS");
String SecLev = (String) clientSession.getAttribute("SecurityLevel");
String ClientID = (String) clientSession.getAttribute("ID");
// Display the UI boilerplate
- DisplayMenu();
- System.out.println("Connected to server [" + SERVERpassedTarget + "] on port [" + SERVERpassedPort + "]");
+ DisplayMenu();
// Activate crypto
crypt = new Crypto(mylog, subject.GetPSK());
// Test bi-directional encryption is working
String rawTest = "Testing!!!12345";
byte[] testdata = crypt.encrypt(rawTest); // Craft test
// Test the SERVER
ServerNetwork.Send(testdata); // Send test
byte[] fetched = ServerNetwork.ReceiveByte(); // Receive return response
String dec = crypt.decrypt(fetched); // Decrypt
if (dec.equals(rawTest + "<S>")) {
mylog.out("INFO", "Functional bi-directional encryption established. (Server)");
} else {
mylog.out("ERROR", "Failed to establish a functional encrypted channel! (Server)");
mylog.out("ERROR", "Expected [" + rawTest + "<S>" + "] but recieved [" + dec + "] (Server)");
ServerNetwork.BringDown();
try {
ServerSock.close();
} catch (IOException e) {
mylog.out("ERROR", "Failed to close client socket (Server)");
}
System.exit(0);
}
// Test the DROPOFF
DropOffNetwork.Send(testdata); // Send test
fetched = DropOffNetwork.ReceiveByte(); // Receive return response
dec = crypt.decrypt(fetched); // Decrypt
if (dec.equals(rawTest + "<S>")) {
mylog.out("INFO", "Functional bi-directional encryption established. (Drop Off)");
} else {
mylog.out("ERROR", "Failed to establish a functional encrypted channel! (Drop Off)");
mylog.out("ERROR", "Expected [" + rawTest + "<S>" + "] but recieved [" + dec + "] (Drop Off)");
DropOffNetwork.BringDown();
try {
ServerSock.close();
} catch (IOException e) {
mylog.out("ERROR", "Failed to close client socket (Drop Off)");
}
System.exit(0);
}
// Use DH to change encryption key
DHrekey(ServerNetwork);
DHrekey(DropOffNetwork);
// First prompt
UserInput = readUI();
// Begin UI loop
int MaxBeforeREKEY = 100;
int Current = 0;
boolean serverUp = true;
boolean flagJob = false;
boolean noSend = false;
while ((UserInput != null) && (UserInput.compareToIgnoreCase("quit") != 0) && (ServerSock.isConnected())
&& (DropOffSock.isConnected())) {
if (!noSend) {
ServerNetwork.Send(crypt.encrypt(UserInput));
fetched = ServerNetwork.ReceiveByte();
ServerResponse = crypt.decrypt(fetched);
if (ServerResponse == null) {
mylog.out("WARN", "Server disconected");
serverUp = false;
break;
}
} else {
// We did not send anything to the server this time, but we will
// reset the boolean flag so we will next time
noSend = false;
}
// If this is the client receiving a job from the server
if (flagJob) {
if (ServerResponse.length() > 0) {
// Print out the job the server has passed us (the client)
System.out.println("JobIn:[" + ServerResponse + "]");
// Adjust the job so it can properly run (Windows clients
// require some padding at the front)
if (OS.contains("Windows")) {
// Pad the job with the required Windows shell
ServerResponse = "cmd /C " + ServerResponse;
}
try {
/*
* Some of the code in this section is from the
* following URL http://www.javaworld
* .com/jw-12-2000/jw-1229-traps.html?page=4
*
* It provides a simple way of calling external code
* while still capturing all of the output (STD and
* STDERR)
*
* @author Michael C. Daconta
*/
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec(ServerResponse);
// any error message?
StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "ERROR");
// any output?
StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), "OUTPUT");
// kick them off
errorGobbler.start();
outputGobbler.start();
// any error???
int exitVal = 0;
try {
exitVal = proc.waitFor();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("ExitValue: " + exitVal);
// TODO send completed work info to the drop off server
// Tell the SERVER that the work is done
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("JobOut:[" + ServerResponse + "]");
} else {
System.out.println("Job:[No jobs available]");
}
flagJob = false;
} else {
System.out.println(ServerResponse);
}
UserInput = readUI().toLowerCase();
// Check input for special commands
if ((UserInput.contains("rekey")) && serverUp) {
UserInput = "Rekey executed.";
DHrekey(ServerNetwork);
DHrekey(DropOffNetwork);
Current = 0;
} else if (UserInput.contains("job")) {
// TODO Initial job requests are missing the meta data?
flagJob = true; // Flags the use of a slightly different display
UserInput = UserInput + ":" + ClientID + ":" + OS + ":" + SecLev;
} else if (UserInput.contains("help")) {
noSend = true; // Do not send anything, the help request stays
// local
DisplayMenu();
}
// Check for forced rekey interval
if (Current == MaxBeforeREKEY) {
DHrekey(ServerNetwork);
DHrekey(DropOffNetwork);
Current = 0;
} else {
Current++;
}
}
if ((UserInput.compareToIgnoreCase("quit") == 0) && serverUp) {
ServerNetwork.Send(crypt.encrypt("quit"));
DropOffNetwork.Send(crypt.encrypt("quit"));
}
// Client has quit or server shutdown
ServerNetwork.BringDown();
DropOffNetwork.BringDown();
try {
ServerSock.close();
DropOffSock.close();
} catch (IOException e) {
mylog.out("ERROR", "Failed to close client socket");
}
}
/**
* Reads input provided by the user, returns a string
*
* @return
*/
private String readUI() {
System.out.flush();
System.out.print("> ");
System.out.flush();
String data = null;
BufferedReader inputHandle = new BufferedReader(new InputStreamReader(System.in));
boolean wait = true;
while (wait) {
try {
if (inputHandle.ready()) {
wait = false;
} else {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
mylog.out("ERROR", "Failed to sleep");
}
}
} catch (IOException err) {
mylog.out("ERROR", "Failed to check if buffered input was ready [" + err + "]");
}
}
try {
data = inputHandle.readLine();
} catch (IOException err) {
mylog.out("ERROR", "Failed to collect user input [" + err + "]");
}
return data;
}
/**
* Starts a DH rekey between the client and the server
*/
private void DHrekey(Networking network) {
// Prep
byte[] fetched = null;
String ServerResponse = null;
// Create a DH instance and generate a PRIME and BASE
DH myDH = new DH(mylog);
// Share data with the server
network.Send(crypt.encrypt("<REKEY>"));
RecieveACK(network); // Wait for ACK
network.Send(crypt.encrypt("<PRIME>"));
RecieveACK(network); // Wait for ACK
network.Send(crypt.encrypt(myDH.GetPrime(16)));
RecieveACK(network); // Wait for ACK
network.Send(crypt.encrypt("<BASE>"));
RecieveACK(network); // Wait for ACK
network.Send(crypt.encrypt(myDH.GetBase(16)));
RecieveACK(network); // Wait for ACK
// Validate server agrees with what has been sent
fetched = network.ReceiveByte();
SendACK(network); // Send ACK
ServerResponse = crypt.decrypt(fetched);
if (ServerResponse.compareToIgnoreCase("<REKEY-STARTING>") != 0) {
mylog.out("ERROR", "Server has failed to acknowledge re-keying!");
}
// Phase 1 of DH
myDH.DHPhase1();
// Send my public DH key to SERVER
network.Send(crypt.encrypt("<PUBLICKEY>"));
RecieveACK(network); // Wait for ACK
network.Send(crypt.encrypt(myDH.GetPublicKeyBF()));
RecieveACK(network); // Wait for ACK
// Validate server agrees with what has been sent
fetched = network.ReceiveByte();
SendACK(network); // Send ACK
ServerResponse = crypt.decrypt(fetched);
if (ServerResponse.compareToIgnoreCase("<PubKey-GOOD>") != 0) {
mylog.out("ERROR", "Server has failed to acknowledge client public key!");
}
// Receive server public DH key
byte[] serverPublicKey = null;
fetched = network.ReceiveByte();
SendACK(network); // Send ACK(); //Send ACK
ServerResponse = crypt.decrypt(fetched);
if (ServerResponse.compareToIgnoreCase("<PUBLICKEY>") != 0) {
mylog.out("ERROR", "Server has failed to send its public key!");
} else {
fetched = network.ReceiveByte();
SendACK(network); // Send ACK(); //Send ACK
serverPublicKey = crypt.decryptByte(fetched);
network.Send(crypt.encrypt("<PubKey-GOOD>"));
RecieveACK(network); // Wait for ACK
}
// Use server DH public key to generate shared secret
myDH.DHPhase2(myDH.CraftPublicKey(serverPublicKey));
// Final verification
// System.out.println("Shared Secret (Hex): " +
// myDH.GetSharedSecret(10));
crypt.ReKey(myDH.GetSharedSecret(10));
}
/**
* Provides message synchronization
*/
private void SendACK(Networking network) {
network.Send(crypt.encrypt("<ACK>"));
if (crypt.decrypt(network.ReceiveByteACK()).compareToIgnoreCase("<ACK>") != 0) {
mylog.out("ERROR", "Partner failed to ACK");
}
}
/**
* Provides message synchronization
*/
private void RecieveACK(Networking network) {
if (crypt.decrypt(network.ReceiveByteACK()).compareToIgnoreCase("<ACK>") != 0) {
mylog.out("ERROR", "Partner failed to ACK");
}
network.Send(crypt.encrypt("<ACK>"));
}
}
/**
* This code is from the following URL
* http://www.javaworld.com/jw-12-2000/jw-1229-traps.html?page=4
*
* It is useful in catching all of the output of an executed sub-process and has
* not been altered from its initial state
*
* @author Michael C. Daconta
*
*/
class StreamGobbler extends Thread {
InputStream is;
String type;
StreamGobbler(InputStream is, String type) {
this.is = is;
this.type = type;
}
public void run() {
try {
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line = null;
while ((line = br.readLine()) != null)
System.out.println(type + ">" + line);
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
| false | true | public void StartClient(int SERVERpassedPort, String SERVERpassedTarget, int DROPOFFpassedPort,
String DROPOFFpassedTarget) {
// Connect to the server
// Start up client networking
ServerNetwork = new Networking(mylog, SERVERpassedPort, SERVERpassedTarget);
// Bring the created socket into this scope
Socket ServerSock = ServerNetwork.PassBackClient();
// Bind I/O to the socket
ServerNetwork.BringUp(ServerSock);
// Connect to the drop off
// Start up client networking
DropOffNetwork = new Networking(mylog, SERVERpassedPort, SERVERpassedTarget);
// Bring the created socket into this scope
Socket DropOffSock = DropOffNetwork.PassBackClient();
// Bind I/O to the socket
DropOffNetwork.BringUp(DropOffSock);
// Prepare the interface
String UserInput = null;
String ServerResponse = null;
// Load client identification data
String OS = (String) clientSession.getAttribute("OS");
String SecLev = (String) clientSession.getAttribute("SecurityLevel");
String ClientID = (String) clientSession.getAttribute("ID");
// Display the UI boilerplate
DisplayMenu();
System.out.println("Connected to server [" + SERVERpassedTarget + "] on port [" + SERVERpassedPort + "]");
// Activate crypto
crypt = new Crypto(mylog, subject.GetPSK());
// Test bi-directional encryption is working
String rawTest = "Testing!!!12345";
byte[] testdata = crypt.encrypt(rawTest); // Craft test
// Test the SERVER
ServerNetwork.Send(testdata); // Send test
byte[] fetched = ServerNetwork.ReceiveByte(); // Receive return response
String dec = crypt.decrypt(fetched); // Decrypt
if (dec.equals(rawTest + "<S>")) {
mylog.out("INFO", "Functional bi-directional encryption established. (Server)");
} else {
mylog.out("ERROR", "Failed to establish a functional encrypted channel! (Server)");
mylog.out("ERROR", "Expected [" + rawTest + "<S>" + "] but recieved [" + dec + "] (Server)");
ServerNetwork.BringDown();
try {
ServerSock.close();
} catch (IOException e) {
mylog.out("ERROR", "Failed to close client socket (Server)");
}
System.exit(0);
}
// Test the DROPOFF
DropOffNetwork.Send(testdata); // Send test
fetched = DropOffNetwork.ReceiveByte(); // Receive return response
dec = crypt.decrypt(fetched); // Decrypt
if (dec.equals(rawTest + "<S>")) {
mylog.out("INFO", "Functional bi-directional encryption established. (Drop Off)");
} else {
mylog.out("ERROR", "Failed to establish a functional encrypted channel! (Drop Off)");
mylog.out("ERROR", "Expected [" + rawTest + "<S>" + "] but recieved [" + dec + "] (Drop Off)");
DropOffNetwork.BringDown();
try {
ServerSock.close();
} catch (IOException e) {
mylog.out("ERROR", "Failed to close client socket (Drop Off)");
}
System.exit(0);
}
// Use DH to change encryption key
DHrekey(ServerNetwork);
DHrekey(DropOffNetwork);
// First prompt
UserInput = readUI();
// Begin UI loop
int MaxBeforeREKEY = 100;
int Current = 0;
boolean serverUp = true;
boolean flagJob = false;
boolean noSend = false;
while ((UserInput != null) && (UserInput.compareToIgnoreCase("quit") != 0) && (ServerSock.isConnected())
&& (DropOffSock.isConnected())) {
if (!noSend) {
ServerNetwork.Send(crypt.encrypt(UserInput));
fetched = ServerNetwork.ReceiveByte();
ServerResponse = crypt.decrypt(fetched);
if (ServerResponse == null) {
mylog.out("WARN", "Server disconected");
serverUp = false;
break;
}
} else {
// We did not send anything to the server this time, but we will
// reset the boolean flag so we will next time
noSend = false;
}
// If this is the client receiving a job from the server
if (flagJob) {
if (ServerResponse.length() > 0) {
// Print out the job the server has passed us (the client)
System.out.println("JobIn:[" + ServerResponse + "]");
// Adjust the job so it can properly run (Windows clients
// require some padding at the front)
if (OS.contains("Windows")) {
// Pad the job with the required Windows shell
ServerResponse = "cmd /C " + ServerResponse;
}
try {
/*
* Some of the code in this section is from the
* following URL http://www.javaworld
* .com/jw-12-2000/jw-1229-traps.html?page=4
*
* It provides a simple way of calling external code
* while still capturing all of the output (STD and
* STDERR)
*
* @author Michael C. Daconta
*/
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec(ServerResponse);
// any error message?
StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "ERROR");
// any output?
StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), "OUTPUT");
// kick them off
errorGobbler.start();
outputGobbler.start();
// any error???
int exitVal = 0;
try {
exitVal = proc.waitFor();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("ExitValue: " + exitVal);
// TODO send completed work info to the drop off server
// Tell the SERVER that the work is done
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("JobOut:[" + ServerResponse + "]");
} else {
System.out.println("Job:[No jobs available]");
}
flagJob = false;
} else {
System.out.println(ServerResponse);
}
UserInput = readUI().toLowerCase();
// Check input for special commands
if ((UserInput.contains("rekey")) && serverUp) {
UserInput = "Rekey executed.";
DHrekey(ServerNetwork);
DHrekey(DropOffNetwork);
Current = 0;
} else if (UserInput.contains("job")) {
// TODO Initial job requests are missing the meta data?
flagJob = true; // Flags the use of a slightly different display
UserInput = UserInput + ":" + ClientID + ":" + OS + ":" + SecLev;
} else if (UserInput.contains("help")) {
noSend = true; // Do not send anything, the help request stays
// local
DisplayMenu();
}
// Check for forced rekey interval
if (Current == MaxBeforeREKEY) {
DHrekey(ServerNetwork);
DHrekey(DropOffNetwork);
Current = 0;
} else {
Current++;
}
}
if ((UserInput.compareToIgnoreCase("quit") == 0) && serverUp) {
ServerNetwork.Send(crypt.encrypt("quit"));
DropOffNetwork.Send(crypt.encrypt("quit"));
}
// Client has quit or server shutdown
ServerNetwork.BringDown();
DropOffNetwork.BringDown();
try {
ServerSock.close();
DropOffSock.close();
} catch (IOException e) {
mylog.out("ERROR", "Failed to close client socket");
}
}
| public void StartClient(int SERVERpassedPort, String SERVERpassedTarget, int DROPOFFpassedPort,
String DROPOFFpassedTarget) {
// Connect to the server
// Start up client networking
ServerNetwork = new Networking(mylog, SERVERpassedPort, SERVERpassedTarget);
// Bring the created socket into this scope
Socket ServerSock = ServerNetwork.PassBackClient();
// Bind I/O to the socket
ServerNetwork.BringUp(ServerSock);
System.out.println("Connected to Server [" + SERVERpassedTarget + "] on port [" + SERVERpassedPort + "]");
// Connect to the drop off
// Start up client networking
DropOffNetwork = new Networking(mylog, DROPOFFpassedPort, DROPOFFpassedTarget);
// Bring the created socket into this scope
Socket DropOffSock = DropOffNetwork.PassBackClient();
// Bind I/O to the socket
DropOffNetwork.BringUp(DropOffSock);
System.out.println("Connected to Drop Off [" + DROPOFFpassedTarget + "] on port [" + DROPOFFpassedPort + "]");
// Prepare the interface
String UserInput = null;
String ServerResponse = null;
// Load client identification data
String OS = (String) clientSession.getAttribute("OS");
String SecLev = (String) clientSession.getAttribute("SecurityLevel");
String ClientID = (String) clientSession.getAttribute("ID");
// Display the UI boilerplate
DisplayMenu();
// Activate crypto
crypt = new Crypto(mylog, subject.GetPSK());
// Test bi-directional encryption is working
String rawTest = "Testing!!!12345";
byte[] testdata = crypt.encrypt(rawTest); // Craft test
// Test the SERVER
ServerNetwork.Send(testdata); // Send test
byte[] fetched = ServerNetwork.ReceiveByte(); // Receive return response
String dec = crypt.decrypt(fetched); // Decrypt
if (dec.equals(rawTest + "<S>")) {
mylog.out("INFO", "Functional bi-directional encryption established. (Server)");
} else {
mylog.out("ERROR", "Failed to establish a functional encrypted channel! (Server)");
mylog.out("ERROR", "Expected [" + rawTest + "<S>" + "] but recieved [" + dec + "] (Server)");
ServerNetwork.BringDown();
try {
ServerSock.close();
} catch (IOException e) {
mylog.out("ERROR", "Failed to close client socket (Server)");
}
System.exit(0);
}
// Test the DROPOFF
DropOffNetwork.Send(testdata); // Send test
fetched = DropOffNetwork.ReceiveByte(); // Receive return response
dec = crypt.decrypt(fetched); // Decrypt
if (dec.equals(rawTest + "<S>")) {
mylog.out("INFO", "Functional bi-directional encryption established. (Drop Off)");
} else {
mylog.out("ERROR", "Failed to establish a functional encrypted channel! (Drop Off)");
mylog.out("ERROR", "Expected [" + rawTest + "<S>" + "] but recieved [" + dec + "] (Drop Off)");
DropOffNetwork.BringDown();
try {
ServerSock.close();
} catch (IOException e) {
mylog.out("ERROR", "Failed to close client socket (Drop Off)");
}
System.exit(0);
}
// Use DH to change encryption key
DHrekey(ServerNetwork);
DHrekey(DropOffNetwork);
// First prompt
UserInput = readUI();
// Begin UI loop
int MaxBeforeREKEY = 100;
int Current = 0;
boolean serverUp = true;
boolean flagJob = false;
boolean noSend = false;
while ((UserInput != null) && (UserInput.compareToIgnoreCase("quit") != 0) && (ServerSock.isConnected())
&& (DropOffSock.isConnected())) {
if (!noSend) {
ServerNetwork.Send(crypt.encrypt(UserInput));
fetched = ServerNetwork.ReceiveByte();
ServerResponse = crypt.decrypt(fetched);
if (ServerResponse == null) {
mylog.out("WARN", "Server disconected");
serverUp = false;
break;
}
} else {
// We did not send anything to the server this time, but we will
// reset the boolean flag so we will next time
noSend = false;
}
// If this is the client receiving a job from the server
if (flagJob) {
if (ServerResponse.length() > 0) {
// Print out the job the server has passed us (the client)
System.out.println("JobIn:[" + ServerResponse + "]");
// Adjust the job so it can properly run (Windows clients
// require some padding at the front)
if (OS.contains("Windows")) {
// Pad the job with the required Windows shell
ServerResponse = "cmd /C " + ServerResponse;
}
try {
/*
* Some of the code in this section is from the
* following URL http://www.javaworld
* .com/jw-12-2000/jw-1229-traps.html?page=4
*
* It provides a simple way of calling external code
* while still capturing all of the output (STD and
* STDERR)
*
* @author Michael C. Daconta
*/
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec(ServerResponse);
// any error message?
StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "ERROR");
// any output?
StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), "OUTPUT");
// kick them off
errorGobbler.start();
outputGobbler.start();
// any error???
int exitVal = 0;
try {
exitVal = proc.waitFor();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("ExitValue: " + exitVal);
// TODO send completed work info to the drop off server
// Tell the SERVER that the work is done
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("JobOut:[" + ServerResponse + "]");
} else {
System.out.println("Job:[No jobs available]");
}
flagJob = false;
} else {
System.out.println(ServerResponse);
}
UserInput = readUI().toLowerCase();
// Check input for special commands
if ((UserInput.contains("rekey")) && serverUp) {
UserInput = "Rekey executed.";
DHrekey(ServerNetwork);
DHrekey(DropOffNetwork);
Current = 0;
} else if (UserInput.contains("job")) {
// TODO Initial job requests are missing the meta data?
flagJob = true; // Flags the use of a slightly different display
UserInput = UserInput + ":" + ClientID + ":" + OS + ":" + SecLev;
} else if (UserInput.contains("help")) {
noSend = true; // Do not send anything, the help request stays
// local
DisplayMenu();
}
// Check for forced rekey interval
if (Current == MaxBeforeREKEY) {
DHrekey(ServerNetwork);
DHrekey(DropOffNetwork);
Current = 0;
} else {
Current++;
}
}
if ((UserInput.compareToIgnoreCase("quit") == 0) && serverUp) {
ServerNetwork.Send(crypt.encrypt("quit"));
DropOffNetwork.Send(crypt.encrypt("quit"));
}
// Client has quit or server shutdown
ServerNetwork.BringDown();
DropOffNetwork.BringDown();
try {
ServerSock.close();
DropOffSock.close();
} catch (IOException e) {
mylog.out("ERROR", "Failed to close client socket");
}
}
|
diff --git a/src/husacct/control/presentation/taskbar/TaskBar.java b/src/husacct/control/presentation/taskbar/TaskBar.java
index 7fcec042..ae36f945 100644
--- a/src/husacct/control/presentation/taskbar/TaskBar.java
+++ b/src/husacct/control/presentation/taskbar/TaskBar.java
@@ -1,151 +1,152 @@
package husacct.control.presentation.taskbar;
import husacct.ServiceProvider;
import husacct.common.locale.ILocaleService;
import husacct.common.services.IServiceListener;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.beans.PropertyVetoException;
import javax.swing.DesktopManager;
import javax.swing.JInternalFrame;
import javax.swing.JPanel;
import javax.swing.JToggleButton;
import javax.swing.event.InternalFrameEvent;
import org.apache.log4j.Logger;
public class TaskBar extends JPanel{
private static final long serialVersionUID = 1L;
private Logger logger = Logger.getLogger(TaskBar.class);
public TaskBar(){
setup();
}
private void setup(){
setLayout(new FlowLayout(FlowLayout.LEFT));
}
public void registerInternalFrame(final JInternalFrame internalFrame){
final JToggleButton toggleButton = new JToggleButton(internalFrame.getTitle());
toggleButton.setIcon(internalFrame.getFrameIcon());
internalFrame.addInternalFrameListener(new InternalFrameAdapter() {
@Override
public void internalFrameActivated(InternalFrameEvent e) {
activateFrame(internalFrame, toggleButton);
}
@Override
public void internalFrameDeactivated(InternalFrameEvent e) {
deactivateFrame(internalFrame, toggleButton);
}
@Override
public void internalFrameClosed(InternalFrameEvent e) {
remove(toggleButton);
validate();
repaint();
}
@Override
public void internalFrameOpened(InternalFrameEvent e) {
activateFrame(internalFrame, toggleButton);
}
@Override
public void internalFrameIconified(InternalFrameEvent e){
deactivateFrame(internalFrame, toggleButton);
internalFrame.setVisible(false);
+ iconifyFrame(internalFrame, toggleButton);
}
@Override
public void internalFrameDeiconified(InternalFrameEvent e){
activateFrame(internalFrame, toggleButton);
internalFrame.setVisible(true);
deiconifyFrame(internalFrame, toggleButton);
}
});
internalFrame.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
activateFrame(internalFrame, toggleButton);
}
});
toggleButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
activateFrame(internalFrame, toggleButton);
}
});
toggleButton.addMouseListener(new ContextClickListener(internalFrame));
ILocaleService localeService = ServiceProvider.getInstance().getLocaleService();
localeService.addServiceListener(new IServiceListener() {
@Override
public void update() {
toggleButton.setText(internalFrame.getTitle());
}
});
activateFrame(internalFrame, toggleButton);
add(toggleButton);
}
private void activateFrame(JInternalFrame internalFrame, JToggleButton button){
DesktopManager manager = internalFrame.getDesktopPane().getDesktopManager();
manager.activateFrame(internalFrame);
try {
internalFrame.setSelected(true);
} catch (PropertyVetoException event) {
logger.debug(event.getMessage());
}
button.setSelected(true);
try {
internalFrame.setIcon(false);
} catch (PropertyVetoException event) {
logger.debug(event.getMessage());
}
}
private void deactivateFrame(JInternalFrame internalFrame, JToggleButton button){
DesktopManager manager = internalFrame.getDesktopPane().getDesktopManager();
manager.deactivateFrame(internalFrame);
try {
internalFrame.setSelected(false);
} catch (PropertyVetoException event) {
logger.debug(event.getMessage());
}
button.setSelected(false);
}
private void iconifyFrame(JInternalFrame internalFrame, JToggleButton button){
DesktopManager manager = internalFrame.getDesktopPane().getDesktopManager();
manager.iconifyFrame(internalFrame);
try {
internalFrame.setIcon(true);
} catch (PropertyVetoException event) {
logger.debug(event.getMessage());
}
}
private void deiconifyFrame(JInternalFrame internalFrame, JToggleButton button){
DesktopManager manager = internalFrame.getDesktopPane().getDesktopManager();
manager.deiconifyFrame(internalFrame);
try {
internalFrame.setIcon(false);
} catch (PropertyVetoException event) {
logger.debug(event.getMessage());
}
}
}
| true | true | public void registerInternalFrame(final JInternalFrame internalFrame){
final JToggleButton toggleButton = new JToggleButton(internalFrame.getTitle());
toggleButton.setIcon(internalFrame.getFrameIcon());
internalFrame.addInternalFrameListener(new InternalFrameAdapter() {
@Override
public void internalFrameActivated(InternalFrameEvent e) {
activateFrame(internalFrame, toggleButton);
}
@Override
public void internalFrameDeactivated(InternalFrameEvent e) {
deactivateFrame(internalFrame, toggleButton);
}
@Override
public void internalFrameClosed(InternalFrameEvent e) {
remove(toggleButton);
validate();
repaint();
}
@Override
public void internalFrameOpened(InternalFrameEvent e) {
activateFrame(internalFrame, toggleButton);
}
@Override
public void internalFrameIconified(InternalFrameEvent e){
deactivateFrame(internalFrame, toggleButton);
internalFrame.setVisible(false);
}
@Override
public void internalFrameDeiconified(InternalFrameEvent e){
activateFrame(internalFrame, toggleButton);
internalFrame.setVisible(true);
deiconifyFrame(internalFrame, toggleButton);
}
});
internalFrame.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
activateFrame(internalFrame, toggleButton);
}
});
toggleButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
activateFrame(internalFrame, toggleButton);
}
});
toggleButton.addMouseListener(new ContextClickListener(internalFrame));
ILocaleService localeService = ServiceProvider.getInstance().getLocaleService();
localeService.addServiceListener(new IServiceListener() {
@Override
public void update() {
toggleButton.setText(internalFrame.getTitle());
}
});
activateFrame(internalFrame, toggleButton);
add(toggleButton);
}
| public void registerInternalFrame(final JInternalFrame internalFrame){
final JToggleButton toggleButton = new JToggleButton(internalFrame.getTitle());
toggleButton.setIcon(internalFrame.getFrameIcon());
internalFrame.addInternalFrameListener(new InternalFrameAdapter() {
@Override
public void internalFrameActivated(InternalFrameEvent e) {
activateFrame(internalFrame, toggleButton);
}
@Override
public void internalFrameDeactivated(InternalFrameEvent e) {
deactivateFrame(internalFrame, toggleButton);
}
@Override
public void internalFrameClosed(InternalFrameEvent e) {
remove(toggleButton);
validate();
repaint();
}
@Override
public void internalFrameOpened(InternalFrameEvent e) {
activateFrame(internalFrame, toggleButton);
}
@Override
public void internalFrameIconified(InternalFrameEvent e){
deactivateFrame(internalFrame, toggleButton);
internalFrame.setVisible(false);
iconifyFrame(internalFrame, toggleButton);
}
@Override
public void internalFrameDeiconified(InternalFrameEvent e){
activateFrame(internalFrame, toggleButton);
internalFrame.setVisible(true);
deiconifyFrame(internalFrame, toggleButton);
}
});
internalFrame.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
activateFrame(internalFrame, toggleButton);
}
});
toggleButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
activateFrame(internalFrame, toggleButton);
}
});
toggleButton.addMouseListener(new ContextClickListener(internalFrame));
ILocaleService localeService = ServiceProvider.getInstance().getLocaleService();
localeService.addServiceListener(new IServiceListener() {
@Override
public void update() {
toggleButton.setText(internalFrame.getTitle());
}
});
activateFrame(internalFrame, toggleButton);
add(toggleButton);
}
|
diff --git a/src/nl/sense_os/commonsense/common/client/communication/SessionManager.java b/src/nl/sense_os/commonsense/common/client/communication/SessionManager.java
index cc26e3dd..9054ebe9 100755
--- a/src/nl/sense_os/commonsense/common/client/communication/SessionManager.java
+++ b/src/nl/sense_os/commonsense/common/client/communication/SessionManager.java
@@ -1,66 +1,69 @@
package nl.sense_os.commonsense.common.client.communication;
import java.util.Date;
import nl.sense_os.commonsense.common.client.util.Constants;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Cookies;
import com.google.gwt.user.client.Window.Location;
public class SessionManager {
private static final String KEY = "session_id";
/**
* Tries to get a session ID from either the URL parameters or from the domain cookies.
*
* @return The session ID or null
*/
public static String getSessionId() {
// check session ID cookie
String sessionId = Cookies.getCookie(KEY);
- if ("".equals(sessionId) || null == sessionId) {
+ if (null == sessionId || "".equals(sessionId)) {
- // check session ID parameter in the URL
+ // sometimes the session ID parameter can be found in the URL
sessionId = Location.getParameter("session_id");
- if ("".equals(sessionId)) {
- sessionId = null;
+ // store the session ID in the cookie if we found it in the URL
+ if (null != sessionId && !"".equals(sessionId)) {
+ setSessionId(sessionId);
+ } else {
+ sessionId = null;
}
}
return sessionId;
}
/**
* Removes the session ID from the sense-os.nl cookie
*/
public static void removeSessionId() {
if (GWT.isProdMode() && Location.getHostName().contains("sense-os.nl")) {
String domain = Constants.DEV_MODE ? "dev.sense-os.nl" : ".sense-os.nl";
Cookies.setCookie(KEY, "", new Date(), domain, null, false);
}
Cookies.removeCookie(KEY);
}
/**
* Stores the session ID in the sense-os.nl cookie
*
* @param sessionId
*/
public static void setSessionId(String sessionId) {
if (GWT.isProdMode() && Location.getHostName().contains("sense-os.nl")) {
String domain = Constants.DEV_MODE ? "dev.sense-os.nl" : ".sense-os.nl";
Cookies.setCookie(KEY, sessionId, null, domain, "", false);
} else {
Cookies.setCookie(KEY, sessionId);
}
}
private SessionManager() {
// private constructor to prevent instantiation
}
}
| false | true | public static String getSessionId() {
// check session ID cookie
String sessionId = Cookies.getCookie(KEY);
if ("".equals(sessionId) || null == sessionId) {
// check session ID parameter in the URL
sessionId = Location.getParameter("session_id");
if ("".equals(sessionId)) {
sessionId = null;
}
}
return sessionId;
}
| public static String getSessionId() {
// check session ID cookie
String sessionId = Cookies.getCookie(KEY);
if (null == sessionId || "".equals(sessionId)) {
// sometimes the session ID parameter can be found in the URL
sessionId = Location.getParameter("session_id");
// store the session ID in the cookie if we found it in the URL
if (null != sessionId && !"".equals(sessionId)) {
setSessionId(sessionId);
} else {
sessionId = null;
}
}
return sessionId;
}
|
diff --git a/autograph/Graph.java b/autograph/Graph.java
index bba42c3..41f3b65 100644
--- a/autograph/Graph.java
+++ b/autograph/Graph.java
@@ -1,365 +1,364 @@
package autograph;
import java.util.ArrayList;
import java.util.Random;
import java.io.Serializable;
import autograph.Edge.PairPosition;
import autograph.exception.*;
import autograph.undo.*;
import javax.swing.event.UndoableEditEvent;
import javax.swing.event.UndoableEditListener;
import javax.swing.undo.AbstractUndoableEdit;
import javax.swing.undo.CannotRedoException;
import javax.swing.undo.CannotUndoException;
import javax.swing.undo.UndoManager;
/**
* Graph contains the data and functionality for building graph objects to be represented by Autograph
*
* @author Keith Wentzel
* @version 1.0
*/
public class Graph implements Serializable {
private ArrayList<Node> vNodeList;
private ArrayList<Edge> vEdgeList;
private String vTitle;
public SelectedItems vSelectedItems;
public UndoManager vUndoManager;
public enum DeleteAction{
BOTH,
NODES,
EDGES
};
/**
* ValidateGraph - ensures valid data is passed to the graph constructor
*
* @param title - title of the graph
*/
private void mValidateGraph(String title) throws CannotCreateGraphException{
if(title == null){
throw new CannotCreateGraphException("The graph must have a title.");
}
}
public Graph(String title){
try{
mValidateGraph(title);
vUndoManager = new UndoManager();
vNodeList = new ArrayList<Node>();
vEdgeList = new ArrayList<Edge>();
vSelectedItems = new SelectedItems();
if(title.isEmpty()){
vTitle = "New Graph";
}
else{
vTitle = title;
}
}
catch(CannotCreateGraphException e){
//TODO: This may need changed to an error file, etc
System.out.println("Error while trying to create graph: " + e.getError());
}
}
/**
* GetNodeList - gets a list of nodes for the graph
*
* @return - node list for the graph
* @see Node
*/
public ArrayList<Node> mGetNodeList(){
return vNodeList;
}
/**
* GetEdgeList - gets an edge list for the graph
*
* @return a list of edges for the graph
* @see Edge
*/
public ArrayList<Edge> mGetEdgeList(){
return vEdgeList;
}
/**
* Returns title of Graph
*
* @return The title of the graph
*/
public String mGetTitle(){
return vTitle;
}
/**
* Sets title of Graph
*
* @param title - the new title of the graph
*/
public void mSetTitle(String title){
if (title !=null && !title.isEmpty()) {
vTitle = title;
}
}
/**
* GetNodeById - returns the node with the selected Id
*
* @param id - id of the node
* @return a node with the selected id, or null if the node is not found
* @see Node
*/
public Node mGetNodeById(String id){
//initialize to null. It will be up to the caller to make sure the value is not
//null when it is returned.
Node node = null;
try{
for(int i = 0; i < vNodeList.size(); i++){
if(vNodeList.get(i).mGetId().equals(id)){
node = vNodeList.get(i);
}
}
}
catch(Exception e){
//This will theoretically only happen if vNodeList.get(i) is null.
//TODO: This may need changed to an error file, etc
System.out.println("Error while trying to find node: " + e.getMessage());
}
return node;
}
/**
* DeleteNodeById - removes a node with the selected id from the node list for the graph
*
* @param id - id of the Node
* @see Node
*/
public void mDeleteNodeById(String id) throws CannotRemoveNodeException {
try{
for(int i = 0; i < vNodeList.size(); i++){
if(vNodeList.get(i).mGetId().equals(id)){
//remove will remove the node and shift left, so it will not create
//a null entry in the list.
vNodeList.remove(i);
}
}
}
catch(Exception e){
//this will theoretically only happen if vNodeList.get(i) is null
//TODO: This may need changed to an error file, etc
System.out.println("Error while trying to find node for deletion: " + e.getMessage());
throw new CannotRemoveNodeException("Could not find node for deletion!", e);
}
}
/**
* GetEdgeById - returns an edge with the selected id in the graph
*
* @param id - id of the Edge
* @return an edge with the selected id, or null if the node is not found
* @see Edge
*/
public Edge mGetEdgeById(String id){
Edge edge = null;
try{
for(int i = 0; i < vEdgeList.size(); i++){
if(vEdgeList.get(i).mGetId().equals(id)){
edge = vEdgeList.get(i);
}
}
}
catch(Exception e){
//This will theoretically only happen if vNodeList.get(i) is null.
//TODO: This may need changed to an error file, etc
System.out.println("Error while trying to find edge: " + e.getMessage());
}
return edge;
}
/**
* DeleteEdgeById - removes the edge with the selected id from the graph
*
* @param id of the edge
* @see Edge
*/
public void mDeleteEdgeById(String id) throws CannotRemoveEdgeException {
try{
for(int i = 0; i < vEdgeList.size(); i++){
if(vEdgeList.get(i).mGetId().equals(id)){
//remove will remove the node and shift left, so it will not create
//a null entry in the list.
vEdgeList.remove(i);
}
}
}
catch(Exception e){
//this will theoretically only happen if vNodeList.get(i) is null
//TODO: This may need changed to an error file, etc
System.out.println("Error while trying to find edge for deletion: " + e.getMessage());
throw new CannotRemoveEdgeException("Could not find edge for deletion!", e);
}
}
/**
* AddEdge - adds an edge to the edge list for the graph
*
* @param edge - edge to be added to the edge list
* @see Edge
*
*/
public void mAddEdge(Edge edge) throws CannotAddEdgeException {
try {
vEdgeList.add(edge);
vUndoManager.addEdit( new AddEdgeEdit(edge, this.vEdgeList) );
}
catch (Exception e) {
throw new CannotAddEdgeException("Error while adding edge!", e);
}
}
/**
* AddNode - adds a node to the node list
*
* @param node
* @throws CannotAddNodeException
* @see Node
*
*/
public void mAddNode(Node node) throws CannotAddNodeException {
try {
vNodeList.add(node);
vUndoManager.addEdit( new AddNodeEdit(node, this.vNodeList) );
}
catch (Exception e) {
throw new CannotAddNodeException("Error while adding node!", e);
}
}
/**
* Checks the edge list for a twin to edge and resets the twin variables if a twin
* is found.
* @param edge
* @return
*/
public PairPosition mCheckForEdgeTwin(Edge edge){
PairPosition position = PairPosition.UNPAIRED;
for(int i = 0; i < vEdgeList.size(); i++){
if(vEdgeList.get(i) != edge){
if(vEdgeList.get(i).mGetEndNode() == edge.mGetEndNode() && vEdgeList.get(i).mGetStartNode() == edge.mGetStartNode()){
position = PairPosition.SECOND;
vEdgeList.get(i).mSetPairPosition(PairPosition.FIRST);
vEdgeList.get(i).mSetTwin(edge);
edge.mSetTwin(vEdgeList.get(i));
break;
}
else if(vEdgeList.get(i).mGetEndNode() == edge.mGetStartNode() && vEdgeList.get(i).mGetStartNode() == edge.mGetEndNode()){
position = PairPosition.SECOND;
vEdgeList.get(i).mSetPairPosition(PairPosition.FIRST);
vEdgeList.get(i).mSetTwin(edge);
edge.mSetTwin(edge);
break;
}
}
}
return position;
}
/**
* Check if edgetToCheck already has two twins (we don't want three edges between the same nodes.)
* @param startNode - the startNode for that edge
* @param endNode - the end node for that edge.
* @return - true if it has multiple twins, false otherwise.
*/
public boolean mEdgeHasMultipleTwins(Node startNode, Node endNode) {
Boolean hasMultipleTwins = false;
for(int i = 0; i < vEdgeList.size(); i++){
//Keep the edgeToCheck variable in case edgeToCheck has been added to vEdgeList at this point.
if(vEdgeList.get(i).mGetEndNode() == endNode && vEdgeList.get(i).mGetStartNode() == startNode){
if(vEdgeList.get(i).mGetPairPosition()!= PairPosition.UNPAIRED){
hasMultipleTwins = true;
break;
}
}
if(vEdgeList.get(i).mGetEndNode() == startNode && vEdgeList.get(i).mGetStartNode() == endNode){
if(vEdgeList.get(i).mGetPairPosition() != PairPosition.UNPAIRED){
hasMultipleTwins = true;
break;
}
}
}
return hasMultipleTwins;
}
public void mDeleteSelectedItems(DeleteAction deleteAction) {
ArrayList<Edge> undoableEdges = new ArrayList<Edge>();
ArrayList<Node> undoableNodes = new ArrayList<Node>();
switch(deleteAction) {
case BOTH:
undoableEdges = mDeleteSelectedEdges();
undoableNodes = mDeleteSelectedNodes(undoableEdges);
break;
case NODES:
undoableNodes = mDeleteSelectedNodes(undoableEdges);
break;
case EDGES:
undoableEdges = mDeleteSelectedEdges();
break;
}
vUndoManager.addEdit(new DeleteNodeEdgeEdit(undoableNodes, this.vNodeList,
undoableEdges, this.vEdgeList));
}
private ArrayList<Edge> mDeleteSelectedEdges() {
ArrayList<Edge> sEdges = this.vSelectedItems.mGetSelectedEdges();
ArrayList<Edge> undoableEdges = new ArrayList<Edge>();
for(int i = 0; i < sEdges.size(); i++) {
Edge e = sEdges.get(i);
Edge eTwin = e.mGetTwin();
if(eTwin != null) {
eTwin.mSetTwin(null);
}
undoableEdges.add(e);
this.vEdgeList.remove(this.vEdgeList.indexOf(e));
sEdges.remove(i);
i--;
}
return undoableEdges;
}
private ArrayList<Node> mDeleteSelectedNodes(ArrayList<Edge> undoableEdges) {
ArrayList<Node> sNodes = this.vSelectedItems.mGetSelectedNodes();
ArrayList<Edge> sEdges = this.vSelectedItems.mGetSelectedEdges();
ArrayList<Node> undoableNodes = new ArrayList<Node>();
- vUndoManager.addEdit(new DeleteNodeEdit(sNodes, this.vNodeList));
for(int i = 0; i < sNodes.size(); i++) {
Node n = sNodes.get(i);
for (int j = 0; j < vEdgeList.size(); j++) {
Edge e = this.vEdgeList.get(j);
if ( (e.mGetStartNode() == n) || (e.mGetEndNode() == n) ) {
undoableEdges.add(e);
this.vEdgeList.remove(j);
j--;
int eIndex = sEdges.indexOf(e);
if (eIndex >= 0)
{
sEdges.remove(eIndex);
}
}
}
//System.out.println("Removed Node: " + this.vNodeList.indexOf(n));
undoableNodes.add(n);
this.vNodeList.remove(this.vNodeList.indexOf(n));
sNodes.remove(i);
i--;
}
return undoableNodes;
}
}
| true | true | private ArrayList<Node> mDeleteSelectedNodes(ArrayList<Edge> undoableEdges) {
ArrayList<Node> sNodes = this.vSelectedItems.mGetSelectedNodes();
ArrayList<Edge> sEdges = this.vSelectedItems.mGetSelectedEdges();
ArrayList<Node> undoableNodes = new ArrayList<Node>();
vUndoManager.addEdit(new DeleteNodeEdit(sNodes, this.vNodeList));
for(int i = 0; i < sNodes.size(); i++) {
Node n = sNodes.get(i);
for (int j = 0; j < vEdgeList.size(); j++) {
Edge e = this.vEdgeList.get(j);
if ( (e.mGetStartNode() == n) || (e.mGetEndNode() == n) ) {
undoableEdges.add(e);
this.vEdgeList.remove(j);
j--;
int eIndex = sEdges.indexOf(e);
if (eIndex >= 0)
{
sEdges.remove(eIndex);
}
}
}
//System.out.println("Removed Node: " + this.vNodeList.indexOf(n));
undoableNodes.add(n);
this.vNodeList.remove(this.vNodeList.indexOf(n));
sNodes.remove(i);
i--;
}
return undoableNodes;
}
| private ArrayList<Node> mDeleteSelectedNodes(ArrayList<Edge> undoableEdges) {
ArrayList<Node> sNodes = this.vSelectedItems.mGetSelectedNodes();
ArrayList<Edge> sEdges = this.vSelectedItems.mGetSelectedEdges();
ArrayList<Node> undoableNodes = new ArrayList<Node>();
for(int i = 0; i < sNodes.size(); i++) {
Node n = sNodes.get(i);
for (int j = 0; j < vEdgeList.size(); j++) {
Edge e = this.vEdgeList.get(j);
if ( (e.mGetStartNode() == n) || (e.mGetEndNode() == n) ) {
undoableEdges.add(e);
this.vEdgeList.remove(j);
j--;
int eIndex = sEdges.indexOf(e);
if (eIndex >= 0)
{
sEdges.remove(eIndex);
}
}
}
//System.out.println("Removed Node: " + this.vNodeList.indexOf(n));
undoableNodes.add(n);
this.vNodeList.remove(this.vNodeList.indexOf(n));
sNodes.remove(i);
i--;
}
return undoableNodes;
}
|
diff --git a/java/org/directwebremoting/faces/FacesExtensionFilter.java b/java/org/directwebremoting/faces/FacesExtensionFilter.java
index 1a58bf58..67897012 100644
--- a/java/org/directwebremoting/faces/FacesExtensionFilter.java
+++ b/java/org/directwebremoting/faces/FacesExtensionFilter.java
@@ -1,102 +1,97 @@
/*
* Copyright 2005 Joe Walker
*
* 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.directwebremoting.faces;
import java.io.IOException;
import javax.faces.FactoryFinder;
import javax.faces.context.FacesContext;
import javax.faces.context.FacesContextFactory;
import javax.faces.lifecycle.Lifecycle;
import javax.faces.lifecycle.LifecycleFactory;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
/**
* Filter integration for DWR framework. This filter was inspired by this
* article: http://www.thoughtsabout.net/blog/archives/000033.html
* @author Pierpaolo Follia (Latest revision: $Author: esa50833 $)
* @author Joe Walker [joe at getahead dot ltd dot uk]
* @noinspection AbstractClassNeverImplemented
*/
public class FacesExtensionFilter implements Filter
{
/* (non-Javadoc)
* @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
*/
public void init(FilterConfig config) throws ServletException
{
servletContext = config.getServletContext();
}
/* (non-Javadoc)
* @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
*/
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException
{
- // Create the faces context
- FacesContext facesContext = FacesContext.getCurrentInstance();
- if (facesContext == null)
- {
- FacesContextFactory contextFactory = (FacesContextFactory) FactoryFinder.getFactory(FactoryFinder.FACES_CONTEXT_FACTORY);
- LifecycleFactory lifecycleFactory = (LifecycleFactory) FactoryFinder.getFactory(FactoryFinder.LIFECYCLE_FACTORY);
- Lifecycle lifecycle = lifecycleFactory.getLifecycle(LifecycleFactory.DEFAULT_LIFECYCLE);
+ FacesContextFactory contextFactory = (FacesContextFactory) FactoryFinder.getFactory(FactoryFinder.FACES_CONTEXT_FACTORY);
+ LifecycleFactory lifecycleFactory = (LifecycleFactory) FactoryFinder.getFactory(FactoryFinder.LIFECYCLE_FACTORY);
+ Lifecycle lifecycle = lifecycleFactory.getLifecycle(LifecycleFactory.DEFAULT_LIFECYCLE);
- // Either set a private member
- // servletContext = filterConfig.getServletContext();
- // in your filter init() method or set it here like this:
- // ServletContext servletContext =
- // ((HttpServletRequest) request).getSession().getServletContext();
- // Note that the above line would fail if you are using any other
- // protocol than http
+ // Either set a private member
+ // servletContext = filterConfig.getServletContext();
+ // in your filter init() method or set it here like this:
+ // ServletContext servletContext =
+ // ((HttpServletRequest) request).getSession().getServletContext();
+ // Note that the above line would fail if you are using any other
+ // protocol than http
- // Doesn't set this instance as the current instance of
- // FacesContext.getCurrentInstance
- facesContext = contextFactory.getFacesContext(servletContext, request, response, lifecycle);
+ // Doesn't set this instance as the current instance of
+ // FacesContext.getCurrentInstance
+ FacesContext facesContext = contextFactory.getFacesContext(servletContext, request, response, lifecycle);
- // Set using our inner class
- InnerFacesContext.setFacesContextAsCurrentInstance(facesContext);
- }
+ // Set using our inner class
+ InnerFacesContext.setFacesContextAsCurrentInstance(facesContext);
// call the filter chain
chain.doFilter(request, response);
}
/* (non-Javadoc)
* @see javax.servlet.Filter#destroy()
*/
public void destroy()
{
}
// You need an inner class to be able to call
// FacesContext.setCurrentInstance
// since it's a protected method
private abstract static class InnerFacesContext extends FacesContext
{
protected static void setFacesContextAsCurrentInstance(FacesContext facesContext)
{
FacesContext.setCurrentInstance(facesContext);
}
}
private ServletContext servletContext = null;
}
| false | true | public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException
{
// Create the faces context
FacesContext facesContext = FacesContext.getCurrentInstance();
if (facesContext == null)
{
FacesContextFactory contextFactory = (FacesContextFactory) FactoryFinder.getFactory(FactoryFinder.FACES_CONTEXT_FACTORY);
LifecycleFactory lifecycleFactory = (LifecycleFactory) FactoryFinder.getFactory(FactoryFinder.LIFECYCLE_FACTORY);
Lifecycle lifecycle = lifecycleFactory.getLifecycle(LifecycleFactory.DEFAULT_LIFECYCLE);
// Either set a private member
// servletContext = filterConfig.getServletContext();
// in your filter init() method or set it here like this:
// ServletContext servletContext =
// ((HttpServletRequest) request).getSession().getServletContext();
// Note that the above line would fail if you are using any other
// protocol than http
// Doesn't set this instance as the current instance of
// FacesContext.getCurrentInstance
facesContext = contextFactory.getFacesContext(servletContext, request, response, lifecycle);
// Set using our inner class
InnerFacesContext.setFacesContextAsCurrentInstance(facesContext);
}
// call the filter chain
chain.doFilter(request, response);
}
| public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException
{
FacesContextFactory contextFactory = (FacesContextFactory) FactoryFinder.getFactory(FactoryFinder.FACES_CONTEXT_FACTORY);
LifecycleFactory lifecycleFactory = (LifecycleFactory) FactoryFinder.getFactory(FactoryFinder.LIFECYCLE_FACTORY);
Lifecycle lifecycle = lifecycleFactory.getLifecycle(LifecycleFactory.DEFAULT_LIFECYCLE);
// Either set a private member
// servletContext = filterConfig.getServletContext();
// in your filter init() method or set it here like this:
// ServletContext servletContext =
// ((HttpServletRequest) request).getSession().getServletContext();
// Note that the above line would fail if you are using any other
// protocol than http
// Doesn't set this instance as the current instance of
// FacesContext.getCurrentInstance
FacesContext facesContext = contextFactory.getFacesContext(servletContext, request, response, lifecycle);
// Set using our inner class
InnerFacesContext.setFacesContextAsCurrentInstance(facesContext);
// call the filter chain
chain.doFilter(request, response);
}
|
diff --git a/src/republicaEternityEventIII/republica/devteam/EternityCommandExecutor.java b/src/republicaEternityEventIII/republica/devteam/EternityCommandExecutor.java
index d6bb826..0063626 100644
--- a/src/republicaEternityEventIII/republica/devteam/EternityCommandExecutor.java
+++ b/src/republicaEternityEventIII/republica/devteam/EternityCommandExecutor.java
@@ -1,135 +1,135 @@
package republicaEternityEventIII.republica.devteam;
import java.util.Random;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class EternityCommandExecutor implements CommandExecutor{
private String puppetmaster;
private Ziminiar ziminiar;
private EternityMain em;
private CommandSender lastCS;
private static EternityCommandExecutor INSTANCE = null;
public EternityCommandExecutor(EternityMain em) {
super();
if (INSTANCE != null) {
throw new RuntimeException("Instantiated multiple EternityCommandExecutors");
}
this.em = em;
INSTANCE = this;
}
public static void sendMessageToLastSender(String message) {
INSTANCE.lastCS.sendMessage(message);
}
@Override
public boolean onCommand(CommandSender cs, Command c, String l, String[] args) {
lastCS = cs;
if(c.getLabel().equalsIgnoreCase("Ziminiar")){
if(cs.isOp()){
if (args.length == 1) {
puppetmaster = args[0];
//Code to change player into Ziminiar here
ziminiar = new Ziminiar(getPlayerByNameOf(puppetmaster), em);
setZiminiarInMain(ziminiar);
return true;
}
}
}
if(c.getLabel().equalsIgnoreCase("nerf")){
if(cs.isOp()){
if (args.length == 1) {
String status = args[0];
Ziminiar.cooldownEnabled = Boolean.parseBoolean(status);
return true;
}
}
}
if (c.getLabel().equalsIgnoreCase("setResultsSign")) {
if (cs.isOp()) {
SignPunchingOMatic.change();
cs.sendMessage("Punch a sign to set it.");
}
}
if (c.getLabel().equalsIgnoreCase("TestSFX")) {
if (cs.isOp()) {
SoundEffectsManager.playSpawnSound(((Player) cs).getLocation());
return true;
}
}
if (c.getLabel().equalsIgnoreCase("AddTestData")) {
if (cs.isOp()) {
MagicalStorage.incrementPlayerScore(cs.getName(), 1337);
MagicalStorage.incrementPlayerScore("AnotherPlayer", 19);
MagicalStorage.incrementPlayerScore("OneMorePlayer", 21);
return true;
}
}
if (c.getLabel().equalsIgnoreCase("getBook")) {
if (cs.isOp()) {
EternityItems.loadResults();
((Player) cs).getInventory().addItem(EternityItems.getResultsBook());
return true;
}
}
if (c.getLabel().equalsIgnoreCase("saveResults")) {
if (cs.isOp()) {
EternityItems.saveResults();
return true;
}
}
if(c.getLabel().equalsIgnoreCase("Caesar")){
if(cs.isOp()){
cs.sendMessage("Books begin to fall!");
- Random rand = new Random(4);
- int temp = rand.nextInt();
+ Random rand = new Random();
+ int temp = rand.nextInt(4);
Player[] players = em.getServer().getOnlinePlayers();
for(int i = 0; i < temp && i < players.length; i++){
int temp2 = rand.nextInt();
Player player = players[temp2];
cs.sendMessage("A book was sent to "+ player.getDisplayName() + ".");
player.sendMessage(ChatColor.GREEN + "A book falls from the sky.");
Location l1 = player.getLocation();
l1.add(2, 5, 0);
player.getWorld().dropItemNaturally(l1, EternityItems.caesarBook());
}
return true;
}
}
return false;
}
private Player getPlayerByNameOf(String s){
return em.getPlayer(s);
}
private void setZiminiarInMain(Ziminiar zz){
passZiminiarToMain(zz);
em.ZiminiarPlayer(getPlayerByNameOf(puppetmaster));
}
private void passZiminiarToMain(Ziminiar zz){
em.ziminiarClass(zz);
}
}
| true | true | public boolean onCommand(CommandSender cs, Command c, String l, String[] args) {
lastCS = cs;
if(c.getLabel().equalsIgnoreCase("Ziminiar")){
if(cs.isOp()){
if (args.length == 1) {
puppetmaster = args[0];
//Code to change player into Ziminiar here
ziminiar = new Ziminiar(getPlayerByNameOf(puppetmaster), em);
setZiminiarInMain(ziminiar);
return true;
}
}
}
if(c.getLabel().equalsIgnoreCase("nerf")){
if(cs.isOp()){
if (args.length == 1) {
String status = args[0];
Ziminiar.cooldownEnabled = Boolean.parseBoolean(status);
return true;
}
}
}
if (c.getLabel().equalsIgnoreCase("setResultsSign")) {
if (cs.isOp()) {
SignPunchingOMatic.change();
cs.sendMessage("Punch a sign to set it.");
}
}
if (c.getLabel().equalsIgnoreCase("TestSFX")) {
if (cs.isOp()) {
SoundEffectsManager.playSpawnSound(((Player) cs).getLocation());
return true;
}
}
if (c.getLabel().equalsIgnoreCase("AddTestData")) {
if (cs.isOp()) {
MagicalStorage.incrementPlayerScore(cs.getName(), 1337);
MagicalStorage.incrementPlayerScore("AnotherPlayer", 19);
MagicalStorage.incrementPlayerScore("OneMorePlayer", 21);
return true;
}
}
if (c.getLabel().equalsIgnoreCase("getBook")) {
if (cs.isOp()) {
EternityItems.loadResults();
((Player) cs).getInventory().addItem(EternityItems.getResultsBook());
return true;
}
}
if (c.getLabel().equalsIgnoreCase("saveResults")) {
if (cs.isOp()) {
EternityItems.saveResults();
return true;
}
}
if(c.getLabel().equalsIgnoreCase("Caesar")){
if(cs.isOp()){
cs.sendMessage("Books begin to fall!");
Random rand = new Random(4);
int temp = rand.nextInt();
Player[] players = em.getServer().getOnlinePlayers();
for(int i = 0; i < temp && i < players.length; i++){
int temp2 = rand.nextInt();
Player player = players[temp2];
cs.sendMessage("A book was sent to "+ player.getDisplayName() + ".");
player.sendMessage(ChatColor.GREEN + "A book falls from the sky.");
Location l1 = player.getLocation();
l1.add(2, 5, 0);
player.getWorld().dropItemNaturally(l1, EternityItems.caesarBook());
}
return true;
}
}
return false;
}
| public boolean onCommand(CommandSender cs, Command c, String l, String[] args) {
lastCS = cs;
if(c.getLabel().equalsIgnoreCase("Ziminiar")){
if(cs.isOp()){
if (args.length == 1) {
puppetmaster = args[0];
//Code to change player into Ziminiar here
ziminiar = new Ziminiar(getPlayerByNameOf(puppetmaster), em);
setZiminiarInMain(ziminiar);
return true;
}
}
}
if(c.getLabel().equalsIgnoreCase("nerf")){
if(cs.isOp()){
if (args.length == 1) {
String status = args[0];
Ziminiar.cooldownEnabled = Boolean.parseBoolean(status);
return true;
}
}
}
if (c.getLabel().equalsIgnoreCase("setResultsSign")) {
if (cs.isOp()) {
SignPunchingOMatic.change();
cs.sendMessage("Punch a sign to set it.");
}
}
if (c.getLabel().equalsIgnoreCase("TestSFX")) {
if (cs.isOp()) {
SoundEffectsManager.playSpawnSound(((Player) cs).getLocation());
return true;
}
}
if (c.getLabel().equalsIgnoreCase("AddTestData")) {
if (cs.isOp()) {
MagicalStorage.incrementPlayerScore(cs.getName(), 1337);
MagicalStorage.incrementPlayerScore("AnotherPlayer", 19);
MagicalStorage.incrementPlayerScore("OneMorePlayer", 21);
return true;
}
}
if (c.getLabel().equalsIgnoreCase("getBook")) {
if (cs.isOp()) {
EternityItems.loadResults();
((Player) cs).getInventory().addItem(EternityItems.getResultsBook());
return true;
}
}
if (c.getLabel().equalsIgnoreCase("saveResults")) {
if (cs.isOp()) {
EternityItems.saveResults();
return true;
}
}
if(c.getLabel().equalsIgnoreCase("Caesar")){
if(cs.isOp()){
cs.sendMessage("Books begin to fall!");
Random rand = new Random();
int temp = rand.nextInt(4);
Player[] players = em.getServer().getOnlinePlayers();
for(int i = 0; i < temp && i < players.length; i++){
int temp2 = rand.nextInt();
Player player = players[temp2];
cs.sendMessage("A book was sent to "+ player.getDisplayName() + ".");
player.sendMessage(ChatColor.GREEN + "A book falls from the sky.");
Location l1 = player.getLocation();
l1.add(2, 5, 0);
player.getWorld().dropItemNaturally(l1, EternityItems.caesarBook());
}
return true;
}
}
return false;
}
|
diff --git a/sql12/app/src/net/sourceforge/squirrel_sql/client/gui/db/BaseListInternalFrame.java b/sql12/app/src/net/sourceforge/squirrel_sql/client/gui/db/BaseListInternalFrame.java
index 521756b07..c88cceed1 100644
--- a/sql12/app/src/net/sourceforge/squirrel_sql/client/gui/db/BaseListInternalFrame.java
+++ b/sql12/app/src/net/sourceforge/squirrel_sql/client/gui/db/BaseListInternalFrame.java
@@ -1,275 +1,274 @@
package net.sourceforge.squirrel_sql.client.gui.db;
/*
* Copyright (C) 2001-2004 Colin Bell
* [email protected]
*
* 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
*/
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.event.InternalFrameAdapter;
import javax.swing.event.InternalFrameEvent;
import javax.swing.event.ListDataEvent;
import javax.swing.event.ListDataListener;
import net.sourceforge.squirrel_sql.fw.gui.BasePopupMenu;
import net.sourceforge.squirrel_sql.fw.gui.GUIUtils;
import net.sourceforge.squirrel_sql.fw.gui.ToolBar;
import net.sourceforge.squirrel_sql.fw.util.BaseException;
import net.sourceforge.squirrel_sql.fw.util.ICommand;
import net.sourceforge.squirrel_sql.fw.util.StringManager;
import net.sourceforge.squirrel_sql.fw.util.StringManagerFactory;
import net.sourceforge.squirrel_sql.fw.util.log.ILogger;
import net.sourceforge.squirrel_sql.fw.util.log.LoggerController;
import net.sourceforge.squirrel_sql.client.gui.BaseInternalFrame;
abstract class BaseListInternalFrame extends BaseInternalFrame
{
protected interface IUserInterfaceFactory
{
ToolBar getToolBar();
BasePopupMenu getPopupMenu();
JList getList();
String getWindowTitle();
ICommand getDoubleClickCommand();
void enableDisableActions();
}
/** Logger for this class. */
private static ILogger s_log =
LoggerController.createLogger(BaseListInternalFrame.class);
private IUserInterfaceFactory _uiFactory;
/** Popup menu for the list. */
private BasePopupMenu _popupMenu;
/** Toolbar for window. */
private ToolBar _toolBar;
private boolean _hasBeenBuilt;
private boolean _hasBeenSized = false;
/** Internationalized strings for this class. */
private static final StringManager s_stringMgr =
StringManagerFactory.getStringManager(BaseListInternalFrame.class);
public BaseListInternalFrame(IUserInterfaceFactory uiFactory)
{
super("", true, true);
if (uiFactory == null)
{
throw new IllegalArgumentException("Null IUserInterfaceFactory passed");
}
_uiFactory = uiFactory;
createUserInterface();
}
public void updateUI()
{
super.updateUI();
if (_hasBeenBuilt)
{
_hasBeenSized = false;
privateResize();
}
}
protected IUserInterfaceFactory getUserInterfaceFactory()
{
return _uiFactory;
}
protected void setToolBar(ToolBar tb)
{
final Container content = getContentPane();
if (_toolBar != null)
{
content.remove(_toolBar);
}
if (tb != null)
{
content.add(tb, BorderLayout.NORTH);
}
_toolBar = tb;
}
/**
* Process a mouse press event in this list. If this event is a trigger
* for a popup menu then display the popup menu.
*
* @param evt The mouse event being processed.
*/
private void mousePress(MouseEvent evt)
{
if (evt.isPopupTrigger())
{
if (_popupMenu == null)
{
_popupMenu = _uiFactory.getPopupMenu();
}
_popupMenu.show(evt);
}
}
private void privateResize()
{
if (!_hasBeenSized)
{
if (_toolBar != null)
{
_hasBeenSized = true;
Dimension windowSize = getSize();
int rqdWidth = _toolBar.getPreferredSize().width + 15;
if (rqdWidth > windowSize.width)
{
windowSize.width = rqdWidth;
setSize(windowSize);
}
}
}
}
private void createUserInterface()
{
// This is a tool window.
GUIUtils.makeToolWindow(this, true);
setDefaultCloseOperation(HIDE_ON_CLOSE);
// Pane to add window content to.
final Container content = getContentPane();
content.setLayout(new BorderLayout());
String winTitle = _uiFactory.getWindowTitle();
if (winTitle != null)
{
setTitle(winTitle);
}
// Put toolbar at top of window.
setToolBar(_uiFactory.getToolBar());
// The main list for window.
final JList list = _uiFactory.getList();
// Allow list to scroll.
final JScrollPane sp = new JScrollPane();
sp.setViewportView(list);
sp.setPreferredSize(new Dimension(100, 100));
// List in the centre of the window.
content.add(sp, BorderLayout.CENTER);
// Add mouse listener for displaying popup menu.
list.addMouseListener(new MouseAdapter()
{
public void mousePressed(MouseEvent evt)
{
mousePress(evt);
}
public void mouseReleased(MouseEvent evt)
{
mousePress(evt);
}
});
// Add a listener to handle doubleclick events in the list.
list.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent evt)
{
if (evt.getClickCount() == 2)
{
ICommand cmd = _uiFactory.getDoubleClickCommand();
if (cmd != null)
{
try
{
cmd.execute();
}
catch (BaseException ex)
{
// i18n[BaseListInternalFrame.error.execdoubleclick=Error occured executing doubleclick event]
s_log.error(s_stringMgr.getString("BaseListInternalFrame.error.execdoubleclick"), ex);
}
}
}
}
});
// Add listener to listen for items added/removed from list.
list.getModel().addListDataListener(new ListDataListener()
{
public void intervalAdded(ListDataEvent evt)
{
list.setSelectedIndex(evt.getIndex0()); // select the one just added.
_uiFactory.enableDisableActions();
}
public void intervalRemoved(ListDataEvent evt)
{
int nextIdx = evt.getIndex0();
int lastIdx = list.getModel().getSize() - 1;
if (nextIdx > lastIdx)
{
nextIdx = lastIdx;
}
list.setSelectedIndex(nextIdx);
_uiFactory.enableDisableActions();
}
public void contentsChanged(ListDataEvent evt)
{
// Unused.
}
});
- // When this window is activated give focus to the list box.
// When window opened ensure it is wide enough to display the toolbar.
// There is a bug in JDK1.2 where internalFrameOpened() doesn't get
// called so we've used a workaround. The workaround doesn't work in
// JDK1.3.
addInternalFrameListener(new InternalFrameAdapter()
{
- private boolean _hasBeenActivated = false;
- public void internalFrameActivated(InternalFrameEvent evt)
- {
- if (!_hasBeenActivated)
- {
- _hasBeenActivated = true;
- privateResize();
- }
- list.requestFocus();
- }
+ //private boolean _hasBeenActivated = false;
+ //public void internalFrameActivated(InternalFrameEvent evt)
+ //{
+ //if (!_hasBeenActivated)
+ //{
+ //// _hasBeenActivated = true;
+ // privateResize();
+ //}
+ //list.requestFocus();
+ //}
public void internalFrameOpened(InternalFrameEvent evt)
{
privateResize();
}
});
validate();
}
}
| false | true | private void createUserInterface()
{
// This is a tool window.
GUIUtils.makeToolWindow(this, true);
setDefaultCloseOperation(HIDE_ON_CLOSE);
// Pane to add window content to.
final Container content = getContentPane();
content.setLayout(new BorderLayout());
String winTitle = _uiFactory.getWindowTitle();
if (winTitle != null)
{
setTitle(winTitle);
}
// Put toolbar at top of window.
setToolBar(_uiFactory.getToolBar());
// The main list for window.
final JList list = _uiFactory.getList();
// Allow list to scroll.
final JScrollPane sp = new JScrollPane();
sp.setViewportView(list);
sp.setPreferredSize(new Dimension(100, 100));
// List in the centre of the window.
content.add(sp, BorderLayout.CENTER);
// Add mouse listener for displaying popup menu.
list.addMouseListener(new MouseAdapter()
{
public void mousePressed(MouseEvent evt)
{
mousePress(evt);
}
public void mouseReleased(MouseEvent evt)
{
mousePress(evt);
}
});
// Add a listener to handle doubleclick events in the list.
list.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent evt)
{
if (evt.getClickCount() == 2)
{
ICommand cmd = _uiFactory.getDoubleClickCommand();
if (cmd != null)
{
try
{
cmd.execute();
}
catch (BaseException ex)
{
// i18n[BaseListInternalFrame.error.execdoubleclick=Error occured executing doubleclick event]
s_log.error(s_stringMgr.getString("BaseListInternalFrame.error.execdoubleclick"), ex);
}
}
}
}
});
// Add listener to listen for items added/removed from list.
list.getModel().addListDataListener(new ListDataListener()
{
public void intervalAdded(ListDataEvent evt)
{
list.setSelectedIndex(evt.getIndex0()); // select the one just added.
_uiFactory.enableDisableActions();
}
public void intervalRemoved(ListDataEvent evt)
{
int nextIdx = evt.getIndex0();
int lastIdx = list.getModel().getSize() - 1;
if (nextIdx > lastIdx)
{
nextIdx = lastIdx;
}
list.setSelectedIndex(nextIdx);
_uiFactory.enableDisableActions();
}
public void contentsChanged(ListDataEvent evt)
{
// Unused.
}
});
// When this window is activated give focus to the list box.
// When window opened ensure it is wide enough to display the toolbar.
// There is a bug in JDK1.2 where internalFrameOpened() doesn't get
// called so we've used a workaround. The workaround doesn't work in
// JDK1.3.
addInternalFrameListener(new InternalFrameAdapter()
{
private boolean _hasBeenActivated = false;
public void internalFrameActivated(InternalFrameEvent evt)
{
if (!_hasBeenActivated)
{
_hasBeenActivated = true;
privateResize();
}
list.requestFocus();
}
public void internalFrameOpened(InternalFrameEvent evt)
{
privateResize();
}
});
validate();
}
| private void createUserInterface()
{
// This is a tool window.
GUIUtils.makeToolWindow(this, true);
setDefaultCloseOperation(HIDE_ON_CLOSE);
// Pane to add window content to.
final Container content = getContentPane();
content.setLayout(new BorderLayout());
String winTitle = _uiFactory.getWindowTitle();
if (winTitle != null)
{
setTitle(winTitle);
}
// Put toolbar at top of window.
setToolBar(_uiFactory.getToolBar());
// The main list for window.
final JList list = _uiFactory.getList();
// Allow list to scroll.
final JScrollPane sp = new JScrollPane();
sp.setViewportView(list);
sp.setPreferredSize(new Dimension(100, 100));
// List in the centre of the window.
content.add(sp, BorderLayout.CENTER);
// Add mouse listener for displaying popup menu.
list.addMouseListener(new MouseAdapter()
{
public void mousePressed(MouseEvent evt)
{
mousePress(evt);
}
public void mouseReleased(MouseEvent evt)
{
mousePress(evt);
}
});
// Add a listener to handle doubleclick events in the list.
list.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent evt)
{
if (evt.getClickCount() == 2)
{
ICommand cmd = _uiFactory.getDoubleClickCommand();
if (cmd != null)
{
try
{
cmd.execute();
}
catch (BaseException ex)
{
// i18n[BaseListInternalFrame.error.execdoubleclick=Error occured executing doubleclick event]
s_log.error(s_stringMgr.getString("BaseListInternalFrame.error.execdoubleclick"), ex);
}
}
}
}
});
// Add listener to listen for items added/removed from list.
list.getModel().addListDataListener(new ListDataListener()
{
public void intervalAdded(ListDataEvent evt)
{
list.setSelectedIndex(evt.getIndex0()); // select the one just added.
_uiFactory.enableDisableActions();
}
public void intervalRemoved(ListDataEvent evt)
{
int nextIdx = evt.getIndex0();
int lastIdx = list.getModel().getSize() - 1;
if (nextIdx > lastIdx)
{
nextIdx = lastIdx;
}
list.setSelectedIndex(nextIdx);
_uiFactory.enableDisableActions();
}
public void contentsChanged(ListDataEvent evt)
{
// Unused.
}
});
// When window opened ensure it is wide enough to display the toolbar.
// There is a bug in JDK1.2 where internalFrameOpened() doesn't get
// called so we've used a workaround. The workaround doesn't work in
// JDK1.3.
addInternalFrameListener(new InternalFrameAdapter()
{
//private boolean _hasBeenActivated = false;
//public void internalFrameActivated(InternalFrameEvent evt)
//{
//if (!_hasBeenActivated)
//{
//// _hasBeenActivated = true;
// privateResize();
//}
//list.requestFocus();
//}
public void internalFrameOpened(InternalFrameEvent evt)
{
privateResize();
}
});
validate();
}
|
diff --git a/freeplane/src/org/freeplane/view/swing/map/NodeView.java b/freeplane/src/org/freeplane/view/swing/map/NodeView.java
index 74eecd0dc..cf9c5462e 100644
--- a/freeplane/src/org/freeplane/view/swing/map/NodeView.java
+++ b/freeplane/src/org/freeplane/view/swing/map/NodeView.java
@@ -1,1461 +1,1464 @@
/*
* Freeplane - mind map editor
* Copyright (C) 2008 Joerg Mueller, Daniel Polansky, Christian Foltin, Dimitry Polivaev
*
* This file is modified by Dimitry Polivaev in 2008.
*
* 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, see <http://www.gnu.org/licenses/>.
*/
package org.freeplane.view.swing.map;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.Stroke;
import java.awt.dnd.DnDConstants;
import java.awt.dnd.DragGestureListener;
import java.awt.dnd.DragSource;
import java.awt.dnd.DropTarget;
import java.awt.dnd.DropTargetListener;
import java.util.LinkedList;
import java.util.ListIterator;
import javax.swing.JComponent;
import javax.swing.SwingUtilities;
import javax.swing.tree.TreeNode;
import org.freeplane.core.resources.ResourceController;
import org.freeplane.core.ui.IUserInputListenerFactory;
import org.freeplane.core.ui.components.UITools;
import org.freeplane.features.attribute.AttributeController;
import org.freeplane.features.attribute.NodeAttributeTableModel;
import org.freeplane.features.cloud.CloudController;
import org.freeplane.features.cloud.CloudModel;
import org.freeplane.features.edge.EdgeController;
import org.freeplane.features.edge.EdgeStyle;
import org.freeplane.features.filter.FilterController;
import org.freeplane.features.icon.HierarchicalIcons;
import org.freeplane.features.map.HideChildSubtree;
import org.freeplane.features.map.HistoryInformationModel;
import org.freeplane.features.map.INodeView;
import org.freeplane.features.map.MapChangeEvent;
import org.freeplane.features.map.NodeChangeEvent;
import org.freeplane.features.map.NodeModel;
import org.freeplane.features.map.FreeNode;
import org.freeplane.features.map.SummaryNode;
import org.freeplane.features.map.NodeModel.NodeChangeType;
import org.freeplane.features.mode.Controller;
import org.freeplane.features.mode.ModeController;
import org.freeplane.features.nodelocation.LocationModel;
import org.freeplane.features.nodestyle.NodeStyleController;
import org.freeplane.features.nodestyle.NodeStyleModel;
import org.freeplane.features.styles.MapViewLayout;
import org.freeplane.features.text.ShortenedTextModel;
import org.freeplane.features.text.TextController;
import org.freeplane.view.swing.map.attribute.AttributeView;
import org.freeplane.view.swing.map.cloud.CloudView;
import org.freeplane.view.swing.map.cloud.CloudViewFactory;
import org.freeplane.view.swing.map.edge.EdgeView;
import org.freeplane.view.swing.map.edge.EdgeViewFactory;
/**
* This class represents a single Node of a MindMap (in analogy to
* TreeCellRenderer).
*/
public class NodeView extends JComponent implements INodeView {
final static int ALIGN_BOTTOM = -1;
final static int ALIGN_CENTER = 0;
final static int ALIGN_TOP = 1;
protected final static Color dragColor = Color.lightGray;
public final static int DRAGGED_OVER_NO = 0;
public final static int DRAGGED_OVER_SIBLING = 2;
public final static int DRAGGED_OVER_SON = 1;
/** For RootNodeView. */
public final static int DRAGGED_OVER_SON_LEFT = 3;
static private int FOLDING_SYMBOL_WIDTH = -1;
private static final long serialVersionUID = 1L;
public final static int SHIFT = -2;
static final int SPACE_AROUND = 50;
public static final int MAIN_VIEWER_POSITION = 1;
public static final int NOTE_VIEWER_POSITION = 10;
final static boolean PAINT_DEBUG_BORDER;
static{
boolean paintDebugBorder = false;
try{
paintDebugBorder = System.getProperty("org.freeplane.view.swing.map.NodeView.PAINT_DEBUG_BORDER", "false").equalsIgnoreCase("true");
}
catch(Exception e){
}
PAINT_DEBUG_BORDER = paintDebugBorder;
};
static private int maxToolTipWidth;
private AttributeView attributeView;
private JComponent contentPane;
private MainView mainView;
private final MapView map;
private NodeModel model;
private NodeView preferredChild;
private EdgeStyle edgeStyle = EdgeStyle.EDGESTYLE_HIDDEN;
private Integer edgeWidth = 1;
private Color edgeColor = Color.BLACK;
private Color modelBackgroundColor;
private int topOverlap;
private int bottomOverlap;
public static final int DETAIL_VIEWER_POSITION = 2;
protected NodeView(final NodeModel model, final MapView map, final Container parent) {
setFocusCycleRoot(true);
this.model = model;
this.map = map;
}
void addDragListener(final DragGestureListener dgl) {
if (dgl == null) {
return;
}
final DragSource dragSource = DragSource.getDefaultDragSource();
dragSource.createDefaultDragGestureRecognizer(getMainView(), DnDConstants.ACTION_COPY
| DnDConstants.ACTION_MOVE | DnDConstants.ACTION_LINK, dgl);
}
void addDropListener(final DropTargetListener dtl) {
if (dtl == null) {
return;
}
final DropTarget dropTarget = new DropTarget(getMainView(), dtl);
dropTarget.setActive(true);
}
private int calcShiftY(final LocationModel locationModel) {
try {
final NodeModel parent = model.getParentNode();
return locationModel.getShiftY() + (getMap().getModeController().hasOneVisibleChild(parent) ? SHIFT : 0);
}
catch (final NullPointerException e) {
return 0;
}
}
public static int ADDITIONAL_MOUSE_SENSITIVE_AREA = 50;
@Override
public boolean contains(final int x, final int y) {
final int space = getMap().getZoomed(NodeView.SPACE_AROUND);
final int reducedSpace = space - ADDITIONAL_MOUSE_SENSITIVE_AREA;
if (x >= reducedSpace && x < getWidth() - reducedSpace && y >= reducedSpace && y < getHeight() - reducedSpace){
for(int i = getComponentCount()-1; i >= 0; i--){
final Component comp = getComponent(i);
if(comp.isVisible() && comp.contains(x-comp.getX(), y-comp.getY()))
return true;
}
}
return false;
}
protected void convertPointToMap(final Point p) {
UITools.convertPointToAncestor(this, p, getMap());
}
public void createAttributeView() {
if (attributeView == null && NodeAttributeTableModel.getModel(model).getNode() != null) {
attributeView = new AttributeView(this, true);
}
syncronizeAttributeView();
}
public boolean focused() {
return mainView.hasFocus();
}
/**
*/
public AttributeView getAttributeView() {
if (attributeView == null) {
AttributeController.getController(getMap().getModeController()).createAttributeTableModel(model);
attributeView = new AttributeView(this, true);
}
return attributeView;
}
public Color getBackgroundColor() {
final Color cloudColor = getCloudColor();
if (cloudColor != null) {
return cloudColor;
}
if (isRoot()) {
return getMap().getBackground();
}
return getParentView().getBackgroundColor();
}
public Color getCloudColor() {
final CloudModel cloudModel = getCloudModel();
if(cloudModel != null){
final Color cloudColor = cloudModel.getColor();
return cloudColor;
}
return null;
}
/**
* This method returns the NodeViews that are children of this node.
*/
public LinkedList<NodeView> getChildrenViews() {
final LinkedList<NodeView> childrenViews = new LinkedList<NodeView>();
final Component[] components = getComponents();
for (int i = 0; i < components.length; i++) {
if (!(components[i] instanceof NodeView)) {
continue;
}
final NodeView view = (NodeView) components[i];
childrenViews.add(view);
}
return childrenViews;
}
public JComponent getContent() {
final JComponent c = contentPane == null ? mainView : contentPane;
assert (c == null || c.getParent() == this);
return c;
}
private Container getContentPane() {
if (contentPane == null) {
contentPane = NodeViewFactory.getInstance().newContentPane(this);
final int index = getComponentCount() - 1;
remove(index);
contentPane.add(mainView);
mainView.putClientProperty("NODE_VIEW_CONTENT_POSITION", MAIN_VIEWER_POSITION);
if(! mainView.isVisible())
mainView.setVisible(true);
add(contentPane, index);
}
return contentPane;
}
/**
* Returns the coordinates occupied by the node and its children as a vector
* of four point per node.
*/
public void getCoordinates(final LinkedList<Point> inList) {
getCoordinates(inList, 0, false, 0, 0);
}
private void getCoordinates(final LinkedList<Point> inList, int additionalDistanceForConvexHull,
final boolean byChildren, final int transX, final int transY) {
if (!isVisible()) {
return;
}
if (isContentVisible()) {
if (byChildren) {
final ModeController modeController = getMap().getModeController();
final CloudController cloudController = CloudController.getController(modeController);
final CloudModel cloud = cloudController.getCloud(getModel());
if (cloud != null) {
additionalDistanceForConvexHull += CloudView.getAdditionalHeigth(cloud, this) / 5;
}
}
final int x = transX + getContent().getX() - getDeltaX();
final int y = transY + getContent().getY() - getDeltaY();
final int width = mainView.getMainViewWidthWithFoldingMark();
final int heightWithFoldingMark = mainView.getMainViewHeightWithFoldingMark();
final int height = Math.max(heightWithFoldingMark, getContent().getHeight());
inList.addLast(new Point(-additionalDistanceForConvexHull + x, -additionalDistanceForConvexHull + y));
inList
.addLast(new Point(-additionalDistanceForConvexHull + x, additionalDistanceForConvexHull + y + height));
inList.addLast(new Point(additionalDistanceForConvexHull + x + width, additionalDistanceForConvexHull + y
+ height));
inList
.addLast(new Point(additionalDistanceForConvexHull + x + width, -additionalDistanceForConvexHull + y));
}
for (final NodeView child : getChildrenViews()) {
child.getCoordinates(inList, additionalDistanceForConvexHull, true, transX + child.getX(),
transY + child.getY());
}
}
/** get x coordinate including folding symbol */
public int getDeltaX() {
return mainView.getDeltaX();
}
/** get y coordinate including folding symbol */
public int getDeltaY() {
return mainView.getDeltaY();
}
/**
* @param startAfter
*/
NodeView getFirst(Component startAfter, final boolean leftOnly, final boolean rightOnly) {
final Component[] components = getComponents();
for (int i = 0; i < components.length; i++) {
if (startAfter != null) {
if (components[i] == startAfter) {
startAfter = null;
}
continue;
}
if (!(components[i] instanceof NodeView)) {
continue;
}
final NodeView view = (NodeView) components[i];
if (leftOnly && !view.isLeft() || rightOnly && view.isLeft()) {
continue;
}
if (view.isContentVisible()) {
return view;
}
final NodeView child = view.getFirst(null, leftOnly, rightOnly);
if (child != null) {
return child;
}
}
return null;
}
public int getHGap() {
return map.getZoomed(LocationModel.getModel(model).getHGap());
}
private NodeView getLast(Component startBefore, final boolean leftOnly, final boolean rightOnly) {
final Component[] components = getComponents();
for (int i = components.length - 1; i >= 0; i--) {
if (startBefore != null) {
if (components[i] == startBefore) {
startBefore = null;
}
continue;
}
if (!(components[i] instanceof NodeView)) {
continue;
}
final NodeView view = (NodeView) components[i];
if (leftOnly && !view.isLeft() || rightOnly && view.isLeft()) {
continue;
}
if (view.isContentVisible()) {
return view;
}
final NodeView child = view.getLast(null, leftOnly, rightOnly);
if (child != null) {
return child;
}
}
return null;
}
LinkedList<NodeView> getLeft(final boolean onlyVisible) {
final LinkedList<NodeView> left = new LinkedList<NodeView>();
for (final NodeView node : getChildrenViews()) {
if (node == null) {
continue;
}
if (node.isLeft()) {
left.add(node);
}
}
return left;
}
/**
* Returns the Point where the Links should arrive the Node.
*/
public Point getLinkPoint(final Point declination) {
int x, y;
Point linkPoint;
if (declination != null) {
x = getMap().getZoomed(declination.x);
y = getMap().getZoomed(declination.y);
}
else {
x = 1;
y = 0;
}
if (isLeft()) {
x = -x;
}
if (y != 0) {
final double ctgRect = Math.abs((double) getContent().getWidth() / getContent().getHeight());
final double ctgLine = Math.abs((double) x / y);
int absLinkX, absLinkY;
if (ctgRect > ctgLine) {
absLinkX = Math.abs(x * getContent().getHeight() / (2 * y));
absLinkY = getContent().getHeight() / 2;
}
else {
absLinkX = getContent().getWidth() / 2;
absLinkY = Math.abs(y * getContent().getWidth() / (2 * x));
}
linkPoint = new Point(getContent().getWidth() / 2 + (x > 0 ? absLinkX : -absLinkX), getContent()
.getHeight() / 2 + (y > 0 ? absLinkY : -absLinkY));
}
else {
linkPoint = new Point((x > 0 ? getContent().getWidth() : 0), (getContent().getHeight() / 2));
}
linkPoint.translate(getContent().getX(), getContent().getY());
convertPointToMap(linkPoint);
return linkPoint;
}
public MainView getMainView() {
return mainView;
}
public Point getMainViewConnectorPoint(NodeView target) {
final Point relativeLocation = getRelativeLocation(target);
relativeLocation.x += target.getMainView().getWidth()/2;
relativeLocation.y += target.getMainView().getHeight()/2;
return mainView.getConnectorPoint(relativeLocation);
}
public Point getRelativeLocation(NodeView target) {
Component component;
int targetX = 0;
int targetY = 0;
for(component = target.getMainView();
!(this.equals(component) || component.getClass().equals(MapView.class));
component = component.getParent()){
targetX += component.getX();
targetY += component.getY();
}
Point relativeLocation = new Point();
UITools.convertPointToAncestor(mainView, relativeLocation, component);
relativeLocation.x = targetX - relativeLocation.x;
relativeLocation.y = targetY - relativeLocation.y;
return relativeLocation;
}
public MapView getMap() {
return map;
}
public int getMaxToolTipWidth() {
if (maxToolTipWidth == 0) {
try {
maxToolTipWidth = ResourceController.getResourceController().getIntProperty(
"toolTipManager.max_tooltip_width", 600);
}
catch (final NumberFormatException e) {
maxToolTipWidth = 600;
}
}
return maxToolTipWidth;
}
public NodeModel getModel() {
return model;
}
protected NodeView getNextSiblingSingle() {
LinkedList<NodeView> v = null;
if (getParentView().getModel().isRoot()) {
if (this.isLeft()) {
v = (getParentView()).getLeft(true);
}
else {
v = (getParentView()).getRight(true);
}
}
else {
v = getParentView().getChildrenViews();
}
final int index = v.indexOf(this);
for (int i = index + 1; i < v.size(); i++) {
final NodeView nextView = (NodeView) v.get(i);
if (nextView.isContentVisible()) {
return nextView;
}
else {
final NodeView first = nextView.getFirst(null, false, false);
if (first != null) {
return first;
}
}
}
return this;
}
protected NodeView getNextVisibleSibling() {
NodeView sibling;
NodeView lastSibling = this;
for (sibling = this; !sibling.getModel().isRoot(); sibling = sibling.getParentView()) {
lastSibling = sibling;
sibling = sibling.getNextSiblingSingle();
if (sibling != lastSibling) {
break;
}
}
while (sibling.getModel().getNodeLevel(false) < getMap().getSiblingMaxLevel()) {
final NodeView first = sibling.getFirst(sibling.isRoot() ? lastSibling : null, this.isLeft(),
!this.isLeft());
if (first == null) {
break;
}
sibling = first;
}
if (sibling.isRoot()) {
return this;
}
return sibling;
}
public NodeView getParentView() {
final Container parent = getParent();
if (parent instanceof NodeView) {
return (NodeView) parent;
}
return null;
}
public NodeView getPreferredVisibleChild(final boolean getUpper, final boolean left) {
if (getModel().isLeaf()) {
return null;
}
if (getUpper) {
preferredChild = null;
}
if (preferredChild != null && (left == preferredChild.isLeft()) && preferredChild.getParent() == this) {
if (preferredChild.isContentVisible()) {
return preferredChild;
}
else {
final NodeView newSelected = preferredChild.getPreferredVisibleChild(getUpper, left);
if (newSelected != null) {
return newSelected;
}
}
}
int yGap = Integer.MAX_VALUE;
final NodeView baseComponent;
if (isContentVisible()) {
baseComponent = this;
}
else {
baseComponent = getVisibleParentView();
}
final int ownX = baseComponent.getContent().getX() + baseComponent.getContent().getWidth() / 2;
final int ownY = baseComponent.getContent().getY() + baseComponent.getContent().getHeight() / 2;
NodeView newSelected = null;
for (int i = 0; i < getComponentCount(); i++) {
final Component c = getComponent(i);
if (!(c instanceof NodeView)) {
continue;
}
NodeView childView = (NodeView) c;
if (!(childView.isLeft() == left)) {
continue;
}
if (!childView.isContentVisible()) {
childView = childView.getPreferredVisibleChild(getUpper, left);
if (childView == null) {
continue;
}
}
if (getUpper) {
return childView;
}
- final Point childPoint = new Point(left ? childView.getContent().getWidth() : 0, childView.getContent().getHeight() / 2);
- UITools.convertPointToAncestor(childView.getContent(), childPoint, baseComponent);
+ JComponent childContent = childView.getContent();
+ if(childContent == null)
+ continue;
+ final Point childPoint = new Point(left ? childContent.getWidth() : 0, childContent.getHeight() / 2);
+ UITools.convertPointToAncestor(childContent, childPoint, baseComponent);
final int dy = childPoint.y - ownY;
final int dx = childPoint.x - ownX;
final int gapToChild = dy*dy + dx*dx;
if (gapToChild < yGap) {
newSelected = childView;
preferredChild = (NodeView) c;
yGap = gapToChild;
}
else {
break;
}
}
return newSelected;
}
protected NodeView getPreviousSiblingSingle() {
LinkedList<NodeView> v = null;
if (getParentView().getModel().isRoot()) {
if (this.isLeft()) {
v = (getParentView()).getLeft(true);
}
else {
v = (getParentView()).getRight(true);
}
}
else {
v = getParentView().getChildrenViews();
}
final int index = v.indexOf(this);
for (int i = index - 1; i >= 0; i--) {
final NodeView nextView = (NodeView) v.get(i);
if (nextView.isContentVisible()) {
return nextView;
}
else {
final NodeView last = nextView.getLast(null, false, false);
if (last != null) {
return last;
}
}
}
return this;
}
protected NodeView getPreviousVisibleSibling() {
NodeView sibling;
NodeView previousSibling = this;
for (sibling = this; !sibling.getModel().isRoot(); sibling = sibling.getParentView()) {
previousSibling = sibling;
sibling = sibling.getPreviousSiblingSingle();
if (sibling != previousSibling) {
break;
}
}
while (sibling.getModel().getNodeLevel(false) < getMap().getSiblingMaxLevel()) {
final NodeView last = sibling.getLast(sibling.isRoot() ? previousSibling : null, this.isLeft(),
!this.isLeft());
if (last == null) {
break;
}
sibling = last;
}
if (sibling.isRoot()) {
return this;
}
return sibling;
}
LinkedList<NodeView> getRight(final boolean onlyVisible) {
final LinkedList<NodeView> right = new LinkedList<NodeView>();
for (final NodeView node : getChildrenViews()) {
if (node == null) {
continue;
}
if (!node.isLeft()) {
right.add(node);
}
}
return right;
}
/**
* @return returns the color that should used to select the node.
*/
public Color getSelectedColor() {
return MapView.standardSelectColor;
}
/**
* @return Returns the sHIFT.s
*/
public int getShift() {
final LocationModel locationModel = LocationModel.getModel(model);
return map.getZoomed(calcShiftY(locationModel));
}
protected LinkedList<NodeView> getSiblingViews() {
return getParentView().getChildrenViews();
}
public Color getTextBackground() {
if (modelBackgroundColor != null) {
return modelBackgroundColor;
}
return getBackgroundColor();
}
public Color getTextColor() {
final Color color = NodeStyleController.getController(getMap().getModeController()).getColor(model);
return color;
}
/**
* @return Returns the VGAP.
*/
public int getVGap() {
return map.getZoomed(LocationModel.getModel(model).getVGap());
}
public NodeView getVisibleParentView() {
final Container parent = getParent();
if (!(parent instanceof NodeView)) {
return null;
}
final NodeView parentView = (NodeView) parent;
if (parentView.isContentVisible()) {
return parentView;
}
return parentView.getVisibleParentView();
}
public int getZoomedFoldingSymbolHalfWidth() {
if (NodeView.FOLDING_SYMBOL_WIDTH == -1) {
NodeView.FOLDING_SYMBOL_WIDTH = ResourceController.getResourceController().getIntProperty(
"foldingsymbolwidth", 8);
}
final int preferredFoldingSymbolHalfWidth = (int) ((NodeView.FOLDING_SYMBOL_WIDTH * map.getZoom()) / 2);
return preferredFoldingSymbolHalfWidth;
}
void addChildViews() {
int index = 0;
for (NodeModel child : getMap().getModeController().getMapController().childrenFolded(getModel())) {
if(child.containsExtension(HideChildSubtree.class))
return;
if(getComponentCount() <= index
|| ! (getComponent(index) instanceof NodeView))
addChildView(child, index++);
}
}
/**
* Create views for the newNode and all his descendants, set their isLeft
* attribute according to this view.
* @param index2
*/
void addChildView(final NodeModel newNode, int index) {
NodeViewFactory.getInstance().newNodeView(newNode, getMap(), this, index);
}
/* fc, 25.1.2004: Refactoring necessary: should call the model. */
public boolean isChildOf(final NodeView myNodeView) {
return getParentView() == myNodeView;
}
/**
*/
public boolean isContentVisible() {
return getModel().isVisible();
}
public boolean isLeft() {
if (getMap().getLayoutType() == MapViewLayout.OUTLINE) {
return false;
}
return getModel().isLeft();
}
public boolean isParentHidden() {
final Container parent = getParent();
if (!(parent instanceof NodeView)) {
return false;
}
final NodeView parentView = (NodeView) parent;
return !parentView.isContentVisible();
}
/* fc, 25.1.2004: Refactoring necessary: should call the model. */
public boolean isParentOf(final NodeView myNodeView) {
return (this == myNodeView.getParentView());
}
public boolean isRoot() {
return getModel().isRoot();
}
public boolean isSelected() {
return (getMap().isSelected(this));
}
/* fc, 25.1.2004: Refactoring necessary: should call the model. */
public boolean isSiblingOf(final NodeView myNodeView) {
return getParentView() == myNodeView.getParentView();
}
public void mapChanged(final MapChangeEvent event) {
}
public void nodeChanged(final NodeChangeEvent event) {
final NodeModel node = event.getNode();
// is node is deleted, skip the rest.
if (!node.isRoot() && node.getParent() == null) {
return;
}
final Object property = event.getProperty();
if (property == NodeChangeType.FOLDING) {
treeStructureChanged();
getMap().selectIfSelectionIsEmpty(this);
String shape = NodeStyleController.getController(getMap().getModeController()).getShape(model);
if (shape.equals(NodeStyleModel.SHAPE_COMBINED))
update();
return;
}
// is node is not fully initialized, skip the rest.
if (mainView == null) {
return;
}
if (property.equals(NodeModel.NODE_ICON) || property.equals(HierarchicalIcons.ICONS)) {
mainView.updateIcons(this);
revalidate();
return;
}
if (property.equals(NodeModel.NOTE_TEXT)) {
NodeViewFactory.getInstance().updateNoteViewer(this);
mainView.updateIcons(this);
return;
}
if (property.equals(ShortenedTextModel.SHORTENER)) {
NodeViewFactory.getInstance().updateNoteViewer(this);
}
if (property.equals(HistoryInformationModel.class)) {
return;
}
update();
if (!isRoot())
getParentView().numberingChanged(node.getParent().getIndex(node) + 1);
}
public void onNodeDeleted(final NodeModel parent, final NodeModel child, final int index) {
if (getMap().getModeController().getMapController().isFolded(model)) {
return;
}
final boolean preferredChildIsLeft = preferredChild != null && preferredChild.isLeft();
final NodeView node = (NodeView) getComponent(index);
if (node == preferredChild) {
preferredChild = null;
for (int j = index + 1; j < getComponentCount(); j++) {
final Component c = getComponent(j);
if (!(c instanceof NodeView)) {
break;
}
final NodeView candidate = (NodeView) c;
if (candidate.isVisible() && node.isLeft() == candidate.isLeft()) {
preferredChild = candidate;
break;
}
}
if (preferredChild == null) {
for (int j = index - 1; j >= 0; j--) {
final Component c = getComponent(j);
if (!(c instanceof NodeView)) {
break;
}
final NodeView candidate = (NodeView) c;
if (candidate.isVisible() && node.isLeft() == candidate.isLeft()) {
preferredChild = candidate;
break;
}
}
}
}
numberingChanged(index+1);
node.remove();
NodeView preferred = getPreferredVisibleChild(false, preferredChildIsLeft);
if (preferred == null) {
preferred = this;
}
if(getMap().getSelected() == null)
getMap().selectVisibleAncestorOrSelf(preferred);
revalidate();
}
public void onNodeInserted(final NodeModel parent, final NodeModel child, final int index) {
assert parent == model;
if (getMap().getModeController().getMapController().isFolded(model)) {
return;
}
addChildView(child, index);
numberingChanged(index + 1);
revalidate();
}
public void onNodeMoved(final NodeModel oldParent, final int oldIndex, final NodeModel newParent,
final NodeModel child, final int newIndex) {
}
public void onPreNodeDelete(final NodeModel oldParent, final NodeModel child, final int oldIndex) {
}
// updates children, starting from firstChangedIndex, if necessary.
private void numberingChanged(int firstChangedIndex) {
final TextController textController = TextController.getController(getMap().getModeController());
if (firstChangedIndex > 0 || textController.getNodeNumbering(getModel())) {
final Component[] components = getComponents();
for (int i = firstChangedIndex; i < components.length; i++) {
if (components[i] instanceof NodeView) {
final NodeView view = (NodeView) components[i];
final MainView childMainView = view.getMainView();
if(childMainView != null){
childMainView.updateText(view.getModel());
view.numberingChanged(0);
}
}
}
}
}
/*
* (non-Javadoc)
* @see javax.swing.JComponent#paint(java.awt.Graphics)
*/
@Override
public void paintComponent(final Graphics g) {
if(getMainView() == null)
return;
final PaintingMode paintingMode = map.getPaintingMode();
if (isContentVisible()) {
final Graphics2D g2 = (Graphics2D) g;
final ModeController modeController = map.getModeController();
final Object renderingHint = g2.getRenderingHint(RenderingHints.KEY_ANTIALIASING);
switch (paintingMode) {
case CLOUDS:
modeController.getController().getViewController().setEdgesRenderingHint(g2);
final boolean isRoot = isRoot();
if (isRoot) {
paintCloud(g);
}
paintClouds(g2);
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, renderingHint);
}
switch (paintingMode) {
case NODES:
g2.setStroke(BubbleMainView.DEF_STROKE);
modeController.getController().getViewController().setEdgesRenderingHint(g2);
paintEdges(g2, this);
paintDecoration(g2);
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, renderingHint);
}
}
if (PAINT_DEBUG_BORDER && isSelected()&& paintingMode.equals(PaintingMode.SELECTED_NODES)){
final int spaceAround = getZoomed(SPACE_AROUND);
g.drawRect(spaceAround, spaceAround, getWidth() - 2 * spaceAround, getHeight() - 2 * spaceAround);
}
}
private void paintCloud(final Graphics g) {
if (!isContentVisible()) {
return;
}
final CloudModel cloudModel = getCloudModel();
if (cloudModel == null) {
return;
}
final CloudView cloud = new CloudViewFactory().createCloudView(cloudModel, this);
cloud.paint(g);
}
private void paintClouds(final Graphics2D g) {
for (int i = getComponentCount() - 1; i >= 0; i--) {
final Component component = getComponent(i);
if (!(component instanceof NodeView)) {
continue;
}
final NodeView nodeView = (NodeView) component;
final Point p = new Point();
UITools.convertPointToAncestor(nodeView, p, this);
g.translate(p.x, p.y);
if (nodeView.isContentVisible()) {
nodeView.paintCloud(g);
}
else {
nodeView.paintClouds(g);
}
g.translate(-p.x, -p.y);
}
}
private void paintEdges(final Graphics2D g, NodeView source) {
SummaryEdgePainter summaryEdgePainter = new SummaryEdgePainter(this, isRoot() ? true : isLeft());
SummaryEdgePainter rightSummaryEdgePainter = isRoot() ? new SummaryEdgePainter(this, false) : null;
final int start;
final int end;
final int step;
if (getMap().getLayoutType() == MapViewLayout.OUTLINE){
start = getComponentCount() - 1;
end = -1;
step = -1;
}
else{
start = 0;
end = getComponentCount();
step = 1;
}
for (int i = start; i != end; i+=step) {
final Component component = getComponent(i);
if (!(component instanceof NodeView)) {
continue;
}
final NodeView nodeView = (NodeView) component;
if (getMap().getLayoutType() != MapViewLayout.OUTLINE) {
SummaryEdgePainter activePainter = nodeView.isLeft() || !isRoot() ? summaryEdgePainter : rightSummaryEdgePainter;
activePainter.addChild(nodeView);
if(activePainter.paintSummaryEdge(g, source, nodeView)){
if(! nodeView.isContentVisible()){
final Rectangle bounds = SwingUtilities.convertRectangle(this, nodeView.getBounds(), source);
final Graphics cg = g.create(bounds.x, bounds.y, bounds.width, bounds.height);
try{
nodeView.paintEdges((Graphics2D) cg, nodeView);
}
finally{
cg.dispose();
}
}
continue;
}
}
if (nodeView.isContentVisible()) {
final EdgeView edge = EdgeViewFactory.getInstance().getEdge(source, nodeView, source);
edge.paint(g);
}
else {
nodeView.paintEdges(g, source);
}
}
}
int getSpaceAround() {
return getZoomed(NodeView.SPACE_AROUND);
}
public int getZoomed(int x) {
return getMap().getZoomed(x);
}
void paintDecoration(final Graphics2D g) {
final Point origin = new Point();
UITools.convertPointToAncestor(mainView, origin, this);
g.translate(origin.x, origin.y);
mainView.paintDecoration(this, g);
g.translate(-origin.x, -origin.y);
final FilterController filterController = FilterController.getController(getMap().getModeController().getController());
if(filterController.isNodeHighlighted(getModel())){
final Color oldColor = g.getColor();
final Stroke oldStroke = g.getStroke();
g.setColor(Color.MAGENTA);
g.setStroke(getMap().getStandardSelectionStroke());
final JComponent content = getContent();
Point contentLocation = content.getLocation();
final int arcWidth = 8;
g.drawRoundRect(contentLocation.x - arcWidth, contentLocation.y - arcWidth, content.getWidth() + 2 * arcWidth,
content.getHeight() + 2 * arcWidth, 15, 15);
g.setColor(oldColor);
g.setStroke(oldStroke);
}
}
/**
* This is a bit problematic, because getChildrenViews() only works if model
* is not yet removed. (So do not _really_ delete the model before the view
* removed (it needs to stay in memory)
*/
void remove() {
for (final ListIterator<NodeView> e = getChildrenViews().listIterator(); e.hasNext();) {
e.next().remove();
}
getMap().deselect(this);
getMap().getModeController().onViewRemoved(this);
removeFromMap();
if (attributeView != null) {
attributeView.viewRemoved();
}
getModel().removeViewer(this);
}
protected void removeFromMap() {
setFocusCycleRoot(false);
getParent().remove(this);
}
private void repaintEdge(final NodeView target) {
if (target.getMap().getLayoutType() == MapViewLayout.OUTLINE){
target.getVisibleParentView().repaint();
return;
}
final Point relativeLocation = getRelativeLocation(target);
final MainView targetMainView = target.getMainView();
relativeLocation.x += targetMainView.getWidth()/2;
relativeLocation.y += targetMainView.getHeight()/2;
final Point inPoint = mainView.getConnectorPoint(relativeLocation);
UITools.convertPointToAncestor(targetMainView, inPoint, this);
relativeLocation.x -= targetMainView.getWidth()/2;
relativeLocation.y -= targetMainView.getHeight()/2;
relativeLocation.x = - relativeLocation.x + mainView.getWidth()/2;
relativeLocation.y = - relativeLocation.y + mainView.getHeight()/2;
final Point outPoint = targetMainView.getConnectorPoint(relativeLocation);
UITools.convertPointToAncestor(getMainView(), outPoint, this);
final int x = Math.min(inPoint.x, outPoint.x);
final int y = Math.min(inPoint.y, outPoint.y);
final int w = Math.abs(inPoint.x - outPoint.x);
final int h = Math.abs(inPoint.y - outPoint.y);
final int EXTRA = 50;
repaint(x - EXTRA, y - EXTRA, w + EXTRA * 2, h + EXTRA * 2);
}
void repaintSelected() {
// return if main view was not set
if (mainView == null) {
return;
}
// do not repaint removed nodes
if (model.getParentNode() == null && !model.isRoot()) {
return;
}
if (getEdgeStyle().equals(EdgeStyle.EDGESTYLE_HIDDEN)) {
final NodeView visibleParentView = getVisibleParentView();
if (visibleParentView != null) {
visibleParentView.repaintEdge(this);
}
}
final JComponent content = getContent();
final int EXTRA = 20;
final int x = content.getX() - EXTRA;
final int y = content.getY() - EXTRA;
repaint(x, y, content.getWidth() + EXTRA * 2, content.getHeight() + EXTRA * 2);
}
@Override
public boolean requestFocusInWindow() {
if (mainView == null) {
return false;
}
getMap().scrollNodeToVisible(this);
Controller.getCurrentController().getViewController().addObjectTypeInfo(getModel().getUserObject());
return mainView.requestFocusInWindow();
}
@Override
public void requestFocus() {
if (mainView == null) {
return;
}
getMap().scrollNodeToVisible(this);
Controller.getCurrentController().getViewController().addObjectTypeInfo(getModel().getUserObject());
mainView.requestFocus();
}
void setMainView(final MainView newMainView) {
if (contentPane != null) {
assert (contentPane.getParent() == this);
if (mainView != null)
removeContent(MAIN_VIEWER_POSITION);
addContent(newMainView, MAIN_VIEWER_POSITION);
assert (contentPane.getParent() == this);
}
else if (mainView != null) {
final Container c = mainView.getParent();
int i;
for (i = c.getComponentCount() - 1; i >= 0 && mainView != c.getComponent(i); i--) {
;
}
c.remove(i);
c.add(newMainView, i);
}
else {
add(newMainView);
}
mainView = newMainView;
final IUserInputListenerFactory userInputListenerFactory = getMap().getModeController()
.getUserInputListenerFactory();
mainView.addMouseListener(userInputListenerFactory.getNodeMouseMotionListener());
mainView.addMouseMotionListener(userInputListenerFactory.getNodeMouseMotionListener());
mainView.addKeyListener(userInputListenerFactory.getNodeKeyListener());
addDragListener(userInputListenerFactory.getNodeDragListener());
addDropListener(userInputListenerFactory.getNodeDropTargetListener());
}
protected void setModel(final NodeModel model) {
this.model = model;
}
public void setPreferredChild(final NodeView view) {
if(view != null && ! SummaryNode.isSummaryNode(view.getModel()))
preferredChild = view;
final Container parent = this.getParent();
if (view == null) {
return;
}
else if (parent instanceof NodeView) {
((NodeView) parent).setPreferredChild(this);
}
}
/**
*/
public void setText(final String string) {
mainView.setText(string);
}
void syncronizeAttributeView() {
if (attributeView != null) {
attributeView.syncronizeAttributeView();
}
}
/*
* (non-Javadoc)
* @see java.awt.Component#toString()
*/
@Override
public String toString() {
return getModel().toString() + ", " + super.toString();
}
/*
* (non-Javadoc)
* @see
* javax.swing.event.TreeModelListener#treeStructureChanged(javax.swing.
* event.TreeModelEvent)
*/
private void treeStructureChanged() {
for (final ListIterator<NodeView> i = getChildrenViews().listIterator(); i.hasNext();) {
i.next().remove();
}
addChildViews();
map.revalidateSelecteds();
revalidate();
}
public void update() {
updateShape();
updateEdge();
if (!isContentVisible()) {
mainView.setVisible(false);
return;
}
mainView.setVisible(true);
mainView.updateTextColor(this);
mainView.updateFont(this);
createAttributeView();
if (attributeView != null) {
attributeView.update();
}
final boolean textShortened = isShortened();
if(! textShortened){
NodeViewFactory.getInstance().updateDetails(this);
if (contentPane != null) {
final int componentCount = contentPane.getComponentCount();
for (int i = 1; i < componentCount; i++) {
final Component component = contentPane.getComponent(i);
if (component instanceof JComponent) {
((JComponent) component).revalidate();
}
}
}
}
updateShortener(getModel(), textShortened);
mainView.updateIcons(this);
mainView.updateText(getModel());
updateCloud();
modelBackgroundColor = NodeStyleController.getController(getMap().getModeController()).getBackgroundColor(model);
revalidate();
}
public boolean isShortened() {
final ModeController modeController = getMap().getModeController();
final TextController textController = TextController.getController(modeController);
final boolean textShortened = textController.isMinimized(getModel());
return textShortened;
}
private void updateEdge() {
final EdgeController edgeController = EdgeController.getController(getMap().getModeController());
this.edgeStyle = edgeController.getStyle(model, false);
this.edgeWidth = edgeController.getWidth(model, false);
this.edgeColor = edgeController.getColor(model, false);
}
public EdgeStyle getEdgeStyle() {
if(edgeStyle != null)
return edgeStyle;
return getParentView().getEdgeStyle();
}
public int getEdgeWidth() {
if(edgeWidth != null)
return edgeWidth;
final NodeView parentView = getParentView();
if(parentView != null)
return parentView.getEdgeWidth();
return 1;
}
public Color getEdgeColor() {
if(edgeColor != null)
return edgeColor;
return getParentView().getEdgeColor();
}
private void updateCloud() {
final CloudModel cloudModel = CloudController.getController(getMap().getModeController()).getCloud(model);
putClientProperty(CloudModel.class, cloudModel);
}
public CloudModel getCloudModel() {
return (CloudModel) getClientProperty(CloudModel.class);
}
private void updateShortener(NodeModel nodeModel, boolean textShortened) {
final boolean componentsVisible = !textShortened;
setContentComponentVisible(componentsVisible);
}
private void setContentComponentVisible(final boolean componentsVisible) {
if(contentPane == null)
return;
final Component[] components = getContentPane().getComponents();
int index;
for (index = 0; index < components.length; index++) {
final Component component = components[index];
if (component == getMainView()) {
continue;
}
if (component.isVisible() != componentsVisible) {
component.setVisible(componentsVisible);
}
}
}
public void updateAll() {
NodeViewFactory.getInstance().updateNoteViewer(this);
update();
invalidate();
for (final NodeView child : getChildrenViews()) {
child.updateAll();
}
}
private void updateShape() {
final String newShape = NodeStyleController.getController(getMap().getModeController()).getShape(model);
final String oldShape;
if(mainView != null)
oldShape = mainView.getShape();
else
oldShape = null;
if (mainView != null){
if(oldShape.equals(newShape))
return;
if(model.isRoot()) {
if(newShape != null)
((RootMainView)mainView).setShape(newShape);
return;
}
}
final MainView newMainView = NodeViewFactory.getInstance().newMainView(this);
if(newMainView.getShape().equals(oldShape))
return;
setMainView(newMainView);
if (map.getSelected() == this) {
requestFocusInWindow();
}
}
boolean useSelectionColors() {
return isSelected() && !MapView.standardDrawRectangleForSelection && !map.isPrinting();
}
public void onPreNodeMoved(final NodeModel oldParent, final int oldIndex, final NodeModel newParent,
final NodeModel child, final int newIndex) {
}
@Override
protected void validateTree() {
super.validateTree();
}
public void addContent(JComponent component, int pos) {
component.putClientProperty("NODE_VIEW_CONTENT_POSITION", pos);
final Container contentPane = getContentPane();
for (int i = 0; i < contentPane.getComponentCount(); i++) {
JComponent content = (JComponent) contentPane.getComponent(i);
if (content == null)
throw new RuntimeException("component " + i + "is null");
final Object clientProperty = content.getClientProperty("NODE_VIEW_CONTENT_POSITION");
if (clientProperty == null)
throw new RuntimeException("NODE_VIEW_CONTENT_POSITION not set on component " + content.toString() + i
+ "/" + contentPane.getComponentCount());
if (pos < (Integer) clientProperty) {
contentPane.add(component, i);
return;
}
}
contentPane.add(component);
}
public JComponent removeContent(int pos) {
return removeContent(pos, true);
}
private JComponent removeContent(int pos, boolean remove) {
if (contentPane == null)
return null;
for (int i = 0; i < contentPane.getComponentCount(); i++) {
JComponent component = (JComponent) contentPane.getComponent(i);
Integer contentPos = (Integer) component.getClientProperty("NODE_VIEW_CONTENT_POSITION");
if (contentPos == null) {
continue;
}
if (contentPos == pos) {
if (remove) {
component.putClientProperty("NODE_VIEW_CONTENT_POSITION", null);
contentPane.remove(i);
}
return component;
}
if (contentPos > pos) {
return null;
}
}
return null;
}
public JComponent getContent(int pos) {
return removeContent(pos, false);
}
public boolean isSummary() {
return SummaryNode.isSummaryNode(getModel());
}
public boolean isFirstGroupNode() {
return SummaryNode.isFirstGroupNode(getModel());
}
public boolean isFree() {
return FreeNode.isFreeNode(getModel());
}
public Color getDetailBackground() {
final Color detailBackground = getMap().getDetailBackground();
return detailBackground;
}
int getTopOverlap() {
return topOverlap;
}
void setTopOverlap(int topOverlap) {
this.topOverlap = topOverlap;
}
int getBottomOverlap() {
return bottomOverlap;
}
void setBottomOverlap(int bottomOverlap) {
this.bottomOverlap = bottomOverlap;
}
}
| true | true | public NodeView getPreferredVisibleChild(final boolean getUpper, final boolean left) {
if (getModel().isLeaf()) {
return null;
}
if (getUpper) {
preferredChild = null;
}
if (preferredChild != null && (left == preferredChild.isLeft()) && preferredChild.getParent() == this) {
if (preferredChild.isContentVisible()) {
return preferredChild;
}
else {
final NodeView newSelected = preferredChild.getPreferredVisibleChild(getUpper, left);
if (newSelected != null) {
return newSelected;
}
}
}
int yGap = Integer.MAX_VALUE;
final NodeView baseComponent;
if (isContentVisible()) {
baseComponent = this;
}
else {
baseComponent = getVisibleParentView();
}
final int ownX = baseComponent.getContent().getX() + baseComponent.getContent().getWidth() / 2;
final int ownY = baseComponent.getContent().getY() + baseComponent.getContent().getHeight() / 2;
NodeView newSelected = null;
for (int i = 0; i < getComponentCount(); i++) {
final Component c = getComponent(i);
if (!(c instanceof NodeView)) {
continue;
}
NodeView childView = (NodeView) c;
if (!(childView.isLeft() == left)) {
continue;
}
if (!childView.isContentVisible()) {
childView = childView.getPreferredVisibleChild(getUpper, left);
if (childView == null) {
continue;
}
}
if (getUpper) {
return childView;
}
final Point childPoint = new Point(left ? childView.getContent().getWidth() : 0, childView.getContent().getHeight() / 2);
UITools.convertPointToAncestor(childView.getContent(), childPoint, baseComponent);
final int dy = childPoint.y - ownY;
final int dx = childPoint.x - ownX;
final int gapToChild = dy*dy + dx*dx;
if (gapToChild < yGap) {
newSelected = childView;
preferredChild = (NodeView) c;
yGap = gapToChild;
}
else {
break;
}
}
return newSelected;
}
| public NodeView getPreferredVisibleChild(final boolean getUpper, final boolean left) {
if (getModel().isLeaf()) {
return null;
}
if (getUpper) {
preferredChild = null;
}
if (preferredChild != null && (left == preferredChild.isLeft()) && preferredChild.getParent() == this) {
if (preferredChild.isContentVisible()) {
return preferredChild;
}
else {
final NodeView newSelected = preferredChild.getPreferredVisibleChild(getUpper, left);
if (newSelected != null) {
return newSelected;
}
}
}
int yGap = Integer.MAX_VALUE;
final NodeView baseComponent;
if (isContentVisible()) {
baseComponent = this;
}
else {
baseComponent = getVisibleParentView();
}
final int ownX = baseComponent.getContent().getX() + baseComponent.getContent().getWidth() / 2;
final int ownY = baseComponent.getContent().getY() + baseComponent.getContent().getHeight() / 2;
NodeView newSelected = null;
for (int i = 0; i < getComponentCount(); i++) {
final Component c = getComponent(i);
if (!(c instanceof NodeView)) {
continue;
}
NodeView childView = (NodeView) c;
if (!(childView.isLeft() == left)) {
continue;
}
if (!childView.isContentVisible()) {
childView = childView.getPreferredVisibleChild(getUpper, left);
if (childView == null) {
continue;
}
}
if (getUpper) {
return childView;
}
JComponent childContent = childView.getContent();
if(childContent == null)
continue;
final Point childPoint = new Point(left ? childContent.getWidth() : 0, childContent.getHeight() / 2);
UITools.convertPointToAncestor(childContent, childPoint, baseComponent);
final int dy = childPoint.y - ownY;
final int dx = childPoint.x - ownX;
final int gapToChild = dy*dy + dx*dx;
if (gapToChild < yGap) {
newSelected = childView;
preferredChild = (NodeView) c;
yGap = gapToChild;
}
else {
break;
}
}
return newSelected;
}
|
diff --git a/src/com/wolvencraft/prison/mines/cmd/FlagCommand.java b/src/com/wolvencraft/prison/mines/cmd/FlagCommand.java
index 21828d4..9d0f19b 100644
--- a/src/com/wolvencraft/prison/mines/cmd/FlagCommand.java
+++ b/src/com/wolvencraft/prison/mines/cmd/FlagCommand.java
@@ -1,75 +1,75 @@
package com.wolvencraft.prison.mines.cmd;
import com.wolvencraft.prison.mines.PrisonMine;
import com.wolvencraft.prison.mines.mine.Mine;
import com.wolvencraft.prison.mines.settings.Language;
import com.wolvencraft.prison.mines.util.Message;
import com.wolvencraft.prison.mines.util.constants.MineFlag;
public class FlagCommand implements BaseCommand {
@Override
public boolean run(String[] args) {
if(args.length == 1 || (args.length == 2 && args[1].equalsIgnoreCase("help"))) { getHelp(); return true; }
Language language = PrisonMine.getLanguage();
if(args.length > 3) { Message.sendFormattedError(language.ERROR_ARGUMENTS); return false; }
Mine curMine = PrisonMine.getCurMine();
if(curMine == null) { Message.sendFormattedError(PrisonMine.getLanguage().ERROR_MINENOTSELECTED); return false; }
MineFlag flag = MineFlag.get(args[1]);
if(flag == null) { Message.sendFormattedError("The specified flag does not exist"); return false; }
if(flag.hasOptions()) {
if(args.length != 3) { Message.sendFormattedError(language.ERROR_ARGUMENTS); return false; }
if(!flag.isOptionValid(args[2])) { Message.sendFormattedError("This option is not valid"); return false; }
if(curMine.hasFlag(flag)) {
if(flag.acceptDuplicates()) {
if(curMine.hasFlag(flag, args[2])) {
curMine.removeFlag(flag, args[2]);
Message.sendFormattedMine("Flag " + flag + " has been removed");
} else {
curMine.addFlag(flag, args[2]);
Message.sendFormattedMine("Flag " + flag + " has been added");
}
} else {
- curMine.removeFlag(flag, args[2]);
+ curMine.removeFlag(flag);
Message.sendFormattedMine("Flag " + flag + " has been removed");
}
} else {
curMine.addFlag(flag, args[2]);
Message.sendFormattedMine("Flag " + flag + " has been added");
}
} else {
if(curMine.hasFlag(flag)) {
curMine.removeFlag(flag);
Message.sendFormattedMine("Flag " + flag + " has been removed");
} else {
curMine.addFlag(flag);
Message.sendFormattedMine("Flag " + flag + " has been added");
}
}
return curMine.saveFile();
}
@Override
public void getHelp() {
Message.formatHeader(20, "Flags");
Message.formatHelp("flag", "<flag> [option]", "Adds a flag value to the mine");
MineFlag[] validFlags = MineFlag.values();
String flagString = validFlags[0].getAlias();
for(int i = 1; i < validFlags.length; i++) {
flagString += ", " + validFlags[i].getAlias();
}
Message.send("Available flags: "+ flagString);
Message.send("Not all flags have options available");
}
@Override
public void getHelpLine() {
Message.formatHelp("flag help", "", "Shows the help page on mine flags", "prison.mine.edit");
}
}
| true | true | public boolean run(String[] args) {
if(args.length == 1 || (args.length == 2 && args[1].equalsIgnoreCase("help"))) { getHelp(); return true; }
Language language = PrisonMine.getLanguage();
if(args.length > 3) { Message.sendFormattedError(language.ERROR_ARGUMENTS); return false; }
Mine curMine = PrisonMine.getCurMine();
if(curMine == null) { Message.sendFormattedError(PrisonMine.getLanguage().ERROR_MINENOTSELECTED); return false; }
MineFlag flag = MineFlag.get(args[1]);
if(flag == null) { Message.sendFormattedError("The specified flag does not exist"); return false; }
if(flag.hasOptions()) {
if(args.length != 3) { Message.sendFormattedError(language.ERROR_ARGUMENTS); return false; }
if(!flag.isOptionValid(args[2])) { Message.sendFormattedError("This option is not valid"); return false; }
if(curMine.hasFlag(flag)) {
if(flag.acceptDuplicates()) {
if(curMine.hasFlag(flag, args[2])) {
curMine.removeFlag(flag, args[2]);
Message.sendFormattedMine("Flag " + flag + " has been removed");
} else {
curMine.addFlag(flag, args[2]);
Message.sendFormattedMine("Flag " + flag + " has been added");
}
} else {
curMine.removeFlag(flag, args[2]);
Message.sendFormattedMine("Flag " + flag + " has been removed");
}
} else {
curMine.addFlag(flag, args[2]);
Message.sendFormattedMine("Flag " + flag + " has been added");
}
} else {
if(curMine.hasFlag(flag)) {
curMine.removeFlag(flag);
Message.sendFormattedMine("Flag " + flag + " has been removed");
} else {
curMine.addFlag(flag);
Message.sendFormattedMine("Flag " + flag + " has been added");
}
}
return curMine.saveFile();
}
| public boolean run(String[] args) {
if(args.length == 1 || (args.length == 2 && args[1].equalsIgnoreCase("help"))) { getHelp(); return true; }
Language language = PrisonMine.getLanguage();
if(args.length > 3) { Message.sendFormattedError(language.ERROR_ARGUMENTS); return false; }
Mine curMine = PrisonMine.getCurMine();
if(curMine == null) { Message.sendFormattedError(PrisonMine.getLanguage().ERROR_MINENOTSELECTED); return false; }
MineFlag flag = MineFlag.get(args[1]);
if(flag == null) { Message.sendFormattedError("The specified flag does not exist"); return false; }
if(flag.hasOptions()) {
if(args.length != 3) { Message.sendFormattedError(language.ERROR_ARGUMENTS); return false; }
if(!flag.isOptionValid(args[2])) { Message.sendFormattedError("This option is not valid"); return false; }
if(curMine.hasFlag(flag)) {
if(flag.acceptDuplicates()) {
if(curMine.hasFlag(flag, args[2])) {
curMine.removeFlag(flag, args[2]);
Message.sendFormattedMine("Flag " + flag + " has been removed");
} else {
curMine.addFlag(flag, args[2]);
Message.sendFormattedMine("Flag " + flag + " has been added");
}
} else {
curMine.removeFlag(flag);
Message.sendFormattedMine("Flag " + flag + " has been removed");
}
} else {
curMine.addFlag(flag, args[2]);
Message.sendFormattedMine("Flag " + flag + " has been added");
}
} else {
if(curMine.hasFlag(flag)) {
curMine.removeFlag(flag);
Message.sendFormattedMine("Flag " + flag + " has been removed");
} else {
curMine.addFlag(flag);
Message.sendFormattedMine("Flag " + flag + " has been added");
}
}
return curMine.saveFile();
}
|
diff --git a/src/btwmods/ModLoader.java b/src/btwmods/ModLoader.java
index 4188cbc..2533215 100644
--- a/src/btwmods/ModLoader.java
+++ b/src/btwmods/ModLoader.java
@@ -1,423 +1,425 @@
package btwmods;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Set;
import java.util.AbstractMap.SimpleEntry;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.logging.Level;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;
import net.minecraft.server.MinecraftServer;
import net.minecraft.src.CommandBase;
import net.minecraft.src.World;
import btwmods.events.IAPIListener;
import btwmods.io.Settings;
public class ModLoader {
private ModLoader() {}
private static Thread thread = null;
private static boolean hasInit = false;
private static ClassLoader classLoader = null;
private static Set<URL> classLoaderUrls = new HashSet<URL>();
private static Method classLoaderAddURLMethod = null;
public static final String VERSION = "1.0 (vMC 1.3.2 BTW 4.21)";
public static final String BTWMOD_REGEX = "(?i)^(BTWMod|mod_|BTWMod_).*\\.class$";
private static final String LOGPREFIX = "BTWMods: ";
/**
* Holds failed listeners from other threads.
*/
private static ConcurrentLinkedQueue<SimpleEntry<Throwable, IAPIListener>> failedListenerQueue = new ConcurrentLinkedQueue<SimpleEntry<Throwable, IAPIListener>>();
/**
* Initialize the ModLoader and mods. Should only be called from the {@link World} constructor.
*/
public static void init() {
if (!hasInit) {
// Mark the current thread as the main one.
thread = Thread.currentThread();
outputInfo("Version " + VERSION + " initializing...");
// Attempt to get the URLClassLoader and its private addURL() method.
if (classLoader == null) {
classLoader = ModLoader.class.getClassLoader();
if (classLoader instanceof URLClassLoader) {
try {
classLoaderUrls.addAll(Arrays.asList(((URLClassLoader)classLoader).getURLs()));
classLoaderAddURLMethod = URLClassLoader.class.getDeclaredMethod("addURL", new Class[] { URL.class });
classLoaderAddURLMethod.setAccessible(true);
} catch (Throwable e) {
outputError(e, "Could not load mods from the class path (i.e. any mods directly in your minecraft_server.jar).");
}
}
// TODO: Can we use our own URLClassLoader instead?
}
StatsAPI.init();
try {
TranslationsAPI.init();
}
catch (Exception e) {
outputError(e, "TranslationsAPI failed (" + e.getClass().getSimpleName() + ") to load: " + e.getMessage(), Level.SEVERE);
outputError("Initialization aborted.", Level.SEVERE);
+ hasInit = true;
return;
}
try {
CommandsAPI.init();
}
catch (Exception e) {
outputError(e, "CommandsAPI failed (" + e.getClass().getSimpleName() + ") to load: " + e.getMessage(), Level.SEVERE);
outputError("Initialization aborted.", Level.SEVERE);
+ hasInit = true;
return;
}
findModsInClassPath();
findModsInFolder(new File(".", "btwmods"));
outputInfo("Initialization complete.");
}
hasInit = true;
}
/**
* Return if the current thread is the same one that ModLoader was initialized in.
*
* @return true if the current thread is the same ModLoader was initialized in; false otherwise.
*/
public static boolean inInitThread() {
return Thread.currentThread() == thread;
}
/**
* Returns if {@link URLClassLoader} was successfully set.
*
* @return <code>true</code> if it was set; <code>false</code> otherwise.
*/
public static boolean hasURLClassLoader() {
return classLoader != null && classLoader instanceof URLClassLoader;
}
/**
* Returns if {@link URLClassLoader} was successfully set and we can add URLs to it.
*
* @return <code>true</code> if we can add URLs; <code>false</code> otherwise.
*/
public static boolean supportsAddClassLoaderURL() {
return hasURLClassLoader() && classLoaderAddURLMethod != null;
}
/**
* Add a URL to {@link ModLoader}'s class loader.
*
* @see <a href="http://www.javafaq.nu/java-example-code-895.html">http://www.javafaq.nu/java-example-code-895.html</a>
* @param url
* @return <code>true</code> if the URL was added (or is already set); <code>false</code> if {@link #supportsAddClassLoaderURL()} returns <code>false</code> or the URL could not be added.
* @throws IllegalArgumentException
*/
public static boolean addClassLoaderURL(URL url) throws IllegalArgumentException {
if (url == null)
throw new IllegalArgumentException("url argument cannot be null");
if (classLoaderUrls.contains(url))
return true;
// Add the URL only if the private URLClassLoader#addURL() method has been set.
if (supportsAddClassLoaderURL()) {
try {
classLoaderAddURLMethod.invoke((URLClassLoader)classLoader, new Object[] { url });
return true;
} catch (Throwable e) {
outputError(e, "Failed (" + e.getClass().getSimpleName() + ") to add the following mod path: " + url.toString());
}
}
return false;
}
private static void findModsInFolder(File modsDir) {
if (!modsDir.exists()) {
modsDir.mkdir();
}
if (modsDir.isDirectory()) {
// Get a list of mod folders/files. The contents of these folders/files should be in package format.
File[] file = modsDir.listFiles();
if (file != null) {
for (int i = 0; i < file.length; i++) {
try {
String name = file[i].getName();
// Load mod from a regular directory.
if (file[i].isDirectory()) {
String[] binaryNames = getModBinaryNamesFromDirectory(file[i]);
if (binaryNames.length > 0 && addClassLoaderURL(file[i].toURI().toURL())) {
loadMods(binaryNames);
}
}
// Load mod from a zip or jar.
else if (file[i].isFile() && (name.endsWith(".jar") || name.endsWith(".zip"))) {
String[] binaryNames = getModBinaryNamesFromZip(file[i]);
if (binaryNames.length > 0 && addClassLoaderURL(file[i].toURI().toURL())) {
loadMods(binaryNames);
}
}
} catch (Throwable e) {
outputError(e, "Failed (" + e.getClass().getSimpleName() + ") to load mods from: " + file[i].getPath());
}
}
}
}
}
private static void findModsInClassPath() {
for (URL url : classLoaderUrls) {
try {
File path = new File(url.toURI());
String name = path.getName();
// Load mod from a regular directory.
if (path.isDirectory()) {
loadMods(getModBinaryNamesFromDirectory(path));
}
// Load mod from a zip or jar.
else if (path.isFile() && (name.endsWith(".jar") || name.endsWith(".zip"))) {
loadMods(getModBinaryNamesFromZip(path));
}
} catch (Throwable e) {
outputError(e, "Failed (" + e.getClass().getSimpleName() + ") to search the following classpath for mods: " + url.toString());
}
}
}
/**
* Searches a directory for a 'btwmod' package dir, sub package dirs under it (i.e. 'mymod'), and then for BTWMod*.class files.
*
* @param directory The directory to search.
* @return An array of binary names (see {@link ClassLoader}.
*/
private static String[] getModBinaryNamesFromDirectory(File directory) {
ArrayList<String> names = new ArrayList<String>();
// Make sure the 'btwmod' package folder exists.
File btwmodPackage = new File(directory, "btwmod");
if (btwmodPackage.isDirectory()) {
// Loop through the second level of package names, which should be for mods.
File[] modPackages = btwmodPackage.listFiles();
if (modPackages != null) {
for (int p = 0; p < modPackages.length; p++) {
if (modPackages[p].isDirectory()) {
// Check for mod_*.class files.
File[] classNames = modPackages[p].listFiles();
if (classNames != null) {
for (int c = 0; c < classNames.length; c++) {
if (classNames[c].isFile() && classNames[c].getName().matches(BTWMOD_REGEX)) {
names.add("btwmod." + modPackages[p].getName() + "." + classNames[c].getName().substring(0, classNames[c].getName().length() - ".class".length()));
}
}
}
}
}
}
}
return names.toArray(new String[names.size()]);
}
/**
* Searches a zip file (or jar) for files that match the package pattern btwmod.{somename}.BTWMod{somename}.class.
*
* @see <a href="http://www.javamex.com/tutorials/compression/zip_individual_entries.shtml">http://www.javamex.com/tutorials/compression/zip_individual_entries.shtml</a>
* @param zip The zip (or jar) file to search.
* @return An array of binary names (see {@link ClassLoader}.
* @throws IllegalStateException If an action is taken on a closed zip file.
* @throws ZipException
* @throws IOException If the zip file could not be loaded.
*/
private static String[] getModBinaryNamesFromZip(File zip) throws IllegalStateException, ZipException, IOException {
ArrayList<String> names = new ArrayList<String>();
ZipFile zipFile = null;
try {
zipFile = new ZipFile(zip);
for (Enumeration<? extends ZipEntry> list = zipFile.entries(); list.hasMoreElements(); ) {
ZipEntry entry = list.nextElement();
if (!entry.isDirectory() && entry.getName().matches("^btwmod/[^/]+/BTWMod.+\\.class$")) {
names.add(entry.getName().substring(0, entry.getName().length() - ".class".length()).replace('/', '.'));
}
}
return names.toArray(new String[names.size()]);
} finally {
if (zipFile != null)
try { zipFile.close(); } catch (Throwable e) { }
}
}
private static void loadMod(String binaryName) {
try {
Class mod = classLoader.loadClass(binaryName);
if (IMod.class.isAssignableFrom(mod)) {
IMod modInstance = (IMod)mod.newInstance();
String modName = modInstance.getName();
try {
modInstance.init(loadModSettings(binaryName));
}
catch (Throwable e) {
outputError(e, "Failed (" + e.getClass().getSimpleName() + ") while running init for: " + binaryName);
}
outputInfo("Loaded: " + (modName == null ? binaryName : modName + " (" + binaryName + ")"));
}
} catch (Throwable e) {
outputError(e, "Failed (" + e.getClass().getSimpleName() + ") to create an instance of: " + binaryName);
}
}
private static void loadMods(String[] binaryNames) {
for (int n = 0; n < binaryNames.length; n++) {
loadMod(binaryNames[n]);
}
}
private static Settings loadModSettings(String binaryName) {
File settingsFile = new File(new File("."), "btwmods/" + getModPackageName(binaryName) + ".txt");
if (settingsFile.isFile()) {
try {
return Settings.readSettings(settingsFile);
}
catch (IOException e) {
outputError(e, "Failed (" + e.getClass().getSimpleName() + ") to read the settings file for " + binaryName);
}
}
return new Settings();
}
public static String getModPackageName(IMod mod) {
return getModPackageName(mod.getClass().getName());
}
private static String getModPackageName(String binaryName) {
return binaryName.replaceAll("^btwmod\\.([^.]+)\\..+$", "$1");
}
public static void outputError(String message) {
outputError(message, Level.WARNING);
}
public static void outputError(String message, Level level) {
MinecraftServer.logger.log(level, LOGPREFIX + message);
}
public static void outputError(Throwable throwable, String message) {
outputError(throwable, message, Level.WARNING);
}
public static void outputError(Throwable throwable, String message, Level level) {
outputError(message, level);
throwable.printStackTrace(new PrintStream(System.out));
}
public static void outputInfo(String message) {
MinecraftServer.logger.info(LOGPREFIX + message);
}
/**
* Process any failed listeners that were queued due to being from another thread.
*/
public static void processFailureQueue() {
SimpleEntry<Throwable, IAPIListener> entry;
if (inInitThread()) {
while ((entry = failedListenerQueue.poll()) != null) {
reportListenerFailure(entry.getKey(), entry.getValue());
}
}
}
public static void reportListenerFailure(Throwable t, IAPIListener listener) {
// Queue the failure if it is coming from another thread.
if (!inInitThread()) {
failedListenerQueue.add(new SimpleEntry<Throwable, IAPIListener>(t, listener));
return;
}
processFailureQueue();
// Remove the listener from all APIs.
StatsAPI.removeListener(listener);
WorldAPI.removeListener(listener);
NetworkAPI.unregisterCustomChannels(listener);
PlayerAPI.removeListener(listener);
IMod mod = null;
String name = listener.getClass().getName();
boolean unloadSuccess = false;
try {
mod = listener.getMod();
if (mod != null) {
try {
name = mod.getName() + " (" + name + ")";
}
catch (Throwable e) { }
mod.unload();
unloadSuccess = true;
}
}
catch (Throwable e) { }
// TODO: alert server admins to failed mods.
outputError(t, name + " threw a " + t.getClass().getSimpleName() + (t.getMessage() == null ? "." : ": " + t.getMessage()), Level.SEVERE);
if (unloadSuccess)
outputError(name + " has been unloaded successfully.", Level.INFO);
else
outputError(name + " has been unloaded disabled as much as possible.", Level.SEVERE);
}
public static void reportCommandFailure(RuntimeException e, CommandBase command, IMod mod) {
String name = command.getClass().getName();
try {
name = mod.getName() + " (" + name + ")";
}
catch (Throwable ex) { }
// Unregister the command so it does not run again.
CommandsAPI.unregisterCommand(command);
outputError(e, name + " threw a " + e.getClass().getSimpleName() + (e.getMessage() == null ? "." : ": " + e.getMessage()), Level.SEVERE);
}
}
| false | true | public static void init() {
if (!hasInit) {
// Mark the current thread as the main one.
thread = Thread.currentThread();
outputInfo("Version " + VERSION + " initializing...");
// Attempt to get the URLClassLoader and its private addURL() method.
if (classLoader == null) {
classLoader = ModLoader.class.getClassLoader();
if (classLoader instanceof URLClassLoader) {
try {
classLoaderUrls.addAll(Arrays.asList(((URLClassLoader)classLoader).getURLs()));
classLoaderAddURLMethod = URLClassLoader.class.getDeclaredMethod("addURL", new Class[] { URL.class });
classLoaderAddURLMethod.setAccessible(true);
} catch (Throwable e) {
outputError(e, "Could not load mods from the class path (i.e. any mods directly in your minecraft_server.jar).");
}
}
// TODO: Can we use our own URLClassLoader instead?
}
StatsAPI.init();
try {
TranslationsAPI.init();
}
catch (Exception e) {
outputError(e, "TranslationsAPI failed (" + e.getClass().getSimpleName() + ") to load: " + e.getMessage(), Level.SEVERE);
outputError("Initialization aborted.", Level.SEVERE);
return;
}
try {
CommandsAPI.init();
}
catch (Exception e) {
outputError(e, "CommandsAPI failed (" + e.getClass().getSimpleName() + ") to load: " + e.getMessage(), Level.SEVERE);
outputError("Initialization aborted.", Level.SEVERE);
return;
}
findModsInClassPath();
findModsInFolder(new File(".", "btwmods"));
outputInfo("Initialization complete.");
}
hasInit = true;
}
| public static void init() {
if (!hasInit) {
// Mark the current thread as the main one.
thread = Thread.currentThread();
outputInfo("Version " + VERSION + " initializing...");
// Attempt to get the URLClassLoader and its private addURL() method.
if (classLoader == null) {
classLoader = ModLoader.class.getClassLoader();
if (classLoader instanceof URLClassLoader) {
try {
classLoaderUrls.addAll(Arrays.asList(((URLClassLoader)classLoader).getURLs()));
classLoaderAddURLMethod = URLClassLoader.class.getDeclaredMethod("addURL", new Class[] { URL.class });
classLoaderAddURLMethod.setAccessible(true);
} catch (Throwable e) {
outputError(e, "Could not load mods from the class path (i.e. any mods directly in your minecraft_server.jar).");
}
}
// TODO: Can we use our own URLClassLoader instead?
}
StatsAPI.init();
try {
TranslationsAPI.init();
}
catch (Exception e) {
outputError(e, "TranslationsAPI failed (" + e.getClass().getSimpleName() + ") to load: " + e.getMessage(), Level.SEVERE);
outputError("Initialization aborted.", Level.SEVERE);
hasInit = true;
return;
}
try {
CommandsAPI.init();
}
catch (Exception e) {
outputError(e, "CommandsAPI failed (" + e.getClass().getSimpleName() + ") to load: " + e.getMessage(), Level.SEVERE);
outputError("Initialization aborted.", Level.SEVERE);
hasInit = true;
return;
}
findModsInClassPath();
findModsInFolder(new File(".", "btwmods"));
outputInfo("Initialization complete.");
}
hasInit = true;
}
|
diff --git a/plugins/org.eclipse.birt.report.engine.emitter.html/src/org/eclipse/birt/report/engine/emitter/html/HTMLEmitter.java b/plugins/org.eclipse.birt.report.engine.emitter.html/src/org/eclipse/birt/report/engine/emitter/html/HTMLEmitter.java
index 258090f78..eb540070f 100644
--- a/plugins/org.eclipse.birt.report.engine.emitter.html/src/org/eclipse/birt/report/engine/emitter/html/HTMLEmitter.java
+++ b/plugins/org.eclipse.birt.report.engine.emitter.html/src/org/eclipse/birt/report/engine/emitter/html/HTMLEmitter.java
@@ -1,709 +1,709 @@
/*******************************************************************************
* 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.report.engine.emitter.html;
import java.util.Stack;
import org.eclipse.birt.report.engine.content.ICellContent;
import org.eclipse.birt.report.engine.content.IColumn;
import org.eclipse.birt.report.engine.content.IContainerContent;
import org.eclipse.birt.report.engine.content.IContent;
import org.eclipse.birt.report.engine.content.IForeignContent;
import org.eclipse.birt.report.engine.content.IImageContent;
import org.eclipse.birt.report.engine.content.IPageContent;
import org.eclipse.birt.report.engine.content.IRowContent;
import org.eclipse.birt.report.engine.content.IStyle;
import org.eclipse.birt.report.engine.content.ITableContent;
import org.eclipse.birt.report.engine.content.ITextContent;
import org.eclipse.birt.report.engine.emitter.HTMLTags;
import org.eclipse.birt.report.engine.emitter.HTMLWriter;
import org.eclipse.birt.report.engine.emitter.html.util.HTMLEmitterUtil;
import org.eclipse.birt.report.engine.ir.DimensionType;
import org.eclipse.birt.report.engine.ir.EngineIRConstants;
import org.w3c.dom.css.CSSValue;
/**
*
*/
public abstract class HTMLEmitter
{
protected HTMLReportEmitter reportEmitter;
protected HTMLWriter writer;
protected String layoutPreference;
/**
* The <code>containerDisplayStack</code> that stores the display value of container.
*/
protected Stack containerDisplayStack = new Stack( );
public HTMLEmitter( HTMLReportEmitter reportEmitter, HTMLWriter writer,
String layoutPreference )
{
this.reportEmitter = reportEmitter;
this.writer = writer;
this.layoutPreference = layoutPreference;
}
// FIXME: code review: We shouldn��t pass the style directly. We should pass
// the element and get the style form the element in the method.
public abstract void buildDefaultStyle( StringBuffer styleBuffer,
IStyle style );
public abstract void buildStyle( StringBuffer styleBuffer, IStyle style );
public abstract void buildPageBandStyle( StringBuffer styleBuffer,
IStyle style );
public abstract void buildTableStyle( ITableContent table,
StringBuffer styleBuffer );
public abstract void buildColumnStyle( IColumn column,
StringBuffer styleBuffer );
public abstract void handleColumnAlign( IColumn column );
public abstract void buildRowStyle( IRowContent row,
StringBuffer styleBuffer );
public abstract void handleRowAlign( IRowContent row );
public abstract void buildCellStyle( ICellContent cell,
StringBuffer styleBuffer, boolean isHead );
public abstract void handleCellAlign( ICellContent cell );
public abstract void buildContainerStyle( IContainerContent container,
StringBuffer styleBuffer );
public abstract void handleContainerAlign( IContainerContent container );
// FIXME: code review: Because the display has already been calculated in
// the HTMLReportEmitter, so we can build the display there too. We needn't
// pass the display here.
public abstract void buildTextStyle( ITextContent text,
StringBuffer styleBuffer, int display );
public abstract void buildForeignStyle( IForeignContent foreign,
StringBuffer styleBuffer, int display );
public abstract void buildImageStyle( IImageContent image,
StringBuffer styleBuffer, int display );
/**
* Build the style of the page
*/
public void buildPageStyle( IPageContent page, StringBuffer styleBuffer )
{
// The method getStyle( ) will nevel return a null value;
IStyle style = page.getStyle( );
AttributeBuilder.buildBackground( styleBuffer, style, reportEmitter );
}
/**
* Build size style string say, "width: 10.0mm;". The min-height should be
* implemented by sepcial way.
*
* @param content
* The <code>StringBuffer</code> to which the result is output.
* @param name
* The property name
* @param value
* The values of the property
*/
public void buildSize( StringBuffer content, String name,
DimensionType value )
{
if ( value != null )
{
if ( HTMLTags.ATTR_MIN_HEIGHT.equals( name ) )
{
//To solve the problem that IE do not support min-height.
//Use this way to make Firefox and IE both work well.
content.append( " height: auto !important; height: " );
content.append( value.toString( ) );
content.append( "; min-height: " );
content.append( value.toString( ) );
content.append( ';' );
}
else
{
content.append( ' ' );
content.append( name );
content.append( ": " );
content.append( value.toString( ) );
content.append( ';' );
}
}
}
protected IStyle getElementStyle( IContent content )
{
IStyle style = content.getInlineStyle( );
if ( style == null || style.isEmpty( ) )
{
return null;
}
return style;
}
// FIXME: code review: We should remove all the codes about the x and y.
// BIRT doesn't supoort the x and y now.
/**
* Checks whether the element is block, inline or inline-block level. In
* BIRT, the absolute positioning model is used and a box is explicitly
* offset with respect to its containing block. When an element's x or y is
* set, it will be treated as a block level element regardless of the
* 'Display' property set in style. When designating width or height value
* to an inline element, it will be treated as inline-block.
*
* @param x
* Specifies how far a box's left margin edge is offset to the
* right of the left edge of the box's containing block.
* @param y
* Specifies how far an absolutely positioned box's top margin
* edge is offset below the top edge of the box's containing
* block.
* @param width
* The width of the element.
* @param height
* The height of the element.
* @param style
* The <code>IStyle</code> object.
* @return The display type of the element.
*/
public CSSValue getElementDisplay( DimensionType x, DimensionType y,
DimensionType width, DimensionType height, IStyle style )
{
CSSValue display = null;
if ( style != null )
{
display = style.getProperty( IStyle.STYLE_DISPLAY );
}
if ( IStyle.NONE_VALUE == display )
{
return IStyle.NONE_VALUE;
}
if ( x != null || y != null )
{
return IStyle.BLOCK_VALUE;
}
else if( IStyle.INLINE_VALUE == display )
{
if ( width != null || height != null )
{
return IStyle.INLINE_BLOCK_VALUE;
}
else
{
return IStyle.INLINE_VALUE;
}
}
return IStyle.BLOCK_VALUE;
}
/**
* Checks whether the element is block, inline or inline-block level. In
* BIRT, the absolute positioning model is used and a box is explicitly
* offset with respect to its containing block. When an element's x or y is
* set, it will be treated as a block level element regardless of the
* 'Display' property set in style. When designating width or height value
* to an inline element, it will be treated as inline-block.
*
* @param x
* Specifies how far a box's left margin edge is offset to the
* right of the left edge of the box's containing block.
* @param y
* Specifies how far an absolutely positioned box's top margin
* edge is offset below the top edge of the box's containing
* block.
* @param width
* The width of the element.
* @param height
* The height of the element.
* @param style
* The <code>IStyle</code> object.
* @return The display type of the element.
*/
public int getElementType( DimensionType x, DimensionType y,
DimensionType width, DimensionType height, IStyle style )
{
int type = 0;
String display = null;
if ( style != null )
{
display = style.getDisplay( );
}
if ( EngineIRConstants.DISPLAY_NONE.equalsIgnoreCase( display ) )
{
type |= HTMLEmitterUtil.DISPLAY_NONE;
}
if ( x != null || y != null )
{
return type | HTMLEmitterUtil.DISPLAY_BLOCK;
}
else if ( EngineIRConstants.DISPLAY_INLINE.equalsIgnoreCase( display ) )
{
type |= HTMLEmitterUtil.DISPLAY_INLINE;
if ( width != null || height != null )
{
type |= HTMLEmitterUtil.DISPLAY_INLINE_BLOCK;
}
return type;
}
return type | HTMLEmitterUtil.DISPLAY_BLOCK;
}
/**
* Checks whether the element is block, inline or inline-block level. In
* BIRT, the absolute positioning model is used and a box is explicitly
* offset with respect to its containing block. When an element's x or y is
* set, it will be treated as a block level element regardless of the
* 'Display' property set in style. When designating width or height value
* to an inline element, it will be treated as inline-block.
*
* @param x
* Specifies how far a box's left margin edge is offset to the
* right of the left edge of the box's containing block.
* @param y
* Specifies how far an absolutely positioned box's top margin
* edge is offset below the top edge of the box's containing
* block.
* @param width
* The width of the element.
* @param height
* The height of the element.
* @param style
* The <code>IStyle</code> object.
* @return The display type of the element.
*/
public int getTextElementType( DimensionType x, DimensionType y,
DimensionType width, DimensionType height, IStyle style )
{
int type = 0;
String display = null;
if ( style != null )
{
display = style.getDisplay( );
}
if ( EngineIRConstants.DISPLAY_NONE.equalsIgnoreCase( display ) )
{
type |= HTMLEmitterUtil.DISPLAY_NONE;
}
if ( x != null || y != null )
{
return type | HTMLEmitterUtil.DISPLAY_BLOCK;
}
else if ( EngineIRConstants.DISPLAY_INLINE.equalsIgnoreCase( display ) )
{
type |= HTMLEmitterUtil.DISPLAY_INLINE;
//Inline text doesn't support height.
if ( width != null )
{
type |= HTMLEmitterUtil.DISPLAY_INLINE_BLOCK;
}
return type;
}
return type | HTMLEmitterUtil.DISPLAY_BLOCK;
}
/**
* adds the default table styles
*
* @param styleBuffer
*/
protected void addDefaultTableStyles( StringBuffer styleBuffer )
{
styleBuffer.append( "border-collapse: collapse; empty-cells: show;" ); //$NON-NLS-1$
}
/**
* Checks the 'CanShrink' property and sets the width and height according
* to the table below:
* <p>
* <table border=0 cellspacing=3 cellpadding=0 summary="Chart showing
* symbol, location, localized, and meaning.">
* <tr bgcolor="#ccccff">
* <th align=left>CanShrink</th>
* <th align=left>Element Type</th>
* <th align=left>Width</th>
* <th align=left>Height</th>
* </tr>
* <tr valign=middle>
* <td rowspan="2"><code>true(by default)</code></td>
* <td>in-line</td>
* <td>ignor</td>
* <td>set</td>
* </tr>
* <tr valign=top bgcolor="#eeeeff">
* <td><code>block</code></td>
* <td>set</td>
* <td>ignor</td>
* </tr>
* <tr valign=middle>
* <td rowspan="2" bgcolor="#eeeeff"><code>false</code></td>
* <td>in-line</td>
* <td>replaced by 'min-width' property</td>
* <td>set</td>
* </tr>
* <tr valign=top bgcolor="#eeeeff">
* <td><code>block</code></td>
* <td>set</td>
* <td>replaced by 'min-height' property</td>
* </tr>
* </table>
*
* @param type
* The display type of the element.
* @param style
* The style of an element.
* @param height
* The height property.
* @param width
* The width property.
* @param styleBuffer
* The <code>StringBuffer</code> object that returns 'style'
* content.
* @return A <code>boolean</code> value indicating 'Can-Shrink' property
* is set to <code>true</code> or not.
*/
// protected boolean handleShrink( CSSValue display, IStyle style,
// DimensionType height, DimensionType width, StringBuffer styleBuffer )
// {
// boolean canShrink = style != null
// && "true".equalsIgnoreCase( style.getCanShrink( ) ); //$NON-NLS-1$
//
// if ( IStyle.BLOCK_VALUE == display )
// {
// buildSize( styleBuffer, HTMLTags.ATTR_WIDTH, width );
// if ( !canShrink )
// {
// buildSize( styleBuffer, HTMLTags.ATTR_MIN_HEIGHT, height );
// }
// }
// else if ( IStyle.INLINE_VALUE == display
// || IStyle.INLINE_BLOCK_VALUE == display )
// {
// buildSize( styleBuffer, HTMLTags.ATTR_HEIGHT, height );
// if ( !canShrink )
// {
// buildSize( styleBuffer, HTMLTags.ATTR_MIN_WIDTH, width );
// }
// }
//
// return canShrink;
// }
/**
* Checks the 'CanShrink' property and sets the width and height according
* to the table below:
* <p>
* <table border=0 cellspacing=3 cellpadding=0 summary="Chart showing
* symbol, location, localized, and meaning.">
* <tr bgcolor="#ccccff">
* <th align=left>CanShrink</th>
* <th align=left>Element Type</th>
* <th align=left>Width</th>
* <th align=left>Height</th>
* </tr>
* <tr valign=middle>
* <td rowspan="2"><code>true(by default)</code></td>
* <td>in-line</td>
* <td>ignor</td>
* <td>set</td>
* </tr>
* <tr valign=top bgcolor="#eeeeff">
* <td><code>block</code></td>
* <td>set</td>
* <td>ignor</td>
* </tr>
* <tr valign=middle>
* <td rowspan="2" bgcolor="#eeeeff"><code>false</code></td>
* <td>in-line</td>
* <td>replaced by 'min-width' property</td>
* <td>set</td>
* </tr>
* <tr valign=top bgcolor="#eeeeff">
* <td><code>block</code></td>
* <td>set</td>
* <td>replaced by 'min-height' property</td>
* </tr>
* </table>
*
* @param type
* The display type of the element.
* @param style
* The style of an element.
* @param height
* The height property.
* @param width
* The width property.
* @param styleBuffer
* The <code>StringBuffer</code> object that returns 'style'
* content.
* @return A <code>boolean</code> value indicating 'Can-Shrink' property
* is set to <code>true</code> or not.
*/
protected boolean handleShrink( int type, IStyle style,
DimensionType height, DimensionType width, StringBuffer styleBuffer )
{
boolean canShrink = style != null
&& "true".equalsIgnoreCase( style.getCanShrink( ) ); //$NON-NLS-1$
if ( ( type & HTMLEmitterUtil.DISPLAY_BLOCK ) > 0 )
{
buildSize( styleBuffer, HTMLTags.ATTR_WIDTH, width );
if ( !canShrink )
{
buildSize( styleBuffer, HTMLTags.ATTR_MIN_HEIGHT, height );
}
}
else if ( ( type & HTMLEmitterUtil.DISPLAY_INLINE ) > 0 )
{
buildSize( styleBuffer, HTMLTags.ATTR_HEIGHT, height );
if ( !canShrink )
{
buildSize( styleBuffer, HTMLTags.ATTR_MIN_WIDTH, width );
}
}
else
{
assert false;
}
return canShrink;
}
/**
* Checks the 'CanShrink' property and sets the width and height according
* @param type
* The display type of the element.
* @param style
* The style of an element.
* @param height
* The height property.
* @param width
* The width property.
* @param styleBuffer
* The <code>StringBuffer</code> object that returns 'style'
* content.
* @return A <code>boolean</code> value indicating 'Can-Shrink' property
* is set to <code>true</code> or not.
*/
protected boolean handleTextShrink( int type, IStyle style,
DimensionType height, DimensionType width, StringBuffer styleBuffer )
{
boolean canShrink = style != null
&& "true".equalsIgnoreCase( style.getCanShrink( ) ); //$NON-NLS-1$
if ( ( type & HTMLEmitterUtil.DISPLAY_BLOCK ) > 0 )
{
buildSize( styleBuffer, HTMLTags.ATTR_WIDTH, width );
if ( !canShrink )
{
buildSize( styleBuffer, HTMLTags.ATTR_MIN_HEIGHT, height );
}
}
else if ( ( type & HTMLEmitterUtil.DISPLAY_INLINE ) > 0 )
{
//Inline text doesn't support height. Inline-block text supports height.
//The user can use line height to implement the height effect of inline text.
if ( ( type & HTMLEmitterUtil.DISPLAY_INLINE_BLOCK ) > 0 )
{
buildSize( styleBuffer, HTMLTags.ATTR_HEIGHT, height );
}
if ( !canShrink )
{
- buildSize( styleBuffer, HTMLTags.ATTR_MIN_WIDTH, width );
+ buildSize( styleBuffer, HTMLTags.ATTR_WIDTH, width );
}
}
else
{
assert false;
}
return canShrink;
}
// FIXME: code review: implement the openContainerTag and closeContainerTag
// in the HTMLReportEmitter directly.
/**
* Open the container tag.
*/
public void openContainerTag( IContainerContent container )
{
DimensionType x = container.getX( );
DimensionType y = container.getY( );
DimensionType width = container.getWidth( );
DimensionType height = container.getHeight( );
int display = getElementType( x, y, width, height, container.getStyle( ) );
// The display value is pushed in Stack. It will be popped when close the container tag.
containerDisplayStack.push( new Integer( display ) );
if ( ( ( display & HTMLEmitterUtil.DISPLAY_INLINE ) > 0 )
|| ( ( display & HTMLEmitterUtil.DISPLAY_INLINE_BLOCK ) > 0 ) )
{
// Open the inlineBox tag when implement the inline box.
openInlineBoxTag( );
//FIXME: code review: We should implement the shrink here.
}
writer.openTag( HTMLTags.TAG_DIV );
}
/**
* Close the container tag.
*/
public void closeContainerTag( )
{
writer.closeTag( HTMLTags.TAG_DIV );
int display = ( (Integer) containerDisplayStack.pop( ) ).intValue( );
if ( ( ( display & HTMLEmitterUtil.DISPLAY_INLINE ) > 0 )
|| ( ( display & HTMLEmitterUtil.DISPLAY_INLINE_BLOCK ) > 0 ) )
{
// Close the inlineBox tag when implement the inline box.
closeInlineBoxTag( );
}
}
/**
* Open the tag when implement the inline box.
*/
protected void openInlineBoxTag( )
{
writer.openTag( HTMLTags.TAG_DIV );
// For the IE the display value will be "inline", because the IE can't
// identify the "!important". For the Firefox 1.5 and 2 the display
// value will be "-moz-inline-box", because only the Firefox 3 implement
// the "inline-block". For the Firefox 3 the display value will be
// "inline-block".
writer.attribute( HTMLTags.ATTR_STYLE,
" display:-moz-inline-box !important; display:inline-block !important; display:inline;" );
writer.openTag( HTMLTags.TAG_TABLE );
writer.openTag( HTMLTags.TAG_TR );
writer.openTag( HTMLTags.TAG_TD );
}
/**
* Close the tag when implement the inline box.
*/
protected void closeInlineBoxTag( )
{
writer.closeTag( HTMLTags.TAG_TD );
writer.closeTag( HTMLTags.TAG_TR );
writer.closeTag( HTMLTags.TAG_TABLE );
writer.closeTag( HTMLTags.TAG_DIV );
}
/**
* Set the display property to style.
*
* @param display
* The display type.
* @param mask
* The mask.
* @param styleBuffer
* The <code>StringBuffer</code> object that returns 'style'
* content.
*/
protected void setDisplayProperty( int display, int mask,
StringBuffer styleBuffer )
{
int flag = display & mask;
if ( ( display & HTMLEmitterUtil.DISPLAY_NONE ) > 0 )
{
styleBuffer.append( "display: none;" ); //$NON-NLS-1$
}
else if ( flag > 0 )
{
if ( ( flag & HTMLEmitterUtil.DISPLAY_BLOCK ) > 0 )
{
styleBuffer.append( "display: block;" ); //$NON-NLS-1$
}
else if ( ( flag & HTMLEmitterUtil.DISPLAY_INLINE_BLOCK ) > 0 )
{
styleBuffer.append( "display: inline-block;" ); //$NON-NLS-1$
}
else if ( ( flag & HTMLEmitterUtil.DISPLAY_INLINE ) > 0 )
{
styleBuffer.append( "display: inline;" ); //$NON-NLS-1$
}
}
}
/**
* Open the vertical-align box tag if the element needs implementing the
* vertical-align.
*/
// FIXME: code review: Because only the text element and foreign element use
// this method, so the method name should be changed to
// handleTextVerticalAlignBegin
// FIXME: code review of text: Inline text doesn't need outputting the
// vertical-align. Block and inline-block texts need outputting the
// vertical-align.
public void handleVerticalAlignBegin( IContent element )
{
IStyle style = element.getStyle( );
CSSValue vAlign = style.getProperty( IStyle.STYLE_VERTICAL_ALIGN );
CSSValue canShrink = style.getProperty( IStyle.STYLE_CAN_SHRINK );
DimensionType height = element.getHeight( );
// FIXME: code review: the top value of the vAlign shouldn't be outptted too.
if ( vAlign != null
&& vAlign != IStyle.BASELINE_VALUE && height != null
&& canShrink != IStyle.TRUE_VALUE )
{
// implement vertical align.
writer.openTag( HTMLTags.TAG_TABLE );
StringBuffer nestingTableStyleBuffer = new StringBuffer( );
nestingTableStyleBuffer.append( " width:100%; height:" );
nestingTableStyleBuffer.append( height.toString( ) );
writer.attribute( HTMLTags.ATTR_STYLE,
nestingTableStyleBuffer.toString( ) );
writer.openTag( HTMLTags.TAG_TR );
writer.openTag( HTMLTags.TAG_TD );
StringBuffer textStyleBuffer = new StringBuffer( );
textStyleBuffer.append( " vertical-align:" );
textStyleBuffer.append( vAlign.getCssText( ) );
textStyleBuffer.append( ";" );
writer.attribute( HTMLTags.ATTR_STYLE, textStyleBuffer.toString( ) );
}
}
/**
* Close the vertical-align box tag if the element needs implementing the
* vertical-align.
*/
public void handleVerticalAlignEnd( IContent element )
{
IStyle style = element.getStyle( );
CSSValue vAlign = style.getProperty( IStyle.STYLE_VERTICAL_ALIGN );
CSSValue canShrink = style.getProperty( IStyle.STYLE_CAN_SHRINK );
DimensionType height = element.getHeight( );
if ( vAlign != null
&& vAlign != IStyle.BASELINE_VALUE && height != null
&& canShrink != IStyle.TRUE_VALUE )
{
writer.closeTag( HTMLTags.TAG_TD );
writer.closeTag( HTMLTags.TAG_TR );
writer.closeTag( HTMLTags.TAG_TABLE );
}
}
}
| true | true | protected boolean handleTextShrink( int type, IStyle style,
DimensionType height, DimensionType width, StringBuffer styleBuffer )
{
boolean canShrink = style != null
&& "true".equalsIgnoreCase( style.getCanShrink( ) ); //$NON-NLS-1$
if ( ( type & HTMLEmitterUtil.DISPLAY_BLOCK ) > 0 )
{
buildSize( styleBuffer, HTMLTags.ATTR_WIDTH, width );
if ( !canShrink )
{
buildSize( styleBuffer, HTMLTags.ATTR_MIN_HEIGHT, height );
}
}
else if ( ( type & HTMLEmitterUtil.DISPLAY_INLINE ) > 0 )
{
//Inline text doesn't support height. Inline-block text supports height.
//The user can use line height to implement the height effect of inline text.
if ( ( type & HTMLEmitterUtil.DISPLAY_INLINE_BLOCK ) > 0 )
{
buildSize( styleBuffer, HTMLTags.ATTR_HEIGHT, height );
}
if ( !canShrink )
{
buildSize( styleBuffer, HTMLTags.ATTR_MIN_WIDTH, width );
}
}
else
{
assert false;
}
return canShrink;
}
| protected boolean handleTextShrink( int type, IStyle style,
DimensionType height, DimensionType width, StringBuffer styleBuffer )
{
boolean canShrink = style != null
&& "true".equalsIgnoreCase( style.getCanShrink( ) ); //$NON-NLS-1$
if ( ( type & HTMLEmitterUtil.DISPLAY_BLOCK ) > 0 )
{
buildSize( styleBuffer, HTMLTags.ATTR_WIDTH, width );
if ( !canShrink )
{
buildSize( styleBuffer, HTMLTags.ATTR_MIN_HEIGHT, height );
}
}
else if ( ( type & HTMLEmitterUtil.DISPLAY_INLINE ) > 0 )
{
//Inline text doesn't support height. Inline-block text supports height.
//The user can use line height to implement the height effect of inline text.
if ( ( type & HTMLEmitterUtil.DISPLAY_INLINE_BLOCK ) > 0 )
{
buildSize( styleBuffer, HTMLTags.ATTR_HEIGHT, height );
}
if ( !canShrink )
{
buildSize( styleBuffer, HTMLTags.ATTR_WIDTH, width );
}
}
else
{
assert false;
}
return canShrink;
}
|
diff --git a/src/main/java/hudson/plugins/bazaar/BazaarChangeLogParser.java b/src/main/java/hudson/plugins/bazaar/BazaarChangeLogParser.java
index 7112124..8910625 100644
--- a/src/main/java/hudson/plugins/bazaar/BazaarChangeLogParser.java
+++ b/src/main/java/hudson/plugins/bazaar/BazaarChangeLogParser.java
@@ -1,172 +1,178 @@
package hudson.plugins.bazaar;
import hudson.model.AbstractBuild;
import hudson.scm.ChangeLogParser;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.logging.Logger;
/**
* Parses the output of bzr log.
*
* @author Trond Norbye
*/
public class BazaarChangeLogParser extends ChangeLogParser {
public BazaarChangeSetList parse(AbstractBuild build, File changelogFile) throws IOException {
ArrayList<BazaarChangeSet> entries = new ArrayList<BazaarChangeSet>();
BufferedReader in = new BufferedReader(new FileReader(changelogFile));
StringBuilder message = new StringBuilder();
String s;
BazaarChangeSet entry = null;
int state = 0;
int ident = 0;
while ((s = in.readLine()) != null) {
int nident = 0;
int len = s.length();
while (nident < len && s.charAt(nident) == ' ') {
++nident;
}
s = s.trim();
if ("------------------------------------------------------------".equals(s)) {
if (entry != null && state > 2) {
+ if (message.length() != 0) {
+ entry.setMsg(message.toString());
+ }
entries.add(entry);
}
entry = new BazaarChangeSet();
state = 0;
message.setLength(0);
ident = nident;
continue;
}
switch (state) {
case 0:
if (ident == nident && s.startsWith("revno:")) {
String rev = s.substring("revno:".length()).trim();
entry.setRevno(rev);
++state;
}
break;
case 1:
if (ident == nident && s.startsWith("revision-id:")) {
String rev = s.substring("revision-id:".length()).trim();
entry.setRevid(rev);
++state;
}
break;
case 2:
if (ident == nident && s.startsWith("committer:")) {
int endIndex = s.indexOf('<');
if (endIndex < 0) {
endIndex = len;
}
String author = s.substring("committer:".length(), endIndex).trim();
entry.setAuthor(author);
++state;
}
break;
case 3:
if (ident == nident && s.startsWith("timestamp:")) {
entry.setDate(s.substring("timestamp:".length()).trim());
++state;
}
break;
case 4:
if (!(ident == nident && s.startsWith("message:"))) {
if (ident == nident && (s.startsWith("modified:") || s.startsWith("added:") || s.startsWith("removed:") || s.startsWith("renamed:"))) {
if (s.startsWith("modified")) {
state = 5;
} else if (s.startsWith("added:")) {
state = 6;
} else if (s.startsWith("removed:")) {
state = 7;
} else if (s.startsWith("renamed:")){
- state = 8;
+ state = 8;
}
entry.setMsg(message.toString());
message.setLength(0);
} else {
message.append(s);
message.append("\n");
}
}
break;
case 5: // modified
if (s.startsWith("modified")) {
state = 5;
} else if (s.startsWith("added:")) {
state = 6;
} else if (s.startsWith("removed:")) {
state = 7;
} else if (s.startsWith("renamed:")){
- state = 8;
+ state = 8;
} else {
entry.getModifiedPaths().add(s);
}
break;
case 6: // added
if (s.startsWith("modified")) {
state = 5;
} else if (s.startsWith("added:")) {
state = 6;
} else if (s.startsWith("removed:")) {
state = 7;
} else if (s.startsWith("renamed:")){
- state = 8;
+ state = 8;
} else {
entry.getAddedPaths().add(s);
}
break;
case 7: // removed
if (s.startsWith("modified")) {
state = 5;
} else if (s.startsWith("added:")) {
state = 6;
} else if (s.startsWith("removed:")) {
state = 7;
} else if (s.startsWith("renamed:")){
- state = 8;
+ state = 8;
} else {
entry.getDeletedPaths().add(s);
}
break;
case 8: // renamed
if (s.startsWith("modified")) {
state = 5;
} else if (s.startsWith("added:")) {
state = 6;
} else if (s.startsWith("removed:")) {
state = 7;
} else if (s.startsWith("renamed:")){
- state = 8;
+ state = 8;
} else {
entry.getModifiedPaths().add(s);
}
break;
default: {
Logger logger = Logger.getLogger(BazaarChangeLogParser.class.getName());
logger.warning("Unknown parser state: " + state);
}
}
}
if (entry != null && state > 2) {
+ if (message.length() != 0) {
+ entry.setMsg(message.toString());
+ }
entries.add(entry);
}
return new BazaarChangeSetList(build, entries);
}
}
| false | true | public BazaarChangeSetList parse(AbstractBuild build, File changelogFile) throws IOException {
ArrayList<BazaarChangeSet> entries = new ArrayList<BazaarChangeSet>();
BufferedReader in = new BufferedReader(new FileReader(changelogFile));
StringBuilder message = new StringBuilder();
String s;
BazaarChangeSet entry = null;
int state = 0;
int ident = 0;
while ((s = in.readLine()) != null) {
int nident = 0;
int len = s.length();
while (nident < len && s.charAt(nident) == ' ') {
++nident;
}
s = s.trim();
if ("------------------------------------------------------------".equals(s)) {
if (entry != null && state > 2) {
entries.add(entry);
}
entry = new BazaarChangeSet();
state = 0;
message.setLength(0);
ident = nident;
continue;
}
switch (state) {
case 0:
if (ident == nident && s.startsWith("revno:")) {
String rev = s.substring("revno:".length()).trim();
entry.setRevno(rev);
++state;
}
break;
case 1:
if (ident == nident && s.startsWith("revision-id:")) {
String rev = s.substring("revision-id:".length()).trim();
entry.setRevid(rev);
++state;
}
break;
case 2:
if (ident == nident && s.startsWith("committer:")) {
int endIndex = s.indexOf('<');
if (endIndex < 0) {
endIndex = len;
}
String author = s.substring("committer:".length(), endIndex).trim();
entry.setAuthor(author);
++state;
}
break;
case 3:
if (ident == nident && s.startsWith("timestamp:")) {
entry.setDate(s.substring("timestamp:".length()).trim());
++state;
}
break;
case 4:
if (!(ident == nident && s.startsWith("message:"))) {
if (ident == nident && (s.startsWith("modified:") || s.startsWith("added:") || s.startsWith("removed:") || s.startsWith("renamed:"))) {
if (s.startsWith("modified")) {
state = 5;
} else if (s.startsWith("added:")) {
state = 6;
} else if (s.startsWith("removed:")) {
state = 7;
} else if (s.startsWith("renamed:")){
state = 8;
}
entry.setMsg(message.toString());
message.setLength(0);
} else {
message.append(s);
message.append("\n");
}
}
break;
case 5: // modified
if (s.startsWith("modified")) {
state = 5;
} else if (s.startsWith("added:")) {
state = 6;
} else if (s.startsWith("removed:")) {
state = 7;
} else if (s.startsWith("renamed:")){
state = 8;
} else {
entry.getModifiedPaths().add(s);
}
break;
case 6: // added
if (s.startsWith("modified")) {
state = 5;
} else if (s.startsWith("added:")) {
state = 6;
} else if (s.startsWith("removed:")) {
state = 7;
} else if (s.startsWith("renamed:")){
state = 8;
} else {
entry.getAddedPaths().add(s);
}
break;
case 7: // removed
if (s.startsWith("modified")) {
state = 5;
} else if (s.startsWith("added:")) {
state = 6;
} else if (s.startsWith("removed:")) {
state = 7;
} else if (s.startsWith("renamed:")){
state = 8;
} else {
entry.getDeletedPaths().add(s);
}
break;
case 8: // renamed
if (s.startsWith("modified")) {
state = 5;
} else if (s.startsWith("added:")) {
state = 6;
} else if (s.startsWith("removed:")) {
state = 7;
} else if (s.startsWith("renamed:")){
state = 8;
} else {
entry.getModifiedPaths().add(s);
}
break;
default: {
Logger logger = Logger.getLogger(BazaarChangeLogParser.class.getName());
logger.warning("Unknown parser state: " + state);
}
}
}
if (entry != null && state > 2) {
entries.add(entry);
}
return new BazaarChangeSetList(build, entries);
}
| public BazaarChangeSetList parse(AbstractBuild build, File changelogFile) throws IOException {
ArrayList<BazaarChangeSet> entries = new ArrayList<BazaarChangeSet>();
BufferedReader in = new BufferedReader(new FileReader(changelogFile));
StringBuilder message = new StringBuilder();
String s;
BazaarChangeSet entry = null;
int state = 0;
int ident = 0;
while ((s = in.readLine()) != null) {
int nident = 0;
int len = s.length();
while (nident < len && s.charAt(nident) == ' ') {
++nident;
}
s = s.trim();
if ("------------------------------------------------------------".equals(s)) {
if (entry != null && state > 2) {
if (message.length() != 0) {
entry.setMsg(message.toString());
}
entries.add(entry);
}
entry = new BazaarChangeSet();
state = 0;
message.setLength(0);
ident = nident;
continue;
}
switch (state) {
case 0:
if (ident == nident && s.startsWith("revno:")) {
String rev = s.substring("revno:".length()).trim();
entry.setRevno(rev);
++state;
}
break;
case 1:
if (ident == nident && s.startsWith("revision-id:")) {
String rev = s.substring("revision-id:".length()).trim();
entry.setRevid(rev);
++state;
}
break;
case 2:
if (ident == nident && s.startsWith("committer:")) {
int endIndex = s.indexOf('<');
if (endIndex < 0) {
endIndex = len;
}
String author = s.substring("committer:".length(), endIndex).trim();
entry.setAuthor(author);
++state;
}
break;
case 3:
if (ident == nident && s.startsWith("timestamp:")) {
entry.setDate(s.substring("timestamp:".length()).trim());
++state;
}
break;
case 4:
if (!(ident == nident && s.startsWith("message:"))) {
if (ident == nident && (s.startsWith("modified:") || s.startsWith("added:") || s.startsWith("removed:") || s.startsWith("renamed:"))) {
if (s.startsWith("modified")) {
state = 5;
} else if (s.startsWith("added:")) {
state = 6;
} else if (s.startsWith("removed:")) {
state = 7;
} else if (s.startsWith("renamed:")){
state = 8;
}
entry.setMsg(message.toString());
message.setLength(0);
} else {
message.append(s);
message.append("\n");
}
}
break;
case 5: // modified
if (s.startsWith("modified")) {
state = 5;
} else if (s.startsWith("added:")) {
state = 6;
} else if (s.startsWith("removed:")) {
state = 7;
} else if (s.startsWith("renamed:")){
state = 8;
} else {
entry.getModifiedPaths().add(s);
}
break;
case 6: // added
if (s.startsWith("modified")) {
state = 5;
} else if (s.startsWith("added:")) {
state = 6;
} else if (s.startsWith("removed:")) {
state = 7;
} else if (s.startsWith("renamed:")){
state = 8;
} else {
entry.getAddedPaths().add(s);
}
break;
case 7: // removed
if (s.startsWith("modified")) {
state = 5;
} else if (s.startsWith("added:")) {
state = 6;
} else if (s.startsWith("removed:")) {
state = 7;
} else if (s.startsWith("renamed:")){
state = 8;
} else {
entry.getDeletedPaths().add(s);
}
break;
case 8: // renamed
if (s.startsWith("modified")) {
state = 5;
} else if (s.startsWith("added:")) {
state = 6;
} else if (s.startsWith("removed:")) {
state = 7;
} else if (s.startsWith("renamed:")){
state = 8;
} else {
entry.getModifiedPaths().add(s);
}
break;
default: {
Logger logger = Logger.getLogger(BazaarChangeLogParser.class.getName());
logger.warning("Unknown parser state: " + state);
}
}
}
if (entry != null && state > 2) {
if (message.length() != 0) {
entry.setMsg(message.toString());
}
entries.add(entry);
}
return new BazaarChangeSetList(build, entries);
}
|
diff --git a/common/src/test/java/cz/incad/kramerius/security/impl/http/DbCurrentLoggedUser_ShibbLoggingTest.java b/common/src/test/java/cz/incad/kramerius/security/impl/http/DbCurrentLoggedUser_ShibbLoggingTest.java
index cf3a87c59..c2160a608 100644
--- a/common/src/test/java/cz/incad/kramerius/security/impl/http/DbCurrentLoggedUser_ShibbLoggingTest.java
+++ b/common/src/test/java/cz/incad/kramerius/security/impl/http/DbCurrentLoggedUser_ShibbLoggingTest.java
@@ -1,284 +1,285 @@
/*
* Copyright (C) 2010 Pavel Stastny
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package cz.incad.kramerius.security.impl.http;
import static org.easymock.EasyMock.createMockBuilder;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.logging.Level;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.easymock.EasyMock;
import org.easymock.IAnswer;
import org.junit.Assert;
import org.junit.Test;
import antlr.RecognitionException;
import antlr.TokenStreamException;
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Provides;
import com.google.inject.name.Named;
import cz.incad.kramerius.security.IsActionAllowed;
import cz.incad.kramerius.security.Role;
import cz.incad.kramerius.security.User;
import cz.incad.kramerius.security.UserManager;
import cz.incad.kramerius.security.impl.RoleImpl;
import cz.incad.kramerius.security.impl.UserImpl;
import cz.incad.kramerius.security.utils.UserUtils;
import cz.incad.kramerius.service.TextsService;
import cz.incad.kramerius.service.impl.TextsServiceImpl;
import cz.incad.kramerius.shib.utils.ShibbolethUtilsTest;
import cz.incad.kramerius.users.LoggedUsersSingleton;
import cz.incad.kramerius.users.UserProfileManager;
import cz.incad.kramerius.users.impl.UserProfileManagerImpl;
/**
* Tests shibboleth login
* @author pavels
*/
public class DbCurrentLoggedUser_ShibbLoggingTest {
static java.util.logging.Logger LOGGER = java.util.logging.Logger.getLogger(DbCurrentLoggedUser_ShibbLoggingTest.class.getName());
@Test
public void test() {
// expecting user
UserImpl user = new UserImpl(-1, "", "", "shibuser", 1);
Role role = new RoleImpl(1, "common_users", -1);
user.setGroups(new Role[] {role});
TestModule testModule = new TestModule(user);
Injector inj = Guice.createInjector(testModule);
DbCurrentLoggedUser dbCurUser = inj.getInstance(DbCurrentLoggedUser.class);
User gotUserFromMock = dbCurUser.get();
Assert.assertEquals(user, gotUserFromMock);
}
static class TestModule extends AbstractModule {
private User user;
private HashMap<String, Object> sessionStoreMap = new HashMap<String, Object>();
private TestModule(User user) {
super();
this.user = user;
}
public HashMap<String, Object> getSessionStoreMap() {
return sessionStoreMap;
}
@Override
protected void configure() {
try {
DbCurrentLoggedUser dbCurUser = createMockBuilder(DbCurrentLoggedUser.class)
.withConstructor()
// evaluate withnout shibrules
.addMockedMethod("evaluateShibRules")
// evaluate without save rights to session
.addMockedMethod("saveRightsIntoSession")
.createMock();
UserProfileManager userProfileManager = createMockBuilder(UserProfileManagerImpl.class)
.withConstructor()
// no profile
.addMockedMethod("getProfile")
.createMock();
dbCurUser.evaluateShibRules(user);
dbCurUser.saveRightsIntoSession(user);
EasyMock.replay(dbCurUser);
bind(TextsService.class).to(TextsServiceImpl.class);
bind(UserProfileManager.class).toInstance(userProfileManager);
bind(DbCurrentLoggedUser.class).toInstance(dbCurUser);
} catch (FileNotFoundException e) {
LOGGER.log(Level.SEVERE,e.getMessage(),e);
} catch (RecognitionException e) {
LOGGER.log(Level.SEVERE,e.getMessage(),e);
} catch (TokenStreamException e) {
LOGGER.log(Level.SEVERE,e.getMessage(),e);
} catch (IOException e) {
LOGGER.log(Level.SEVERE,e.getMessage(),e);
}
}
@Provides
@Named("kramerius4")
public Connection getConnection() {
Connection con = EasyMock.createMock(Connection.class);
EasyMock.replay(con);
return con;
}
@Provides
public LoggedUsersSingleton getLoggedUsersSingleton() {
LoggedUsersSingleton sing = EasyMock.createMock(LoggedUsersSingleton.class);
EasyMock.expect(sing.registerLoggedUser(this.user)).andReturn("0xAAA");
EasyMock.replay(sing);
return sing;
}
@Provides
public UserManager getUserManager() {
UserManager um = EasyMock.createMock(UserManager.class);
EasyMock.expect(um.findCommonUsersRole()).andReturn(new RoleImpl(1, "common_users", -1)).anyTimes();
EasyMock.replay(um);
return um;
}
@Provides
public IsActionAllowed getIsActionAllowed() {
IsActionAllowed all = EasyMock.createMock(IsActionAllowed.class);
EasyMock.replay(all);
return all;
}
@Provides
public HttpServletRequest getRequest() {
final Hashtable<String,String> table = ShibbolethUtilsTest.getLoggedShibTable();
HttpServletRequest request = EasyMock.createMock(HttpServletRequest.class);
EasyMock.expect(request.getHeaderNames()).andAnswer(new IAnswer<Enumeration>() {
@Override
public Enumeration answer() throws Throwable {
return table.keys();
}
}).anyTimes();
+ EasyMock.expect(request.getRemoteUser()).andReturn("user").anyTimes();
Enumeration<String> keys = table.keys();
while(keys.hasMoreElements()) {
final String k = keys.nextElement();
EasyMock.expect(request.getHeader(k)).andAnswer(new IAnswer<String>() {
@Override
public String answer() throws Throwable {
return table.get(k);
}
}).anyTimes();
}
final HttpSession session = EasyMock.createMock(HttpSession.class);
getSessionExpectation(request, session);
getSessionParamsExpectations(session);
setSessionParamsExpectations(session);
EasyMock.replay(request,session);
return request;
}
public void setSessionParamsExpectations(final HttpSession session) {
final User user = this.user;
session.setAttribute(UserUtils.LOGGED_USER_PARAM,this.user);
EasyMock.expectLastCall().andAnswer(new IAnswer<Object>() {
@Override
public Object answer() throws Throwable {
sessionStoreMap.put(UserUtils.LOGGED_USER_PARAM, user);
return null;
}
});
session.setAttribute(UserUtils.LOGGED_USER_KEY_PARAM,"0xAAA");
EasyMock.expectLastCall().andAnswer(new IAnswer<Object>() {
@Override
public Object answer() throws Throwable {
sessionStoreMap.put(UserUtils.LOGGED_USER_KEY_PARAM, "0xAAA");
return null;
}
});
session.setAttribute("SHIB_USER_KEY","true");
EasyMock.expectLastCall().andAnswer(new IAnswer<Object>() {
@Override
public Object answer() throws Throwable {
sessionStoreMap.put("SHIB_USER_KEY", "true");
return null;
}
});
}
public void getSessionParamsExpectations(final HttpSession session) {
EasyMock.expect(session.getAttribute(DbCurrentLoggedUser.SHIB_USER_KEY)).andAnswer(new IAnswer<String>() {
@Override
public String answer() throws Throwable {
return (String) sessionStoreMap.get(DbCurrentLoggedUser.SHIB_USER_KEY);
}
}).anyTimes();
EasyMock.expect(session.getAttribute("loggedUser")).andAnswer(new IAnswer<User>() {
@Override
public User answer() throws Throwable {
return (User) sessionStoreMap.get("loggedUser");
}
}).anyTimes();
EasyMock.expect(session.getAttribute("securityForRepository")).andAnswer(new IAnswer<String>() {
@Override
public String answer() throws Throwable {
return (String) sessionStoreMap.get("securityForRepository");
}
}).anyTimes();
}
public void getSessionExpectation(HttpServletRequest request, final HttpSession session) {
EasyMock.expect(request.getSession()).andAnswer(new IAnswer<HttpSession>() {
@Override
public HttpSession answer() throws Throwable {
return session;
}
}).anyTimes();
EasyMock.expect(request.getSession(true)).andAnswer(new IAnswer<HttpSession>() {
@Override
public HttpSession answer() throws Throwable {
return session;
}
}).anyTimes();
}
}
}
| true | true | public HttpServletRequest getRequest() {
final Hashtable<String,String> table = ShibbolethUtilsTest.getLoggedShibTable();
HttpServletRequest request = EasyMock.createMock(HttpServletRequest.class);
EasyMock.expect(request.getHeaderNames()).andAnswer(new IAnswer<Enumeration>() {
@Override
public Enumeration answer() throws Throwable {
return table.keys();
}
}).anyTimes();
Enumeration<String> keys = table.keys();
while(keys.hasMoreElements()) {
final String k = keys.nextElement();
EasyMock.expect(request.getHeader(k)).andAnswer(new IAnswer<String>() {
@Override
public String answer() throws Throwable {
return table.get(k);
}
}).anyTimes();
}
final HttpSession session = EasyMock.createMock(HttpSession.class);
getSessionExpectation(request, session);
getSessionParamsExpectations(session);
setSessionParamsExpectations(session);
EasyMock.replay(request,session);
return request;
}
| public HttpServletRequest getRequest() {
final Hashtable<String,String> table = ShibbolethUtilsTest.getLoggedShibTable();
HttpServletRequest request = EasyMock.createMock(HttpServletRequest.class);
EasyMock.expect(request.getHeaderNames()).andAnswer(new IAnswer<Enumeration>() {
@Override
public Enumeration answer() throws Throwable {
return table.keys();
}
}).anyTimes();
EasyMock.expect(request.getRemoteUser()).andReturn("user").anyTimes();
Enumeration<String> keys = table.keys();
while(keys.hasMoreElements()) {
final String k = keys.nextElement();
EasyMock.expect(request.getHeader(k)).andAnswer(new IAnswer<String>() {
@Override
public String answer() throws Throwable {
return table.get(k);
}
}).anyTimes();
}
final HttpSession session = EasyMock.createMock(HttpSession.class);
getSessionExpectation(request, session);
getSessionParamsExpectations(session);
setSessionParamsExpectations(session);
EasyMock.replay(request,session);
return request;
}
|
diff --git a/src/org/openjump/core/ui/plugin/queries/SimpleQueryPlugIn.java b/src/org/openjump/core/ui/plugin/queries/SimpleQueryPlugIn.java
index 3ef1beaf..cf02e952 100644
--- a/src/org/openjump/core/ui/plugin/queries/SimpleQueryPlugIn.java
+++ b/src/org/openjump/core/ui/plugin/queries/SimpleQueryPlugIn.java
@@ -1,45 +1,49 @@
package org.openjump.core.ui.plugin.queries;
import com.vividsolutions.jump.workbench.plugin.AbstractPlugIn;
import com.vividsolutions.jump.workbench.plugin.PlugInContext;
import com.vividsolutions.jump.workbench.ui.MenuNames;
import org.openjump.core.ui.plugin.queries.QueryDialog;
import com.vividsolutions.jump.I18N;
/**
* SimpleQueryPlugIn is a query editor and processor.
* It has the following capabilities :
* <OL><LI>query one or more layers</LI>
* <LI>attribute queries and spatial queries</LI>
* <LI>numerical and string functions</LI>
* <LI>regular expression to find strings</LI>
* <LI>results as a selection, a table or a new layer</LI></OL>
* Version 0.2 of the SimpleQueryPlugIn is an adaptation of the original
* version to the core of OpenJUMP (refactoring, internationalization)
* @author Michaël MICHAUD
* @version 0.2 (16 Oct 2005)
*/
public class SimpleQueryPlugIn extends AbstractPlugIn {
static QueryDialog queryDialog;
public void initialize(PlugInContext context) throws Exception {
context.getFeatureInstaller().addMainMenuItemWithJava14Fix(this,
new String[]{MenuNames.TOOLS, MenuNames.TOOLS_QUERIES},
this.getName() + "...", false, null, null);
}
public boolean execute(PlugInContext context) throws Exception {
if (queryDialog==null) {
queryDialog = new QueryDialog(context);
}
- else {queryDialog.setVisible(true);}
+ else {
+ queryDialog.setVisible(true);
+ // Refresh layer list in case the user switched to another project
+ queryDialog.initComboBoxes();
+ }
return false;
}
public String getName(){
return I18N.get("org.openjump.core.ui.plugin.queries.SimpleQuery.menuitem");
}
}
| true | true | public boolean execute(PlugInContext context) throws Exception {
if (queryDialog==null) {
queryDialog = new QueryDialog(context);
}
else {queryDialog.setVisible(true);}
return false;
}
| public boolean execute(PlugInContext context) throws Exception {
if (queryDialog==null) {
queryDialog = new QueryDialog(context);
}
else {
queryDialog.setVisible(true);
// Refresh layer list in case the user switched to another project
queryDialog.initComboBoxes();
}
return false;
}
|
diff --git a/Osmer/src/it/giacomos/android/osmer/locationUtils/GeocodeAddressTask.java b/Osmer/src/it/giacomos/android/osmer/locationUtils/GeocodeAddressTask.java
index 628f8e2..607b7c3 100644
--- a/Osmer/src/it/giacomos/android/osmer/locationUtils/GeocodeAddressTask.java
+++ b/Osmer/src/it/giacomos/android/osmer/locationUtils/GeocodeAddressTask.java
@@ -1,83 +1,85 @@
package it.giacomos.android.osmer.locationUtils;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import android.annotation.TargetApi;
import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Build;
import it.giacomos.android.osmer.locationUtils.LocationInfo;
public class GeocodeAddressTask extends AsyncTask<Location, Integer, LocationInfo>
{
public GeocodeAddressTask(Context ctx, GeocodeAddressUpdateListener listener)
{
mContext = ctx;
mUpdateListener = listener;
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public final AsyncTask<Location, Integer, LocationInfo> parallelExecute (Location... location)
{
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
{
return super.executeOnExecutor(THREAD_POOL_EXECUTOR, location);
}
else
{
return super.execute(location);
}
}
protected LocationInfo doInBackground(Location... location)
{
/* get new address and locality only if lat and long are different from those
* in previous location.
*/
LocationInfo locationInfo = new LocationInfo();
if(location[0] != null)
{
Geocoder geocoder = new Geocoder(mContext, Locale.getDefault());
try{
locationInfo.provider = location[0].getProvider();
locationInfo.accuracy = location[0].getAccuracy();
List<Address> listAddresses = geocoder.getFromLocation(location[0].getLatitude(), location[0].getLongitude(), 1);
- if(listAddresses != null && listAddresses.get(0) != null)
+ if(listAddresses != null
+ && listAddresses.size() > 0
+ && listAddresses.get(0) != null)
{
locationInfo.address = "";
locationInfo.locality = "";
for(int i = 0; i < listAddresses.get(0).getMaxAddressLineIndex() - 1; i++)
locationInfo.address += listAddresses.get(0).getAddressLine(0) + "\n";
locationInfo.locality = listAddresses.get(0).getLocality();
locationInfo.subLocality = listAddresses.get(0).getSubLocality();
if(locationInfo.locality == null)
locationInfo.locality = "";
if(locationInfo.subLocality == null)
locationInfo.subLocality = "";
}
}
catch (IOException e)
{
locationInfo.locality = "-";
locationInfo.error = e.getLocalizedMessage();
}
}
return locationInfo;
}
protected void onPostExecute(LocationInfo result)
{
mUpdateListener.onGeocodeAddressUpdate(result);
}
private Context mContext;
private GeocodeAddressUpdateListener mUpdateListener;
}
| true | true | protected LocationInfo doInBackground(Location... location)
{
/* get new address and locality only if lat and long are different from those
* in previous location.
*/
LocationInfo locationInfo = new LocationInfo();
if(location[0] != null)
{
Geocoder geocoder = new Geocoder(mContext, Locale.getDefault());
try{
locationInfo.provider = location[0].getProvider();
locationInfo.accuracy = location[0].getAccuracy();
List<Address> listAddresses = geocoder.getFromLocation(location[0].getLatitude(), location[0].getLongitude(), 1);
if(listAddresses != null && listAddresses.get(0) != null)
{
locationInfo.address = "";
locationInfo.locality = "";
for(int i = 0; i < listAddresses.get(0).getMaxAddressLineIndex() - 1; i++)
locationInfo.address += listAddresses.get(0).getAddressLine(0) + "\n";
locationInfo.locality = listAddresses.get(0).getLocality();
locationInfo.subLocality = listAddresses.get(0).getSubLocality();
if(locationInfo.locality == null)
locationInfo.locality = "";
if(locationInfo.subLocality == null)
locationInfo.subLocality = "";
}
}
catch (IOException e)
{
locationInfo.locality = "-";
locationInfo.error = e.getLocalizedMessage();
}
}
return locationInfo;
}
| protected LocationInfo doInBackground(Location... location)
{
/* get new address and locality only if lat and long are different from those
* in previous location.
*/
LocationInfo locationInfo = new LocationInfo();
if(location[0] != null)
{
Geocoder geocoder = new Geocoder(mContext, Locale.getDefault());
try{
locationInfo.provider = location[0].getProvider();
locationInfo.accuracy = location[0].getAccuracy();
List<Address> listAddresses = geocoder.getFromLocation(location[0].getLatitude(), location[0].getLongitude(), 1);
if(listAddresses != null
&& listAddresses.size() > 0
&& listAddresses.get(0) != null)
{
locationInfo.address = "";
locationInfo.locality = "";
for(int i = 0; i < listAddresses.get(0).getMaxAddressLineIndex() - 1; i++)
locationInfo.address += listAddresses.get(0).getAddressLine(0) + "\n";
locationInfo.locality = listAddresses.get(0).getLocality();
locationInfo.subLocality = listAddresses.get(0).getSubLocality();
if(locationInfo.locality == null)
locationInfo.locality = "";
if(locationInfo.subLocality == null)
locationInfo.subLocality = "";
}
}
catch (IOException e)
{
locationInfo.locality = "-";
locationInfo.error = e.getLocalizedMessage();
}
}
return locationInfo;
}
|
diff --git a/src/main/java/org/trancecode/xproc/Environment.java b/src/main/java/org/trancecode/xproc/Environment.java
index 71afbc2c..5cb559ee 100644
--- a/src/main/java/org/trancecode/xproc/Environment.java
+++ b/src/main/java/org/trancecode/xproc/Environment.java
@@ -1,665 +1,665 @@
/*
* Copyright (C) 2008 TranceCode Software
*
* 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
*
* $Id$
*/
package org.trancecode.xproc;
import org.trancecode.annotation.ReturnsNullable;
import org.trancecode.core.CollectionUtil;
import org.trancecode.xml.SaxonUtil;
import java.net.URI;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.Map;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import com.google.common.collect.Maps;
import net.sf.saxon.s9api.QName;
import net.sf.saxon.s9api.SaxonApiException;
import net.sf.saxon.s9api.XPathCompiler;
import net.sf.saxon.s9api.XPathSelector;
import net.sf.saxon.s9api.XdmAtomicValue;
import net.sf.saxon.s9api.XdmNode;
import net.sf.saxon.s9api.XdmValue;
import org.slf4j.ext.XLogger;
import org.slf4j.ext.XLoggerFactory;
/**
* @author Herve Quiroz
* @version $Revision$
*/
public class Environment
{
private static final XLogger LOG = XLoggerFactory.getXLogger(Environment.class);
private static final Map<QName, String> EMPTY_VARIABLES_MAP = Collections.emptyMap();
private static final Map<PortReference, EnvironmentPort> EMPTY_PORTS_MAP = Collections.emptyMap();
private static final Iterable<EnvironmentPort> EMPTY_PORTS_LIST = Collections.emptyList();
private static final Function<EnvironmentPort, PortReference> FUNCTION_GET_PORT_REFERENCE =
new Function<EnvironmentPort, PortReference>()
{
@Override
public PortReference apply(final EnvironmentPort environmentPort)
{
return environmentPort.getDeclaredPort().getPortReference();
}
};
private static final Predicate<Port> PREDICATE_HAS_PORT_BINDINGS = new Predicate<Port>()
{
@Override
public boolean apply(final Port port)
{
return !port.getPortBindings().isEmpty();
}
};
private final EnvironmentPort defaultReadablePort;
private final Map<QName, String> inheritedVariables;
private final Map<QName, String> localVariables;
private final Configuration configuration;
private final Map<PortReference, EnvironmentPort> ports;
private final Step pipeline;
private final EnvironmentPort defaultParametersPort;
private final EnvironmentPort xpathContextPort;
private static Map<PortReference, EnvironmentPort> getPortsMap(final Iterable<EnvironmentPort> ports)
{
return Maps.uniqueIndex(ports, FUNCTION_GET_PORT_REFERENCE);
}
public static Environment newEnvironment(final Step pipeline, final Configuration configuration)
{
return new Environment(pipeline, configuration, EMPTY_PORTS_LIST, null, null, null, EMPTY_VARIABLES_MAP,
EMPTY_VARIABLES_MAP);
}
private Environment(
final Step pipeline, final Configuration configuration, final Iterable<EnvironmentPort> ports,
final EnvironmentPort defaultReadablePort, final EnvironmentPort defaultParametersPort,
final EnvironmentPort xpathContextPort, final Map<QName, String> inheritedVariables,
final Map<QName, String> localVariables)
{
this(pipeline, configuration, getPortsMap(ports), defaultReadablePort, defaultParametersPort, xpathContextPort,
inheritedVariables, localVariables);
}
private Environment(
final Step pipeline, final Configuration configuration, final Map<PortReference, EnvironmentPort> ports,
final EnvironmentPort defaultReadablePort, final EnvironmentPort defaultParametersPort,
final EnvironmentPort xpathContextPort, final Map<QName, String> inheritedVariables,
final Map<QName, String> localVariables)
{
this.pipeline = pipeline;
this.configuration = configuration;
this.ports = ImmutableMap.copyOf(ports);
this.defaultReadablePort = defaultReadablePort;
this.defaultParametersPort = defaultParametersPort;
this.xpathContextPort = xpathContextPort;
this.inheritedVariables = ImmutableMap.copyOf(inheritedVariables);
this.localVariables = ImmutableMap.copyOf(localVariables);
}
private Environment setupStepEnvironment(final Step step)
{
LOG.trace("step = {}", step.getName());
return setupInputPorts(step).setPrimaryInputPortAsDefaultReadablePort(step).setXPathContextPort(step)
.setupVariables(step);
}
private Environment setupInputPorts(final Step step)
{
LOG.trace("step = {}", step.getName());
final Map<PortReference, EnvironmentPort> newPorts = Maps.newHashMap();
for (final Port port : step.getInputPorts())
{
newPorts.put(port.getPortReference(), EnvironmentPort.newEnvironmentPort(port, this));
}
for (final Port port : step.getOutputPorts())
{
if (port.portBindings.isEmpty())
{
newPorts.put(port.getPortReference(), EnvironmentPort.newEnvironmentPort(port, this));
}
}
return addPorts(newPorts);
}
public Environment setupOutputPorts(final Step step)
{
LOG.trace("step = {}", step.getName());
return setupOutputPorts(step, this);
}
public Environment setupOutputPorts(final Step step, final Environment sourceEnvironment)
{
LOG.trace("step = {}", step.getName());
final Map<PortReference, EnvironmentPort> newPorts = Maps.newHashMap();
for (final Port port : step.getOutputPorts())
{
if (!ports.containsKey(port.getPortReference()))
{
newPorts.put(port.getPortReference(), EnvironmentPort.newEnvironmentPort(port, sourceEnvironment));
}
}
return addPorts(newPorts).setPrimaryOutputPortAsDefaultReadablePort(step, sourceEnvironment);
}
private Environment setPrimaryInputPortAsDefaultReadablePort(final Step step)
{
LOG.trace("step = {} ; type = {}", step.getName(), step.getType());
final Port primaryInputPort = step.getPrimaryInputPort();
LOG.trace("primaryInputPort = {}", primaryInputPort);
if (primaryInputPort == null)
{
return this;
}
LOG.trace("new default readable port = {}", primaryInputPort);
// if port is empty then pipe to existing default readable port
final EnvironmentPort environmentPort = getEnvironmentPort(primaryInputPort);
final EnvironmentPort nonEmptyEnvironmentPort;
if (Iterables.isEmpty(environmentPort.portBindings) && getDefaultReadablePort() != null)
{
nonEmptyEnvironmentPort = environmentPort.pipe(getDefaultReadablePort());
}
else
{
nonEmptyEnvironmentPort = environmentPort;
}
return addPorts(nonEmptyEnvironmentPort).setDefaultReadablePort(nonEmptyEnvironmentPort);
}
private Environment setPrimaryOutputPortAsDefaultReadablePort(final Step step, final Environment sourceEnvironment)
{
LOG.trace("step = {}", step.getName());
final Port primaryOutputPort = step.getPrimaryOutputPort();
if (primaryOutputPort == null)
{
return this;
}
LOG.trace("new default readable port = {}", primaryOutputPort);
final EnvironmentPort environmentPort = getEnvironmentPort(primaryOutputPort);
final EnvironmentPort nonEmptyEnvironmentPort;
if (Iterables.isEmpty(environmentPort.portBindings))
{
nonEmptyEnvironmentPort = environmentPort.pipe(sourceEnvironment.getDefaultReadablePort());
}
else
{
nonEmptyEnvironmentPort = environmentPort;
}
return addPorts(nonEmptyEnvironmentPort).setDefaultReadablePort(nonEmptyEnvironmentPort);
}
private Environment setXPathContextPort(final Step step)
{
LOG.trace("step = {}", step.getName());
final Port xpathContextPort = step.getXPathContextPort();
if (xpathContextPort == null)
{
return this;
}
return setXPathContextPort(getEnvironmentPort(xpathContextPort));
}
private Environment setupVariables(final Step step)
{
LOG.trace("step = {}", step.getName());
final Map<QName, String> allVariables = Maps.newHashMap(inheritedVariables);
allVariables.putAll(localVariables);
final Map<QName, String> newLocalVariables = Maps.newHashMap(localVariables);
for (final Variable variable : step.getVariables())
{
final String value;
if (variable.getValue() != null)
{
value = variable.getValue();
}
else
{
value =
SaxonUtil.evaluateXPath(
variable.getSelect(), getConfiguration().getProcessor(), getXPathContextNode(), allVariables,
variable.getLocation()).toString();
}
LOG.trace("{} = {}", variable.getName(), value);
if (variable.isParameter())
{
final EnvironmentPort parametersPort = getDefaultParametersPort();
assert parametersPort != null;
final XdmNode parameterNode =
XProcUtil.newParameterElement(variable.getName(), value, getConfiguration().getProcessor());
parametersPort.writeNodes(parameterNode);
}
else
{
allVariables.put(variable.getName(), value);
newLocalVariables.put(variable.getName(), value);
}
}
return setLocalVariables(newLocalVariables);
}
public Environment newFollowingStepEnvironment(final Step step)
{
LOG.trace("step = {}", step.getName());
return newFollowingStepEnvironment().setupStepEnvironment(step);
}
public Environment newFollowingStepEnvironment()
{
return new Environment(pipeline, configuration, ports, defaultReadablePort, defaultParametersPort,
xpathContextPort, inheritedVariables, localVariables);
}
public Environment newChildStepEnvironment(final Step step)
{
LOG.trace("step = {}", step.getName());
return newChildStepEnvironment().setupStepEnvironment(step);
}
public Environment newChildStepEnvironment()
{
return new Environment(pipeline, configuration, ports, defaultReadablePort, defaultParametersPort,
xpathContextPort, CollectionUtil.merge(inheritedVariables, localVariables), EMPTY_VARIABLES_MAP);
}
public Environment setLocalVariables(final Map<QName, String> localVariables)
{
assert localVariables != null;
return new Environment(pipeline, configuration, ports, defaultReadablePort, defaultParametersPort,
xpathContextPort, inheritedVariables, CollectionUtil.merge(this.localVariables, localVariables));
}
public void setLocalVariable(final QName name, final String value)
{
localVariables.put(name, value);
}
public EnvironmentPort getDefaultReadablePort()
{
return defaultReadablePort;
}
public EnvironmentPort getXPathContextPort()
{
return xpathContextPort;
}
public Environment setXPathContextPort(final EnvironmentPort xpathContextPort)
{
assert xpathContextPort != null;
assert ports.containsValue(xpathContextPort);
return new Environment(pipeline, configuration, ports, defaultReadablePort, defaultParametersPort,
xpathContextPort, inheritedVariables, localVariables);
}
public Configuration getConfiguration()
{
return configuration;
}
public String getVariable(final QName name, final String defaultValue)
{
assert name != null;
LOG.trace("name = {} ; defaultValue = {}", name, defaultValue);
final String value = getVariable(name);
if (value != null)
{
return value;
}
return defaultValue;
}
public String getVariable(final QName name)
{
assert name != null;
LOG.trace("name = {}", name);
final String localValue = localVariables.get(name);
if (localValue != null)
{
return localValue;
}
return inheritedVariables.get(name);
}
public Environment setDefaultReadablePort(final EnvironmentPort defaultReadablePort)
{
assert defaultReadablePort != null;
assert ports.containsValue(defaultReadablePort);
LOG.trace("defaultReadablePort = {}", defaultReadablePort);
return new Environment(pipeline, configuration, ports, defaultReadablePort, defaultParametersPort,
xpathContextPort, inheritedVariables, localVariables);
}
public Environment setDefaultReadablePort(final String stepName, final String portName)
{
return setDefaultReadablePort(getPort(stepName, portName));
}
public Map<PortReference, EnvironmentPort> getPorts()
{
return ports;
}
public EnvironmentPort getEnvironmentPort(final Port port)
{
return getEnvironmentPort(port.getPortReference());
}
public EnvironmentPort getEnvironmentPort(final String stepName, final String portName)
{
return ports.get(new PortReference(stepName, portName));
}
private EnvironmentPort getEnvironmentPort(final PortReference portReference)
{
assert ports.containsKey(portReference) : "port = " + portReference + " ; ports = " + ports;
return ports.get(portReference);
}
public Environment addPorts(final EnvironmentPort... ports)
{
return addPorts(Arrays.asList(ports));
}
public Environment addPorts(final Iterable<EnvironmentPort> ports)
{
assert ports != null;
LOG.trace("ports = {}", ports);
final Map<PortReference, EnvironmentPort> newPorts = Maps.newHashMap(this.ports);
newPorts.putAll(getPortsMap(ports));
return new Environment(pipeline, configuration, newPorts, defaultReadablePort, defaultParametersPort,
xpathContextPort, inheritedVariables, localVariables);
}
public Environment addPorts(final Map<PortReference, EnvironmentPort> ports)
{
assert ports != null;
LOG.trace("ports = {}", ports);
return new Environment(pipeline, configuration, CollectionUtil.merge(this.ports, ports), defaultReadablePort,
defaultParametersPort, xpathContextPort, inheritedVariables, localVariables);
}
public EnvironmentPort addEnvironmentPort(final Port port)
{
LOG.entry(port);
assert port.getPortReference().equals(port.getPortReference());
assert !ports.containsKey(port.getPortReference());
final EnvironmentPort environmentPort = EnvironmentPort.newEnvironmentPort(port, this);
ports.put(port.getPortReference(), environmentPort);
return environmentPort;
}
public Step getPipeline()
{
return pipeline;
}
public URI getBaseUri()
{
return URI.create(pipeline.getLocation().getSystemId());
}
public EnvironmentPort getDefaultParametersPort()
{
return defaultParametersPort;
}
public Environment setDefaultParametersPort(final EnvironmentPort defaultParametersPort)
{
assert defaultParametersPort != null;
assert ports.containsValue(defaultParametersPort);
LOG.trace("defaultParametersPort = {}", defaultParametersPort);
return new Environment(pipeline, configuration, ports, defaultReadablePort, defaultParametersPort,
xpathContextPort, inheritedVariables, localVariables);
}
@ReturnsNullable
public XdmNode getXPathContextNode()
{
// TODO cache
final EnvironmentPort xpathContextPort = getXPathContextPort();
if (xpathContextPort != null)
{
final Iterator<XdmNode> contextNodes = xpathContextPort.readNodes().iterator();
if (!contextNodes.hasNext())
{
return null;
}
final XdmNode contextNode = contextNodes.next();
if (xpathContextPort.getDeclaredPort().getPortName().equals(XProcPorts.XPATH_CONTEXT))
{
// TODO XProc error
assert !contextNodes.hasNext();
}
return contextNode;
}
return null;
}
public XdmValue evaluateXPath(final String select)
{
assert select != null;
LOG.entry(select);
// TODO slow
final Map<QName, String> variables = CollectionUtil.merge(inheritedVariables, localVariables);
try
{
final XPathCompiler xpathCompiler = configuration.getProcessor().newXPathCompiler();
final String pipelineSystemId = getPipeline().getLocation().getSystemId();
if (pipelineSystemId != null)
{
xpathCompiler.setBaseURI(URI.create(pipelineSystemId));
}
for (final Map.Entry<QName, String> variableEntry : variables.entrySet())
{
if (variableEntry.getValue() != null)
{
xpathCompiler.declareVariable(variableEntry.getKey());
}
}
final XPathSelector selector = xpathCompiler.compile(select).load();
final XdmNode xpathContextNode = getXPathContextNode();
if (xpathContextNode != null)
{
LOG.trace("xpathContextNode = {}", xpathContextNode);
selector.setContextItem(xpathContextNode);
}
for (final Map.Entry<QName, String> variableEntry : variables.entrySet())
{
if (variableEntry.getValue() != null)
{
selector.setVariable(variableEntry.getKey(), new XdmAtomicValue(variableEntry.getValue()));
}
}
return selector.evaluate();
}
catch (final Exception e)
{
- throw new PipelineException(e, "error while evaluating XPath query: %s", select);
+ throw new IllegalStateException("error while evaluating XPath query: " + select, e);
}
}
private EnvironmentPort getPort(final PortReference portReference)
{
assert ports.containsKey(portReference) : "port = " + portReference.toString() + " ; ports = " + ports.keySet();
return ports.get(portReference);
}
private EnvironmentPort getPort(final String stepName, final String portName)
{
return getPort(new PortReference(stepName, portName));
}
public Environment writeNodes(final String stepName, final String portName, final XdmNode... nodes)
{
return writeNodes(stepName, portName, ImmutableList.of(nodes));
}
public Environment writeNodes(final String stepName, final String portName, final Iterable<XdmNode> nodes)
{
LOG.trace("stepName = {} ; portName = {}", stepName, portName);
return addPorts(getPort(stepName, portName).writeNodes(nodes));
}
public Iterable<XdmNode> readNodes(final String stepName, final String portName)
{
LOG.trace("stepName = {} ; portName = {}", stepName, portName);
final Iterable<XdmNode> nodes = getPort(stepName, portName).readNodes();
LOG.trace("nodes = {}", nodes);
return nodes;
}
public XdmNode readNode(final String stepName, final String portName)
{
return Iterables.getOnlyElement(getPort(stepName, portName).readNodes());
}
public Map<QName, String> readParameters(final String stepName, final String portName)
{
final Map<QName, String> parameters = CollectionUtil.newSmallWriteOnceMap();
for (final XdmNode parameterNode : readNodes(stepName, portName))
{
final XPathCompiler xpathCompiler = getConfiguration().getProcessor().newXPathCompiler();
try
{
final XPathSelector nameSelector = xpathCompiler.compile("string(//@name)").load();
nameSelector.setContextItem(parameterNode);
final String name = nameSelector.evaluateSingle().toString();
final XPathSelector valueSelector = xpathCompiler.compile("string(//@value)").load();
valueSelector.setContextItem(parameterNode);
final String value = valueSelector.evaluateSingle().toString();
// TODO name should be real QName
parameters.put(new QName(name), value);
}
catch (final SaxonApiException e)
{
throw new PipelineException(e);
}
}
return parameters;
}
}
| true | true | public XdmValue evaluateXPath(final String select)
{
assert select != null;
LOG.entry(select);
// TODO slow
final Map<QName, String> variables = CollectionUtil.merge(inheritedVariables, localVariables);
try
{
final XPathCompiler xpathCompiler = configuration.getProcessor().newXPathCompiler();
final String pipelineSystemId = getPipeline().getLocation().getSystemId();
if (pipelineSystemId != null)
{
xpathCompiler.setBaseURI(URI.create(pipelineSystemId));
}
for (final Map.Entry<QName, String> variableEntry : variables.entrySet())
{
if (variableEntry.getValue() != null)
{
xpathCompiler.declareVariable(variableEntry.getKey());
}
}
final XPathSelector selector = xpathCompiler.compile(select).load();
final XdmNode xpathContextNode = getXPathContextNode();
if (xpathContextNode != null)
{
LOG.trace("xpathContextNode = {}", xpathContextNode);
selector.setContextItem(xpathContextNode);
}
for (final Map.Entry<QName, String> variableEntry : variables.entrySet())
{
if (variableEntry.getValue() != null)
{
selector.setVariable(variableEntry.getKey(), new XdmAtomicValue(variableEntry.getValue()));
}
}
return selector.evaluate();
}
catch (final Exception e)
{
throw new PipelineException(e, "error while evaluating XPath query: %s", select);
}
}
| public XdmValue evaluateXPath(final String select)
{
assert select != null;
LOG.entry(select);
// TODO slow
final Map<QName, String> variables = CollectionUtil.merge(inheritedVariables, localVariables);
try
{
final XPathCompiler xpathCompiler = configuration.getProcessor().newXPathCompiler();
final String pipelineSystemId = getPipeline().getLocation().getSystemId();
if (pipelineSystemId != null)
{
xpathCompiler.setBaseURI(URI.create(pipelineSystemId));
}
for (final Map.Entry<QName, String> variableEntry : variables.entrySet())
{
if (variableEntry.getValue() != null)
{
xpathCompiler.declareVariable(variableEntry.getKey());
}
}
final XPathSelector selector = xpathCompiler.compile(select).load();
final XdmNode xpathContextNode = getXPathContextNode();
if (xpathContextNode != null)
{
LOG.trace("xpathContextNode = {}", xpathContextNode);
selector.setContextItem(xpathContextNode);
}
for (final Map.Entry<QName, String> variableEntry : variables.entrySet())
{
if (variableEntry.getValue() != null)
{
selector.setVariable(variableEntry.getKey(), new XdmAtomicValue(variableEntry.getValue()));
}
}
return selector.evaluate();
}
catch (final Exception e)
{
throw new IllegalStateException("error while evaluating XPath query: " + select, e);
}
}
|
diff --git a/src/main/java/org/cloudifysource/quality/iTests/test/cli/cloudify/cloud/openstack/examples/OpenstackDistributedAvailabilityZonesTest.java b/src/main/java/org/cloudifysource/quality/iTests/test/cli/cloudify/cloud/openstack/examples/OpenstackDistributedAvailabilityZonesTest.java
index 5d740fc8..4ba70a8a 100644
--- a/src/main/java/org/cloudifysource/quality/iTests/test/cli/cloudify/cloud/openstack/examples/OpenstackDistributedAvailabilityZonesTest.java
+++ b/src/main/java/org/cloudifysource/quality/iTests/test/cli/cloudify/cloud/openstack/examples/OpenstackDistributedAvailabilityZonesTest.java
@@ -1,99 +1,98 @@
package org.cloudifysource.quality.iTests.test.cli.cloudify.cloud.openstack.examples;
import java.io.IOException;
import java.util.List;
import org.cloudifysource.esc.driver.provisioning.CloudProvisioningException;
import org.cloudifysource.esc.driver.provisioning.ComputeDriverConfiguration;
import org.cloudifysource.esc.driver.provisioning.openstack.OpenStackCloudifyDriver;
import org.cloudifysource.esc.driver.provisioning.openstack.OpenStackComputeClient;
import org.cloudifysource.esc.driver.provisioning.openstack.OpenstackException;
import org.cloudifysource.esc.driver.provisioning.openstack.rest.NovaServer;
import org.cloudifysource.quality.iTests.test.AbstractTestSupport;
import org.cloudifysource.quality.iTests.test.cli.cloudify.CommandTestUtils;
import org.cloudifysource.quality.iTests.test.cli.cloudify.cloud.AbstractExamplesTest;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
/**
* install a service with 4 instances on the HP cloud.
* The 4 agent machines started must start in different availability zones.
*
* @author adaml
*
*/
public class OpenstackDistributedAvailabilityZonesTest extends AbstractExamplesTest {
private static final String AGENT_MACHINE_SUFFIX = "agent";
private static final String AGENT_MACHINE_PREFIX = "openstackdistribute";
private static final String SERVICE_PATH = CommandTestUtils.getPath("/src/main/resources/apps/USM/usm/simpleAZ");
private static final String SERVICE_NAME = "simpleAZ";
private OpenStackCloudifyDriver openstackCloudDriver;
@BeforeClass(alwaysRun = true)
protected void bootstrap() throws Exception {
super.bootstrap();
}
@Override
protected String getCloudName() {
return "hp-grizzly";
}
@Test(timeOut = AbstractTestSupport.DEFAULT_TEST_TIMEOUT * 4, enabled = false)
public void testDistributedAvailabilityZones() throws IOException, InterruptedException, OpenstackException, CloudProvisioningException {
//we create an instance of the cloud driver so we could query it regarding its availability zones
initCloudDriver();
// install a simple service with 4 instances.
installServiceAndWait(SERVICE_PATH, SERVICE_NAME);
//assert the 4 agent machines started in different availability zones
assertServersAZ();
}
private void assertServersAZ() throws OpenstackException {
List<NovaServer> servers = ((OpenStackComputeClient) openstackCloudDriver.getComputeContext()).getServers();
- assertTrue("Expecting 4 agent machines got " + servers.size(), servers.size() == 4);
int az1 = 0;
int az2 = 0;
int az3 = 0;
for (NovaServer novaServer : servers) {
String serverName = novaServer.getName();
if (serverName.contains(AGENT_MACHINE_PREFIX) && serverName.contains(AGENT_MACHINE_SUFFIX)) {
// this is an agent machine.
final String availabilityZone = novaServer.getAvailabilityZone();
if (availabilityZone.equals("az1")) {
az1 = az1 + 1;
}
if (availabilityZone.equals("az2")) {
az2 = az2 + 1;
}
if (availabilityZone.equals("az3")) {
az3 = az3 + 1;
}
}
}
assertTrue("Expecting 2 machines in az1", az1 == 2);
assertTrue("Expecting 1 machines in az2", az2 == 1);
assertTrue("Expecting 1 machines in az3", az3 == 1);
}
private void initCloudDriver() throws CloudProvisioningException {
openstackCloudDriver = new OpenStackCloudifyDriver();
ComputeDriverConfiguration conf = new ComputeDriverConfiguration();
conf.setCloud(getService().getCloud());
conf.setServiceName("default." + SERVICE_NAME);
conf.setCloudTemplate("SMALL_LINUX");
openstackCloudDriver.setConfig(conf);
}
@AfterClass(alwaysRun = true)
protected void teardown() throws Exception {
super.teardown();
}
}
| true | true | private void assertServersAZ() throws OpenstackException {
List<NovaServer> servers = ((OpenStackComputeClient) openstackCloudDriver.getComputeContext()).getServers();
assertTrue("Expecting 4 agent machines got " + servers.size(), servers.size() == 4);
int az1 = 0;
int az2 = 0;
int az3 = 0;
for (NovaServer novaServer : servers) {
String serverName = novaServer.getName();
if (serverName.contains(AGENT_MACHINE_PREFIX) && serverName.contains(AGENT_MACHINE_SUFFIX)) {
// this is an agent machine.
final String availabilityZone = novaServer.getAvailabilityZone();
if (availabilityZone.equals("az1")) {
az1 = az1 + 1;
}
if (availabilityZone.equals("az2")) {
az2 = az2 + 1;
}
if (availabilityZone.equals("az3")) {
az3 = az3 + 1;
}
}
}
assertTrue("Expecting 2 machines in az1", az1 == 2);
assertTrue("Expecting 1 machines in az2", az2 == 1);
assertTrue("Expecting 1 machines in az3", az3 == 1);
}
| private void assertServersAZ() throws OpenstackException {
List<NovaServer> servers = ((OpenStackComputeClient) openstackCloudDriver.getComputeContext()).getServers();
int az1 = 0;
int az2 = 0;
int az3 = 0;
for (NovaServer novaServer : servers) {
String serverName = novaServer.getName();
if (serverName.contains(AGENT_MACHINE_PREFIX) && serverName.contains(AGENT_MACHINE_SUFFIX)) {
// this is an agent machine.
final String availabilityZone = novaServer.getAvailabilityZone();
if (availabilityZone.equals("az1")) {
az1 = az1 + 1;
}
if (availabilityZone.equals("az2")) {
az2 = az2 + 1;
}
if (availabilityZone.equals("az3")) {
az3 = az3 + 1;
}
}
}
assertTrue("Expecting 2 machines in az1", az1 == 2);
assertTrue("Expecting 1 machines in az2", az2 == 1);
assertTrue("Expecting 1 machines in az3", az3 == 1);
}
|
diff --git a/ProviGenTests/src/com/tjeannin/provigen/test/basis/SimpleContentProviderTest.java b/ProviGenTests/src/com/tjeannin/provigen/test/basis/SimpleContentProviderTest.java
index 53510d2..1858843 100644
--- a/ProviGenTests/src/com/tjeannin/provigen/test/basis/SimpleContentProviderTest.java
+++ b/ProviGenTests/src/com/tjeannin/provigen/test/basis/SimpleContentProviderTest.java
@@ -1,91 +1,91 @@
package com.tjeannin.provigen.test.basis;
import java.util.Arrays;
import java.util.List;
import android.database.Cursor;
import android.net.Uri;
import android.test.mock.MockContentResolver;
import com.tjeannin.provigen.InvalidContractException;
import com.tjeannin.provigen.test.ExtendedProviderTestCase;
import com.tjeannin.provigen.test.basis.SimpleContentProvider.ContractOne;
import com.tjeannin.provigen.test.basis.SimpleContentProvider.ContractTwo;
public class SimpleContentProviderTest extends ExtendedProviderTestCase<SimpleContentProvider> {
private MockContentResolver contentResolver;
public SimpleContentProviderTest() {
super(SimpleContentProvider.class, "com.test.simple");
}
@Override
protected void setUp() throws Exception {
super.setUp();
contentResolver = getMockContentResolver();
}
public void testProviderIsEmpty() {
Cursor cursor = contentResolver.query(ContractOne.CONTENT_URI, null,
"", null, "");
assertEquals(0, cursor.getCount());
cursor.close();
}
public void testInsert() {
contentResolver.insert(ContractOne.CONTENT_URI, getContentValues(ContractOne.class));
Cursor cursor = contentResolver.query(ContractOne.CONTENT_URI, null, "", null, "");
assertEquals(1, cursor.getCount());
cursor.close();
}
public void testAutoIncrement() {
contentResolver.insert(ContractOne.CONTENT_URI, getContentValues(ContractOne.class));
contentResolver.insert(ContractOne.CONTENT_URI, getContentValues(ContractOne.class));
contentResolver.insert(ContractOne.CONTENT_URI, getContentValues(ContractOne.class));
contentResolver.delete(Uri.withAppendedPath(ContractOne.CONTENT_URI, String.valueOf(3)), "", null);
contentResolver.insert(ContractOne.CONTENT_URI, getContentValues(ContractOne.class));
assertEquals(1, getRowCount(Uri.withAppendedPath(ContractOne.CONTENT_URI, String.valueOf(4))));
assertEquals(0, getRowCount(Uri.withAppendedPath(ContractOne.CONTENT_URI, String.valueOf(3))));
}
public void testUpgradeFromContractOneToTwo() throws InvalidContractException {
getProvider().setContractClasses(new Class[] { ContractOne.class });
contentResolver.insert(ContractOne.CONTENT_URI, getContentValues(ContractOne.class));
// Check database fits ContractOne.
Cursor cursor = contentResolver.query(ContractOne.CONTENT_URI, null, "", null, "");
assertEquals(2, cursor.getColumnCount());
List<String> columnNameList = Arrays.asList(cursor.getColumnNames());
assertTrue(columnNameList.contains(ContractOne._ID));
assertTrue(columnNameList.contains(ContractOne.MY_INT));
assertFalse(columnNameList.contains(ContractTwo.MY_REAL));
assertFalse(columnNameList.contains(ContractTwo.MY_STRING));
cursor.close();
getProvider().setContractClasses(new Class[] { ContractTwo.class });
// Check database fits ContractTwo.
- cursor = contentResolver.query(ContractOne.CONTENT_URI, null, "", null, "");
- assertEquals(2, cursor.getColumnCount());
+ cursor = contentResolver.query(ContractTwo.CONTENT_URI, null, "", null, "");
+ assertEquals(4, cursor.getColumnCount());
columnNameList = Arrays.asList(cursor.getColumnNames());
- assertTrue(columnNameList.contains(ContractOne._ID));
- assertTrue(columnNameList.contains(ContractOne.MY_INT));
- assertFalse(columnNameList.contains(ContractTwo.MY_REAL));
- assertFalse(columnNameList.contains(ContractTwo.MY_STRING));
+ assertTrue(columnNameList.contains(ContractTwo._ID));
+ assertTrue(columnNameList.contains(ContractTwo.MY_INT));
+ assertTrue(columnNameList.contains(ContractTwo.MY_REAL));
+ assertTrue(columnNameList.contains(ContractTwo.MY_STRING));
cursor.close();
}
public void testGetMimeType() {
String mimeType = getProvider().getType(ContractOne.CONTENT_URI);
assertEquals("vnd.android.cursor.dir/vdn.table_name_simple", mimeType);
}
}
| false | true | public void testUpgradeFromContractOneToTwo() throws InvalidContractException {
getProvider().setContractClasses(new Class[] { ContractOne.class });
contentResolver.insert(ContractOne.CONTENT_URI, getContentValues(ContractOne.class));
// Check database fits ContractOne.
Cursor cursor = contentResolver.query(ContractOne.CONTENT_URI, null, "", null, "");
assertEquals(2, cursor.getColumnCount());
List<String> columnNameList = Arrays.asList(cursor.getColumnNames());
assertTrue(columnNameList.contains(ContractOne._ID));
assertTrue(columnNameList.contains(ContractOne.MY_INT));
assertFalse(columnNameList.contains(ContractTwo.MY_REAL));
assertFalse(columnNameList.contains(ContractTwo.MY_STRING));
cursor.close();
getProvider().setContractClasses(new Class[] { ContractTwo.class });
// Check database fits ContractTwo.
cursor = contentResolver.query(ContractOne.CONTENT_URI, null, "", null, "");
assertEquals(2, cursor.getColumnCount());
columnNameList = Arrays.asList(cursor.getColumnNames());
assertTrue(columnNameList.contains(ContractOne._ID));
assertTrue(columnNameList.contains(ContractOne.MY_INT));
assertFalse(columnNameList.contains(ContractTwo.MY_REAL));
assertFalse(columnNameList.contains(ContractTwo.MY_STRING));
cursor.close();
}
| public void testUpgradeFromContractOneToTwo() throws InvalidContractException {
getProvider().setContractClasses(new Class[] { ContractOne.class });
contentResolver.insert(ContractOne.CONTENT_URI, getContentValues(ContractOne.class));
// Check database fits ContractOne.
Cursor cursor = contentResolver.query(ContractOne.CONTENT_URI, null, "", null, "");
assertEquals(2, cursor.getColumnCount());
List<String> columnNameList = Arrays.asList(cursor.getColumnNames());
assertTrue(columnNameList.contains(ContractOne._ID));
assertTrue(columnNameList.contains(ContractOne.MY_INT));
assertFalse(columnNameList.contains(ContractTwo.MY_REAL));
assertFalse(columnNameList.contains(ContractTwo.MY_STRING));
cursor.close();
getProvider().setContractClasses(new Class[] { ContractTwo.class });
// Check database fits ContractTwo.
cursor = contentResolver.query(ContractTwo.CONTENT_URI, null, "", null, "");
assertEquals(4, cursor.getColumnCount());
columnNameList = Arrays.asList(cursor.getColumnNames());
assertTrue(columnNameList.contains(ContractTwo._ID));
assertTrue(columnNameList.contains(ContractTwo.MY_INT));
assertTrue(columnNameList.contains(ContractTwo.MY_REAL));
assertTrue(columnNameList.contains(ContractTwo.MY_STRING));
cursor.close();
}
|
diff --git a/asterix-external-data/src/main/java/edu/uci/ics/asterix/external/dataset/adapter/NCFileSystemAdapter.java b/asterix-external-data/src/main/java/edu/uci/ics/asterix/external/dataset/adapter/NCFileSystemAdapter.java
index ae9b412e..ef39d454 100644
--- a/asterix-external-data/src/main/java/edu/uci/ics/asterix/external/dataset/adapter/NCFileSystemAdapter.java
+++ b/asterix-external-data/src/main/java/edu/uci/ics/asterix/external/dataset/adapter/NCFileSystemAdapter.java
@@ -1,111 +1,115 @@
/*
* Copyright 2009-2012 by The Regents of the University of California
* 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 from
*
* 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 edu.uci.ics.asterix.external.dataset.adapter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import edu.uci.ics.asterix.common.exceptions.AsterixException;
import edu.uci.ics.asterix.om.types.IAType;
import edu.uci.ics.hyracks.algebricks.common.constraints.AlgebricksAbsolutePartitionConstraint;
import edu.uci.ics.hyracks.algebricks.common.constraints.AlgebricksPartitionConstraint;
import edu.uci.ics.hyracks.api.context.IHyracksTaskContext;
import edu.uci.ics.hyracks.api.io.FileReference;
import edu.uci.ics.hyracks.dataflow.std.file.FileSplit;
/**
* Factory class for creating an instance of NCFileSystemAdapter. An
* NCFileSystemAdapter reads external data residing on the local file system of
* an NC.
*/
public class NCFileSystemAdapter extends FileSystemBasedAdapter {
private static final long serialVersionUID = 1L;
private FileSplit[] fileSplits;
public NCFileSystemAdapter(IAType atype) {
super(atype);
}
@Override
public void configure(Map<String, String> arguments) throws Exception {
this.configuration = arguments;
String[] splits = arguments.get(KEY_PATH).split(",");
configureFileSplits(splits);
configureFormat();
}
@Override
public void initialize(IHyracksTaskContext ctx) throws Exception {
this.ctx = ctx;
}
@Override
public AdapterType getAdapterType() {
return AdapterType.READ;
}
- private void configureFileSplits(String[] splits) {
+ private void configureFileSplits(String[] splits) throws AsterixException {
if (fileSplits == null) {
fileSplits = new FileSplit[splits.length];
String nodeName;
String nodeLocalPath;
int count = 0;
String trimmedValue;
for (String splitPath : splits) {
trimmedValue = splitPath.trim();
+ if (!trimmedValue.contains("://")) {
+ throw new AsterixException("Invalid path: " + splitPath
+ + "\nUsage- path=\"Host://Absolute File Path\"");
+ }
nodeName = trimmedValue.split(":")[0];
nodeLocalPath = trimmedValue.split("://")[1];
FileSplit fileSplit = new FileSplit(nodeName, new FileReference(new File(nodeLocalPath)));
fileSplits[count++] = fileSplit;
}
}
}
private void configurePartitionConstraint() throws AsterixException {
String[] locs = new String[fileSplits.length];
String location;
for (int i = 0; i < fileSplits.length; i++) {
location = getNodeResolver().resolveNode(fileSplits[i].getNodeName());
locs[i] = location;
}
partitionConstraint = new AlgebricksAbsolutePartitionConstraint(locs);
}
@Override
public InputStream getInputStream(int partition) throws IOException {
FileSplit split = fileSplits[partition];
File inputFile = split.getLocalFile().getFile();
InputStream in;
try {
in = new FileInputStream(inputFile);
return in;
} catch (FileNotFoundException e) {
throw new IOException(e);
}
}
@Override
public AlgebricksPartitionConstraint getPartitionConstraint() throws Exception {
if (partitionConstraint == null) {
configurePartitionConstraint();
}
return partitionConstraint;
}
}
| false | true | private void configureFileSplits(String[] splits) {
if (fileSplits == null) {
fileSplits = new FileSplit[splits.length];
String nodeName;
String nodeLocalPath;
int count = 0;
String trimmedValue;
for (String splitPath : splits) {
trimmedValue = splitPath.trim();
nodeName = trimmedValue.split(":")[0];
nodeLocalPath = trimmedValue.split("://")[1];
FileSplit fileSplit = new FileSplit(nodeName, new FileReference(new File(nodeLocalPath)));
fileSplits[count++] = fileSplit;
}
}
}
| private void configureFileSplits(String[] splits) throws AsterixException {
if (fileSplits == null) {
fileSplits = new FileSplit[splits.length];
String nodeName;
String nodeLocalPath;
int count = 0;
String trimmedValue;
for (String splitPath : splits) {
trimmedValue = splitPath.trim();
if (!trimmedValue.contains("://")) {
throw new AsterixException("Invalid path: " + splitPath
+ "\nUsage- path=\"Host://Absolute File Path\"");
}
nodeName = trimmedValue.split(":")[0];
nodeLocalPath = trimmedValue.split("://")[1];
FileSplit fileSplit = new FileSplit(nodeName, new FileReference(new File(nodeLocalPath)));
fileSplits[count++] = fileSplit;
}
}
}
|
diff --git a/Essentials/src/com/earth2me/essentials/AlternativeCommandsHandler.java b/Essentials/src/com/earth2me/essentials/AlternativeCommandsHandler.java
index 583401a5..5fc2e23d 100644
--- a/Essentials/src/com/earth2me/essentials/AlternativeCommandsHandler.java
+++ b/Essentials/src/com/earth2me/essentials/AlternativeCommandsHandler.java
@@ -1,113 +1,117 @@
package com.earth2me.essentials;
import java.util.*;
import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.PluginCommand;
import org.bukkit.command.PluginCommandYamlParser;
import org.bukkit.plugin.Plugin;
public class AlternativeCommandsHandler
{
private final transient Map<String, List<PluginCommand>> altcommands = new HashMap<String, List<PluginCommand>>();
private final transient IEssentials ess;
public AlternativeCommandsHandler(final IEssentials ess)
{
this.ess = ess;
for (Plugin plugin : ess.getServer().getPluginManager().getPlugins())
{
if (plugin.isEnabled()) {
addPlugin(plugin);
}
}
}
public final void addPlugin(final Plugin plugin)
{
if (plugin.getDescription().getMain().contains("com.earth2me.essentials"))
{
return;
}
final List<Command> commands = PluginCommandYamlParser.parse(plugin);
final String pluginName = plugin.getDescription().getName().toLowerCase(Locale.ENGLISH);
for (Command command : commands)
{
final PluginCommand pc = (PluginCommand)command;
final List<String> labels = new ArrayList<String>(pc.getAliases());
labels.add(pc.getName());
PluginCommand reg = ess.getServer().getPluginCommand(pluginName + ":" + pc.getName().toLowerCase(Locale.ENGLISH));
if (reg == null)
{
- reg = Bukkit.getServer().getPluginCommand(pc.getName().toLowerCase(Locale.ENGLISH));
+ reg = ess.getServer().getPluginCommand(pc.getName().toLowerCase(Locale.ENGLISH));
+ }
+ if (reg == null)
+ {
+ continue;
}
for (String label : labels)
{
List<PluginCommand> plugincommands = altcommands.get(label.toLowerCase(Locale.ENGLISH));
if (plugincommands == null)
{
plugincommands = new ArrayList<PluginCommand>();
altcommands.put(label.toLowerCase(Locale.ENGLISH), plugincommands);
}
boolean found = false;
for (PluginCommand pc2 : plugincommands)
{
if (pc2.getPlugin().equals(plugin))
{
found = true;
}
}
if (!found)
{
plugincommands.add(reg);
}
}
}
}
public void removePlugin(final Plugin plugin)
{
final Iterator<Map.Entry<String, List<PluginCommand>>> iterator = altcommands.entrySet().iterator();
while (iterator.hasNext())
{
final Map.Entry<String, List<PluginCommand>> entry = iterator.next();
final Iterator<PluginCommand> pcIterator = entry.getValue().iterator();
while (pcIterator.hasNext())
{
final PluginCommand pc = pcIterator.next();
if (pc.getPlugin() == null || pc.getPlugin().equals(plugin))
{
pcIterator.remove();
}
}
if (entry.getValue().isEmpty())
{
iterator.remove();
}
}
}
public PluginCommand getAlternative(final String label)
{
final List<PluginCommand> commands = altcommands.get(label);
if (commands == null || commands.isEmpty())
{
return null;
}
if (commands.size() == 1)
{
return commands.get(0);
}
// return the first command that is not an alias
for (PluginCommand command : commands) {
if (command.getName().equalsIgnoreCase(label)) {
return command;
}
}
// return the first alias
return commands.get(0);
}
}
| true | true | public final void addPlugin(final Plugin plugin)
{
if (plugin.getDescription().getMain().contains("com.earth2me.essentials"))
{
return;
}
final List<Command> commands = PluginCommandYamlParser.parse(plugin);
final String pluginName = plugin.getDescription().getName().toLowerCase(Locale.ENGLISH);
for (Command command : commands)
{
final PluginCommand pc = (PluginCommand)command;
final List<String> labels = new ArrayList<String>(pc.getAliases());
labels.add(pc.getName());
PluginCommand reg = ess.getServer().getPluginCommand(pluginName + ":" + pc.getName().toLowerCase(Locale.ENGLISH));
if (reg == null)
{
reg = Bukkit.getServer().getPluginCommand(pc.getName().toLowerCase(Locale.ENGLISH));
}
for (String label : labels)
{
List<PluginCommand> plugincommands = altcommands.get(label.toLowerCase(Locale.ENGLISH));
if (plugincommands == null)
{
plugincommands = new ArrayList<PluginCommand>();
altcommands.put(label.toLowerCase(Locale.ENGLISH), plugincommands);
}
boolean found = false;
for (PluginCommand pc2 : plugincommands)
{
if (pc2.getPlugin().equals(plugin))
{
found = true;
}
}
if (!found)
{
plugincommands.add(reg);
}
}
}
}
| public final void addPlugin(final Plugin plugin)
{
if (plugin.getDescription().getMain().contains("com.earth2me.essentials"))
{
return;
}
final List<Command> commands = PluginCommandYamlParser.parse(plugin);
final String pluginName = plugin.getDescription().getName().toLowerCase(Locale.ENGLISH);
for (Command command : commands)
{
final PluginCommand pc = (PluginCommand)command;
final List<String> labels = new ArrayList<String>(pc.getAliases());
labels.add(pc.getName());
PluginCommand reg = ess.getServer().getPluginCommand(pluginName + ":" + pc.getName().toLowerCase(Locale.ENGLISH));
if (reg == null)
{
reg = ess.getServer().getPluginCommand(pc.getName().toLowerCase(Locale.ENGLISH));
}
if (reg == null)
{
continue;
}
for (String label : labels)
{
List<PluginCommand> plugincommands = altcommands.get(label.toLowerCase(Locale.ENGLISH));
if (plugincommands == null)
{
plugincommands = new ArrayList<PluginCommand>();
altcommands.put(label.toLowerCase(Locale.ENGLISH), plugincommands);
}
boolean found = false;
for (PluginCommand pc2 : plugincommands)
{
if (pc2.getPlugin().equals(plugin))
{
found = true;
}
}
if (!found)
{
plugincommands.add(reg);
}
}
}
}
|
diff --git a/modules/org.pathvisio.core/src/org/pathvisio/core/model/MGroup.java b/modules/org.pathvisio.core/src/org/pathvisio/core/model/MGroup.java
index ba78133e..ee508836 100644
--- a/modules/org.pathvisio.core/src/org/pathvisio/core/model/MGroup.java
+++ b/modules/org.pathvisio.core/src/org/pathvisio/core/model/MGroup.java
@@ -1,181 +1,181 @@
// PathVisio,
// a tool for data visualization and analysis using Biological Pathways
// Copyright 2006-2009 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 org.pathvisio.core.model;
import java.awt.geom.Rectangle2D;
import java.util.HashSet;
import java.util.Set;
/**
* Group specific implementation of methods that calculate derived
* coordinates that are not stored in GPML directly
* @author thomas
*/
public class MGroup extends PathwayElement {
protected MGroup() {
super(ObjectType.GROUP);
}
/**
* Center x of the group bounds
*/
public double getMCenterX() {
return getMBounds().getCenterX();
}
/**
* Center y of the group bounds
*/
public double getMCenterY() {
return getMBounds().getCenterY();
}
/**
* Height of the group bounds
*/
public double getMHeight() {
return getMBounds().getHeight();
}
/**
* Left of the group bounds
*/
public double getMLeft() {
return getMBounds().getX();
}
/**
* Top of the group bounds
*/
public double getMTop() {
return getMBounds().getY();
}
/**
* Width of the group bounds
*/
public double getMWidth() {
return getMBounds().getWidth();
}
public void setMCenterX(double v) {
double d = v - getMBounds().getCenterX();
for(PathwayElement e : getGroupElements()) {
e.setMCenterX(e.getMCenterX() + d);
}
}
public void setMCenterY(double v) {
double d = v - getMBounds().getCenterY();
for(PathwayElement e : getGroupElements()) {
e.setMCenterY(e.getMCenterY() + d);
}
}
public void setMHeight(double v) {
double d = v - getMBounds().getHeight();
for(PathwayElement e : getGroupElements()) {
e.setMHeight(e.getMHeight() + d);
}
}
public void setMWidth(double v) {
double d = v - getMBounds().getWidth();
for(PathwayElement e : getGroupElements()) {
e.setMWidth(e.getMWidth() + d);
}
}
public void setMLeft(double v) {
double d = v - getMBounds().getX();
for(PathwayElement e : getGroupElements()) {
e.setMLeft(e.getMLeft() + d);
}
}
public void setMTop(double v) {
double d = v - getMBounds().getY();
for(PathwayElement e : getGroupElements()) {
e.setMTop(e.getMTop() + d);
}
}
/**
* Iterates over all group elements to find
* the total rectangular bounds.
* Note: doesn't include rotation of the nested elements.
* If you want to include rotation, use {@link #getRBounds()} instead.
*/
public Rectangle2D getMBounds() {
Rectangle2D bounds = null;
for(PathwayElement e : getGroupElements()) {
if(e == this) continue; //To prevent recursion error
if(bounds == null) bounds = e.getMBounds();
else bounds.add(e.getMBounds());
}
if(bounds != null) {
- double margin = groupStyle.getMMargin();
+ double margin = getGroupStyle().getMMargin();
return new Rectangle2D.Double(
bounds.getX() - margin,
bounds.getY() - margin,
bounds.getWidth() + 2*margin,
bounds.getHeight() + 2*margin
);
} else {
return new Rectangle2D.Double();
}
}
/**
* Iterates over all group elements to find
* the total rectangular bounds, taking into
* account rotation of the nested elements
*/
public Rectangle2D getRBounds() {
Rectangle2D bounds = null;
for(PathwayElement e : getGroupElements()) {
if(e == this) continue; //To prevent recursion error
if(bounds == null) bounds = e.getRBounds();
else bounds.add(e.getRBounds());
}
if(bounds != null) {
double margin = groupStyle.getMMargin();
return new Rectangle2D.Double(
bounds.getX() - margin,
bounds.getY() - margin,
bounds.getWidth() + 2 * margin,
bounds.getHeight() + 2 * margin
);
} else {
return new Rectangle2D.Double();
}
}
/**
* Get the group elements. Convenience method that
* checks for a valid parent and never returns
* null
*/
private Set<PathwayElement> getGroupElements() {
Set<PathwayElement> result = new HashSet<PathwayElement>();
Pathway parent = getParent();
if(parent != null) {
result = parent.getGroupElements(getGroupId());
}
return result;
}
}
| true | true | public Rectangle2D getMBounds() {
Rectangle2D bounds = null;
for(PathwayElement e : getGroupElements()) {
if(e == this) continue; //To prevent recursion error
if(bounds == null) bounds = e.getMBounds();
else bounds.add(e.getMBounds());
}
if(bounds != null) {
double margin = groupStyle.getMMargin();
return new Rectangle2D.Double(
bounds.getX() - margin,
bounds.getY() - margin,
bounds.getWidth() + 2*margin,
bounds.getHeight() + 2*margin
);
} else {
return new Rectangle2D.Double();
}
}
| public Rectangle2D getMBounds() {
Rectangle2D bounds = null;
for(PathwayElement e : getGroupElements()) {
if(e == this) continue; //To prevent recursion error
if(bounds == null) bounds = e.getMBounds();
else bounds.add(e.getMBounds());
}
if(bounds != null) {
double margin = getGroupStyle().getMMargin();
return new Rectangle2D.Double(
bounds.getX() - margin,
bounds.getY() - margin,
bounds.getWidth() + 2*margin,
bounds.getHeight() + 2*margin
);
} else {
return new Rectangle2D.Double();
}
}
|
diff --git a/src/org/jacorb/idl/UnionType.java b/src/org/jacorb/idl/UnionType.java
index 14070453..91e08652 100644
--- a/src/org/jacorb/idl/UnionType.java
+++ b/src/org/jacorb/idl/UnionType.java
@@ -1,1179 +1,1179 @@
package org.jacorb.idl;
/*
* JacORB - a free Java ORB
*
* Copyright (C) 1997-2002 Gerald Brose.
*
* 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., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.PrintWriter;
import java.util.*;
class UnionType
extends TypeDeclaration
implements Scope
{
/** the union's discriminator's type spec */
TypeSpec switch_type_spec;
SwitchBody switch_body;
boolean written = false;
private ScopeData scopeData;
private boolean allCasesCovered = false;
private boolean switch_is_enum = false;
private boolean switch_is_bool = false;
private boolean switch_is_longlong = false;
private boolean explicit_default_case = false;
private int labels;
public UnionType( int num )
{
super( num );
pack_name = "";
}
public Object clone()
{
UnionType ut = new UnionType( new_num() );
ut.switch_type_spec = this.switch_type_spec;
ut.switch_body = switch_body;
ut.pack_name = this.pack_name;
ut.name = this.name;
ut.written = this.written;
ut.scopeData = this.scopeData;
ut.enclosing_symbol = this.enclosing_symbol;
ut.token = this.token;
return ut;
}
public void setScopeData( ScopeData data )
{
scopeData = data;
}
public ScopeData getScopeData()
{
return scopeData;
}
public TypeDeclaration declaration()
{
return this;
}
public void setEnclosingSymbol( IdlSymbol s )
{
if( enclosing_symbol != null && enclosing_symbol != s )
throw new RuntimeException( "Compiler Error: trying to reassign container for " + name );
enclosing_symbol = s;
if (switch_body != null)
{
switch_body.setEnclosingSymbol( s );
}
}
public String typeName()
{
if( typeName == null )
setPrintPhaseNames();
return typeName;
}
public String className()
{
String fullName = typeName();
if( fullName.indexOf( '.' ) > 0 )
{
return fullName.substring( fullName.lastIndexOf( '.' ) + 1 );
}
else
{
return fullName;
}
}
public String printReadExpression( String Streamname )
{
return typeName() + "Helper.read(" + Streamname + ")";
}
public String printWriteStatement( String var_name, String streamname )
{
return typeName() + "Helper.write(" + streamname + "," + var_name + ");";
}
public String holderName()
{
return typeName() + "Holder";
}
public void set_included( boolean i )
{
included = i;
}
public void setSwitchType( TypeSpec s )
{
switch_type_spec = s;
}
public void setSwitchBody( SwitchBody sb )
{
switch_body = sb;
}
public void setPackage( String s )
{
s = parser.pack_replace( s );
if( pack_name.length() > 0 )
{
pack_name = new String( s + "." + pack_name);
}
else
{
pack_name = s;
}
if (switch_type_spec != null)
{
switch_type_spec.setPackage (s);
}
if (switch_body != null)
{
switch_body.setPackage( s );
}
}
public boolean basic()
{
return false;
}
public void parse()
{
boolean justAnotherOne = false;
escapeName();
ConstrTypeSpec ctspec = new ConstrTypeSpec( new_num() );
try
{
ScopedName.definePseudoScope( full_name() );
ctspec.c_type_spec = this;
NameTable.define( full_name(), "type-union" );
TypeMap.typedef( full_name(), ctspec );
}
catch (NameAlreadyDefined nad)
{
if (parser.get_pending (full_name ()) != null)
{
if (switch_type_spec == null )
{
justAnotherOne = true;
}
// else actual definition
if( !full_name().equals( "org.omg.CORBA.TypeCode" ) && switch_type_spec != null )
{
TypeMap.replaceForwardDeclaration( full_name(), ctspec );
}
}
else
{
Environment.output( 4, nad );
parser.error( "Union " + full_name() + " already defined", token );
}
}
if (switch_type_spec != null)
{
// Resolve scoped names and aliases
TypeSpec ts;
if( switch_type_spec.type_spec instanceof ScopedName )
{
ts = ( (ScopedName)switch_type_spec.type_spec ).resolvedTypeSpec();
while( ts instanceof ScopedName || ts instanceof AliasTypeSpec )
{
if( ts instanceof ScopedName )
{
ts = ( (ScopedName)ts ).resolvedTypeSpec();
}
else
{
ts = ( (AliasTypeSpec)ts ).originalType();
}
}
addImportedName( switch_type_spec.typeName() );
}
else
{
ts = switch_type_spec.type_spec;
}
// Check if we have a valid discriminator type
if
( !(
( ( ts instanceof SwitchTypeSpec ) &&
( ( (SwitchTypeSpec)ts ).isSwitchable() ) )
||
( ( ts instanceof BaseType ) &&
( ( (BaseType)ts ).isSwitchType() ) )
||
( ( ts instanceof ConstrTypeSpec ) &&
( ( (ConstrTypeSpec)ts ).c_type_spec instanceof EnumType ) )
) )
{
parser.error( "Illegal Switch Type: " + ts.typeName(), token );
}
switch_type_spec.parse();
switch_body.setTypeSpec( switch_type_spec );
switch_body.setUnion( this );
ScopedName.addRecursionScope( typeName() );
switch_body.parse();
ScopedName.removeRecursionScope( typeName() );
// Fixup array typing
for( Enumeration e = switch_body.caseListVector.elements(); e.hasMoreElements(); )
{
Case c = (Case)e.nextElement();
c.element_spec.t = getElementType( c.element_spec );
}
NameTable.parsed_interfaces.put( full_name(), "" );
parser.remove_pending( full_name() );
}
else if( !justAnotherOne )
{
// i am forward declared, must set myself as
// pending further parsing
parser.set_pending( full_name() );
}
}
/**
* @returns a string for an expression of type TypeCode that
* describes this type
*/
public String getTypeCodeExpression()
{
return typeName() + "Helper.type()";
}
public String getTypeCodeExpression( Set knownTypes )
{
if( knownTypes.contains( this ) )
{
return this.getRecursiveTypeCodeExpression();
}
else
{
return this.getTypeCodeExpression();
}
}
private void printClassComment( String className, PrintWriter ps )
{
ps.println( "/**" );
ps.println( " *\tGenerated from IDL definition of union " +
"\"" + className + "\"" );
ps.println( " *\t@author JacORB IDL compiler " );
ps.println( " */\n" );
}
public void printUnionClass( String className, PrintWriter pw )
{
if( !pack_name.equals( "" ) )
pw.println( "package " + pack_name + ";" );
printImport( pw );
printClassComment( className, pw );
pw.println( "public" + parser.getFinalString() + " class " + className );
pw.println( "\timplements org.omg.CORBA.portable.IDLEntity" );
pw.println( "{" );
TypeSpec ts = switch_type_spec.typeSpec();
while( ts instanceof ScopedName || ts instanceof AliasTypeSpec )
{
if( ts instanceof ScopedName )
ts = ( (ScopedName)ts ).resolvedTypeSpec();
if( ts instanceof AliasTypeSpec )
ts = ( (AliasTypeSpec)ts ).originalType();
}
pw.println( "\tprivate " + ts.typeName() + " discriminator;" );
/* find a "default" value */
String defaultStr = "";
/* start by concatenating all case label lists into one list
* (this list is used only for finding a default)
*/
int def = 0;
java.util.Vector allCaseLabels = new java.util.Vector();
for( Enumeration e = switch_body.caseListVector.elements(); e.hasMoreElements(); )
{
Case c = (Case)e.nextElement();
for( int i = 0; i < c.case_label_list.v.size(); i++ )
{
labels++; // the overall number of labels is needed in a number of places...
Object ce = c.case_label_list.v.elementAt( i );
if( ce != null )
{
if( ce instanceof ConstExpr )
{
allCaseLabels.addElement( ( (ConstExpr)ce ).value() );
}
else
{
allCaseLabels.addElement( ( (ScopedName)ce ).resolvedName() ); // this is a scoped name
Environment.output( 4, "Adding " + ( (ScopedName)ce ).resolvedName() + " case labels." );
}
}
else
{
def = 1;
explicit_default_case = true;
}
}
}
/* if switch type is an enum, the default is null */
if( ( ts instanceof ConstrTypeSpec &&
( (ConstrTypeSpec)ts ).declaration() instanceof EnumType ) )
{
this.switch_is_enum = true;
EnumType et = (EnumType)( (ConstrTypeSpec)ts ).declaration();
if( allCaseLabels.size() + def > et.size() )
{
lexer.emit_warn( "Too many case labels in definition of union " +
full_name() + ", default cannot apply", token );
}
if( allCaseLabels.size() + def == et.size() )
{
allCasesCovered = true;
}
for( int i = 0; i < et.size(); i++ )
{
String qualifiedCaseLabel =
ts.typeName() + "." + (String)et.enumlist.v.elementAt( i );
if( !( allCaseLabels.contains( qualifiedCaseLabel ) ) )
{
defaultStr = qualifiedCaseLabel;
break;
}
}
}
else
{
if( ts instanceof BaseType )
{
ts = ( (BaseType)ts ).typeSpec();
}
if( ts instanceof BooleanType )
{
this.switch_is_bool = true;
// find a "default" for boolean
if( allCaseLabels.size() + def > 2 )
{
parser.error( "Case label error: too many default labels.", token );
return;
}
else if( allCaseLabels.size() == 1 )
{
if( ( (String)allCaseLabels.elementAt( 0 ) ).equals( "true" ) )
defaultStr = "false";
else
defaultStr = "true";
}
else
{
// labels for both true and false -> no default possible
}
}
else if( ts instanceof CharType )
{
// find a "default" for char
for( short s = 0; s < 256; s++ )
{
if( !( allCaseLabels.contains( new Character( (char)s ).toString() ) ) )
{
defaultStr = "(char)" + s;
break;
}
}
}
else if( ts instanceof IntType )
{
int maxint = 65536; // 2^16, max short
if( ts instanceof LongType )
maxint = 2147483647; // -2^31, max long
for( int i = 0; i < maxint; i++ )
{
if( !( allCaseLabels.contains( String.valueOf( i ) ) ) )
{
defaultStr = Integer.toString( i );
break;
}
}
if( ts instanceof LongLongType )
{
this.switch_is_longlong = true;
}
}
else
{
System.err.println( "Something went wrong in UnionType, "
+ "could not identify switch type "
+ switch_type_spec.type_spec );
}
}
/* print members */
for( Enumeration e = switch_body.caseListVector.elements(); e.hasMoreElements(); )
{
Case c = (Case)e.nextElement();
int caseLabelNum = c.case_label_list.v.size();
String label[] = new String[ caseLabelNum ];
for( int i = 0; i < caseLabelNum; i++ )
{
Object o = c.case_label_list.v.elementAt( i );
if( o == null ) // null means "default"
{
label[ i ] = null;
}
else if( o != null && o instanceof ConstExpr )
{
label[ i ] = ( (ConstExpr)o ).value();
}
else if( o instanceof ScopedName )
{
label[ i ] = ( (ScopedName)o ).typeName();
}
}
pw.println( "\tprivate " + c.element_spec.t.typeName()
+ " " + c.element_spec.d.name() + ";" );
}
/*
* print a constructor for class member initialization
*/
pw.println( "\n\tpublic " + className + " ()" );
pw.println( "\t{" );
pw.println( "\t}\n" );
/*
* print an accessor method for the discriminator
*/
pw.println( "\tpublic " + ts.typeName() + " discriminator ()" );
pw.println( "\t{" );
pw.println( "\t\treturn discriminator;" );
pw.println( "\t}\n" );
/*
* print accessor and modifiers for each case label and branch
*/
for( Enumeration e = switch_body.caseListVector.elements(); e.hasMoreElements(); )
{
Case c = (Case)e.nextElement();
boolean thisCaseIsDefault = false;
int caseLabelNum = c.case_label_list.v.size();
String label[] = new String[ caseLabelNum ];
/* make case labels available as strings */
for( int i = 0; i < caseLabelNum; i++ )
{
Object o = c.case_label_list.v.elementAt( i );
if( o == null ) // null means "default"
{
label[ i ] = null;
thisCaseIsDefault = true;
}
else if( o instanceof ConstExpr )
label[ i ] = ( (ConstExpr)o ).value();
else if( o instanceof ScopedName )
label[ i ] = ( (ScopedName)o ).typeName();
}
// accessors
pw.println( "\tpublic " + c.element_spec.t.typeName()
+ " " + c.element_spec.d.name() + " ()" );
pw.println( "\t{" );
// if( switch_is_enum )
// pw.print("\t\tif( !discriminator.equals( ");
// else
pw.print( "\t\tif( discriminator != " );
for( int i = 0; i < caseLabelNum; i++ )
{
if( label[ i ] == null )
pw.print( defaultStr );
else
pw.print( label[ i ] );
if( i < caseLabelNum - 1 )
{
// if( switch_is_enum )
// pw.print(") && !discriminator.equals( ");
// else
pw.print( " && discriminator != " );
}
}
pw.println( ")\n\t\t\tthrow new org.omg.CORBA.BAD_OPERATION();" );
pw.println( "\t\treturn " + c.element_spec.d.name() + ";" );
pw.println( "\t}\n" );
// modifiers
pw.println( "\tpublic void " + c.element_spec.d.name() +
" (" + c.element_spec.t.typeName() + " _x)" );
pw.println( "\t{" );
pw.print( "\t\tdiscriminator = " );
if( label[ 0 ] == null )
pw.println( defaultStr + ";" );
else
pw.println( label[ 0 ] + ";" );
pw.println( "\t\t" + c.element_spec.d.name() + " = _x;" );
pw.println( "\t}\n" );
if( caseLabelNum > 1 || thisCaseIsDefault )
{
pw.println( "\tpublic void " + c.element_spec.d.name() + "( " +
ts.typeName() + " _discriminator, " +
c.element_spec.t.typeName() + " _x )" );
pw.println( "\t{" );
pw.print( "\t\tif( _discriminator != " );
for( int i = 0; i < caseLabelNum; i++ )
{
if( label[ i ] != null )
pw.print( label[ i ] );
else
pw.print( defaultStr );
if( i < caseLabelNum - 1 )
{
pw.print( " && _discriminator != " );
}
}
pw.println( ")\n\t\t\tthrow new org.omg.CORBA.BAD_OPERATION();" );
pw.println( "\t\tdiscriminator = _discriminator;" );
pw.println( "\t\t" + c.element_spec.d.name() + " = _x;" );
pw.println( "\t}\n" );
}
}
/* if there is no default case and case labels do not cover
* all discriminator values, we have to generate __defaultmethods
*/
if( def == 0 && defaultStr.length() > 0 )
{
pw.println( "\tpublic void __default ()" );
pw.println( "\t{" );
pw.println( "\t\tdiscriminator = " + defaultStr + ";" );
pw.println( "\t}" );
pw.println( "\tpublic void __default (" + ts.typeName() + " _discriminator)" );
pw.println( "\t{" );
pw.println( "\t\tdiscriminator = _discriminator;" );
pw.println( "\t}" );
}
pw.println( "}" );
}
public void printHolderClass( String className, PrintWriter ps )
{
if( !pack_name.equals( "" ) )
ps.println( "package " + pack_name + ";" );
printClassComment( className, ps );
ps.println( "public" + parser.getFinalString() + " class " + className + "Holder" );
ps.println( "\timplements org.omg.CORBA.portable.Streamable" );
ps.println( "{" );
ps.println( "\tpublic " + className + " value;\n" );
ps.println( "\tpublic " + className + "Holder ()" );
ps.println( "\t{" );
ps.println( "\t}" );
ps.println( "\tpublic " + className + "Holder (final " + className + " initial)" );
ps.println( "\t{" );
ps.println( "\t\tvalue = initial;" );
ps.println( "\t}" );
ps.println( "\tpublic org.omg.CORBA.TypeCode _type ()" );
ps.println( "\t{" );
ps.println( "\t\treturn " + className + "Helper.type ();" );
ps.println( "\t}" );
ps.println( "\tpublic void _read (final org.omg.CORBA.portable.InputStream in)" );
ps.println( "\t{" );
ps.println( "\t\tvalue = " + className + "Helper.read (in);" );
ps.println( "\t}" );
ps.println( "\tpublic void _write (final org.omg.CORBA.portable.OutputStream out)" );
ps.println( "\t{" );
ps.println( "\t\t" + className + "Helper.write (out, value);" );
ps.println( "\t}" );
ps.println( "}" );
}
private void printHelperClass( String className, PrintWriter ps )
{
if( !pack_name.equals( "" ) )
ps.println( "package " + pack_name + ";" );
printImport( ps );
printClassComment( className, ps );
ps.println( "public" + parser.getFinalString() + " class " + className + "Helper" );
ps.println( "{" );
ps.println( "\tprivate static org.omg.CORBA.TypeCode _type;" );
String _type = typeName();
TypeSpec.printInsertExtractMethods( ps, typeName() );
printIdMethod( ps );
/** read method */
ps.println( "\tpublic static " + className + " read (org.omg.CORBA.portable.InputStream in)" );
ps.println( "\t{" );
ps.println( "\t\t" + className + " result = new " + className + " ();" );
TypeSpec switch_ts_resolved = switch_type_spec;
if( switch_type_spec.type_spec instanceof ScopedName )
{
switch_ts_resolved = ( (ScopedName)switch_type_spec.type_spec ).resolvedTypeSpec();
}
String indent1 = "\t\t\t";
String indent2 = "\t\t\t\t";
if( switch_is_longlong )
{
indent1 = "\t\t";
indent2 = "\t\t\t";
}
String case_str = "case ";
String colon_str = ":";
String default_str = "default:";
if( switch_is_enum )
{
ps.println( "\t\t" + switch_ts_resolved.toString() + " disc = " +
switch_ts_resolved.toString() + ".from_int(in.read_long());" );
ps.println( "\t\tswitch (disc.value ())" );
ps.println( "\t\t{" );
}
else
{
ps.println( "\t\t" + switch_ts_resolved.toString() + " "
+ switch_ts_resolved.printReadStatement( "disc", "in" ) );
if( switch_is_bool )
{
/* special case: boolean is not a switch type in java */
case_str = "if (disc == ";
colon_str = ")";
default_str = "else";
}
else if( switch_is_longlong )
{
/* special case: long is not a switch type in java */
case_str = "if (disc == ";
colon_str = ")";
default_str = "else";
}
else
{
ps.println( "\t\tswitch (disc)" );
ps.println( "\t\t{" );
}
}
ByteArrayOutputStream bos = new ByteArrayOutputStream();
PrintWriter defaultWriter = new PrintWriter( bos );
PrintWriter alt = null;
for( Enumeration e = switch_body.caseListVector.elements(); e.hasMoreElements(); )
{
Case c = (Case)e.nextElement();
TypeSpec t = c.element_spec.t;
Declarator d = c.element_spec.d;
int caseLabelNum = c.case_label_list.v.size();
boolean was_default = false;
for( int i = 0; i < caseLabelNum; i++ )
{
Object o = c.case_label_list.v.elementAt( i );
if( o == null )
{
// null means "default"
defaultWriter.println( indent1 + default_str );
was_default = true;
}
else if( o instanceof ConstExpr )
{
ps.println( indent1 + case_str + ( (ConstExpr)o ).value() + colon_str );
}
else if( o instanceof ScopedName )
{
String _t = ( (ScopedName)o ).typeName();
if( switch_is_enum )
ps.println( indent1 + case_str + _t.substring( 0, _t.lastIndexOf( '.' ) + 1 )
+ "_" + _t.substring( _t.lastIndexOf( '.' ) + 1 ) + colon_str );
else
ps.println( indent1 + case_str + _t + colon_str );
}
if( i == caseLabelNum - 1 )
{
if( o == null )
{
alt = ps;
ps = defaultWriter;
}
ps.println( indent1 + "{" );
if( t instanceof ScopedName )
{
t = ( (ScopedName)t ).resolvedTypeSpec();
}
t = t.typeSpec();
String varname = "_var";
ps.println( indent2 + t.typeName() + " " + varname + ";" );
ps.println( indent2 + t.printReadStatement( varname, "in" ) );
ps.print( indent2 + "result." + d.name() + " (" );
if( caseLabelNum > 1 )
{
ps.print( "disc," );
}
ps.println( varname + ");" );
// no "break" written for default case or for "if" construct
if( o != null && !switch_is_bool && !switch_is_longlong )
{
ps.println( indent2 + "break;" );
}
if( switch_is_longlong )
{
ps.println( indent2 + "return result;" );
}
ps.println( indent1 + "}" );
if( o == null )
{
ps = alt;
}
}
}
if( switch_is_bool && !was_default )
{
case_str = "else " + case_str;
}
}
if( !explicit_default_case && !switch_is_bool && !switch_is_longlong && !allCasesCovered )
{
defaultWriter.println( "\t\t\tdefault: result.__default (disc);" );
}
if( !explicit_default_case && switch_is_longlong )
{
defaultWriter.println( "\t\tresult.__default (disc);" );
defaultWriter.println( "\t\treturn result;" );
}
defaultWriter.close();
if( bos.size() > 0 )
{
ps.print( bos.toString() );
}
if( !switch_is_bool && !switch_is_longlong )
{
ps.println( "\t\t}" ); // close switch statement
}
if( !switch_is_longlong )
{
ps.println( "\t\treturn result;" );
}
ps.println( "\t}" );
/** write method */
ps.println( "\tpublic static void write (org.omg.CORBA.portable.OutputStream out, " + className + " s)" );
ps.println( "\t{" );
if( switch_is_enum )
{
ps.println( "\t\tout.write_long(s.discriminator().value());" );
ps.println( "\t\tswitch(s.discriminator().value())" );
ps.println( "\t\t{" );
}
else
{
ps.println( "\t\t" + switch_type_spec.typeSpec().printWriteStatement( "s.discriminator ()", "out" ) + ";" );
if( switch_is_bool )
{
/* special case: booleans are no switch type in java */
case_str = "if(s.discriminator()==";
// colon_str and default_str are already set correctly
}
else if( switch_is_longlong )
{
ps.println( "\t\tlong disc = s.discriminator ();" );
}
else
{
ps.println( "\t\tswitch (s.discriminator ())" );
ps.println( "\t\t{" );
}
}
bos = new ByteArrayOutputStream();
defaultWriter = new PrintWriter( bos );
alt = null;
for( Enumeration e = switch_body.caseListVector.elements(); e.hasMoreElements(); )
{
Case c = (Case)e.nextElement();
TypeSpec t = c.element_spec.t;
Declarator d = c.element_spec.d;
int caseLabelNum = c.case_label_list.v.size();
boolean was_default = false;
for( int i = 0; i < caseLabelNum; i++ )
{
Object o = c.case_label_list.v.elementAt( i );
if( o == null )
{
// null means "default"
defaultWriter.println( indent1 + default_str );
was_default = true;
}
else if( o != null && o instanceof ConstExpr )
{
ps.println( indent1 + case_str + ( (ConstExpr)o ).value() + colon_str );
}
else if( o instanceof ScopedName )
{
String _t = ( (ScopedName)o ).typeName();
if( switch_is_enum )
ps.println( indent1 + case_str + _t.substring( 0, _t.lastIndexOf( '.' ) + 1 )
+ "_" + _t.substring( _t.lastIndexOf( '.' ) + 1 ) + colon_str );
else
ps.println( indent1 + case_str + _t + colon_str );
}
if( i == caseLabelNum - 1 )
{
if( o == null )
{
alt = ps;
ps = defaultWriter;
}
ps.println( indent1 + "{" );
if( t instanceof ScopedName )
t = ( (ScopedName)t ).resolvedTypeSpec();
t = t.typeSpec();
ps.println( indent2 + t.printWriteStatement( "s." + d.name() + " ()", "out" ) );
// no "break" written for default case
if( o != null && !switch_is_bool && !switch_is_longlong )
{
ps.println( indent2 + "break;" );
}
if( switch_is_longlong )
{
ps.println( indent2 + "return;" );
}
ps.println( indent1 + "}" );
if( o == null )
{
ps = alt;
}
}
}
if( switch_is_bool && !was_default )
{
case_str = "else " + case_str;
}
}
defaultWriter.close();
if( bos.size() > 0 )
{
ps.print( bos.toString() );
}
/* close switch statement */
if( !switch_is_bool && !switch_is_longlong )
{
ps.println( "\t\t}" );
}
ps.println( "\t}" );
/** type() */
ps.println( "\tpublic static org.omg.CORBA.TypeCode type ()" );
ps.println( "\t{" );
ps.println( "\t\tif (_type == null)" );
ps.println( "\t\t{" );
ps.println( "\t\t\torg.omg.CORBA.UnionMember[] members = new org.omg.CORBA.UnionMember[" + labels + "];" );
ps.println( "\t\t\torg.omg.CORBA.Any label_any;" );
- int mi = 0;
TypeSpec label_t = switch_type_spec.typeSpec();
while( label_t instanceof ScopedName || label_t instanceof AliasTypeSpec )
{
if( label_t instanceof ScopedName )
label_t = ( (ScopedName)label_t ).resolvedTypeSpec();
if( label_t instanceof AliasTypeSpec )
label_t = ( (AliasTypeSpec)label_t ).originalType();
}
label_t = label_t.typeSpec();
+ int mi = switch_body.caseListVector.size () - 1;
for( Enumeration e = switch_body.caseListVector.elements(); e.hasMoreElements(); )
{
Case c = (Case)e.nextElement();
TypeSpec t = c.element_spec.t;
while( t instanceof ScopedName || t instanceof AliasTypeSpec )
{
if( t instanceof ScopedName )
t = ( (ScopedName)t ).resolvedTypeSpec();
if( t instanceof AliasTypeSpec )
t = ( (AliasTypeSpec)t ).originalType();
}
t = t.typeSpec();
Declarator d = c.element_spec.d;
int caseLabelNum = c.case_label_list.v.size();
for( int i = 0; i < caseLabelNum; i++ )
{
Object o = c.case_label_list.v.elementAt( i );
ps.println( "\t\t\tlabel_any = org.omg.CORBA.ORB.init().create_any ();" );
if( o == null )
{
ps.println( "\t\t\tlabel_any.insert_octet ((byte)0);" );
}
else if( label_t instanceof BaseType )
{
if( ( label_t instanceof CharType ) ||
( label_t instanceof BooleanType ) ||
( label_t instanceof LongType ) ||
( label_t instanceof LongLongType ) )
{
ps.print( "\t\t\tlabel_any." + label_t.printInsertExpression() + " (" );
}
else if( label_t instanceof ShortType )
{
ps.print( "\t\t\tlabel_any." + label_t.printInsertExpression() + " ((short)" );
}
else
{
throw new RuntimeException( "Compiler error: unrecognized BaseType: "
+ label_t.typeName() + ":" + label_t + ": " + label_t.typeSpec()
+ ": " + label_t.getClass().getName() );
}
ps.println( ( (ConstExpr)o ).value() + ");" );
}
else if( switch_is_enum )
{
String _t = ( (ScopedName)o ).typeName();
ps.println( "\t\t\t" + _t.substring( 0, _t.lastIndexOf( '.' ) )
+ "Helper.insert( label_any, " + _t + " );" );
}
else
{
throw new Error( "Compiler error: unrecognized label type: " + label_t.typeName() );
}
- ps.print( "\t\t\tmembers[" + ( mi++ ) + "] = new org.omg.CORBA.UnionMember (\"" + d.deEscapeName() + "\", label_any, " );
+ ps.print( "\t\t\tmembers[" + ( mi-- ) + "] = new org.omg.CORBA.UnionMember (\"" + d.deEscapeName() + "\", label_any, " );
if( t instanceof ConstrTypeSpec )
{
ps.print( t.typeSpec().toString() + "Helper.type()," );
}
else
{
ps.print( t.typeSpec().getTypeCodeExpression() + "," );
}
ps.println( "null);" );
}
}
ps.print( "\t\t\t _type = org.omg.CORBA.ORB.init().create_union_tc(id(),\"" + className() + "\"," );
ps.println( switch_type_spec.typeSpec().getTypeCodeExpression() + ", members);" );
ps.println( "\t\t}" );
ps.println( "\t\treturn _type;" );
ps.println( "\t}" );
ps.println( "}" ); // end of helper class
}
/** generate required classes */
public void print( PrintWriter ps )
{
setPrintPhaseNames();
/** no code generation for included definitions */
if( included && !generateIncluded() )
return;
/** only write once */
if( written )
{
return;
}
// Forward declaration
if (switch_type_spec != null)
{
try
{
switch_body.print( ps );
String className = className();
String path = parser.out_dir + fileSeparator +
pack_name.replace( '.', fileSeparator );
File dir = new File( path );
if( !dir.exists() )
if( !dir.mkdirs() )
{
org.jacorb.idl.parser.fatal_error( "Unable to create " + path, null );
}
/** print the mapped java class */
String fname = className + ".java";
PrintWriter decl_ps = new PrintWriter( new java.io.FileWriter( new File( dir, fname ) ) );
printUnionClass( className, decl_ps );
decl_ps.close();
/** print the holder class */
fname = className + "Holder.java";
decl_ps = new PrintWriter( new java.io.FileWriter( new File( dir, fname ) ) );
printHolderClass( className, decl_ps );
decl_ps.close();
/** print the helper class */
fname = className + "Helper.java";
decl_ps = new PrintWriter( new java.io.FileWriter( new File( dir, fname ) ) );
printHelperClass( className, decl_ps );
decl_ps.close();
written = true;
}
catch( java.io.IOException i )
{
System.err.println( "File IO error" );
i.printStackTrace();
}
}
}
private TypeSpec getElementType( ElementSpec element )
{
TypeSpec tspec = element.t;
// Arrays are handled as a special case. Parser generates
// an ArrayDeclarator for an array, need to spot this and
// create appropriate type information with an ArrayTypeSpec.
if( element.d.d instanceof ArrayDeclarator )
{
tspec = new ArrayTypeSpec( new_num(), tspec,
(ArrayDeclarator)element.d.d, pack_name );
tspec.parse();
}
return tspec;
}
}
| false | true | private void printHelperClass( String className, PrintWriter ps )
{
if( !pack_name.equals( "" ) )
ps.println( "package " + pack_name + ";" );
printImport( ps );
printClassComment( className, ps );
ps.println( "public" + parser.getFinalString() + " class " + className + "Helper" );
ps.println( "{" );
ps.println( "\tprivate static org.omg.CORBA.TypeCode _type;" );
String _type = typeName();
TypeSpec.printInsertExtractMethods( ps, typeName() );
printIdMethod( ps );
/** read method */
ps.println( "\tpublic static " + className + " read (org.omg.CORBA.portable.InputStream in)" );
ps.println( "\t{" );
ps.println( "\t\t" + className + " result = new " + className + " ();" );
TypeSpec switch_ts_resolved = switch_type_spec;
if( switch_type_spec.type_spec instanceof ScopedName )
{
switch_ts_resolved = ( (ScopedName)switch_type_spec.type_spec ).resolvedTypeSpec();
}
String indent1 = "\t\t\t";
String indent2 = "\t\t\t\t";
if( switch_is_longlong )
{
indent1 = "\t\t";
indent2 = "\t\t\t";
}
String case_str = "case ";
String colon_str = ":";
String default_str = "default:";
if( switch_is_enum )
{
ps.println( "\t\t" + switch_ts_resolved.toString() + " disc = " +
switch_ts_resolved.toString() + ".from_int(in.read_long());" );
ps.println( "\t\tswitch (disc.value ())" );
ps.println( "\t\t{" );
}
else
{
ps.println( "\t\t" + switch_ts_resolved.toString() + " "
+ switch_ts_resolved.printReadStatement( "disc", "in" ) );
if( switch_is_bool )
{
/* special case: boolean is not a switch type in java */
case_str = "if (disc == ";
colon_str = ")";
default_str = "else";
}
else if( switch_is_longlong )
{
/* special case: long is not a switch type in java */
case_str = "if (disc == ";
colon_str = ")";
default_str = "else";
}
else
{
ps.println( "\t\tswitch (disc)" );
ps.println( "\t\t{" );
}
}
ByteArrayOutputStream bos = new ByteArrayOutputStream();
PrintWriter defaultWriter = new PrintWriter( bos );
PrintWriter alt = null;
for( Enumeration e = switch_body.caseListVector.elements(); e.hasMoreElements(); )
{
Case c = (Case)e.nextElement();
TypeSpec t = c.element_spec.t;
Declarator d = c.element_spec.d;
int caseLabelNum = c.case_label_list.v.size();
boolean was_default = false;
for( int i = 0; i < caseLabelNum; i++ )
{
Object o = c.case_label_list.v.elementAt( i );
if( o == null )
{
// null means "default"
defaultWriter.println( indent1 + default_str );
was_default = true;
}
else if( o instanceof ConstExpr )
{
ps.println( indent1 + case_str + ( (ConstExpr)o ).value() + colon_str );
}
else if( o instanceof ScopedName )
{
String _t = ( (ScopedName)o ).typeName();
if( switch_is_enum )
ps.println( indent1 + case_str + _t.substring( 0, _t.lastIndexOf( '.' ) + 1 )
+ "_" + _t.substring( _t.lastIndexOf( '.' ) + 1 ) + colon_str );
else
ps.println( indent1 + case_str + _t + colon_str );
}
if( i == caseLabelNum - 1 )
{
if( o == null )
{
alt = ps;
ps = defaultWriter;
}
ps.println( indent1 + "{" );
if( t instanceof ScopedName )
{
t = ( (ScopedName)t ).resolvedTypeSpec();
}
t = t.typeSpec();
String varname = "_var";
ps.println( indent2 + t.typeName() + " " + varname + ";" );
ps.println( indent2 + t.printReadStatement( varname, "in" ) );
ps.print( indent2 + "result." + d.name() + " (" );
if( caseLabelNum > 1 )
{
ps.print( "disc," );
}
ps.println( varname + ");" );
// no "break" written for default case or for "if" construct
if( o != null && !switch_is_bool && !switch_is_longlong )
{
ps.println( indent2 + "break;" );
}
if( switch_is_longlong )
{
ps.println( indent2 + "return result;" );
}
ps.println( indent1 + "}" );
if( o == null )
{
ps = alt;
}
}
}
if( switch_is_bool && !was_default )
{
case_str = "else " + case_str;
}
}
if( !explicit_default_case && !switch_is_bool && !switch_is_longlong && !allCasesCovered )
{
defaultWriter.println( "\t\t\tdefault: result.__default (disc);" );
}
if( !explicit_default_case && switch_is_longlong )
{
defaultWriter.println( "\t\tresult.__default (disc);" );
defaultWriter.println( "\t\treturn result;" );
}
defaultWriter.close();
if( bos.size() > 0 )
{
ps.print( bos.toString() );
}
if( !switch_is_bool && !switch_is_longlong )
{
ps.println( "\t\t}" ); // close switch statement
}
if( !switch_is_longlong )
{
ps.println( "\t\treturn result;" );
}
ps.println( "\t}" );
/** write method */
ps.println( "\tpublic static void write (org.omg.CORBA.portable.OutputStream out, " + className + " s)" );
ps.println( "\t{" );
if( switch_is_enum )
{
ps.println( "\t\tout.write_long(s.discriminator().value());" );
ps.println( "\t\tswitch(s.discriminator().value())" );
ps.println( "\t\t{" );
}
else
{
ps.println( "\t\t" + switch_type_spec.typeSpec().printWriteStatement( "s.discriminator ()", "out" ) + ";" );
if( switch_is_bool )
{
/* special case: booleans are no switch type in java */
case_str = "if(s.discriminator()==";
// colon_str and default_str are already set correctly
}
else if( switch_is_longlong )
{
ps.println( "\t\tlong disc = s.discriminator ();" );
}
else
{
ps.println( "\t\tswitch (s.discriminator ())" );
ps.println( "\t\t{" );
}
}
bos = new ByteArrayOutputStream();
defaultWriter = new PrintWriter( bos );
alt = null;
for( Enumeration e = switch_body.caseListVector.elements(); e.hasMoreElements(); )
{
Case c = (Case)e.nextElement();
TypeSpec t = c.element_spec.t;
Declarator d = c.element_spec.d;
int caseLabelNum = c.case_label_list.v.size();
boolean was_default = false;
for( int i = 0; i < caseLabelNum; i++ )
{
Object o = c.case_label_list.v.elementAt( i );
if( o == null )
{
// null means "default"
defaultWriter.println( indent1 + default_str );
was_default = true;
}
else if( o != null && o instanceof ConstExpr )
{
ps.println( indent1 + case_str + ( (ConstExpr)o ).value() + colon_str );
}
else if( o instanceof ScopedName )
{
String _t = ( (ScopedName)o ).typeName();
if( switch_is_enum )
ps.println( indent1 + case_str + _t.substring( 0, _t.lastIndexOf( '.' ) + 1 )
+ "_" + _t.substring( _t.lastIndexOf( '.' ) + 1 ) + colon_str );
else
ps.println( indent1 + case_str + _t + colon_str );
}
if( i == caseLabelNum - 1 )
{
if( o == null )
{
alt = ps;
ps = defaultWriter;
}
ps.println( indent1 + "{" );
if( t instanceof ScopedName )
t = ( (ScopedName)t ).resolvedTypeSpec();
t = t.typeSpec();
ps.println( indent2 + t.printWriteStatement( "s." + d.name() + " ()", "out" ) );
// no "break" written for default case
if( o != null && !switch_is_bool && !switch_is_longlong )
{
ps.println( indent2 + "break;" );
}
if( switch_is_longlong )
{
ps.println( indent2 + "return;" );
}
ps.println( indent1 + "}" );
if( o == null )
{
ps = alt;
}
}
}
if( switch_is_bool && !was_default )
{
case_str = "else " + case_str;
}
}
defaultWriter.close();
if( bos.size() > 0 )
{
ps.print( bos.toString() );
}
/* close switch statement */
if( !switch_is_bool && !switch_is_longlong )
{
ps.println( "\t\t}" );
}
ps.println( "\t}" );
/** type() */
ps.println( "\tpublic static org.omg.CORBA.TypeCode type ()" );
ps.println( "\t{" );
ps.println( "\t\tif (_type == null)" );
ps.println( "\t\t{" );
ps.println( "\t\t\torg.omg.CORBA.UnionMember[] members = new org.omg.CORBA.UnionMember[" + labels + "];" );
ps.println( "\t\t\torg.omg.CORBA.Any label_any;" );
int mi = 0;
TypeSpec label_t = switch_type_spec.typeSpec();
while( label_t instanceof ScopedName || label_t instanceof AliasTypeSpec )
{
if( label_t instanceof ScopedName )
label_t = ( (ScopedName)label_t ).resolvedTypeSpec();
if( label_t instanceof AliasTypeSpec )
label_t = ( (AliasTypeSpec)label_t ).originalType();
}
label_t = label_t.typeSpec();
for( Enumeration e = switch_body.caseListVector.elements(); e.hasMoreElements(); )
{
Case c = (Case)e.nextElement();
TypeSpec t = c.element_spec.t;
while( t instanceof ScopedName || t instanceof AliasTypeSpec )
{
if( t instanceof ScopedName )
t = ( (ScopedName)t ).resolvedTypeSpec();
if( t instanceof AliasTypeSpec )
t = ( (AliasTypeSpec)t ).originalType();
}
t = t.typeSpec();
Declarator d = c.element_spec.d;
int caseLabelNum = c.case_label_list.v.size();
for( int i = 0; i < caseLabelNum; i++ )
{
Object o = c.case_label_list.v.elementAt( i );
ps.println( "\t\t\tlabel_any = org.omg.CORBA.ORB.init().create_any ();" );
if( o == null )
{
ps.println( "\t\t\tlabel_any.insert_octet ((byte)0);" );
}
else if( label_t instanceof BaseType )
{
if( ( label_t instanceof CharType ) ||
( label_t instanceof BooleanType ) ||
( label_t instanceof LongType ) ||
( label_t instanceof LongLongType ) )
{
ps.print( "\t\t\tlabel_any." + label_t.printInsertExpression() + " (" );
}
else if( label_t instanceof ShortType )
{
ps.print( "\t\t\tlabel_any." + label_t.printInsertExpression() + " ((short)" );
}
else
{
throw new RuntimeException( "Compiler error: unrecognized BaseType: "
+ label_t.typeName() + ":" + label_t + ": " + label_t.typeSpec()
+ ": " + label_t.getClass().getName() );
}
ps.println( ( (ConstExpr)o ).value() + ");" );
}
else if( switch_is_enum )
{
String _t = ( (ScopedName)o ).typeName();
ps.println( "\t\t\t" + _t.substring( 0, _t.lastIndexOf( '.' ) )
+ "Helper.insert( label_any, " + _t + " );" );
}
else
{
throw new Error( "Compiler error: unrecognized label type: " + label_t.typeName() );
}
ps.print( "\t\t\tmembers[" + ( mi++ ) + "] = new org.omg.CORBA.UnionMember (\"" + d.deEscapeName() + "\", label_any, " );
if( t instanceof ConstrTypeSpec )
{
ps.print( t.typeSpec().toString() + "Helper.type()," );
}
else
{
ps.print( t.typeSpec().getTypeCodeExpression() + "," );
}
ps.println( "null);" );
}
}
ps.print( "\t\t\t _type = org.omg.CORBA.ORB.init().create_union_tc(id(),\"" + className() + "\"," );
ps.println( switch_type_spec.typeSpec().getTypeCodeExpression() + ", members);" );
ps.println( "\t\t}" );
ps.println( "\t\treturn _type;" );
ps.println( "\t}" );
ps.println( "}" ); // end of helper class
}
| private void printHelperClass( String className, PrintWriter ps )
{
if( !pack_name.equals( "" ) )
ps.println( "package " + pack_name + ";" );
printImport( ps );
printClassComment( className, ps );
ps.println( "public" + parser.getFinalString() + " class " + className + "Helper" );
ps.println( "{" );
ps.println( "\tprivate static org.omg.CORBA.TypeCode _type;" );
String _type = typeName();
TypeSpec.printInsertExtractMethods( ps, typeName() );
printIdMethod( ps );
/** read method */
ps.println( "\tpublic static " + className + " read (org.omg.CORBA.portable.InputStream in)" );
ps.println( "\t{" );
ps.println( "\t\t" + className + " result = new " + className + " ();" );
TypeSpec switch_ts_resolved = switch_type_spec;
if( switch_type_spec.type_spec instanceof ScopedName )
{
switch_ts_resolved = ( (ScopedName)switch_type_spec.type_spec ).resolvedTypeSpec();
}
String indent1 = "\t\t\t";
String indent2 = "\t\t\t\t";
if( switch_is_longlong )
{
indent1 = "\t\t";
indent2 = "\t\t\t";
}
String case_str = "case ";
String colon_str = ":";
String default_str = "default:";
if( switch_is_enum )
{
ps.println( "\t\t" + switch_ts_resolved.toString() + " disc = " +
switch_ts_resolved.toString() + ".from_int(in.read_long());" );
ps.println( "\t\tswitch (disc.value ())" );
ps.println( "\t\t{" );
}
else
{
ps.println( "\t\t" + switch_ts_resolved.toString() + " "
+ switch_ts_resolved.printReadStatement( "disc", "in" ) );
if( switch_is_bool )
{
/* special case: boolean is not a switch type in java */
case_str = "if (disc == ";
colon_str = ")";
default_str = "else";
}
else if( switch_is_longlong )
{
/* special case: long is not a switch type in java */
case_str = "if (disc == ";
colon_str = ")";
default_str = "else";
}
else
{
ps.println( "\t\tswitch (disc)" );
ps.println( "\t\t{" );
}
}
ByteArrayOutputStream bos = new ByteArrayOutputStream();
PrintWriter defaultWriter = new PrintWriter( bos );
PrintWriter alt = null;
for( Enumeration e = switch_body.caseListVector.elements(); e.hasMoreElements(); )
{
Case c = (Case)e.nextElement();
TypeSpec t = c.element_spec.t;
Declarator d = c.element_spec.d;
int caseLabelNum = c.case_label_list.v.size();
boolean was_default = false;
for( int i = 0; i < caseLabelNum; i++ )
{
Object o = c.case_label_list.v.elementAt( i );
if( o == null )
{
// null means "default"
defaultWriter.println( indent1 + default_str );
was_default = true;
}
else if( o instanceof ConstExpr )
{
ps.println( indent1 + case_str + ( (ConstExpr)o ).value() + colon_str );
}
else if( o instanceof ScopedName )
{
String _t = ( (ScopedName)o ).typeName();
if( switch_is_enum )
ps.println( indent1 + case_str + _t.substring( 0, _t.lastIndexOf( '.' ) + 1 )
+ "_" + _t.substring( _t.lastIndexOf( '.' ) + 1 ) + colon_str );
else
ps.println( indent1 + case_str + _t + colon_str );
}
if( i == caseLabelNum - 1 )
{
if( o == null )
{
alt = ps;
ps = defaultWriter;
}
ps.println( indent1 + "{" );
if( t instanceof ScopedName )
{
t = ( (ScopedName)t ).resolvedTypeSpec();
}
t = t.typeSpec();
String varname = "_var";
ps.println( indent2 + t.typeName() + " " + varname + ";" );
ps.println( indent2 + t.printReadStatement( varname, "in" ) );
ps.print( indent2 + "result." + d.name() + " (" );
if( caseLabelNum > 1 )
{
ps.print( "disc," );
}
ps.println( varname + ");" );
// no "break" written for default case or for "if" construct
if( o != null && !switch_is_bool && !switch_is_longlong )
{
ps.println( indent2 + "break;" );
}
if( switch_is_longlong )
{
ps.println( indent2 + "return result;" );
}
ps.println( indent1 + "}" );
if( o == null )
{
ps = alt;
}
}
}
if( switch_is_bool && !was_default )
{
case_str = "else " + case_str;
}
}
if( !explicit_default_case && !switch_is_bool && !switch_is_longlong && !allCasesCovered )
{
defaultWriter.println( "\t\t\tdefault: result.__default (disc);" );
}
if( !explicit_default_case && switch_is_longlong )
{
defaultWriter.println( "\t\tresult.__default (disc);" );
defaultWriter.println( "\t\treturn result;" );
}
defaultWriter.close();
if( bos.size() > 0 )
{
ps.print( bos.toString() );
}
if( !switch_is_bool && !switch_is_longlong )
{
ps.println( "\t\t}" ); // close switch statement
}
if( !switch_is_longlong )
{
ps.println( "\t\treturn result;" );
}
ps.println( "\t}" );
/** write method */
ps.println( "\tpublic static void write (org.omg.CORBA.portable.OutputStream out, " + className + " s)" );
ps.println( "\t{" );
if( switch_is_enum )
{
ps.println( "\t\tout.write_long(s.discriminator().value());" );
ps.println( "\t\tswitch(s.discriminator().value())" );
ps.println( "\t\t{" );
}
else
{
ps.println( "\t\t" + switch_type_spec.typeSpec().printWriteStatement( "s.discriminator ()", "out" ) + ";" );
if( switch_is_bool )
{
/* special case: booleans are no switch type in java */
case_str = "if(s.discriminator()==";
// colon_str and default_str are already set correctly
}
else if( switch_is_longlong )
{
ps.println( "\t\tlong disc = s.discriminator ();" );
}
else
{
ps.println( "\t\tswitch (s.discriminator ())" );
ps.println( "\t\t{" );
}
}
bos = new ByteArrayOutputStream();
defaultWriter = new PrintWriter( bos );
alt = null;
for( Enumeration e = switch_body.caseListVector.elements(); e.hasMoreElements(); )
{
Case c = (Case)e.nextElement();
TypeSpec t = c.element_spec.t;
Declarator d = c.element_spec.d;
int caseLabelNum = c.case_label_list.v.size();
boolean was_default = false;
for( int i = 0; i < caseLabelNum; i++ )
{
Object o = c.case_label_list.v.elementAt( i );
if( o == null )
{
// null means "default"
defaultWriter.println( indent1 + default_str );
was_default = true;
}
else if( o != null && o instanceof ConstExpr )
{
ps.println( indent1 + case_str + ( (ConstExpr)o ).value() + colon_str );
}
else if( o instanceof ScopedName )
{
String _t = ( (ScopedName)o ).typeName();
if( switch_is_enum )
ps.println( indent1 + case_str + _t.substring( 0, _t.lastIndexOf( '.' ) + 1 )
+ "_" + _t.substring( _t.lastIndexOf( '.' ) + 1 ) + colon_str );
else
ps.println( indent1 + case_str + _t + colon_str );
}
if( i == caseLabelNum - 1 )
{
if( o == null )
{
alt = ps;
ps = defaultWriter;
}
ps.println( indent1 + "{" );
if( t instanceof ScopedName )
t = ( (ScopedName)t ).resolvedTypeSpec();
t = t.typeSpec();
ps.println( indent2 + t.printWriteStatement( "s." + d.name() + " ()", "out" ) );
// no "break" written for default case
if( o != null && !switch_is_bool && !switch_is_longlong )
{
ps.println( indent2 + "break;" );
}
if( switch_is_longlong )
{
ps.println( indent2 + "return;" );
}
ps.println( indent1 + "}" );
if( o == null )
{
ps = alt;
}
}
}
if( switch_is_bool && !was_default )
{
case_str = "else " + case_str;
}
}
defaultWriter.close();
if( bos.size() > 0 )
{
ps.print( bos.toString() );
}
/* close switch statement */
if( !switch_is_bool && !switch_is_longlong )
{
ps.println( "\t\t}" );
}
ps.println( "\t}" );
/** type() */
ps.println( "\tpublic static org.omg.CORBA.TypeCode type ()" );
ps.println( "\t{" );
ps.println( "\t\tif (_type == null)" );
ps.println( "\t\t{" );
ps.println( "\t\t\torg.omg.CORBA.UnionMember[] members = new org.omg.CORBA.UnionMember[" + labels + "];" );
ps.println( "\t\t\torg.omg.CORBA.Any label_any;" );
TypeSpec label_t = switch_type_spec.typeSpec();
while( label_t instanceof ScopedName || label_t instanceof AliasTypeSpec )
{
if( label_t instanceof ScopedName )
label_t = ( (ScopedName)label_t ).resolvedTypeSpec();
if( label_t instanceof AliasTypeSpec )
label_t = ( (AliasTypeSpec)label_t ).originalType();
}
label_t = label_t.typeSpec();
int mi = switch_body.caseListVector.size () - 1;
for( Enumeration e = switch_body.caseListVector.elements(); e.hasMoreElements(); )
{
Case c = (Case)e.nextElement();
TypeSpec t = c.element_spec.t;
while( t instanceof ScopedName || t instanceof AliasTypeSpec )
{
if( t instanceof ScopedName )
t = ( (ScopedName)t ).resolvedTypeSpec();
if( t instanceof AliasTypeSpec )
t = ( (AliasTypeSpec)t ).originalType();
}
t = t.typeSpec();
Declarator d = c.element_spec.d;
int caseLabelNum = c.case_label_list.v.size();
for( int i = 0; i < caseLabelNum; i++ )
{
Object o = c.case_label_list.v.elementAt( i );
ps.println( "\t\t\tlabel_any = org.omg.CORBA.ORB.init().create_any ();" );
if( o == null )
{
ps.println( "\t\t\tlabel_any.insert_octet ((byte)0);" );
}
else if( label_t instanceof BaseType )
{
if( ( label_t instanceof CharType ) ||
( label_t instanceof BooleanType ) ||
( label_t instanceof LongType ) ||
( label_t instanceof LongLongType ) )
{
ps.print( "\t\t\tlabel_any." + label_t.printInsertExpression() + " (" );
}
else if( label_t instanceof ShortType )
{
ps.print( "\t\t\tlabel_any." + label_t.printInsertExpression() + " ((short)" );
}
else
{
throw new RuntimeException( "Compiler error: unrecognized BaseType: "
+ label_t.typeName() + ":" + label_t + ": " + label_t.typeSpec()
+ ": " + label_t.getClass().getName() );
}
ps.println( ( (ConstExpr)o ).value() + ");" );
}
else if( switch_is_enum )
{
String _t = ( (ScopedName)o ).typeName();
ps.println( "\t\t\t" + _t.substring( 0, _t.lastIndexOf( '.' ) )
+ "Helper.insert( label_any, " + _t + " );" );
}
else
{
throw new Error( "Compiler error: unrecognized label type: " + label_t.typeName() );
}
ps.print( "\t\t\tmembers[" + ( mi-- ) + "] = new org.omg.CORBA.UnionMember (\"" + d.deEscapeName() + "\", label_any, " );
if( t instanceof ConstrTypeSpec )
{
ps.print( t.typeSpec().toString() + "Helper.type()," );
}
else
{
ps.print( t.typeSpec().getTypeCodeExpression() + "," );
}
ps.println( "null);" );
}
}
ps.print( "\t\t\t _type = org.omg.CORBA.ORB.init().create_union_tc(id(),\"" + className() + "\"," );
ps.println( switch_type_spec.typeSpec().getTypeCodeExpression() + ", members);" );
ps.println( "\t\t}" );
ps.println( "\t\treturn _type;" );
ps.println( "\t}" );
ps.println( "}" ); // end of helper class
}
|
diff --git a/JavaSource/org/aitools/programd/util/Settings.java b/JavaSource/org/aitools/programd/util/Settings.java
index 69595b9..936fab9 100644
--- a/JavaSource/org/aitools/programd/util/Settings.java
+++ b/JavaSource/org/aitools/programd/util/Settings.java
@@ -1,80 +1,80 @@
/*
* 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. 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.,
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package org.aitools.programd.util;
import java.io.IOException;
import java.net.URL;
import java.util.InvalidPropertiesFormatException;
import java.util.Properties;
/**
* A Settings object can read properties from a given path, or initialize itself
* with default values. It also contains getter and setter methods for every
* property value. Usually the subclasses of Settings will be generated
* automatically from some other structure, such as (as currently) the
* properties file itself, since it's annoying to create and maintain these by
* hand.
*
* @author <a href="mailto:[email protected]">Noel Bush</a>
*/
abstract public class Settings
{
/** The properties. */
protected Properties properties;
/**
* Creates a new Settings object, initializing it with default values.
*/
public Settings()
{
this.properties = new Properties();
initialize();
}
/**
* Creates a new Settings object, filling it with properties read from the
* given path.
*
* @param propertiesPath the path to the properties file
*/
public Settings(URL propertiesPath)
{
this.properties = new Properties();
try
{
this.properties.loadFromXML(propertiesPath.openStream());
}
catch (InvalidPropertiesFormatException e)
{
throw new UserError("Invalid properties format: ", e);
}
catch (IOException e)
{
- throw new DeveloperError("I/O Exception while loading properties: ", e);
+ throw new DeveloperError("I/O Exception while loading properties from \"" + propertiesPath.toString() + "\".", e);
}
catch (NullPointerException e)
{
throw new DeveloperError("Unable to open FileInputStream for \"" + propertiesPath + "\".", e);
}
catch (ClassCastException e)
{
throw new UserError(
"There is a problem with the format of your XML properties file. Not all valid XML is actually accepted by the JDK's XML Properties parser!",
e);
}
initialize();
}
/**
* Initializes the Settings object with values from properties as read, or
* defaults (if properties are not provided).
*/
abstract protected void initialize();
}
| true | true | public Settings(URL propertiesPath)
{
this.properties = new Properties();
try
{
this.properties.loadFromXML(propertiesPath.openStream());
}
catch (InvalidPropertiesFormatException e)
{
throw new UserError("Invalid properties format: ", e);
}
catch (IOException e)
{
throw new DeveloperError("I/O Exception while loading properties: ", e);
}
catch (NullPointerException e)
{
throw new DeveloperError("Unable to open FileInputStream for \"" + propertiesPath + "\".", e);
}
catch (ClassCastException e)
{
throw new UserError(
"There is a problem with the format of your XML properties file. Not all valid XML is actually accepted by the JDK's XML Properties parser!",
e);
}
initialize();
}
| public Settings(URL propertiesPath)
{
this.properties = new Properties();
try
{
this.properties.loadFromXML(propertiesPath.openStream());
}
catch (InvalidPropertiesFormatException e)
{
throw new UserError("Invalid properties format: ", e);
}
catch (IOException e)
{
throw new DeveloperError("I/O Exception while loading properties from \"" + propertiesPath.toString() + "\".", e);
}
catch (NullPointerException e)
{
throw new DeveloperError("Unable to open FileInputStream for \"" + propertiesPath + "\".", e);
}
catch (ClassCastException e)
{
throw new UserError(
"There is a problem with the format of your XML properties file. Not all valid XML is actually accepted by the JDK's XML Properties parser!",
e);
}
initialize();
}
|
diff --git a/src/main/java/org/werti/uima/ae/SentenceBoundaryDetector.java b/src/main/java/org/werti/uima/ae/SentenceBoundaryDetector.java
index 218cbc9..c2b5e7a 100644
--- a/src/main/java/org/werti/uima/ae/SentenceBoundaryDetector.java
+++ b/src/main/java/org/werti/uima/ae/SentenceBoundaryDetector.java
@@ -1,103 +1,102 @@
package org.werti.uima.ae;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import org.apache.log4j.Logger;
import org.apache.uima.analysis_component.JCasAnnotator_ImplBase;
import org.apache.uima.cas.FSIndex;
import org.apache.uima.jcas.JCas;
import org.werti.uima.types.annot.SentenceAnnotation;
import org.werti.uima.types.annot.Token;
/**
* A simple sentence boundary detector.
*
* It does a good job at basic SB-detection, but it would be nice to
* use the lingpipe chunker for this instead, because it's probably better.
*
* We mark sentence boundaries at <tt>.</tt>, <tt>!</tt> and <tt>?<tt>. All sentenc
* boundaries can be followed by one or more tokens that typically follow our sentence
* boundary triggers without introducing a new sentence. (currently <tt>)</tt>, <tt>]</tt>,
* <tt>"</tt>, <tt>'</tt> and <tt>''</tt>.)
*
* This concept is taken from the Stanford tagger's way of doing SBD.
*
* @author Aleksandar Dimitrov
* @version 0.1
*/
public class SentenceBoundaryDetector extends JCasAnnotator_ImplBase {
private static final Logger log =
Logger.getLogger(SentenceBoundaryDetector.class);
private static final Set<String> sentenceBoundaries =
new HashSet<String>(Arrays.asList(new String[]{".", "!", "?"}));
private static final Set<String> sentenceBoundaryFollowers =
new HashSet<String>(Arrays.asList(new String[]{")", "]", "\"", "'", "''", }));
private static final double COH_TRESHOLD = 0.1;
/**
* Marks up sentences in the cas.
* Note that those sentences will not be part-of-speech tagged.
*
* @param cas The Cas the Tokens come from and the sentences go to.
*/
@SuppressWarnings("unchecked")
public void process(JCas cas) {
log.info("Starting sentence boundary detection.");
final FSIndex textIndex = cas.getAnnotationIndex(Token.type);
final Iterator<Token> tit = textIndex.iterator();
int coh_gaps = 0;
Token t;
while (tit.hasNext()) {
t = tit.next();
if (log.isDebugEnabled()) {
log.debug("Looking at token: " + t.getCoveredText());
}
SentenceAnnotation sa = new SentenceAnnotation(cas);
sa.setBegin(t.getBegin());
// skip tokens unil we find a new sentence boundary
while (tit.hasNext() && !sentenceBoundaries.contains(t.getCoveredText())) {
// adjust coherence gaps and load next element
coh_gaps -= t.getEnd() - (t = tit.next()).getBegin();
}
- if (tit.hasNext()) tit.next(); // skip over sentence boundary.
final int length = sa.getBegin() + t.getEnd();
final double coherence = coherence(length, coh_gaps);
if (!(coherence < COH_TRESHOLD)
|| !(coherence == 1.0)) { //skip sentence boundary followers
while (tit.hasNext()
&& sentenceBoundaryFollowers.contains(t.getCoveredText())) {
t = tit.next();
}
}
sa.setEnd(t.getEnd());
sa.setCoherence(coherence);
sa.addToIndexes();
coh_gaps = 0;
}
log.info("Finished sentence boundary detection.");
}
// holds the formula for calculating the coherence based on the length
// and the gap value
private final double coherence(int length, int coh_gaps) {
return ((double)(length - coh_gaps))/length;
}
}
| true | true | public void process(JCas cas) {
log.info("Starting sentence boundary detection.");
final FSIndex textIndex = cas.getAnnotationIndex(Token.type);
final Iterator<Token> tit = textIndex.iterator();
int coh_gaps = 0;
Token t;
while (tit.hasNext()) {
t = tit.next();
if (log.isDebugEnabled()) {
log.debug("Looking at token: " + t.getCoveredText());
}
SentenceAnnotation sa = new SentenceAnnotation(cas);
sa.setBegin(t.getBegin());
// skip tokens unil we find a new sentence boundary
while (tit.hasNext() && !sentenceBoundaries.contains(t.getCoveredText())) {
// adjust coherence gaps and load next element
coh_gaps -= t.getEnd() - (t = tit.next()).getBegin();
}
if (tit.hasNext()) tit.next(); // skip over sentence boundary.
final int length = sa.getBegin() + t.getEnd();
final double coherence = coherence(length, coh_gaps);
if (!(coherence < COH_TRESHOLD)
|| !(coherence == 1.0)) { //skip sentence boundary followers
while (tit.hasNext()
&& sentenceBoundaryFollowers.contains(t.getCoveredText())) {
t = tit.next();
}
}
sa.setEnd(t.getEnd());
sa.setCoherence(coherence);
sa.addToIndexes();
coh_gaps = 0;
}
log.info("Finished sentence boundary detection.");
}
| public void process(JCas cas) {
log.info("Starting sentence boundary detection.");
final FSIndex textIndex = cas.getAnnotationIndex(Token.type);
final Iterator<Token> tit = textIndex.iterator();
int coh_gaps = 0;
Token t;
while (tit.hasNext()) {
t = tit.next();
if (log.isDebugEnabled()) {
log.debug("Looking at token: " + t.getCoveredText());
}
SentenceAnnotation sa = new SentenceAnnotation(cas);
sa.setBegin(t.getBegin());
// skip tokens unil we find a new sentence boundary
while (tit.hasNext() && !sentenceBoundaries.contains(t.getCoveredText())) {
// adjust coherence gaps and load next element
coh_gaps -= t.getEnd() - (t = tit.next()).getBegin();
}
final int length = sa.getBegin() + t.getEnd();
final double coherence = coherence(length, coh_gaps);
if (!(coherence < COH_TRESHOLD)
|| !(coherence == 1.0)) { //skip sentence boundary followers
while (tit.hasNext()
&& sentenceBoundaryFollowers.contains(t.getCoveredText())) {
t = tit.next();
}
}
sa.setEnd(t.getEnd());
sa.setCoherence(coherence);
sa.addToIndexes();
coh_gaps = 0;
}
log.info("Finished sentence boundary detection.");
}
|
diff --git a/de.fu_berlin.inf.dpp/src/de/fu_berlin/inf/dpp/invitation/OutgoingProjectNegotiation.java b/de.fu_berlin.inf.dpp/src/de/fu_berlin/inf/dpp/invitation/OutgoingProjectNegotiation.java
index 71e01cd25..bb428f1cc 100644
--- a/de.fu_berlin.inf.dpp/src/de/fu_berlin/inf/dpp/invitation/OutgoingProjectNegotiation.java
+++ b/de.fu_berlin.inf.dpp/src/de/fu_berlin/inf/dpp/invitation/OutgoingProjectNegotiation.java
@@ -1,566 +1,566 @@
package de.fu_berlin.inf.dpp.invitation;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.CancellationException;
import org.apache.log4j.Logger;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.core.runtime.SubMonitor;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smackx.filetransfer.OutgoingFileTransfer;
import org.picocontainer.annotations.Inject;
import de.fu_berlin.inf.dpp.FileList;
import de.fu_berlin.inf.dpp.FileListFactory;
import de.fu_berlin.inf.dpp.ISarosContext;
import de.fu_berlin.inf.dpp.User;
import de.fu_berlin.inf.dpp.activities.ProjectExchangeInfo;
import de.fu_berlin.inf.dpp.activities.SPath;
import de.fu_berlin.inf.dpp.editor.EditorManager;
import de.fu_berlin.inf.dpp.editor.internal.EditorAPI;
import de.fu_berlin.inf.dpp.exceptions.LocalCancellationException;
import de.fu_berlin.inf.dpp.exceptions.SarosCancellationException;
import de.fu_berlin.inf.dpp.invitation.ProcessTools.CancelOption;
import de.fu_berlin.inf.dpp.net.JID;
import de.fu_berlin.inf.dpp.net.SarosPacketCollector;
import de.fu_berlin.inf.dpp.net.internal.extensions.FileListExtension;
import de.fu_berlin.inf.dpp.net.internal.extensions.ProjectNegotiationOfferingExtension;
import de.fu_berlin.inf.dpp.net.internal.extensions.StartActivityQueuingRequest;
import de.fu_berlin.inf.dpp.net.internal.extensions.StartActivityQueuingResponse;
import de.fu_berlin.inf.dpp.project.IChecksumCache;
import de.fu_berlin.inf.dpp.project.ISarosSession;
import de.fu_berlin.inf.dpp.project.Messages;
import de.fu_berlin.inf.dpp.synchronize.StartHandle;
import de.fu_berlin.inf.dpp.util.FileZipper;
import de.fu_berlin.inf.dpp.util.MappedList;
import de.fu_berlin.inf.dpp.util.Utils;
import de.fu_berlin.inf.dpp.util.ZipProgressMonitor;
public class OutgoingProjectNegotiation extends ProjectNegotiation {
private static Logger log = Logger
.getLogger(OutgoingProjectNegotiation.class);
/**
* this maps the currently exchanging projects. projectID => project in
* workspace
*/
private List<IProject> projects;
private ISarosSession sarosSession;
/**
* projectID => List of {@link IPath files} that will be send to peer
*/
private MappedList<String, IPath> projectFilesToSend = new MappedList<String, IPath>();
private final static Random INVITATION_RAND = new Random();
@Inject
private EditorManager editorManager;
@Inject
private IChecksumCache checksumCache;
private SarosPacketCollector remoteFileListResponseCollector;
private SarosPacketCollector startActivityQueuingResponseCollector;
public OutgoingProjectNegotiation(JID to, ISarosSession sarosSession,
List<IProject> projects, ISarosContext sarosContext) {
super(to, sarosContext);
this.processID = String.valueOf(INVITATION_RAND.nextLong());
this.sarosSession = sarosSession;
this.projects = projects;
}
public Status start(IProgressMonitor monitor) {
createCollectors();
File zipArchive = null;
List<File> zipArchives = new ArrayList<File>();
observeMonitor(monitor);
Exception exception = null;
try {
if (fileTransferManager == null)
// FIXME: the logic will try to send this to the remote contact
throw new IOException("not connected to a XMPP server");
sendFileList(createProjectExchangeInfoList(projects, monitor),
monitor);
monitor.subTask("");
getRemoteFileList(monitor);
monitor.subTask("");
/*
* FIXME why do we unlock the editors here when we are going to
* block ourself in the next call ?!
*/
editorManager.setAllLocalOpenedEditorsLocked(false);
List<StartHandle> stoppedUsers = null;
try {
stoppedUsers = stopUsers(monitor);
monitor.subTask("");
sendAndAwaitActivityQueueingActivation(monitor);
monitor.subTask("");
/*
* inform all listeners that the peer has started queuing and
* can therefore process IResourceActivities now
*
* TODO this needs a review as this is called inside the
* "blocked" section and so it is not allowed to send resource
* activities at this time. Maybe change the description of the
* listener interface ?
*/
User user = sarosSession.getUser(peer);
if (user == null)
throw new LocalCancellationException(null,
CancelOption.DO_NOT_NOTIFY_PEER);
sarosSession.userStartedQueuing(user);
zipArchives = createProjectArchives(projectFilesToSend, monitor);
monitor.subTask("");
} finally {
if (stoppedUsers != null)
startUsers(stoppedUsers);
}
checkCancellation(CancelOption.NOTIFY_PEER);
if (zipArchives.size() > 0) {
// pack all archive files into one big archive
zipArchive = File.createTempFile("SarosSyncArchive", ".zip");
try {
FileZipper.zipFiles(zipArchives, zipArchive, false,
new ZipProgressMonitor(monitor, zipArchives.size(),
false));
monitor.subTask("");
monitor.done();
} catch (OperationCanceledException e) {
throw new LocalCancellationException();
}
zipArchives.add(zipArchive);
sendArchive(zipArchive, peer, processID, monitor);
+ }
- User user = sarosSession.getUser(peer);
+ User user = sarosSession.getUser(peer);
- if (user == null)
- throw new LocalCancellationException(null,
- CancelOption.DO_NOT_NOTIFY_PEER);
+ if (user == null)
+ throw new LocalCancellationException(null,
+ CancelOption.DO_NOT_NOTIFY_PEER);
- sarosSession.userFinishedProjectNegotiation(user);
+ sarosSession.userFinishedProjectNegotiation(user);
- }
} catch (Exception e) {
exception = e;
} finally {
for (File archive : zipArchives) {
if (!archive.delete())
log.warn("could not archive file: "
+ archive.getAbsolutePath());
}
deleteCollectors();
monitor.done();
}
return terminateProcess(exception);
}
private void sendFileList(List<ProjectExchangeInfo> projectExchangeInfos,
IProgressMonitor monitor) throws SarosCancellationException {
/*
* FIXME must be calculated while the session is blocked !
*
* FIXME display the remote side something that will it receive
* something in the near future
*/
checkCancellation(CancelOption.NOTIFY_PEER);
log.debug(this + " : sending file list");
/*
* sending an activity takes 0 ms because the activity will be buffered
* and send by another thread
*/
// monitor.setTaskName("Sending file list...");
/*
* The Remote receives this message at the InvitationHandler which calls
* the SarosSessionManager which creates a IncomingProjectNegotiation
* instance and pass it to the SarosUI which finally opens the Wizard on
* the remote side
*/
ProjectNegotiationOfferingExtension offering = new ProjectNegotiationOfferingExtension(
sessionID, projectExchangeInfos, processID);
try {
transmitter.sendToSessionUser(ISarosSession.SESSION_CONNECTION_ID,
peer,
ProjectNegotiationOfferingExtension.PROVIDER.create(offering));
} catch (IOException e) {
// TODO cancel negotiation
log.error("Failed sending Project Negotiation offering", e);
}
}
/**
* Retrieve the peer's partial file list and remember which files need to be
* sent to that user
*
* @param monitor
* @throws IOException
* @throws SarosCancellationException
*/
protected void getRemoteFileList(IProgressMonitor monitor)
throws IOException, SarosCancellationException {
log.debug(this + " : waiting for remote file list");
monitor.beginTask("Waiting for " + peer.getName()
+ " to choose project(s) location", IProgressMonitor.UNKNOWN);
checkCancellation(CancelOption.NOTIFY_PEER);
Packet packet = collectPacket(remoteFileListResponseCollector,
60 * 60 * 1000);
if (packet == null)
throw new LocalCancellationException("received no response from "
+ peer + " while waiting for the file list",
CancelOption.DO_NOT_NOTIFY_PEER);
List<FileList> remoteFileLists = FileListExtension.PROVIDER.getPayload(
packet).getFileLists();
log.debug(this + " : remote file list has been received");
checkCancellation(CancelOption.NOTIFY_PEER);
for (FileList fileList : remoteFileLists) {
projectFilesToSend
.put(fileList.getProjectID(), fileList.getPaths());
}
monitor.done();
}
@Override
public Map<String, String> getProjectNames() {
Map<String, String> result = new HashMap<String, String>();
for (IProject project : projects)
result.put(sarosSession.getProjectID(project), project.getName());
return result;
}
@Override
public String getProcessID() {
return this.processID;
}
@Override
protected void executeCancellation() {
if (sarosSession.getRemoteUsers().isEmpty())
sessionManager.stopSarosSession();
}
private List<StartHandle> stopUsers(IProgressMonitor monitor)
throws SarosCancellationException {
Collection<User> usersToStop;
/*
* Make sure that all users are fully registered, otherwise failures
* might occur while a user is currently joining and has not fully
* initialized yet.
*
* See also OutgoingSessionNegotiation#completeInvitation
*/
synchronized (CancelableProcess.SHARED_LOCK) {
usersToStop = new ArrayList<User>(sarosSession.getUsers());
}
log.debug(this + " : stopping users " + usersToStop);
List<StartHandle> startHandles;
monitor.beginTask("Locking the session...", IProgressMonitor.UNKNOWN);
/*
* FIMXE the StopManager should use a timeout as it can happen that a
* user leaves the session during the stop request. Currently it is up
* to the user to press the cancel button because the StopManager did
* not check if the user already left the session.
*
* Stefan Rossbach: The StopManager should not check for the absence of
* a user and so either retry again or just stop the sharing (which
* currently would lead to a broken session because we have no proper
* cancellation logic !
*/
try {
startHandles = sarosSession.getStopManager().stop(usersToStop,
"Synchronizing invitation", monitor);
} catch (CancellationException e) {
checkCancellation(CancelOption.NOTIFY_PEER);
return null;
}
monitor.done();
return startHandles;
}
private void startUsers(List<StartHandle> startHandles) {
for (StartHandle startHandle : startHandles) {
log.debug(this + " : restarting user "
+ Utils.prefix(startHandle.getUser().getJID()));
startHandle.start();
}
}
/**
*
* @param projectFilesToSend
* projectID => List of {@link IPath files} that will be sent to
* peer
* @return List of project archives
*/
private List<File> createProjectArchives(
MappedList<String, IPath> projectFilesToSend, IProgressMonitor monitor)
throws IOException, SarosCancellationException {
log.debug(this + " : creating archive(s)");
SubMonitor subMonitor = SubMonitor.convert(monitor,
"Creating project archives...", projectFilesToSend.keySet().size());
/*
* Use editorManager.saveText() because the EditorAPI.saveProject() will
* not save files which were modified in the background. This is what
* happens for example if a user edits a file which is not opened by the
* local user.
*
* Stefan Rossbach: this will still fail if a user edited a file and
* then closes the editor without saving it.
*/
// FIXME this throws a NPE if the session has already been stopped
for (SPath path : editorManager.getOpenEditorsOfAllParticipants())
editorManager.saveText(path);
checkCancellation(CancelOption.NOTIFY_PEER);
List<File> archivesToSend = new LinkedList<File>();
for (Map.Entry<String, List<IPath>> entry : projectFilesToSend
.entrySet()) {
String projectID = entry.getKey();
List<IPath> filesToCompress = entry.getValue();
File projectArchive = createProjectArchive(subMonitor.newChild(1),
filesToCompress, projectID);
if (projectArchive != null)
archivesToSend.add(projectArchive);
}
subMonitor.done();
return archivesToSend;
}
private File createProjectArchive(IProgressMonitor monitor,
List<IPath> toSend, String projectID) throws IOException,
SarosCancellationException {
IProject project = sarosSession.getProject(projectID);
/*
* TODO: Ask the user whether to save the resources, but only if they
* have changed. How to ask Eclipse whether there are resource changes?
* if (outInvitationUI.confirmProjectSave(peer)) getOpenEditors =>
* filter per Project => if dirty ask to save
*/
EditorAPI.saveProject(project, false);
String prefix = projectID + projectIDDelimiter;
File tempArchive = null;
try {
if (toSend.size() > 0) {
tempArchive = File.createTempFile(prefix, ".zip");
FileZipper.createProjectZipArchive(project, toSend,
tempArchive, new ZipProgressMonitor(monitor, toSend.size(),
true));
}
} catch (OperationCanceledException e) {
throw new LocalCancellationException();
}
monitor.done();
return tempArchive;
}
private void createCollectors() {
remoteFileListResponseCollector = xmppReceiver
.createCollector(FileListExtension.PROVIDER.getPacketFilter(
sessionID, processID));
startActivityQueuingResponseCollector = xmppReceiver
.createCollector(StartActivityQueuingResponse.PROVIDER
.getPacketFilter(sessionID, processID));
}
private void deleteCollectors() {
remoteFileListResponseCollector.cancel();
startActivityQueuingResponseCollector.cancel();
}
private void sendArchive(File archive, JID remoteContact,
String transferID, IProgressMonitor monitor)
throws SarosCancellationException, IOException {
log.debug(this + " : sending archive");
monitor.beginTask("Sending archive file...", 100);
assert fileTransferManager != null;
try {
OutgoingFileTransfer transfer = fileTransferManager
.createOutgoingFileTransfer(remoteContact.toString());
transfer.sendFile(archive, transferID);
monitorFileTransfer(transfer, monitor);
} catch (XMPPException e) {
throw new IOException(e.getMessage(), e);
}
monitor.done();
log.debug(this + " : archive send");
}
/**
* Method to create list of ProjectExchangeInfo.
*
* @param projectsToShare
* List of projects to share
*/
private List<ProjectExchangeInfo> createProjectExchangeInfoList(
List<IProject> projectsToShare, IProgressMonitor monitor)
throws IOException, LocalCancellationException {
SubMonitor subMonitor = SubMonitor.convert(monitor,
Messages.SarosSessionManager_creating_file_list,
projectsToShare.size());
List<ProjectExchangeInfo> pInfos = new ArrayList<ProjectExchangeInfo>(
projectsToShare.size());
for (IProject project : projectsToShare) {
if (monitor.isCanceled())
throw new LocalCancellationException(null,
CancelOption.DO_NOT_NOTIFY_PEER);
try {
String projectID = sarosSession.getProjectID(project);
String projectName = project.getName();
FileList projectFileList = FileListFactory.createFileList(
project, sarosSession.getSharedResources(project),
checksumCache, sarosSession.useVersionControl(),
subMonitor.newChild(1));
projectFileList.setProjectID(projectID);
boolean partial = !sarosSession.isCompletelyShared(project);
ProjectExchangeInfo pInfo = new ProjectExchangeInfo(projectID,
project.getName(), projectName, partial, projectFileList);
pInfos.add(pInfo);
} catch (CoreException e) {
/*
* avoid that the error is send to remote side (which is default
* for IOExceptions) at this point because the remote side has
* no existing project negotiation yet
*/
localCancel(e.getMessage(), CancelOption.DO_NOT_NOTIFY_PEER);
// throw to log this error in the CancelableProcess class
throw new IOException(e.getMessage(), e);
}
}
subMonitor.done();
return pInfos;
}
/**
* Sends an activity queuing request to the remote side and awaits the
* confirmation of the request.
*
* @param monitor
*/
private void sendAndAwaitActivityQueueingActivation(IProgressMonitor monitor)
throws IOException, SarosCancellationException {
monitor.beginTask("Waiting for " + peer.getName()
+ " to perform additional initialization...",
IProgressMonitor.UNKNOWN);
transmitter.sendToSessionUser(ISarosSession.SESSION_CONNECTION_ID,
getPeer(), StartActivityQueuingRequest.PROVIDER
.create(new StartActivityQueuingRequest(sessionID, processID)));
Packet packet = collectPacket(startActivityQueuingResponseCollector,
PACKET_TIMEOUT);
if (packet == null)
throw new LocalCancellationException("received no response from "
+ peer + " while waiting to finish additional initialization",
CancelOption.DO_NOT_NOTIFY_PEER);
monitor.done();
}
@Override
public String toString() {
return "OPN [remote side: " + peer + "]";
}
}
| false | true | public Status start(IProgressMonitor monitor) {
createCollectors();
File zipArchive = null;
List<File> zipArchives = new ArrayList<File>();
observeMonitor(monitor);
Exception exception = null;
try {
if (fileTransferManager == null)
// FIXME: the logic will try to send this to the remote contact
throw new IOException("not connected to a XMPP server");
sendFileList(createProjectExchangeInfoList(projects, monitor),
monitor);
monitor.subTask("");
getRemoteFileList(monitor);
monitor.subTask("");
/*
* FIXME why do we unlock the editors here when we are going to
* block ourself in the next call ?!
*/
editorManager.setAllLocalOpenedEditorsLocked(false);
List<StartHandle> stoppedUsers = null;
try {
stoppedUsers = stopUsers(monitor);
monitor.subTask("");
sendAndAwaitActivityQueueingActivation(monitor);
monitor.subTask("");
/*
* inform all listeners that the peer has started queuing and
* can therefore process IResourceActivities now
*
* TODO this needs a review as this is called inside the
* "blocked" section and so it is not allowed to send resource
* activities at this time. Maybe change the description of the
* listener interface ?
*/
User user = sarosSession.getUser(peer);
if (user == null)
throw new LocalCancellationException(null,
CancelOption.DO_NOT_NOTIFY_PEER);
sarosSession.userStartedQueuing(user);
zipArchives = createProjectArchives(projectFilesToSend, monitor);
monitor.subTask("");
} finally {
if (stoppedUsers != null)
startUsers(stoppedUsers);
}
checkCancellation(CancelOption.NOTIFY_PEER);
if (zipArchives.size() > 0) {
// pack all archive files into one big archive
zipArchive = File.createTempFile("SarosSyncArchive", ".zip");
try {
FileZipper.zipFiles(zipArchives, zipArchive, false,
new ZipProgressMonitor(monitor, zipArchives.size(),
false));
monitor.subTask("");
monitor.done();
} catch (OperationCanceledException e) {
throw new LocalCancellationException();
}
zipArchives.add(zipArchive);
sendArchive(zipArchive, peer, processID, monitor);
User user = sarosSession.getUser(peer);
if (user == null)
throw new LocalCancellationException(null,
CancelOption.DO_NOT_NOTIFY_PEER);
sarosSession.userFinishedProjectNegotiation(user);
}
} catch (Exception e) {
exception = e;
} finally {
for (File archive : zipArchives) {
if (!archive.delete())
log.warn("could not archive file: "
+ archive.getAbsolutePath());
}
deleteCollectors();
monitor.done();
}
return terminateProcess(exception);
}
| public Status start(IProgressMonitor monitor) {
createCollectors();
File zipArchive = null;
List<File> zipArchives = new ArrayList<File>();
observeMonitor(monitor);
Exception exception = null;
try {
if (fileTransferManager == null)
// FIXME: the logic will try to send this to the remote contact
throw new IOException("not connected to a XMPP server");
sendFileList(createProjectExchangeInfoList(projects, monitor),
monitor);
monitor.subTask("");
getRemoteFileList(monitor);
monitor.subTask("");
/*
* FIXME why do we unlock the editors here when we are going to
* block ourself in the next call ?!
*/
editorManager.setAllLocalOpenedEditorsLocked(false);
List<StartHandle> stoppedUsers = null;
try {
stoppedUsers = stopUsers(monitor);
monitor.subTask("");
sendAndAwaitActivityQueueingActivation(monitor);
monitor.subTask("");
/*
* inform all listeners that the peer has started queuing and
* can therefore process IResourceActivities now
*
* TODO this needs a review as this is called inside the
* "blocked" section and so it is not allowed to send resource
* activities at this time. Maybe change the description of the
* listener interface ?
*/
User user = sarosSession.getUser(peer);
if (user == null)
throw new LocalCancellationException(null,
CancelOption.DO_NOT_NOTIFY_PEER);
sarosSession.userStartedQueuing(user);
zipArchives = createProjectArchives(projectFilesToSend, monitor);
monitor.subTask("");
} finally {
if (stoppedUsers != null)
startUsers(stoppedUsers);
}
checkCancellation(CancelOption.NOTIFY_PEER);
if (zipArchives.size() > 0) {
// pack all archive files into one big archive
zipArchive = File.createTempFile("SarosSyncArchive", ".zip");
try {
FileZipper.zipFiles(zipArchives, zipArchive, false,
new ZipProgressMonitor(monitor, zipArchives.size(),
false));
monitor.subTask("");
monitor.done();
} catch (OperationCanceledException e) {
throw new LocalCancellationException();
}
zipArchives.add(zipArchive);
sendArchive(zipArchive, peer, processID, monitor);
}
User user = sarosSession.getUser(peer);
if (user == null)
throw new LocalCancellationException(null,
CancelOption.DO_NOT_NOTIFY_PEER);
sarosSession.userFinishedProjectNegotiation(user);
} catch (Exception e) {
exception = e;
} finally {
for (File archive : zipArchives) {
if (!archive.delete())
log.warn("could not archive file: "
+ archive.getAbsolutePath());
}
deleteCollectors();
monitor.done();
}
return terminateProcess(exception);
}
|
diff --git a/src/lib/com/izforge/izpack/panels/XInfoPanel.java b/src/lib/com/izforge/izpack/panels/XInfoPanel.java
index 50194c6f..4f2ef501 100644
--- a/src/lib/com/izforge/izpack/panels/XInfoPanel.java
+++ b/src/lib/com/izforge/izpack/panels/XInfoPanel.java
@@ -1,162 +1,162 @@
/*
* $Id$
* IzPack
* Copyright (C) 2001-2003 Julien Ponge
*
* File : XInfoPanel.java
* Description : A panel to show some adaptative textual information.
* Author's email : [email protected]
* Author's Website : http://www.izforge.com
*
* Portions are Copyright (c) 2001 Johannes Lehtinen
* [email protected]
* http://www.iki.fi/jle/
*
* 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 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package com.izforge.izpack.panels;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import com.izforge.izpack.installer.InstallData;
import com.izforge.izpack.installer.InstallerFrame;
import com.izforge.izpack.installer.IzPanel;
import com.izforge.izpack.installer.ResourceManager;
import com.izforge.izpack.installer.VariableSubstitutor;
/**
* The XInfo panel class - shows some adaptative text (ie by parsing for some
* variables.
*
* @author Julien Ponge
*/
public class XInfoPanel extends IzPanel
{
/** The layout. */
private GridBagLayout layout;
/** The layout constraints. */
private GridBagConstraints gbConstraints;
/** The info label. */
private JLabel infoLabel;
/** The text area. */
private JTextArea textArea;
/** The info to display. */
private String info;
/**
* The constructor.
*
* @param parent The parent window.
* @param idata The installation data.
*/
public XInfoPanel(InstallerFrame parent, InstallData idata)
{
super(parent, idata);
// We initialize our layout
layout = new GridBagLayout();
gbConstraints = new GridBagConstraints();
setLayout(layout);
// We add the components
infoLabel = new JLabel(parent.langpack.getString("InfoPanel.info"),
parent.icons.getImageIcon("edit"), JLabel.TRAILING);
parent.buildConstraints(gbConstraints, 0, 0, 1, 1, 1.0, 0.0);
gbConstraints.insets = new Insets(5, 5, 5, 5);
- gbConstraints.fill = GridBagConstraints.NONE;
+ gbConstraints.fill = GridBagConstraints.BOTH;
gbConstraints.anchor = GridBagConstraints.SOUTHWEST;
layout.addLayoutComponent(infoLabel, gbConstraints);
add(infoLabel);
textArea = new JTextArea();
textArea.setEditable(false);
JScrollPane scroller = new JScrollPane(textArea);
parent.buildConstraints(gbConstraints, 0, 1, 1, 1, 1.0, 0.9);
gbConstraints.anchor = GridBagConstraints.CENTER;
layout.addLayoutComponent(scroller, gbConstraints);
add(scroller);
}
/** Loads the info text. */
private void loadInfo()
{
try
{
// We read it
info = ResourceManager.getInstance().getTextResource("XInfoPanel.info");
}
catch (Exception err)
{
info = "Error : could not load the info text !";
}
}
/** Parses the text for special variables. */
private void parseText()
{
try
{
// Initialize the variable substitutor
VariableSubstitutor vs = new VariableSubstitutor
(idata.getVariableValueMap());
// Parses the info text
info = vs.substitute(info, null);
}
catch (Exception err)
{
err.printStackTrace();
}
}
/** Called when the panel becomes active. */
public void panelActivate()
{
// Text handling
loadInfo();
parseText();
// UI handling
textArea.setText(info.toString());
textArea.setCaretPosition(0);
}
/**
* Indicates wether the panel has been validated or not.
*
* @return Always true.
*/
public boolean isValidated()
{
return true;
}
}
| true | true | public XInfoPanel(InstallerFrame parent, InstallData idata)
{
super(parent, idata);
// We initialize our layout
layout = new GridBagLayout();
gbConstraints = new GridBagConstraints();
setLayout(layout);
// We add the components
infoLabel = new JLabel(parent.langpack.getString("InfoPanel.info"),
parent.icons.getImageIcon("edit"), JLabel.TRAILING);
parent.buildConstraints(gbConstraints, 0, 0, 1, 1, 1.0, 0.0);
gbConstraints.insets = new Insets(5, 5, 5, 5);
gbConstraints.fill = GridBagConstraints.NONE;
gbConstraints.anchor = GridBagConstraints.SOUTHWEST;
layout.addLayoutComponent(infoLabel, gbConstraints);
add(infoLabel);
textArea = new JTextArea();
textArea.setEditable(false);
JScrollPane scroller = new JScrollPane(textArea);
parent.buildConstraints(gbConstraints, 0, 1, 1, 1, 1.0, 0.9);
gbConstraints.anchor = GridBagConstraints.CENTER;
layout.addLayoutComponent(scroller, gbConstraints);
add(scroller);
}
| public XInfoPanel(InstallerFrame parent, InstallData idata)
{
super(parent, idata);
// We initialize our layout
layout = new GridBagLayout();
gbConstraints = new GridBagConstraints();
setLayout(layout);
// We add the components
infoLabel = new JLabel(parent.langpack.getString("InfoPanel.info"),
parent.icons.getImageIcon("edit"), JLabel.TRAILING);
parent.buildConstraints(gbConstraints, 0, 0, 1, 1, 1.0, 0.0);
gbConstraints.insets = new Insets(5, 5, 5, 5);
gbConstraints.fill = GridBagConstraints.BOTH;
gbConstraints.anchor = GridBagConstraints.SOUTHWEST;
layout.addLayoutComponent(infoLabel, gbConstraints);
add(infoLabel);
textArea = new JTextArea();
textArea.setEditable(false);
JScrollPane scroller = new JScrollPane(textArea);
parent.buildConstraints(gbConstraints, 0, 1, 1, 1, 1.0, 0.9);
gbConstraints.anchor = GridBagConstraints.CENTER;
layout.addLayoutComponent(scroller, gbConstraints);
add(scroller);
}
|
diff --git a/src/web/org/codehaus/groovy/grails/web/mapping/RegexUrlMapping.java b/src/web/org/codehaus/groovy/grails/web/mapping/RegexUrlMapping.java
index 668f14074..a358bc977 100644
--- a/src/web/org/codehaus/groovy/grails/web/mapping/RegexUrlMapping.java
+++ b/src/web/org/codehaus/groovy/grails/web/mapping/RegexUrlMapping.java
@@ -1,493 +1,497 @@
/* Copyright 2004-2005 Graeme Rocher
*
* 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.mapping;
import groovy.lang.Closure;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.groovy.grails.commons.GrailsControllerClass;
import org.codehaus.groovy.grails.validation.ConstrainedProperty;
import org.codehaus.groovy.grails.web.mapping.exceptions.UrlMappingException;
import org.codehaus.groovy.grails.web.servlet.mvc.GrailsWebRequest;
import org.codehaus.groovy.grails.web.servlet.mvc.exceptions.ControllerExecutionException;
import org.springframework.validation.Errors;
import org.springframework.validation.MapBindingResult;
import org.springframework.web.context.request.RequestContextHolder;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
/**
* <p>A UrlMapping implementation that takes a Grails URL pattern and turns it into a regex matcher so that
* URLs can be matched and information captured from the match.</p>
*
* <p>A Grails URL pattern is not a regex, but is an extension to the form defined by Apache Ant and used by
* Spring AntPathMatcher. Unlike regular Ant paths Grails URL patterns allow for capturing groups in the form:</p>
*
* <code>/blog/(*)/**</code>
*
* <p>The parenthesis define a capturing group. This implementation transforms regular Ant paths into regular expressions
* that are able to use capturing groups</p>
*
*
* @see org.springframework.util.AntPathMatcher
*
* @author Graeme Rocher
* @since 0.5
*
* <p/>
* Created: Feb 28, 2007
* Time: 6:12:52 PM
*/
public class RegexUrlMapping extends AbstractUrlMapping implements UrlMapping {
private Pattern[] patterns;
private UrlMappingData urlData;
private static final String WILDCARD = "*";
private static final String CAPTURED_WILDCARD = "(*)";
private static final String SLASH = "/";
private static final char QUESTION_MARK = '?';
private static final String ENTITY_AMPERSAND = "&";
private static final char AMPERSAND = '&';
private static final String DOUBLE_WILDCARD = "**";
private static final String DEFAULT_ENCODING = "UTF-8";
private static final String CAPTURED_DOUBLE_WILDCARD = "(**)";
private static final Log LOG = LogFactory.getLog(RegexUrlMapping.class);
/**
* Constructs a new RegexUrlMapping for the given pattern, controller name, action name and constraints.
*
* @param data An instance of the UrlMappingData class that holds necessary information of the URL mapping
* @param controllerName The name of the controller the URL maps to (required)
* @param actionName The name of the action the URL maps to
* @param viewName The name of the view as an alternative to the name of the action. If the action is specified it takes precedence over the view name during mapping
* @param constraints A list of ConstrainedProperty instances that relate to tokens in the URL
*
* @see org.codehaus.groovy.grails.validation.ConstrainedProperty
*/
public RegexUrlMapping(UrlMappingData data, Object controllerName, Object actionName, Object viewName, ConstrainedProperty[] constraints) {
super(controllerName, actionName, viewName, constraints != null ? constraints : new ConstrainedProperty[0]);
parse(data, constraints);
}
private void parse(UrlMappingData data, ConstrainedProperty[] constraints) {
if(data == null) throw new IllegalArgumentException("Argument [pattern] cannot be null");
String[] urls = data.getLogicalUrls();
this.urlData = data;
this.patterns = new Pattern[urls.length];
for (int i = 0; i < urls.length; i++) {
String url = urls[i];
Pattern pattern = convertToRegex(url);
if(pattern == null) throw new IllegalStateException("Cannot use null pattern in regular expression mapping for url ["+data.getUrlPattern()+"]");
this.patterns[i] = pattern;
}
if(constraints != null) {
for (int i = 0; i < constraints.length; i++) {
ConstrainedProperty constraint = constraints[i];
if(data.isOptional(i)) {
constraint.setNullable(true);
}
}
}
}
/**
* Converst a Grails URL provides via the UrlMappingData interface to a regular expression
*
* @param url The URL to convert
* @return A regex Pattern objet
*/
protected Pattern convertToRegex(String url) {
Pattern regex;
String pattern = null;
try {
pattern = "^" + url.replaceAll("([^\\*])\\*([^\\*])", "$1[^/]+$2").replaceAll("([^\\*])\\*$", "$1[^/]+").replaceAll("\\*\\*", ".*");
pattern += "/??$";
regex = Pattern.compile(pattern);
} catch (PatternSyntaxException pse) {
throw new UrlMappingException("Error evaluating mapping for pattern ["+pattern+"] from Grails URL mappings: " + pse.getMessage(), pse);
}
return regex;
}
/**
* Matches the given URI and returns a DefaultUrlMappingInfo instance or null
*
*
* @param uri The URI to match
* @return A UrlMappingInfo instance or null
*
* @see org.codehaus.groovy.grails.web.mapping.UrlMappingInfo
*/
public UrlMappingInfo match(String uri) {
for (int i = 0; i < patterns.length; i++) {
Pattern pattern = patterns[i];
Matcher m = pattern.matcher(uri);
if(m.matches()) {
UrlMappingInfo urlInfo = createUrlMappingInfo(uri,m);
if(urlInfo!=null) {
return urlInfo;
}
}
}
return null;
}
/**
* @see org.codehaus.groovy.grails.web.mapping.UrlMapping
*/
public String createURL(Map parameterValues, String encoding) {
return createURLInternal(parameterValues, encoding, true);
}
private String createURLInternal(Map parameterValues, String encoding, boolean includeContextPath) {
if(encoding == null) encoding = "utf-8";
String contextPath = "";
if(includeContextPath) {
GrailsWebRequest webRequest = (GrailsWebRequest) RequestContextHolder.getRequestAttributes();
if(webRequest != null) {
contextPath = webRequest.getAttributes().getApplicationUri(webRequest.getCurrentRequest());
}
}
if(parameterValues==null)parameterValues= Collections.EMPTY_MAP;
StringBuffer uri = new StringBuffer(contextPath);
Set usedParams = new HashSet();
String[] tokens = urlData.getTokens();
int paramIndex = 0;
for (int i = 0; i < tokens.length; i++) {
String token = tokens[i];
if(CAPTURED_WILDCARD.equals(token) || CAPTURED_DOUBLE_WILDCARD.equals(token)) {
ConstrainedProperty prop = this.constraints[paramIndex++];
String propName = prop.getPropertyName();
Object value = parameterValues.get(propName);
usedParams.add(propName);
if(value == null && !prop.isNullable())
throw new UrlMappingException("Unable to create URL for mapping ["+this+"] and parameters ["+parameterValues+"]. Parameter ["+prop.getPropertyName()+"] is required, but was not specified!");
else if(value == null)
break;
try {
uri.append(SLASH).append(URLEncoder.encode(value.toString(), encoding));
} catch (UnsupportedEncodingException e) {
throw new ControllerExecutionException("Error creating URL for parameters ["+parameterValues +"], problem encoding URL part ["+value +"]: " + e.getMessage(),e);
}
}
else {
uri.append(SLASH).append(token);
}
}
populateParameterList(parameterValues, encoding, uri, usedParams);
if(LOG.isDebugEnabled()) {
LOG.debug("Created reverse URL mapping ["+uri.toString()+"] for parameters ["+parameterValues+"]");
}
return uri.toString();
}
public String createURL(Map parameterValues, String encoding, String fragment) {
String url = createURL(parameterValues, encoding);
return createUrlWithFragment(url, fragment, encoding);
}
public String createURL(String controller, String action, Map parameterValues, String encoding) {
return createURLInternal(controller, action, parameterValues, encoding, true);
}
private String createURLInternal(String controller, String action, Map parameterValues, String encoding, boolean includeContextPath) {
if(parameterValues == null) parameterValues = new HashMap();
boolean hasController = !StringUtils.isBlank(controller);
boolean hasAction = !StringUtils.isBlank(action);
try {
if(hasController)
parameterValues.put(CONTROLLER, controller);
if(hasAction)
parameterValues.put(ACTION, action);
return createURLInternal(parameterValues, encoding, includeContextPath);
} finally {
if(hasController)
parameterValues.remove(CONTROLLER);
if(hasAction)
parameterValues.remove(ACTION);
}
}
public String createRelativeURL(String controller, String action, Map parameterValues, String encoding) {
return createURLInternal(controller, action, parameterValues, encoding, false);
}
public String createURL(String controller, String action, Map parameterValues, String encoding, String fragment) {
String url = createURL(controller, action, parameterValues, encoding);
return createUrlWithFragment(url, fragment, encoding);
}
private String createUrlWithFragment(String url, String fragment, String encoding) {
if(fragment != null) {
// A 'null' encoding will cause an exception, so default to 'UTF-8'.
if (encoding == null) {
encoding = DEFAULT_ENCODING;
}
try {
return url + '#' + URLEncoder.encode(fragment, encoding);
} catch (UnsupportedEncodingException ex) {
throw new ControllerExecutionException("Error creating URL ["+url +"], problem encoding URL fragment ["+fragment +"]: " + ex.getMessage(),ex);
}
}
else {
return url;
}
}
private void populateParameterList(Map parameterValues, String encoding, StringBuffer uri, Set usedParams) {
boolean addedParams = false;
usedParams.add( "controller" );
usedParams.add( "action" );
// A 'null' encoding will cause an exception, so default to 'UTF-8'.
if (encoding == null) {
encoding = DEFAULT_ENCODING;
}
for (Iterator i = parameterValues.keySet().iterator(); i.hasNext();) {
String name = i.next().toString();
if(!usedParams.contains(name)) {
if(!addedParams) {
uri.append(QUESTION_MARK);
addedParams = true;
}
else {
uri.append(AMPERSAND);
}
Object value = parameterValues.get(name);
if(value != null && value instanceof Collection) {
Collection multiValues = (Collection)value;
for (Iterator j = multiValues.iterator(); j.hasNext();) {
Object o = j.next();
appendValueToURI(encoding, uri, name, o);
if(j.hasNext()) {
uri.append(AMPERSAND);
}
}
}
else if(value!= null && value.getClass().isArray()) {
Object[] multiValues = (Object[])value;
for (int j = 0; j < multiValues.length; j++) {
Object o = multiValues[j];
appendValueToURI(encoding, uri, name, o);
if(j+1 < multiValues.length) {
uri.append(AMPERSAND);
}
}
}
else {
appendValueToURI(encoding, uri, name, value);
}
}
}
}
private void appendValueToURI(String encoding, StringBuffer uri, String name, Object value) {
try {
uri.append(URLEncoder.encode(name,encoding)).append('=')
.append(URLEncoder.encode(value != null ? value.toString() : "",encoding));
} catch (UnsupportedEncodingException e) {
throw new ControllerExecutionException("Error redirecting request for url ["+name+":"+value +"]: " + e.getMessage(),e);
}
}
public UrlMappingData getUrlData() {
return this.urlData;
}
private UrlMappingInfo createUrlMappingInfo(String uri, Matcher m) {
Map params = new HashMap();
Errors errors = new MapBindingResult(params, "urlMapping");
String lastGroup = null;
for (int i = 0; i < m.groupCount(); i++) {
lastGroup = m.group(i+1);
+ int j = lastGroup.indexOf('?');
+ if(j >-1) {
+ lastGroup = lastGroup.substring(0,j);
+ }
if(constraints.length > i) {
ConstrainedProperty cp = constraints[i];
cp.validate(this,lastGroup, errors);
if(errors.hasErrors()) return null;
else {
params.put(cp.getPropertyName(), lastGroup);
}
}
}
if(lastGroup!= null) {
String remainingUri = uri.substring(uri.lastIndexOf(lastGroup)+lastGroup.length());
if(remainingUri.length() > 0) {
if(remainingUri.startsWith(SLASH))remainingUri = remainingUri.substring(1);
String[] tokens = remainingUri.split(SLASH);
for (int i = 0; i < tokens.length; i=i+2) {
String token = tokens[i];
if((i+1) < tokens.length) {
params.put(token, tokens[i+1]);
}
}
}
}
for (Iterator i = this.parameterValues.keySet().iterator(); i.hasNext();) {
Object key = i.next();
params.put(key, this.parameterValues.get(key));
}
if(controllerName == null) {
this.controllerName = createRuntimeConstraintEvaluator(GrailsControllerClass.CONTROLLER, this.constraints);
}
if(actionName == null) {
this.actionName = createRuntimeConstraintEvaluator(GrailsControllerClass.ACTION, this.constraints);
}
if(viewName == null) {
this.viewName = createRuntimeConstraintEvaluator(GrailsControllerClass.VIEW, this.constraints);
}
if (viewName != null && this.controllerName == null) {
return new DefaultUrlMappingInfo(viewName, params,this.urlData);
}
else {
return new DefaultUrlMappingInfo(this.controllerName, this.actionName,getViewName(), params,this.urlData);
}
}
/**
* This method will look for a constraint for the given name and return a closure that when executed will
* attempt to evaluate its value from the bound request parameters at runtime.
*
* @param name The name of the constrained property
* @param constraints The array of current ConstrainedProperty instances
* @return Either a Closure or null
*/
private Object createRuntimeConstraintEvaluator(final String name, ConstrainedProperty[] constraints) {
if(constraints == null)return null;
for (int i = 0; i < constraints.length; i++) {
ConstrainedProperty constraint = constraints[i];
if(constraint.getPropertyName().equals(name)) {
return new Closure(this) {
public Object call(Object[] objects) {
GrailsWebRequest webRequest = (GrailsWebRequest)RequestContextHolder.currentRequestAttributes();
return webRequest.getParams().get(name);
}
};
}
}
return null;
}
public String[] getLogicalMappings() {
return this.urlData.getLogicalUrls();
}
/**
* Compares this UrlMapping instance with the specified UrlMapping instance and deals with URL mapping precedence rules.
*
* @param o An instance of the UrlMapping interface
* @return 1 if this UrlMapping should match before the specified UrlMapping. 0 if they are equal or -1 if this UrlMapping should match after the given UrlMapping
*/
public int compareTo(Object o) {
if(!(o instanceof UrlMapping)) throw new IllegalArgumentException("Cannot compare with Object ["+o+"]. It is not an instance of UrlMapping!");
UrlMapping other = (UrlMapping)o;
String[] otherTokens = other
.getUrlData()
.getTokens();
String[] tokens = getUrlData().getTokens();
if( isWildcard(this) && !isWildcard( other ) ) return -1;
if( !isWildcard(this) && isWildcard( other ) ) return 1;
if(tokens.length < otherTokens.length) {
return -1;
}
else if(tokens.length > otherTokens.length) {
return 1;
}
int result = 0;
for (int i = 0; i < tokens.length; i++) {
String token = tokens[i];
if(otherTokens.length > i) {
String otherToken = otherTokens[i];
if(isWildcard(token) && !isWildcard(otherToken)) {
result = -1;
break;
}
else if(!isWildcard(token) && isWildcard(otherToken)) {
result = 1;
break;
}
}
else {
break;
}
}
return result;
}
private boolean isWildcard(UrlMapping mapping) {
String[] tokens = mapping.getUrlData().getTokens();
for( int i = 0; i < tokens.length; i++ ) {
if( isWildcard( tokens[i] )) return true;
}
return false;
}
private boolean isWildcard(String token) {
return WILDCARD.equals(token) || CAPTURED_WILDCARD.equals(token) || DOUBLE_WILDCARD.equals(token) || CAPTURED_DOUBLE_WILDCARD.equals(token);
}
public String toString() {
return this.urlData.getUrlPattern();
}
}
| true | true | private UrlMappingInfo createUrlMappingInfo(String uri, Matcher m) {
Map params = new HashMap();
Errors errors = new MapBindingResult(params, "urlMapping");
String lastGroup = null;
for (int i = 0; i < m.groupCount(); i++) {
lastGroup = m.group(i+1);
if(constraints.length > i) {
ConstrainedProperty cp = constraints[i];
cp.validate(this,lastGroup, errors);
if(errors.hasErrors()) return null;
else {
params.put(cp.getPropertyName(), lastGroup);
}
}
}
if(lastGroup!= null) {
String remainingUri = uri.substring(uri.lastIndexOf(lastGroup)+lastGroup.length());
if(remainingUri.length() > 0) {
if(remainingUri.startsWith(SLASH))remainingUri = remainingUri.substring(1);
String[] tokens = remainingUri.split(SLASH);
for (int i = 0; i < tokens.length; i=i+2) {
String token = tokens[i];
if((i+1) < tokens.length) {
params.put(token, tokens[i+1]);
}
}
}
}
for (Iterator i = this.parameterValues.keySet().iterator(); i.hasNext();) {
Object key = i.next();
params.put(key, this.parameterValues.get(key));
}
if(controllerName == null) {
this.controllerName = createRuntimeConstraintEvaluator(GrailsControllerClass.CONTROLLER, this.constraints);
}
if(actionName == null) {
this.actionName = createRuntimeConstraintEvaluator(GrailsControllerClass.ACTION, this.constraints);
}
if(viewName == null) {
this.viewName = createRuntimeConstraintEvaluator(GrailsControllerClass.VIEW, this.constraints);
}
if (viewName != null && this.controllerName == null) {
return new DefaultUrlMappingInfo(viewName, params,this.urlData);
}
else {
return new DefaultUrlMappingInfo(this.controllerName, this.actionName,getViewName(), params,this.urlData);
}
}
| private UrlMappingInfo createUrlMappingInfo(String uri, Matcher m) {
Map params = new HashMap();
Errors errors = new MapBindingResult(params, "urlMapping");
String lastGroup = null;
for (int i = 0; i < m.groupCount(); i++) {
lastGroup = m.group(i+1);
int j = lastGroup.indexOf('?');
if(j >-1) {
lastGroup = lastGroup.substring(0,j);
}
if(constraints.length > i) {
ConstrainedProperty cp = constraints[i];
cp.validate(this,lastGroup, errors);
if(errors.hasErrors()) return null;
else {
params.put(cp.getPropertyName(), lastGroup);
}
}
}
if(lastGroup!= null) {
String remainingUri = uri.substring(uri.lastIndexOf(lastGroup)+lastGroup.length());
if(remainingUri.length() > 0) {
if(remainingUri.startsWith(SLASH))remainingUri = remainingUri.substring(1);
String[] tokens = remainingUri.split(SLASH);
for (int i = 0; i < tokens.length; i=i+2) {
String token = tokens[i];
if((i+1) < tokens.length) {
params.put(token, tokens[i+1]);
}
}
}
}
for (Iterator i = this.parameterValues.keySet().iterator(); i.hasNext();) {
Object key = i.next();
params.put(key, this.parameterValues.get(key));
}
if(controllerName == null) {
this.controllerName = createRuntimeConstraintEvaluator(GrailsControllerClass.CONTROLLER, this.constraints);
}
if(actionName == null) {
this.actionName = createRuntimeConstraintEvaluator(GrailsControllerClass.ACTION, this.constraints);
}
if(viewName == null) {
this.viewName = createRuntimeConstraintEvaluator(GrailsControllerClass.VIEW, this.constraints);
}
if (viewName != null && this.controllerName == null) {
return new DefaultUrlMappingInfo(viewName, params,this.urlData);
}
else {
return new DefaultUrlMappingInfo(this.controllerName, this.actionName,getViewName(), params,this.urlData);
}
}
|
diff --git a/core/src/main/java/hudson/maven/reporters/MavenArtifactArchiver.java b/core/src/main/java/hudson/maven/reporters/MavenArtifactArchiver.java
index eabfe544f..c6e4cf6eb 100644
--- a/core/src/main/java/hudson/maven/reporters/MavenArtifactArchiver.java
+++ b/core/src/main/java/hudson/maven/reporters/MavenArtifactArchiver.java
@@ -1,192 +1,194 @@
package hudson.maven.reporters;
import hudson.FilePath;
import hudson.maven.MavenBuild;
import hudson.maven.MavenBuildProxy;
import hudson.maven.MavenBuildProxy.BuildCallable;
import hudson.maven.MavenEmbedder;
import hudson.maven.MavenModule;
import hudson.maven.MavenReporter;
import hudson.maven.MavenReporterDescriptor;
import hudson.maven.MavenUtil;
import hudson.maven.MojoInfo;
import hudson.model.BuildListener;
import hudson.model.FingerprintMap;
import hudson.model.Hudson;
import hudson.model.Result;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.factory.ArtifactFactory;
import org.apache.maven.artifact.installer.ArtifactInstallationException;
import org.apache.maven.artifact.installer.ArtifactInstaller;
import org.apache.maven.embedder.MavenEmbedderException;
import org.apache.maven.project.MavenProject;
import org.apache.maven.project.artifact.ProjectArtifactMetadata;
import org.codehaus.plexus.component.repository.exception.ComponentLookupException;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
/**
* Archives artifacts of the build.
*
* <p>
* Archive will be created in two places. One is inside the build directory,
* to be served from Hudson. The other is to the local repository of the master,
* so that artifacts can be shared in maven builds happening in other slaves.
*
* @author Kohsuke Kawaguchi
*/
public class MavenArtifactArchiver extends MavenReporter {
private transient boolean installed;
public boolean postExecute(MavenBuildProxy build, MavenProject pom, MojoInfo mojo, BuildListener listener, Throwable error) throws InterruptedException, IOException {
if(!mojo.pluginName.matches("org.apache.maven.plugins","maven-install-plugin"))
return true;
if(!mojo.getGoal().equals("install"))
return true;
this.installed = true;
return true;
}
public boolean postBuild(MavenBuildProxy build, MavenProject pom, final BuildListener listener) throws InterruptedException, IOException {
final Set<ArtifactInfo> archivedFiles = new HashSet<ArtifactInfo>();
// record POM
- listener.getLogger().println("[HUDSON] Archiving "+ pom.getFile());
- final FilePath archivedPom = getArtifactArchivePath(build, pom.getGroupId(), pom.getArtifactId(), pom.getVersion())
- .child(pom.getArtifactId() + '-' + pom.getVersion() + ".pom");
- new FilePath(pom.getFile()).copyTo(archivedPom);
+ if(pom.getFile()!=null) {// goals like 'clean' runs without loading POM, apparently.
+ listener.getLogger().println("[HUDSON] Archiving "+ pom.getFile());
+ final FilePath archivedPom = getArtifactArchivePath(build, pom.getGroupId(), pom.getArtifactId(), pom.getVersion())
+ .child(pom.getArtifactId() + '-' + pom.getVersion() + ".pom");
+ new FilePath(pom.getFile()).copyTo(archivedPom);
+ }
// record artifacts
record(build,pom.getArtifact(),listener,archivedFiles,true);
for( Object a : pom.getAttachedArtifacts() )
record(build,(Artifact)a,listener,archivedFiles,false);
final boolean installed = this.installed;
final boolean builtOnSlave = archivedPom.isRemote();
if(!archivedFiles.isEmpty()) {
build.execute(new BuildCallable<Void,IOException>() {
public Void call(MavenBuild build) throws IOException, InterruptedException {
// record fingerprints
FingerprintMap map = Hudson.getInstance().getFingerprintMap();
for (ArtifactInfo a : archivedFiles)
map.getOrCreate(build, a.path.getName(), a.path.digest());
// install files on the master
if(installed && builtOnSlave) {
try {
MavenEmbedder embedder = MavenUtil.createEmbedder(listener);
ArtifactInstaller installer = (ArtifactInstaller) embedder.getContainer().lookup(ArtifactInstaller.class.getName());
ArtifactFactory factory = (ArtifactFactory) embedder.getContainer().lookup(ArtifactFactory.class.getName());
for (ArtifactInfo a : archivedFiles) {
Artifact artifact = a.toArtifact(factory);
if(a.isPrimary)
artifact.addMetadata( new ProjectArtifactMetadata( artifact, new File(archivedPom.getRemote()) ) );
installer.install(new File(a.path.getRemote()), artifact,embedder.getLocalRepository());
}
embedder.stop();
} catch (MavenEmbedderException e) {
e.printStackTrace(listener.error("Failed to install artifact to the master"));
build.setResult(Result.FAILURE);
} catch (ComponentLookupException e) {
e.printStackTrace(listener.error("Failed to install artifact to the master"));
build.setResult(Result.FAILURE);
} catch (ArtifactInstallationException e) {
e.printStackTrace(listener.error("Failed to install artifact to the master"));
build.setResult(Result.FAILURE);
}
}
return null;
}
});
}
return true;
}
/**
* Archives the given {@link Artifact}.
*/
private void record(MavenBuildProxy build, Artifact a, BuildListener listener, Set<ArtifactInfo> archivedFiles, boolean primary) throws IOException, InterruptedException {
File file = a.getFile();
if(file==null)
return; // perhaps build failed and didn't leave an artifact
if(!file.exists() || file.isDirectory())
return; // during a build maven sets a class folder instead of a jar file as artifact. ignore.
listener.getLogger().println("[HUDSON] Archiving "+ file);
FilePath target = getArtifactArchivePath(build, a.getGroupId(), a.getArtifactId(), a.getVersion())
.child(a.getArtifactId() + '-' + a.getVersion() + (a.getClassifier() != null ? '-' + a.getClassifier() : "") + '.' + a.getType());
new FilePath(file).copyTo(target);
archivedFiles.add(new ArtifactInfo(a,target,primary));
}
private FilePath getArtifactArchivePath(MavenBuildProxy build, String groupId, String artifactId, String version) {
return build.getArtifactsDir().child(groupId).child(artifactId).child(version);
}
public DescriptorImpl getDescriptor() {
return DescriptorImpl.DESCRIPTOR;
}
public static final class DescriptorImpl extends MavenReporterDescriptor {
public static final DescriptorImpl DESCRIPTOR = new DescriptorImpl();
private DescriptorImpl() {
super(MavenArtifactArchiver.class);
}
public String getDisplayName() {
return "Archive the artifacts";
}
public MavenReporter newAutoInstance(MavenModule module) {
return new MavenArtifactArchiver();
}
}
/**
* Serializable datatype that captures {@link Artifact} so that it can be
* sent from the slave to the master.
*/
static final class ArtifactInfo implements Serializable {
private final String groupId, artifactId, version, classifier, type;
/**
* Archived artifact on the master.
*/
final FilePath path;
/**
* True for the main artifact. Maven install mojo only seems to associate POM
* with the primary artifact, hence this flag.
*/
final boolean isPrimary;
ArtifactInfo(Artifact a, FilePath path, boolean primary) {
this.groupId = a.getGroupId();
this.artifactId = a.getArtifactId();
this.version = a.getVersion();
this.classifier = a.getClassifier();
this.type = a.getType();
this.path = path;
this.isPrimary = primary;
}
Artifact toArtifact(ArtifactFactory factory) {
return factory.createArtifactWithClassifier(groupId, artifactId, version, type, classifier);
}
private static final long serialVersionUID = 1L;
}
private static final long serialVersionUID = 1L;
}
| true | true | public boolean postBuild(MavenBuildProxy build, MavenProject pom, final BuildListener listener) throws InterruptedException, IOException {
final Set<ArtifactInfo> archivedFiles = new HashSet<ArtifactInfo>();
// record POM
listener.getLogger().println("[HUDSON] Archiving "+ pom.getFile());
final FilePath archivedPom = getArtifactArchivePath(build, pom.getGroupId(), pom.getArtifactId(), pom.getVersion())
.child(pom.getArtifactId() + '-' + pom.getVersion() + ".pom");
new FilePath(pom.getFile()).copyTo(archivedPom);
// record artifacts
record(build,pom.getArtifact(),listener,archivedFiles,true);
for( Object a : pom.getAttachedArtifacts() )
record(build,(Artifact)a,listener,archivedFiles,false);
final boolean installed = this.installed;
final boolean builtOnSlave = archivedPom.isRemote();
if(!archivedFiles.isEmpty()) {
build.execute(new BuildCallable<Void,IOException>() {
public Void call(MavenBuild build) throws IOException, InterruptedException {
// record fingerprints
FingerprintMap map = Hudson.getInstance().getFingerprintMap();
for (ArtifactInfo a : archivedFiles)
map.getOrCreate(build, a.path.getName(), a.path.digest());
// install files on the master
if(installed && builtOnSlave) {
try {
MavenEmbedder embedder = MavenUtil.createEmbedder(listener);
ArtifactInstaller installer = (ArtifactInstaller) embedder.getContainer().lookup(ArtifactInstaller.class.getName());
ArtifactFactory factory = (ArtifactFactory) embedder.getContainer().lookup(ArtifactFactory.class.getName());
for (ArtifactInfo a : archivedFiles) {
Artifact artifact = a.toArtifact(factory);
if(a.isPrimary)
artifact.addMetadata( new ProjectArtifactMetadata( artifact, new File(archivedPom.getRemote()) ) );
installer.install(new File(a.path.getRemote()), artifact,embedder.getLocalRepository());
}
embedder.stop();
} catch (MavenEmbedderException e) {
e.printStackTrace(listener.error("Failed to install artifact to the master"));
build.setResult(Result.FAILURE);
} catch (ComponentLookupException e) {
e.printStackTrace(listener.error("Failed to install artifact to the master"));
build.setResult(Result.FAILURE);
} catch (ArtifactInstallationException e) {
e.printStackTrace(listener.error("Failed to install artifact to the master"));
build.setResult(Result.FAILURE);
}
}
return null;
}
});
}
return true;
}
| public boolean postBuild(MavenBuildProxy build, MavenProject pom, final BuildListener listener) throws InterruptedException, IOException {
final Set<ArtifactInfo> archivedFiles = new HashSet<ArtifactInfo>();
// record POM
if(pom.getFile()!=null) {// goals like 'clean' runs without loading POM, apparently.
listener.getLogger().println("[HUDSON] Archiving "+ pom.getFile());
final FilePath archivedPom = getArtifactArchivePath(build, pom.getGroupId(), pom.getArtifactId(), pom.getVersion())
.child(pom.getArtifactId() + '-' + pom.getVersion() + ".pom");
new FilePath(pom.getFile()).copyTo(archivedPom);
}
// record artifacts
record(build,pom.getArtifact(),listener,archivedFiles,true);
for( Object a : pom.getAttachedArtifacts() )
record(build,(Artifact)a,listener,archivedFiles,false);
final boolean installed = this.installed;
final boolean builtOnSlave = archivedPom.isRemote();
if(!archivedFiles.isEmpty()) {
build.execute(new BuildCallable<Void,IOException>() {
public Void call(MavenBuild build) throws IOException, InterruptedException {
// record fingerprints
FingerprintMap map = Hudson.getInstance().getFingerprintMap();
for (ArtifactInfo a : archivedFiles)
map.getOrCreate(build, a.path.getName(), a.path.digest());
// install files on the master
if(installed && builtOnSlave) {
try {
MavenEmbedder embedder = MavenUtil.createEmbedder(listener);
ArtifactInstaller installer = (ArtifactInstaller) embedder.getContainer().lookup(ArtifactInstaller.class.getName());
ArtifactFactory factory = (ArtifactFactory) embedder.getContainer().lookup(ArtifactFactory.class.getName());
for (ArtifactInfo a : archivedFiles) {
Artifact artifact = a.toArtifact(factory);
if(a.isPrimary)
artifact.addMetadata( new ProjectArtifactMetadata( artifact, new File(archivedPom.getRemote()) ) );
installer.install(new File(a.path.getRemote()), artifact,embedder.getLocalRepository());
}
embedder.stop();
} catch (MavenEmbedderException e) {
e.printStackTrace(listener.error("Failed to install artifact to the master"));
build.setResult(Result.FAILURE);
} catch (ComponentLookupException e) {
e.printStackTrace(listener.error("Failed to install artifact to the master"));
build.setResult(Result.FAILURE);
} catch (ArtifactInstallationException e) {
e.printStackTrace(listener.error("Failed to install artifact to the master"));
build.setResult(Result.FAILURE);
}
}
return null;
}
});
}
return true;
}
|
diff --git a/src/com/aetrion/flickr/photos/PhotosInterface.java b/src/com/aetrion/flickr/photos/PhotosInterface.java
index 4088852..b237ab7 100644
--- a/src/com/aetrion/flickr/photos/PhotosInterface.java
+++ b/src/com/aetrion/flickr/photos/PhotosInterface.java
@@ -1,1274 +1,1274 @@
/*
* Copyright (c) 2005 Aetrion LLC.
*/
package com.aetrion.flickr.photos;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import com.aetrion.flickr.FlickrException;
import com.aetrion.flickr.Parameter;
import com.aetrion.flickr.RequestContext;
import com.aetrion.flickr.Response;
import com.aetrion.flickr.Transport;
import com.aetrion.flickr.people.User;
import com.aetrion.flickr.photos.geo.GeoInterface;
import com.aetrion.flickr.tags.Tag;
import com.aetrion.flickr.util.StringUtilities;
import com.aetrion.flickr.util.XMLUtilities;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
import org.xml.sax.SAXException;
/**
* @author Anthony Eden
*/
public class PhotosInterface {
public static final String METHOD_ADD_TAGS = "flickr.photos.addTags";
public static final String METHOD_DELETE = "flickr.photos.delete";
public static final String METHOD_GET_ALL_CONTEXTS = "flickr.photos.getAllContexts";
public static final String METHOD_GET_CONTACTS_PHOTOS = "flickr.photos.getContactsPhotos";
public static final String METHOD_GET_CONTACTS_PUBLIC_PHOTOS = "flickr.photos.getContactsPublicPhotos";
public static final String METHOD_GET_CONTEXT = "flickr.photos.getContext";
public static final String METHOD_GET_COUNTS = "flickr.photos.getCounts";
public static final String METHOD_GET_EXIF = "flickr.photos.getExif";
public static final String METHOD_GET_INFO = "flickr.photos.getInfo";
public static final String METHOD_GET_NOT_IN_SET = "flickr.photos.getNotInSet";
public static final String METHOD_GET_PERMS = "flickr.photos.getPerms";
public static final String METHOD_GET_RECENT = "flickr.photos.getRecent";
public static final String METHOD_GET_SIZES = "flickr.photos.getSizes";
public static final String METHOD_GET_UNTAGGED = "flickr.photos.getUntagged";
public static final String METHOD_GET_WITH_GEO_DATA = "flickr.photos.getWithGeoData";
public static final String METHOD_GET_WITHOUT_GEO_DATA = "flickr.photos.getWithoutGeoData";
public static final String METHOD_RECENTLY_UPLOADED ="flickr.photos.recentlyUpdated";
public static final String METHOD_REMOVE_TAG = "flickr.photos.removeTag";
public static final String METHOD_SEARCH = "flickr.photos.search";
public static final String METHOD_SET_DATES = "flickr.photos.setDates";
public static final String METHOD_SET_META = "flickr.photos.setMeta";
public static final String METHOD_SET_PERMS = "flickr.photos.setPerms";
public static final String METHOD_SET_TAGS = "flickr.photos.setTags";
public static final String METHOD_GET_INTERESTINGNESS = "flickr.interestingness.getList";
private static final DateFormat DF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
private GeoInterface geoInterface = null;
private String apiKey;
private Transport transport;
public PhotosInterface(String apiKey, Transport transport) {
this.apiKey = apiKey;
this.transport = transport;
}
/**
* Get the geo interface.
* @return Access class to the flickr.photos.geo methods.
*/
public synchronized GeoInterface getGeoInterface() {
if (geoInterface == null) {
geoInterface = new GeoInterface(apiKey, transport);
}
return geoInterface;
}
/**
* Delete a photo from flickr.
* This method requires authentication with 'delete' permission.
* @param photoId
* @throws SAXException
* @throws IOException
* @throws FlickrException
*/
public void delete(String photoId) throws IOException, SAXException, FlickrException {
List parameters = new ArrayList();
parameters.add(new Parameter("method", METHOD_DELETE));
parameters.add(new Parameter("api_key", apiKey));
parameters.add(new Parameter("photo_id", photoId));
// Note: This method requires an HTTP POST request.
Response response = transport.post(transport.getPath(), parameters);
if (response.isError()) {
throw new FlickrException(response.getErrorCode(), response.getErrorMessage());
}
// This method has no specific response - It returns an empty
// sucess response if it completes without error.
}
/**
* Returns all visble sets and pools the photo belongs to.
* This method does not require authentication.
* @param photoId The photo to return information for.
* @return a list of {@link PhotoPlace} objects
* @throws IOException
* @throws SAXException
* @throws FlickrException
*/
public List getAllContexts(String photoId) throws IOException, SAXException, FlickrException {
List list = new ArrayList();
List parameters = new ArrayList();
parameters.add(new Parameter("method", METHOD_GET_ALL_CONTEXTS));
parameters.add(new Parameter("api_key", apiKey));
parameters.add(new Parameter("photo_id", photoId));
Response response = transport.get(transport.getPath(), parameters);
if (response.isError()) {
throw new FlickrException(response.getErrorCode(), response.getErrorMessage());
}
Collection coll = response.getPayloadCollection();
Iterator it = coll.iterator();
while (it.hasNext()) {
Element el = (Element)it.next();
String id = el.getAttribute("id");
String title = el.getAttribute("title");
String kind = el.getTagName();
list.add(new PhotoPlace(kind, id, title));
}
return list;
}
/**
* Add tags to a photo.
*
* @param photoId The photo ID
* @param tags The tags
* @throws IOException
* @throws SAXException
* @throws FlickrException
*/
public void addTags(String photoId, String[] tags) throws IOException, SAXException, FlickrException {
List parameters = new ArrayList();
parameters.add(new Parameter("method", METHOD_ADD_TAGS));
parameters.add(new Parameter("api_key", apiKey));
parameters.add(new Parameter("photo_id", photoId));
parameters.add(new Parameter("tags", StringUtilities.join(tags, " ", true)));
Response response = transport.post(transport.getPath(), parameters);
if (response.isError()) {
throw new FlickrException(response.getErrorCode(), response.getErrorMessage());
}
}
/**
* Get photos from the user's contacts.
*
* @param count The number of photos to return
* @param justFriends Set to true to only show friends photos
* @param singlePhoto Set to true to get a single photo
* @param includeSelf Set to true to include self
* @return The Collection of photos
* @throws IOException
* @throws SAXException
* @throws FlickrException
*/
public PhotoList getContactsPhotos(int count, boolean justFriends, boolean singlePhoto, boolean includeSelf)
throws IOException, SAXException, FlickrException {
PhotoList photos = new PhotoList();
List parameters = new ArrayList();
parameters.add(new Parameter("method", METHOD_GET_CONTACTS_PHOTOS));
parameters.add(new Parameter("api_key", apiKey));
if (count > 0) {
parameters.add(new Parameter("count", new Integer(count)));
}
if (justFriends) {
parameters.add(new Parameter("just_friends", "1"));
}
if (singlePhoto) {
parameters.add(new Parameter("single_photo", "1"));
}
if (includeSelf) {
parameters.add(new Parameter("include_self", "1"));
}
Response response = transport.get(transport.getPath(), parameters);
if (response.isError()) {
throw new FlickrException(response.getErrorCode(), response.getErrorMessage());
}
Element photosElement = response.getPayload();
photos.setPage(photosElement.getAttribute("page"));
photos.setPages(photosElement.getAttribute("pages"));
photos.setPerPage(photosElement.getAttribute("perpage"));
photos.setTotal(photosElement.getAttribute("total"));
NodeList photoNodes = photosElement.getElementsByTagName("photo");
for (int i = 0; i < photoNodes.getLength(); i++) {
Element photoElement = (Element) photoNodes.item(i);
Photo photo = new Photo();
photo.setId(photoElement.getAttribute("id"));
User owner = new User();
owner.setId(photoElement.getAttribute("owner"));
owner.setUsername(photoElement.getAttribute("username"));
photo.setOwner(owner);
photo.setSecret(photoElement.getAttribute("secret"));
photo.setServer(photoElement.getAttribute("server"));
photo.setTitle(photoElement.getAttribute("title"));
photo.setPublicFlag("1".equals(photoElement.getAttribute("ispublic")));
photo.setFriendFlag("1".equals(photoElement.getAttribute("isfriend")));
photo.setFamilyFlag("1".equals(photoElement.getAttribute("isfamily")));
photos.add(photo);
}
return photos;
}
/**
* Get public photos from the user's contacts.
*
* @param userId The user ID
* @param count The number of photos to return
* @param justFriends True to include friends
* @param singlePhoto True to get a single photo
* @param includeSelf True to include self
* @return A collection of Photo objects
* @throws IOException
* @throws SAXException
* @throws FlickrException
*/
public PhotoList getContactsPublicPhotos(String userId, int count, boolean justFriends, boolean singlePhoto, boolean includeSelf)
throws IOException, SAXException, FlickrException {
PhotoList photos = new PhotoList();
List parameters = new ArrayList();
parameters.add(new Parameter("method", METHOD_GET_CONTACTS_PUBLIC_PHOTOS));
parameters.add(new Parameter("api_key", apiKey));
parameters.add(new Parameter("user_id", userId));
if (count > 0) {
parameters.add(new Parameter("count", new Integer(count)));
}
if (justFriends) {
parameters.add(new Parameter("just_friends", "1"));
}
if (singlePhoto) {
parameters.add(new Parameter("single_photo", "1"));
}
if (includeSelf) {
parameters.add(new Parameter("include_self", "1"));
}
Response response = transport.get(transport.getPath(), parameters);
if (response.isError()) {
throw new FlickrException(response.getErrorCode(), response.getErrorMessage());
}
Element photosElement = response.getPayload();
photos.setPage(photosElement.getAttribute("page"));
photos.setPages(photosElement.getAttribute("pages"));
photos.setPerPage(photosElement.getAttribute("perpage"));
photos.setTotal(photosElement.getAttribute("total"));
NodeList photoNodes = photosElement.getElementsByTagName("photo");
for (int i = 0; i < photoNodes.getLength(); i++) {
Element photoElement = (Element) photoNodes.item(i);
Photo photo = new Photo();
photo.setId(photoElement.getAttribute("id"));
User owner = new User();
owner.setId(photoElement.getAttribute("owner"));
owner.setUsername(photoElement.getAttribute("username"));
photo.setOwner(owner);
photo.setSecret(photoElement.getAttribute("secret"));
photo.setServer(photoElement.getAttribute("server"));
photo.setTitle(photoElement.getAttribute("name"));
photos.add(photo);
}
return photos;
}
/**
* Get the context for the specified photo.
*
* @param photoId The photo ID
* @return The PhotoContext
* @throws IOException
* @throws SAXException
* @throws FlickrException
*/
public PhotoContext getContext(String photoId) throws IOException, SAXException, FlickrException {
List parameters = new ArrayList();
parameters.add(new Parameter("method", METHOD_GET_CONTEXT));
parameters.add(new Parameter("api_key", apiKey));
parameters.add(new Parameter("photo_id", photoId));
Response response = transport.get(transport.getPath(), parameters);
if (response.isError()) {
throw new FlickrException(response.getErrorCode(), response.getErrorMessage());
}
PhotoContext photoContext = new PhotoContext();
Collection payload = response.getPayloadCollection();
Iterator iter = payload.iterator();
while (iter.hasNext()) {
Element payloadElement = (Element) iter.next();
String tagName = payloadElement.getTagName();
if (tagName.equals("prevphoto")) {
Photo photo = new Photo();
photo.setId(payloadElement.getAttribute("id"));
photo.setSecret(payloadElement.getAttribute("secret"));
photo.setTitle(payloadElement.getAttribute("title"));
photo.setUrl(payloadElement.getAttribute("url"));
photoContext.setPreviousPhoto(photo);
} else if (tagName.equals("nextphoto")) {
Photo photo = new Photo();
photo.setId(payloadElement.getAttribute("id"));
photo.setSecret(payloadElement.getAttribute("secret"));
photo.setTitle(payloadElement.getAttribute("title"));
photo.setUrl(payloadElement.getAttribute("url"));
photoContext.setNextPhoto(photo);
}
}
return photoContext;
}
/**
* Gets a collection of photo counts for the given date ranges for the calling user.
*
* @param dates An array of dates, denoting the periods to return counts for. They should be specified smallest
* first.
* @param takenDates An array of dates, denoting the periods to return counts for. They should be specified smallest
* first.
* @return A Collection of Photocount objects
*/
public Collection getCounts(Date[] dates, Date[] takenDates) throws IOException, SAXException,
FlickrException {
List photocounts = new ArrayList();
List parameters = new ArrayList();
parameters.add(new Parameter("method", METHOD_GET_COUNTS));
parameters.add(new Parameter("api_key", apiKey));
if (dates == null && takenDates == null) {
throw new IllegalArgumentException("You must provide a value for either dates or takenDates");
}
if (dates != null) {
List dateList = new ArrayList();
for (int i = 0; i < dates.length; i++) {
dateList.add(dates[i]);
}
parameters.add(new Parameter("dates", StringUtilities.join(dateList, ",")));
}
if (takenDates != null) {
List dateList = new ArrayList();
for (int i = 0; i < dates.length; i++) {
dateList.add(dates[i]);
}
parameters.add(new Parameter("taken_dates", StringUtilities.join(dateList, ",")));
}
Response response = transport.get(transport.getPath(), parameters);
if (response.isError()) {
throw new FlickrException(response.getErrorCode(), response.getErrorMessage());
}
Element photocountsElement = response.getPayload();
NodeList photocountNodes = photocountsElement.getElementsByTagName("photocount");
for (int i = 0; i < photocountNodes.getLength(); i++) {
Element photocountElement = (Element) photocountNodes.item(i);
Photocount photocount = new Photocount();
photocount.setCount(photocountElement.getAttribute("count"));
photocount.setFromDate(photocountElement.getAttribute("fromdate"));
photocount.setToDate(photocountElement.getAttribute("todate"));
photocounts.add(photocount);
}
return photocounts;
}
/**
* Get the Exif data for the photo.
*
* @param photoId The photo ID
* @param secret The secret
* @return A collection of Exif objects
* @throws IOException
* @throws SAXException
* @throws FlickrException
*/
public Collection getExif(String photoId, String secret) throws IOException, SAXException, FlickrException {
List parameters = new ArrayList();
parameters.add(new Parameter("method", METHOD_GET_EXIF));
parameters.add(new Parameter("api_key", apiKey));
parameters.add(new Parameter("photo_id", photoId));
if (secret != null) {
parameters.add(new Parameter("secret", secret));
}
Response response = transport.get(transport.getPath(), parameters);
if (response.isError()) {
throw new FlickrException(response.getErrorCode(), response.getErrorMessage());
}
List exifs = new ArrayList();
Element photoElement = response.getPayload();
NodeList exifElements = photoElement.getElementsByTagName("exif");
for (int i = 0; i < exifElements.getLength(); i++) {
Element exifElement = (Element) exifElements.item(i);
Exif exif = new Exif();
exif.setTagspace(exifElement.getAttribute("tagspace"));
exif.setTagspaceId(exifElement.getAttribute("tagspaceid"));
exif.setTag(exifElement.getAttribute("tag"));
exif.setLabel(exifElement.getAttribute("label"));
exif.setRaw(XMLUtilities.getChildValue(exifElement, "raw"));
exif.setClean(XMLUtilities.getChildValue(exifElement, "clean"));
exifs.add(exif);
}
return exifs;
}
/**
* Get all info for the specified photo.
*
* @param photoId The photo Id
* @param secret The optional secret String
* @return The Photo
* @throws IOException
* @throws SAXException
* @throws FlickrException
*/
public Photo getInfo(String photoId, String secret) throws IOException, SAXException, FlickrException {
List parameters = new ArrayList();
parameters.add(new Parameter("method", METHOD_GET_INFO));
parameters.add(new Parameter("api_key", apiKey));
parameters.add(new Parameter("photo_id", photoId));
if (secret != null) {
parameters.add(new Parameter("secret", secret));
}
Response response = transport.get(transport.getPath(), parameters);
if (response.isError()) {
throw new FlickrException(response.getErrorCode(), response.getErrorMessage());
}
- Element photoElement = (Element)response.getPayload().getElementsByTagName( "photo" ).item( 0 );
+ Element photoElement = (Element)response.getPayload();
Photo photo = new Photo();
photo.setId(photoElement.getAttribute("id"));
photo.setSecret(photoElement.getAttribute("secret"));
photo.setServer(photoElement.getAttribute("server"));
photo.setFavorite("1".equals(photoElement.getAttribute("isfavorite")));
photo.setLicense(photoElement.getAttribute("license"));
Element ownerElement = (Element) photoElement.getElementsByTagName("owner").item(0);
User owner = new User();
owner.setId(ownerElement.getAttribute("nsid"));
owner.setUsername(ownerElement.getAttribute("username"));
owner.setRealName(ownerElement.getAttribute("realname"));
owner.setLocation(ownerElement.getAttribute("location"));
photo.setOwner(owner);
photo.setTitle(XMLUtilities.getChildValue(photoElement, "title"));
photo.setDescription(XMLUtilities.getChildValue(photoElement, "description"));
Element visibilityElement = (Element) photoElement.getElementsByTagName("visibility").item(0);
photo.setPublicFlag("1".equals(visibilityElement.getAttribute("ispublic")));
photo.setFriendFlag("1".equals(visibilityElement.getAttribute("isfriend")));
photo.setFamilyFlag("1".equals(visibilityElement.getAttribute("isfamily")));
Element datesElement = XMLUtilities.getChild(photoElement, "dates");
photo.setDatePosted(datesElement.getAttribute("posted"));
photo.setDateTaken(datesElement.getAttribute("taken"));
photo.setTakenGranularity(datesElement.getAttribute("takengranularity"));
NodeList permissionsNodes = photoElement.getElementsByTagName("permissions");
if (permissionsNodes.getLength() > 0) {
Element permissionsElement = (Element) permissionsNodes.item(0);
Permissions permissions = new Permissions();
permissions.setComment(permissionsElement.getAttribute("permcomment"));
permissions.setAddmeta(permissionsElement.getAttribute("permaddmeta"));
}
Element editabilityElement = (Element) photoElement.getElementsByTagName("editability").item(0);
Editability editability = new Editability();
editability.setComment("1".equals(editabilityElement.getAttribute("cancomment")));
editability.setAddmeta("1".equals(editabilityElement.getAttribute("canaddmeta")));
Element commentsElement = (Element) photoElement.getElementsByTagName("comments").item(0);
photo.setComments(((Text) commentsElement.getFirstChild()).getData());
Element notesElement = (Element) photoElement.getElementsByTagName("notes").item(0);
List notes = new ArrayList();
NodeList noteNodes = notesElement.getElementsByTagName("note");
for (int i = 0; i < noteNodes.getLength(); i++) {
Element noteElement = (Element) noteNodes.item(i);
Note note = new Note();
note.setId(noteElement.getAttribute("id"));
note.setAuthor(noteElement.getAttribute("author"));
note.setAuthorName(noteElement.getAttribute("authorname"));
note.setBounds(noteElement.getAttribute("x"), noteElement.getAttribute("y"),
noteElement.getAttribute("w"), noteElement.getAttribute("h"));
notes.add(note);
}
photo.setNotes(notes);
Element tagsElement = (Element) photoElement.getElementsByTagName("tags").item(0);
List tags = new ArrayList();
NodeList tagNodes = tagsElement.getElementsByTagName("tag");
for (int i = 0; i < tagNodes.getLength(); i++) {
Element tagElement = (Element) tagNodes.item(i);
Tag tag = new Tag();
tag.setId(tagElement.getAttribute("id"));
tag.setAuthor(tagElement.getAttribute("author"));
tag.setRaw(tagElement.getAttribute("raw"));
tag.setValue(((Text) tagElement.getFirstChild()).getData());
tags.add(tag);
}
photo.setTags(tags);
Element urlsElement = (Element) photoElement.getElementsByTagName("urls").item(0);
List urls = new ArrayList();
NodeList urlNodes = urlsElement.getElementsByTagName("url");
for (int i = 0; i < urlNodes.getLength(); i++) {
Element urlElement = (Element) urlNodes.item(i);
PhotoUrl photoUrl = new PhotoUrl();
photoUrl.setType(urlElement.getAttribute("type"));
photoUrl.setUrl(XMLUtilities.getValue(urlElement));
if (photoUrl.getType().equals("photopage")) {
photo.setUrl(photoUrl.getUrl());
}
}
photo.setUrls(urls);
return photo;
}
/**
* Return a collection of Photo objects not in part of any sets.
*
* @param perPage The per page
* @param page The page
* @return The collection of Photo objects
* @throws IOException
* @throws SAXException
* @throws FlickrException
*/
public PhotoList getNotInSet(int perPage, int page) throws IOException, SAXException, FlickrException {
PhotoList photos = new PhotoList();
List parameters = new ArrayList();
parameters.add(new Parameter("method", PhotosInterface.METHOD_GET_NOT_IN_SET));
parameters.add(new Parameter("api_key", apiKey));
RequestContext requestContext = RequestContext.getRequestContext();
List extras = requestContext.getExtras();
if (extras.size() > 0) {
parameters.add(new Parameter("extras", StringUtilities.join(extras, ",")));
}
if (perPage > 0) {
parameters.add(new Parameter("per_page", new Integer(perPage)));
}
if (page > 0) {
parameters.add(new Parameter("page", new Integer(page)));
}
Response response = transport.get(transport.getPath(), parameters);
if (response.isError()) {
throw new FlickrException(response.getErrorCode(), response.getErrorMessage());
}
Element photosElement = response.getPayload();
photos.setPage(photosElement.getAttribute("page"));
photos.setPages(photosElement.getAttribute("pages"));
photos.setPerPage(photosElement.getAttribute("perpage"));
photos.setTotal(photosElement.getAttribute("total"));
NodeList photoElements = photosElement.getElementsByTagName("photo");
for (int i = 0; i < photoElements.getLength(); i++) {
Element photoElement = (Element) photoElements.item(i);
Photo photo = new Photo();
photo.setId(photoElement.getAttribute("id"));
photo.setSecret(photoElement.getAttribute("secret"));
photo.setServer(photoElement.getAttribute("server"));
photo.setTitle(photoElement.getAttribute("title"));
photo.setPublicFlag("1".equals(photoElement.getAttribute("ispublic")));
photo.setFriendFlag("1".equals(photoElement.getAttribute("isfriend")));
photo.setFamilyFlag("1".equals(photoElement.getAttribute("isfamily")));
User user = new User();
user.setId(photoElement.getAttribute("owner"));
photo.setOwner(user);
photos.add(photo);
}
return photos;
}
/**
* Get the permission information for the specified photo.
*
* @param photoId The photo id
* @return The Permissions object
* @throws IOException
* @throws SAXException
* @throws FlickrException
*/
public Permissions getPerms(String photoId) throws IOException, SAXException, FlickrException {
List parameters = new ArrayList();
parameters.add(new Parameter("method", METHOD_GET_PERMS));
parameters.add(new Parameter("api_key", apiKey));
parameters.add(new Parameter("photo_id", photoId));
Response response = transport.get(transport.getPath(), parameters);
if (response.isError()) {
throw new FlickrException(response.getErrorCode(), response.getErrorMessage());
}
Element permissionsElement = response.getPayload();
Permissions permissions = new Permissions();
permissions.setId(permissionsElement.getAttribute("id"));
permissions.setPublicFlag("1".equals(permissionsElement.getAttribute("ispublic")));
permissions.setFamilyFlag("1".equals(permissionsElement.getAttribute("isfamily")));
permissions.setComment(permissionsElement.getAttribute("permcomment"));
permissions.setAddmeta(permissionsElement.getAttribute("permaddmeta"));
return permissions;
}
/**
* Get a collection of recent photos.
*
* @param perPage The number of photos per page
* @param page The page offset
* @return A collection of Photo objects
* @throws IOException
* @throws SAXException
* @throws FlickrException
*/
public PhotoList getRecent(int perPage, int page) throws IOException, SAXException, FlickrException {
PhotoList photos = new PhotoList();
List parameters = new ArrayList();
parameters.add(new Parameter("method", METHOD_GET_RECENT));
parameters.add(new Parameter("api_key", apiKey));
if (perPage > 0) {
parameters.add(new Parameter("per_page", new Integer(perPage)));
}
if (page > 0) {
parameters.add(new Parameter("page", new Integer(page)));
}
Response response = transport.get(transport.getPath(), parameters);
if (response.isError()) {
throw new FlickrException(response.getErrorCode(), response.getErrorMessage());
}
Element photosElement = response.getPayload();
photos.setPage(photosElement.getAttribute("page"));
photos.setPages(photosElement.getAttribute("pages"));
photos.setPerPage(photosElement.getAttribute("perpage"));
photos.setTotal(photosElement.getAttribute("total"));
NodeList photoNodes = photosElement.getElementsByTagName("photo");
for (int i = 0; i < photoNodes.getLength(); i++) {
Element photoElement = (Element) photoNodes.item(i);
Photo photo = new Photo();
photo.setId(photoElement.getAttribute("id"));
User owner = new User();
owner.setId(photoElement.getAttribute("owner"));
photo.setOwner(owner);
photo.setSecret(photoElement.getAttribute("secret"));
photo.setServer(photoElement.getAttribute("server"));
photo.setTitle(photoElement.getAttribute("name"));
photo.setPublicFlag("1".equals(photoElement.getAttribute("ispublic")));
photo.setFriendFlag("1".equals(photoElement.getAttribute("isfriend")));
photo.setFamilyFlag("1".equals(photoElement.getAttribute("isfamily")));
photos.add(photo);
}
return photos;
}
/**
* Get the available sizes for sizes.
*
* @param photoId The photo ID
* @return The size collection
* @throws IOException
* @throws SAXException
* @throws FlickrException
*/
public Collection getSizes(String photoId) throws IOException, SAXException, FlickrException {
List sizes = new ArrayList();
List parameters = new ArrayList();
parameters.add(new Parameter("method", METHOD_GET_SIZES));
parameters.add(new Parameter("api_key", apiKey));
parameters.add(new Parameter("photo_id", photoId));
Response response = transport.get(transport.getPath(), parameters);
if (response.isError()) {
throw new FlickrException(response.getErrorCode(), response.getErrorMessage());
}
Element sizesElement = response.getPayload();
NodeList sizeNodes = sizesElement.getElementsByTagName("size");
for (int i = 0; i < sizeNodes.getLength(); i++) {
Element sizeElement = (Element) sizeNodes.item(i);
Size size = new Size();
size.setLabel(sizeElement.getAttribute("label"));
size.setWidth(sizeElement.getAttribute("width"));
size.setHeight(sizeElement.getAttribute("height"));
size.setSource(sizeElement.getAttribute("source"));
size.setUrl(sizeElement.getAttribute("url"));
sizes.add(size);
}
return sizes;
}
/**
* Get the collection of untagged photos.
*
* @param perPage
* @param page
* @return A Collection of Photos
* @throws IOException
* @throws SAXException
* @throws FlickrException
*/
public PhotoList getUntagged(int perPage, int page) throws IOException, SAXException,
FlickrException {
PhotoList photos = new PhotoList();
List parameters = new ArrayList();
parameters.add(new Parameter("method", METHOD_GET_UNTAGGED));
parameters.add(new Parameter("api_key", apiKey));
if (perPage > 0) {
parameters.add(new Parameter("per_page", new Integer(perPage)));
}
if (page > 0) {
parameters.add(new Parameter("page", new Integer(page)));
}
Response response = transport.get(transport.getPath(), parameters);
if (response.isError()) {
throw new FlickrException(response.getErrorCode(), response.getErrorMessage());
}
Element photosElement = response.getPayload();
photos.setPage(photosElement.getAttribute("page"));
photos.setPages(photosElement.getAttribute("pages"));
photos.setPerPage(photosElement.getAttribute("perpage"));
photos.setTotal(photosElement.getAttribute("total"));
NodeList photoNodes = photosElement.getElementsByTagName("photo");
for (int i = 0; i < photoNodes.getLength(); i++) {
Element photoElement = (Element) photoNodes.item(i);
Photo photo = new Photo();
photo.setId(photoElement.getAttribute("id"));
User owner = new User();
owner.setId(photoElement.getAttribute("owner"));
photo.setOwner(owner);
photo.setSecret(photoElement.getAttribute("secret"));
photo.setServer(photoElement.getAttribute("server"));
photo.setTitle(photoElement.getAttribute("title"));
photo.setPublicFlag("1".equals(photoElement.getAttribute("ispublic")));
photo.setFriendFlag("1".equals(photoElement.getAttribute("isfriend")));
photo.setFamilyFlag("1".equals(photoElement.getAttribute("isfamily")));
photos.add(photo);
}
return photos;
}
/**
* Returns a list of your geo-tagged photos.
* This method requires authentication with 'read' permission.
* @param minUploadDate Minimum upload date. Photos with an upload date greater than or equal to this value will be returned. Set to null to not specify a date.
* @param maxUploadDate Maximum upload date. Photos with an upload date less than or equal to this value will be returned. Set to null to not specify a date.
* @param minTakenDate Minimum taken date. Photos with an taken date greater than or equal to this value will be returned. Set to null to not specify a date.
* @param maxTakenDate Maximum taken date. Photos with an taken date less than or equal to this value will be returned. Set to null to not specify a date.
* @param privacyFilter Return photos only matching a certain privacy level. Valid values are:
* <ul>
* <li>1 public photos</li>
* <li>2 private photos visible to friends</li>
* <li>3 private photos visible to family</li>
* <li>4 private photos visible to friends & family</li>
* <li>5 completely private photos</li>
* </ul>
* Set to 0 to not specify a privacy Filter.
* @param sort The order in which to sort returned photos. Deafults to date-posted-desc. The possible values are: date-posted-asc, date-posted-desc, date-taken-asc, date-taken-desc, interestingness-desc, and interestingness-asc.
* @param extras A set of Strings controlling the extra information to fetch for each returned record. Currently supported fields are: license, date_upload, date_taken, owner_name, icon_server, original_format, last_update, geo. Set to null or an empty set to not specify any extras.
* @param perPage Number of photos to return per page. If this argument is 0, it defaults to 100. The maximum allowed value is 500.
* @param page The page of results to return. If this argument is 0, it defaults to 1.
* @return
* @throws FlickrException
* @throws IOException
* @throws SAXException
*/
public PhotoList getWithGeoData(Date minUploadDate, Date maxUploadDate, Date minTakenDate, Date maxTakenDate, int privacyFilter, String sort, Set extras, int perPage, int page) throws FlickrException, IOException, SAXException {
List parameters = new ArrayList();
parameters.add(new Parameter("method", METHOD_GET_WITH_GEO_DATA));
parameters.add(new Parameter("api_key", apiKey));
if (minUploadDate != null) {
parameters.add(new Parameter("min_upload_date", minUploadDate.getTime() / 1000L));
}
if (maxUploadDate != null) {
parameters.add(new Parameter("max_upload_date", maxUploadDate.getTime() / 1000L));
}
if (minTakenDate != null) {
parameters.add(new Parameter("min_taken_date", minTakenDate.getTime() / 1000L));
}
if (maxTakenDate != null) {
parameters.add(new Parameter("max_taken_date", maxTakenDate.getTime() / 1000L));
}
if (privacyFilter > 0) {
parameters.add(new Parameter("privacy_filter", privacyFilter));
}
if (sort != null) {
parameters.add(new Parameter("sort", sort));
}
if (extras != null && !extras.isEmpty()) {
StringBuffer sb = new StringBuffer();
Iterator it = extras.iterator();
while (it.hasNext()) {
if (sb.length() > 0) {
sb.append(",");
}
sb.append(it.next());
}
parameters.add(new Parameter("extras", sb.toString()));
}
if (perPage > 0) {
parameters.add(new Parameter("per_page", perPage));
}
if (page > 0) {
parameters.add(new Parameter("page", page));
}
Response response = transport.get(transport.getPath(), parameters);
if (response.isError()) {
throw new FlickrException(response.getErrorCode(), response.getErrorMessage());
}
Element photosElement = response.getPayload();
PhotoList photos = PhotoUtils.createPhotoList(photosElement);
return photos;
}
/**
* Returns a list of your photos which haven't been geo-tagged.
* This method requires authentication with 'read' permission.
* @param minUploadDate Minimum upload date. Photos with an upload date greater than or equal to this value will be returned. Set to null to not specify a date.
* @param maxUploadDate Maximum upload date. Photos with an upload date less than or equal to this value will be returned. Set to null to not specify a date.
* @param minTakenDate Minimum taken date. Photos with an taken date greater than or equal to this value will be returned. Set to null to not specify a date.
* @param maxTakenDate Maximum taken date. Photos with an taken date less than or equal to this value will be returned. Set to null to not specify a date.
* @param privacyFilter Return photos only matching a certain privacy level. Valid values are:
* <ul>
* <li>1 public photos</li>
* <li>2 private photos visible to friends</li>
* <li>3 private photos visible to family</li>
* <li>4 private photos visible to friends & family</li>
* <li>5 completely private photos</li>
* </ul>
* Set to 0 to not specify a privacy Filter.
* @param sort The order in which to sort returned photos. Deafults to date-posted-desc. The possible values are: date-posted-asc, date-posted-desc, date-taken-asc, date-taken-desc, interestingness-desc, and interestingness-asc.
* @param extras A set of Strings controlling the extra information to fetch for each returned record. Currently supported fields are: license, date_upload, date_taken, owner_name, icon_server, original_format, last_update, geo. Set to null or an empty set to not specify any extras.
* @param perPage Number of photos to return per page. If this argument is 0, it defaults to 100. The maximum allowed value is 500.
* @param page The page of results to return. If this argument is 0, it defaults to 1.
* @return a photo list
* @throws FlickrException
* @throws IOException
* @throws SAXException
*/
public PhotoList getWithoutGeoData(Date minUploadDate, Date maxUploadDate, Date minTakenDate, Date maxTakenDate, int privacyFilter, String sort, Set extras, int perPage, int page) throws FlickrException, IOException, SAXException {
List parameters = new ArrayList();
parameters.add(new Parameter("method", METHOD_GET_WITHOUT_GEO_DATA));
parameters.add(new Parameter("api_key", apiKey));
if (minUploadDate != null) {
parameters.add(new Parameter("min_upload_date", minUploadDate.getTime() / 1000L));
}
if (maxUploadDate != null) {
parameters.add(new Parameter("max_upload_date", maxUploadDate.getTime() / 1000L));
}
if (minTakenDate != null) {
parameters.add(new Parameter("min_taken_date", minTakenDate.getTime() / 1000L));
}
if (maxTakenDate != null) {
parameters.add(new Parameter("max_taken_date", maxTakenDate.getTime() / 1000L));
}
if (privacyFilter > 0) {
parameters.add(new Parameter("privacy_filter", privacyFilter));
}
if (sort != null) {
parameters.add(new Parameter("sort", sort));
}
if (extras != null && !extras.isEmpty()) {
StringBuffer sb = new StringBuffer();
Iterator it = extras.iterator();
while (it.hasNext()) {
if (sb.length() > 0) {
sb.append(",");
}
sb.append(it.next());
}
parameters.add(new Parameter("extras", sb.toString()));
}
if (perPage > 0) {
parameters.add(new Parameter("per_page", perPage));
}
if (page > 0) {
parameters.add(new Parameter("page", page));
}
Response response = transport.get(transport.getPath(), parameters);
if (response.isError()) {
throw new FlickrException(response.getErrorCode(), response.getErrorMessage());
}
Element photosElement = response.getPayload();
PhotoList photos = PhotoUtils.createPhotoList(photosElement);
return photos;
}
/**
* Return a list of your photos that have been recently created or which have been recently modified.
* Recently modified may mean that the photo's metadata (title, description, tags) may have been changed or a comment has been added (or just modified somehow :-)
* @param minDate Date indicating the date from which modifications should be compared. Must be given.
* @param extras A set of Strings controlling the extra information to fetch for each returned record. Currently supported fields are: license, date_upload, date_taken, owner_name, icon_server, original_format, last_update, geo. Set to null or an empty set to not specify any extras.
* @param perPage Number of photos to return per page. If this argument is 0, it defaults to 100. The maximum allowed value is 500.
* @param page The page of results to return. If this argument is 0, it defaults to 1.
* @return a list of photos
* @throws SAXException
* @throws IOException
* @throws FlickrException
*/
public PhotoList recentlyUpdated(Date minDate, Set extras, int perPage, int page) throws IOException, SAXException, FlickrException {
List parameters = new ArrayList();
parameters.add(new Parameter("method", METHOD_GET_WITHOUT_GEO_DATA));
parameters.add(new Parameter("api_key", apiKey));
parameters.add(new Parameter("min_date", minDate.getTime() / 1000L));
if (extras != null && !extras.isEmpty()) {
StringBuffer sb = new StringBuffer();
Iterator it = extras.iterator();
while (it.hasNext()) {
if (sb.length() > 0) {
sb.append(",");
}
sb.append(it.next());
}
parameters.add(new Parameter("extras", sb.toString()));
}
if (perPage > 0) {
parameters.add(new Parameter("per_page", perPage));
}
if (page > 0) {
parameters.add(new Parameter("page", page));
}
Response response = transport.get(transport.getPath(), parameters);
if (response.isError()) {
throw new FlickrException(response.getErrorCode(), response.getErrorMessage());
}
Element photosElement = response.getPayload();
PhotoList photos = PhotoUtils.createPhotoList(photosElement);
return photos;
}
/**
* Remove a tag from a photo.
*
* @param tagId The tag ID
* @throws IOException
* @throws SAXException
* @throws FlickrException
*/
public void removeTag(String tagId) throws IOException, SAXException, FlickrException {
List parameters = new ArrayList();
parameters.add(new Parameter("method", METHOD_REMOVE_TAG));
parameters.add(new Parameter("api_key", apiKey));
parameters.add(new Parameter("tag_id", tagId));
Response response = transport.post(transport.getPath(), parameters);
if (response.isError()) {
throw new FlickrException(response.getErrorCode(), response.getErrorMessage());
}
}
/**
* Search for photos which match the given search parameters.
*
* @param params The search parameters
* @param perPage The number of photos to show per page
* @param page The page offset
* @return A PhotoList
* @throws IOException
* @throws SAXException
* @throws FlickrException
*/
public PhotoList search(SearchParameters params, int perPage, int page) throws IOException, SAXException,
FlickrException {
PhotoList photos = new PhotoList();
List parameters = new ArrayList();
parameters.add(new Parameter("method", METHOD_SEARCH));
parameters.add(new Parameter("api_key", apiKey));
parameters.addAll(params.getAsParameters());
if (perPage > 0) {
parameters.add(new Parameter("per_page", new Integer(perPage)));
}
if (page > 0) {
parameters.add(new Parameter("page", new Integer(page)));
}
Response response = transport.get(transport.getPath(), parameters);
if (response.isError()) {
throw new FlickrException(response.getErrorCode(), response.getErrorMessage());
}
Element photosElement = response.getPayload();
photos.setPage(photosElement.getAttribute("page"));
photos.setPages(photosElement.getAttribute("pages"));
photos.setPerPage(photosElement.getAttribute("perpage"));
photos.setTotal(photosElement.getAttribute("total"));
NodeList photoNodes = photosElement.getElementsByTagName("photo");
for (int i = 0; i < photoNodes.getLength(); i++) {
Element photoElement = (Element) photoNodes.item(i);
Photo photo = new Photo();
photo.setId(photoElement.getAttribute("id"));
User owner = new User();
owner.setId(photoElement.getAttribute("owner"));
photo.setOwner(owner);
photo.setSecret(photoElement.getAttribute("secret"));
photo.setServer(photoElement.getAttribute("server"));
photo.setTitle(photoElement.getAttribute("title"));
photo.setPublicFlag("1".equals(photoElement.getAttribute("ispublic")));
photo.setFriendFlag("1".equals(photoElement.getAttribute("isfriend")));
photo.setFamilyFlag("1".equals(photoElement.getAttribute("isfamily")));
photos.add(photo);
}
return photos;
}
/**
* Search for interesting photos using the Flickr Interestingness algorithm.
*
* @param params Any search parameters
* @param perPage Number of items per page
* @param page The page to start on
* @return A PhotoList
* @throws IOException
* @throws SAXException
* @throws FlickrException
*/
public PhotoList searchInterestingness(SearchParameters params, int perPage, int page)
throws IOException, SAXException, FlickrException {
PhotoList photos = new PhotoList();
List parameters = new ArrayList();
parameters.add(new Parameter("method", METHOD_GET_INTERESTINGNESS));
parameters.add(new Parameter("api_key", apiKey));
parameters.addAll(params.getAsParameters());
if (perPage > 0) {
parameters.add(new Parameter("per_page", new Integer(perPage)));
}
if (page > 0) {
parameters.add(new Parameter("page", new Integer(page)));
}
Response response = transport.get(transport.getPath(), parameters);
if (response.isError()) {
throw new FlickrException(response.getErrorCode(), response
.getErrorMessage());
}
Element photosElement = response.getPayload();
photos.setPage(photosElement.getAttribute("page"));
photos.setPages(photosElement.getAttribute("pages"));
photos.setPerPage(photosElement.getAttribute("perpage"));
photos.setTotal(photosElement.getAttribute("total"));
NodeList photoNodes = photosElement.getElementsByTagName("photo");
for (int i = 0; i < photoNodes.getLength(); i++) {
Element photoElement = (Element) photoNodes.item(i);
Photo photo = new Photo();
photo.setId(photoElement.getAttribute("id"));
User owner = new User();
owner.setId(photoElement.getAttribute("owner"));
photo.setOwner(owner);
photo.setSecret(photoElement.getAttribute("secret"));
photo.setServer(photoElement.getAttribute("server"));
photo.setTitle(photoElement.getAttribute("title"));
photo.setPublicFlag("1".equals(photoElement
.getAttribute("ispublic")));
photo.setFriendFlag("1".equals(photoElement
.getAttribute("isfriend")));
photo.setFamilyFlag("1".equals(photoElement
.getAttribute("isfamily")));
photos.add(photo);
}
return photos;
}
/**
* Set the dates for the specified photo.
*
* @param photoId The photo ID
* @param datePosted The date the photo was posted or null
* @param dateTaken The date the photo was taken or null
* @param dateTakenGranularity The granularity of the taken date or null
* @throws IOException
* @throws SAXException
* @throws FlickrException
*/
public void setDates(String photoId, Date datePosted, Date dateTaken, String dateTakenGranularity)
throws IOException, SAXException, FlickrException {
List parameters = new ArrayList();
parameters.add(new Parameter("method", METHOD_SET_DATES));
parameters.add(new Parameter("api_key", apiKey));
parameters.add(new Parameter("photo_id", photoId));
if (datePosted != null) {
parameters.add(new Parameter("date_posted", new Long(datePosted.getTime() / 1000)));
}
if (dateTaken != null) {
parameters.add(new Parameter("date_taken", DF.format(dateTaken)));
}
if (dateTakenGranularity != null) {
parameters.add(new Parameter("date_taken_granularity", dateTakenGranularity));
}
Response response = transport.post(transport.getPath(), parameters);
if (response.isError()) {
throw new FlickrException(response.getErrorCode(), response.getErrorMessage());
}
}
/**
* Set the meta data for the photo.
*
* @param photoId The photo ID
* @param title The new title
* @param description The new description
* @throws IOException
* @throws SAXException
* @throws FlickrException
*/
public void setMeta(String photoId, String title, String description) throws IOException,
SAXException, FlickrException {
List parameters = new ArrayList();
parameters.add(new Parameter("method", METHOD_SET_META));
parameters.add(new Parameter("api_key", apiKey));
parameters.add(new Parameter("photo_id", photoId));
parameters.add(new Parameter("title", title));
parameters.add(new Parameter("description", description));
Response response = transport.post(transport.getPath(), parameters);
if (response.isError()) {
throw new FlickrException(response.getErrorCode(), response.getErrorMessage());
}
}
/**
* Set the permissions for the photo.
*
* @param photoId The photo ID
* @param permissions The permissions object
* @throws IOException
* @throws SAXException
* @throws FlickrException
*/
public void setPerms(String photoId, Permissions permissions) throws IOException,
SAXException, FlickrException {
List parameters = new ArrayList();
parameters.add(new Parameter("method", METHOD_SET_META));
parameters.add(new Parameter("api_key", apiKey));
parameters.add(new Parameter("photo_id", photoId));
parameters.add(new Parameter("is_public", permissions.isPublicFlag() ? "1" : "0"));
parameters.add(new Parameter("is_friend", permissions.isFriendFlag() ? "1" : "0"));
parameters.add(new Parameter("is_family", permissions.isFamilyFlag() ? "1" : "0"));
parameters.add(new Parameter("perm_comment", new Integer(permissions.getComment())));
parameters.add(new Parameter("perm_addmeta", new Integer(permissions.getAddmeta())));
Response response = transport.post(transport.getPath(), parameters);
if (response.isError()) {
throw new FlickrException(response.getErrorCode(), response.getErrorMessage());
}
}
/**
* Set the tags for a photo.
*
* @param photoId The photo ID
* @param tags The tag array
* @throws IOException
* @throws SAXException
* @throws FlickrException
*/
public void setTags(String photoId, String[] tags) throws IOException, SAXException,
FlickrException {
List parameters = new ArrayList();
parameters.add(new Parameter("method", METHOD_SET_TAGS));
parameters.add(new Parameter("api_key", apiKey));
parameters.add(new Parameter("photo_id", photoId));
parameters.add(new Parameter("tags", StringUtilities.join(tags, " ", true)));
Response response = transport.post(transport.getPath(), parameters);
if (response.isError()) {
throw new FlickrException(response.getErrorCode(), response.getErrorMessage());
}
}
/**
* Get the photo for the specified ID. Currently maps to the getInfo() method.
*
* @param id The ID
* @return The Photo
* @throws IOException
* @throws FlickrException
* @throws SAXException
*/
public Photo getPhoto(String id) throws IOException, FlickrException, SAXException {
return getPhoto(id, null);
}
/**
* Get the photo for the specified ID with the given secret. Currently maps to the getInfo() method.
*
* @param id The ID
* @param secret The secret
* @return The Photo
* @throws IOException
* @throws FlickrException
* @throws SAXException
*/
public Photo getPhoto(String id, String secret) throws IOException, FlickrException, SAXException {
return getInfo(id, secret);
}
}
| true | true | public Photo getInfo(String photoId, String secret) throws IOException, SAXException, FlickrException {
List parameters = new ArrayList();
parameters.add(new Parameter("method", METHOD_GET_INFO));
parameters.add(new Parameter("api_key", apiKey));
parameters.add(new Parameter("photo_id", photoId));
if (secret != null) {
parameters.add(new Parameter("secret", secret));
}
Response response = transport.get(transport.getPath(), parameters);
if (response.isError()) {
throw new FlickrException(response.getErrorCode(), response.getErrorMessage());
}
Element photoElement = (Element)response.getPayload().getElementsByTagName( "photo" ).item( 0 );
Photo photo = new Photo();
photo.setId(photoElement.getAttribute("id"));
photo.setSecret(photoElement.getAttribute("secret"));
photo.setServer(photoElement.getAttribute("server"));
photo.setFavorite("1".equals(photoElement.getAttribute("isfavorite")));
photo.setLicense(photoElement.getAttribute("license"));
Element ownerElement = (Element) photoElement.getElementsByTagName("owner").item(0);
User owner = new User();
owner.setId(ownerElement.getAttribute("nsid"));
owner.setUsername(ownerElement.getAttribute("username"));
owner.setRealName(ownerElement.getAttribute("realname"));
owner.setLocation(ownerElement.getAttribute("location"));
photo.setOwner(owner);
photo.setTitle(XMLUtilities.getChildValue(photoElement, "title"));
photo.setDescription(XMLUtilities.getChildValue(photoElement, "description"));
Element visibilityElement = (Element) photoElement.getElementsByTagName("visibility").item(0);
photo.setPublicFlag("1".equals(visibilityElement.getAttribute("ispublic")));
photo.setFriendFlag("1".equals(visibilityElement.getAttribute("isfriend")));
photo.setFamilyFlag("1".equals(visibilityElement.getAttribute("isfamily")));
Element datesElement = XMLUtilities.getChild(photoElement, "dates");
photo.setDatePosted(datesElement.getAttribute("posted"));
photo.setDateTaken(datesElement.getAttribute("taken"));
photo.setTakenGranularity(datesElement.getAttribute("takengranularity"));
NodeList permissionsNodes = photoElement.getElementsByTagName("permissions");
if (permissionsNodes.getLength() > 0) {
Element permissionsElement = (Element) permissionsNodes.item(0);
Permissions permissions = new Permissions();
permissions.setComment(permissionsElement.getAttribute("permcomment"));
permissions.setAddmeta(permissionsElement.getAttribute("permaddmeta"));
}
Element editabilityElement = (Element) photoElement.getElementsByTagName("editability").item(0);
Editability editability = new Editability();
editability.setComment("1".equals(editabilityElement.getAttribute("cancomment")));
editability.setAddmeta("1".equals(editabilityElement.getAttribute("canaddmeta")));
Element commentsElement = (Element) photoElement.getElementsByTagName("comments").item(0);
photo.setComments(((Text) commentsElement.getFirstChild()).getData());
Element notesElement = (Element) photoElement.getElementsByTagName("notes").item(0);
List notes = new ArrayList();
NodeList noteNodes = notesElement.getElementsByTagName("note");
for (int i = 0; i < noteNodes.getLength(); i++) {
Element noteElement = (Element) noteNodes.item(i);
Note note = new Note();
note.setId(noteElement.getAttribute("id"));
note.setAuthor(noteElement.getAttribute("author"));
note.setAuthorName(noteElement.getAttribute("authorname"));
note.setBounds(noteElement.getAttribute("x"), noteElement.getAttribute("y"),
noteElement.getAttribute("w"), noteElement.getAttribute("h"));
notes.add(note);
}
photo.setNotes(notes);
Element tagsElement = (Element) photoElement.getElementsByTagName("tags").item(0);
List tags = new ArrayList();
NodeList tagNodes = tagsElement.getElementsByTagName("tag");
for (int i = 0; i < tagNodes.getLength(); i++) {
Element tagElement = (Element) tagNodes.item(i);
Tag tag = new Tag();
tag.setId(tagElement.getAttribute("id"));
tag.setAuthor(tagElement.getAttribute("author"));
tag.setRaw(tagElement.getAttribute("raw"));
tag.setValue(((Text) tagElement.getFirstChild()).getData());
tags.add(tag);
}
photo.setTags(tags);
Element urlsElement = (Element) photoElement.getElementsByTagName("urls").item(0);
List urls = new ArrayList();
NodeList urlNodes = urlsElement.getElementsByTagName("url");
for (int i = 0; i < urlNodes.getLength(); i++) {
Element urlElement = (Element) urlNodes.item(i);
PhotoUrl photoUrl = new PhotoUrl();
photoUrl.setType(urlElement.getAttribute("type"));
photoUrl.setUrl(XMLUtilities.getValue(urlElement));
if (photoUrl.getType().equals("photopage")) {
photo.setUrl(photoUrl.getUrl());
}
}
photo.setUrls(urls);
return photo;
}
| public Photo getInfo(String photoId, String secret) throws IOException, SAXException, FlickrException {
List parameters = new ArrayList();
parameters.add(new Parameter("method", METHOD_GET_INFO));
parameters.add(new Parameter("api_key", apiKey));
parameters.add(new Parameter("photo_id", photoId));
if (secret != null) {
parameters.add(new Parameter("secret", secret));
}
Response response = transport.get(transport.getPath(), parameters);
if (response.isError()) {
throw new FlickrException(response.getErrorCode(), response.getErrorMessage());
}
Element photoElement = (Element)response.getPayload();
Photo photo = new Photo();
photo.setId(photoElement.getAttribute("id"));
photo.setSecret(photoElement.getAttribute("secret"));
photo.setServer(photoElement.getAttribute("server"));
photo.setFavorite("1".equals(photoElement.getAttribute("isfavorite")));
photo.setLicense(photoElement.getAttribute("license"));
Element ownerElement = (Element) photoElement.getElementsByTagName("owner").item(0);
User owner = new User();
owner.setId(ownerElement.getAttribute("nsid"));
owner.setUsername(ownerElement.getAttribute("username"));
owner.setRealName(ownerElement.getAttribute("realname"));
owner.setLocation(ownerElement.getAttribute("location"));
photo.setOwner(owner);
photo.setTitle(XMLUtilities.getChildValue(photoElement, "title"));
photo.setDescription(XMLUtilities.getChildValue(photoElement, "description"));
Element visibilityElement = (Element) photoElement.getElementsByTagName("visibility").item(0);
photo.setPublicFlag("1".equals(visibilityElement.getAttribute("ispublic")));
photo.setFriendFlag("1".equals(visibilityElement.getAttribute("isfriend")));
photo.setFamilyFlag("1".equals(visibilityElement.getAttribute("isfamily")));
Element datesElement = XMLUtilities.getChild(photoElement, "dates");
photo.setDatePosted(datesElement.getAttribute("posted"));
photo.setDateTaken(datesElement.getAttribute("taken"));
photo.setTakenGranularity(datesElement.getAttribute("takengranularity"));
NodeList permissionsNodes = photoElement.getElementsByTagName("permissions");
if (permissionsNodes.getLength() > 0) {
Element permissionsElement = (Element) permissionsNodes.item(0);
Permissions permissions = new Permissions();
permissions.setComment(permissionsElement.getAttribute("permcomment"));
permissions.setAddmeta(permissionsElement.getAttribute("permaddmeta"));
}
Element editabilityElement = (Element) photoElement.getElementsByTagName("editability").item(0);
Editability editability = new Editability();
editability.setComment("1".equals(editabilityElement.getAttribute("cancomment")));
editability.setAddmeta("1".equals(editabilityElement.getAttribute("canaddmeta")));
Element commentsElement = (Element) photoElement.getElementsByTagName("comments").item(0);
photo.setComments(((Text) commentsElement.getFirstChild()).getData());
Element notesElement = (Element) photoElement.getElementsByTagName("notes").item(0);
List notes = new ArrayList();
NodeList noteNodes = notesElement.getElementsByTagName("note");
for (int i = 0; i < noteNodes.getLength(); i++) {
Element noteElement = (Element) noteNodes.item(i);
Note note = new Note();
note.setId(noteElement.getAttribute("id"));
note.setAuthor(noteElement.getAttribute("author"));
note.setAuthorName(noteElement.getAttribute("authorname"));
note.setBounds(noteElement.getAttribute("x"), noteElement.getAttribute("y"),
noteElement.getAttribute("w"), noteElement.getAttribute("h"));
notes.add(note);
}
photo.setNotes(notes);
Element tagsElement = (Element) photoElement.getElementsByTagName("tags").item(0);
List tags = new ArrayList();
NodeList tagNodes = tagsElement.getElementsByTagName("tag");
for (int i = 0; i < tagNodes.getLength(); i++) {
Element tagElement = (Element) tagNodes.item(i);
Tag tag = new Tag();
tag.setId(tagElement.getAttribute("id"));
tag.setAuthor(tagElement.getAttribute("author"));
tag.setRaw(tagElement.getAttribute("raw"));
tag.setValue(((Text) tagElement.getFirstChild()).getData());
tags.add(tag);
}
photo.setTags(tags);
Element urlsElement = (Element) photoElement.getElementsByTagName("urls").item(0);
List urls = new ArrayList();
NodeList urlNodes = urlsElement.getElementsByTagName("url");
for (int i = 0; i < urlNodes.getLength(); i++) {
Element urlElement = (Element) urlNodes.item(i);
PhotoUrl photoUrl = new PhotoUrl();
photoUrl.setType(urlElement.getAttribute("type"));
photoUrl.setUrl(XMLUtilities.getValue(urlElement));
if (photoUrl.getType().equals("photopage")) {
photo.setUrl(photoUrl.getUrl());
}
}
photo.setUrls(urls);
return photo;
}
|
diff --git a/src/main/java/de/dobermai/mqttbot/ioc/MqttBotModule.java b/src/main/java/de/dobermai/mqttbot/ioc/MqttBotModule.java
index 9cd9659..4144ff0 100644
--- a/src/main/java/de/dobermai/mqttbot/ioc/MqttBotModule.java
+++ b/src/main/java/de/dobermai/mqttbot/ioc/MqttBotModule.java
@@ -1,33 +1,33 @@
package de.dobermai.mqttbot.ioc;
import com.google.inject.AbstractModule;
import com.google.inject.Provides;
import de.dobermai.mqttbot.config.MQTTProperties;
import org.fusesource.mqtt.client.CallbackConnection;
import org.fusesource.mqtt.client.MQTT;
import javax.inject.Singleton;
/**
* @author Dominik Obermaier
*/
public class MqttBotModule extends AbstractModule {
@Override
protected void configure() {
}
@Provides
@Singleton
public CallbackConnection provideMqttConnection(final MQTTProperties mqttProperties) throws Exception {
MQTT mqtt = new MQTT();
mqtt.setHost(mqttProperties.getBrokerHost(), mqttProperties.getBrokerPort());
mqtt.setCleanSession(mqttProperties.isMqttcleanSession());
mqtt.setClientId(mqttProperties.getMqttClientId());
- mqtt.setKeepAlive(mqtt.getKeepAlive());
+ mqtt.setKeepAlive((short) mqttProperties.getMqttKeepAlive());
mqtt.setUserName(mqttProperties.getMqttUsername());
mqtt.setPassword(mqttProperties.getMqttPassword());
return mqtt.callbackConnection();
}
}
| true | true | public CallbackConnection provideMqttConnection(final MQTTProperties mqttProperties) throws Exception {
MQTT mqtt = new MQTT();
mqtt.setHost(mqttProperties.getBrokerHost(), mqttProperties.getBrokerPort());
mqtt.setCleanSession(mqttProperties.isMqttcleanSession());
mqtt.setClientId(mqttProperties.getMqttClientId());
mqtt.setKeepAlive(mqtt.getKeepAlive());
mqtt.setUserName(mqttProperties.getMqttUsername());
mqtt.setPassword(mqttProperties.getMqttPassword());
return mqtt.callbackConnection();
}
| public CallbackConnection provideMqttConnection(final MQTTProperties mqttProperties) throws Exception {
MQTT mqtt = new MQTT();
mqtt.setHost(mqttProperties.getBrokerHost(), mqttProperties.getBrokerPort());
mqtt.setCleanSession(mqttProperties.isMqttcleanSession());
mqtt.setClientId(mqttProperties.getMqttClientId());
mqtt.setKeepAlive((short) mqttProperties.getMqttKeepAlive());
mqtt.setUserName(mqttProperties.getMqttUsername());
mqtt.setPassword(mqttProperties.getMqttPassword());
return mqtt.callbackConnection();
}
|
diff --git a/src/main/java/me/tehbeard/BeardAch/dataSource/AchievementLoader.java b/src/main/java/me/tehbeard/BeardAch/dataSource/AchievementLoader.java
index ea2805f..1cc87de 100644
--- a/src/main/java/me/tehbeard/BeardAch/dataSource/AchievementLoader.java
+++ b/src/main/java/me/tehbeard/BeardAch/dataSource/AchievementLoader.java
@@ -1,249 +1,250 @@
package me.tehbeard.BeardAch.dataSource;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.configuration.ConfigurationSection;
import me.tehbeard.BeardAch.BeardAch;
import me.tehbeard.BeardAch.achievement.Achievement;
import me.tehbeard.BeardAch.achievement.Achievement.Display;
import me.tehbeard.BeardAch.achievement.rewards.IReward;
import me.tehbeard.BeardAch.achievement.triggers.ITrigger;
import me.tehbeard.BeardAch.dataSource.json.ClassCatalogue;
import me.tehbeard.BeardAch.dataSource.json.LocationJSONParser;
import me.tehbeard.BeardAch.dataSource.json.RewardJSONParser;
import me.tehbeard.BeardAch.dataSource.json.TriggerJSONParser;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonIOException;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonWriter;
/**
* Loads achievements from an external Gson file
* @author James
*
*/
public class AchievementLoader {
public static final ClassCatalogue<ITrigger> triggerFactory = new ClassCatalogue<ITrigger>();
public static final ClassCatalogue<IReward> rewardFactory = new ClassCatalogue<IReward>();
/**
* Create prime Gson object,
* Only export annotated fields
* Pretty print for human debugging.
* Also adds type adapters for trigger, reward and location
*/
private static Gson gson = new GsonBuilder().
excludeFieldsWithoutExposeAnnotation().
setPrettyPrinting().
registerTypeHierarchyAdapter(ITrigger.class, new TriggerJSONParser()).
registerTypeHierarchyAdapter(IReward.class, new RewardJSONParser()).
registerTypeHierarchyAdapter(Location.class,new LocationJSONParser()).
create();
private static List<Achievement> loadAchievementsFromJSONFile(File file){
try {
return gson.fromJson(new FileReader(file), new TypeToken<List<Achievement>>(){}.getType());
} catch (JsonIOException e) {
BeardAch.printError("An error occured reading " + file.toString(),e);
} catch (JsonSyntaxException e) {
BeardAch.printError("There is a problem with the syntax of " + file.toString(),e);
} catch (FileNotFoundException e) {
BeardAch.printError(file.toString() + " not found",e);
} catch (IOException e) {
BeardAch.printError("An error occured reading " + file.toString(),e);
}
return null;
}
public static void loadAchievements(){
try {
//Load and create file
File file = new File(BeardAch.self.getDataFolder(),"ach.json");
file.createNewFile();
List<Achievement> achievements = loadAchievementsFromJSONFile(file);
if(achievements!=null){
//Run postLoad() on all achievements and add them to manager if successful
for(Achievement a : achievements){
if(a.postLoad()){
BeardAch.printDebugCon("Loading achievement " + a.getName());
BeardAch.self.getAchievementManager().addAchievement(a);
}
else
{
BeardAch.printCon("Could not load " + a.getName());
}
}
}
File achDir = new File(BeardAch.self.getDataFolder(),"config");
if(achDir.isDirectory() && achDir.exists()){
for(String f : achDir.list(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.endsWith(".json");
}
})){
achievements = loadAchievementsFromJSONFile(new File(achDir,f));
if(achievements!=null){
//Run postLoad() on all achievements and add them to manager if successful
for(Achievement a : achievements){
+ if(a==null){continue;}
if(a.postLoad()){
BeardAch.printDebugCon("Loading achievement " + a.getName());
BeardAch.self.getAchievementManager().addAchievement(a);
}
else
{
BeardAch.printCon("Could not load " + a.getName());
}
}
}
}
}
//TODO: Kill in 0.6
//old method to load achievements
List<Achievement> l = loadOldConfigAchievements();
boolean tripped = false;
for(Achievement a:l){
tripped = true;
BeardAch.printCon("Loading achievement " + a.getName());
BeardAch.self.getAchievementManager().addAchievement(a);
}
//convert old to new json awesomeness
if(tripped){
JsonWriter jw = new JsonWriter(new FileWriter(file));
jw.setIndent(" ");
gson.toJson(
BeardAch.self.getAchievementManager().getLoadedAchievements(),
new TypeToken<List<Achievement>>(){}.getType(),
jw
);
jw.flush();
jw.close();
Bukkit.getConsoleSender().sendMessage(ChatColor.RED + "[BEARDACH] CONVERTED ACHIEVEMENTS TO JSON, PLEASE CHECK CONVERSION WORKED AND REMOVE ACHIEVEMENTS ENTRY FROM config.yml");
}
} catch (JsonIOException e) {
BeardAch.printError("An error occured reading ach.json",e);
} catch (JsonSyntaxException e) {
BeardAch.printError("There is a problem with the syntax of ach.json",e);
e.printStackTrace();
} catch (FileNotFoundException e) {
BeardAch.printError("ach.json not found",e);
} catch (IOException e) {
BeardAch.printError("An error occured reading ach.json",e);
e.printStackTrace();
}
}
//TODO: KILL THIS WITH FIRE IN 0.6
public static List<Achievement> loadOldConfigAchievements(){
List<Achievement> a = new ArrayList<Achievement>();
BeardAch.printDebugCon("Loading Achievement Data");
BeardAch.self.reloadConfig();
if(BeardAch.self.getConfig().isConfigurationSection("achievements")){
BeardAch.printCon("[PANIC] OLD ACHIEVEMENTS CONFIG FOUND, CONVERSION WILL BE DONE");
}
else
{
return a;
}
Set<String> achs = BeardAch.self.getConfig().getConfigurationSection("achievements").getKeys(false);
for(String slug : achs){
ConfigurationSection e = BeardAch.self.getConfig().getConfigurationSection("achievements").getConfigurationSection(slug);
if(e==null){
continue;
}
//load information
String name = e.getString("name");
String descrip = e.getString("descrip");
Display broadcast = Achievement.Display.valueOf(e.getString("broadcast",BeardAch.self.getConfig().getString("ach.msg.send","NONE")));
slug = e.getString("alias",slug);
boolean hidden = e.getBoolean("hidden",false);
BeardAch.printDebugCon("Loading achievement " + name);
@SuppressWarnings("deprecation")
Achievement ach = new Achievement(slug,name, descrip,broadcast,hidden);
//load triggers
try{
List<String> triggers = e.getStringList("triggers");
for(String trig: triggers){
String[] part = trig.split("\\|");
if(part.length==2){
BeardAch.printDebugCon("Trigger => " + trig);
ITrigger trigger = triggerFactory.get(part[0]).newInstance();
if(trigger==null){BeardAch.printCon("[PANIC] TRIGGER " + part[0] + " NOT FOUND!!! SKIPPING.");continue;}
trigger.configure(ach,part[1]);
trigger.configure(ach);
ach.addTrigger(trigger);
}
else
{
BeardAch.printCon("[PANIC] ERROR! MALFORMED TRIGGER FOR ACHIEVEMENT " + name);
}
}
List<String> rewards = e.getStringList("rewards");
for(String reward: rewards){
String[] part = reward.split("\\|");
if(part.length==2){
BeardAch.printDebugCon("Reward => " + reward);
IReward rewardInst = rewardFactory.get(part[0]).newInstance();
rewardInst.configure(ach,part[1]);
rewardInst.configure(ach);
ach.addReward(rewardInst);
}
else
{
BeardAch.printCon("[PANIC] ERROR! MALFORMED REWARD FOR ACHIEVEMENT " + name);
}
}
} catch (InstantiationException e1) {
BeardAch.printError("Error loading old achievements",e1);
} catch (IllegalAccessException e1) {
BeardAch.printError("Error loading old achievements",e1);
}
a.add(ach);
}
BeardAch.self.getConfig().set("oldAchievements", BeardAch.self.getConfig().getConfigurationSection("achievements"));
BeardAch.self.getConfig().set("achievements",null);
BeardAch.self.saveConfig();
return a;
}
}
| true | true | public static void loadAchievements(){
try {
//Load and create file
File file = new File(BeardAch.self.getDataFolder(),"ach.json");
file.createNewFile();
List<Achievement> achievements = loadAchievementsFromJSONFile(file);
if(achievements!=null){
//Run postLoad() on all achievements and add them to manager if successful
for(Achievement a : achievements){
if(a.postLoad()){
BeardAch.printDebugCon("Loading achievement " + a.getName());
BeardAch.self.getAchievementManager().addAchievement(a);
}
else
{
BeardAch.printCon("Could not load " + a.getName());
}
}
}
File achDir = new File(BeardAch.self.getDataFolder(),"config");
if(achDir.isDirectory() && achDir.exists()){
for(String f : achDir.list(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.endsWith(".json");
}
})){
achievements = loadAchievementsFromJSONFile(new File(achDir,f));
if(achievements!=null){
//Run postLoad() on all achievements and add them to manager if successful
for(Achievement a : achievements){
if(a.postLoad()){
BeardAch.printDebugCon("Loading achievement " + a.getName());
BeardAch.self.getAchievementManager().addAchievement(a);
}
else
{
BeardAch.printCon("Could not load " + a.getName());
}
}
}
}
}
//TODO: Kill in 0.6
//old method to load achievements
List<Achievement> l = loadOldConfigAchievements();
boolean tripped = false;
for(Achievement a:l){
tripped = true;
BeardAch.printCon("Loading achievement " + a.getName());
BeardAch.self.getAchievementManager().addAchievement(a);
}
//convert old to new json awesomeness
if(tripped){
JsonWriter jw = new JsonWriter(new FileWriter(file));
jw.setIndent(" ");
gson.toJson(
BeardAch.self.getAchievementManager().getLoadedAchievements(),
new TypeToken<List<Achievement>>(){}.getType(),
jw
);
jw.flush();
jw.close();
Bukkit.getConsoleSender().sendMessage(ChatColor.RED + "[BEARDACH] CONVERTED ACHIEVEMENTS TO JSON, PLEASE CHECK CONVERSION WORKED AND REMOVE ACHIEVEMENTS ENTRY FROM config.yml");
}
} catch (JsonIOException e) {
BeardAch.printError("An error occured reading ach.json",e);
} catch (JsonSyntaxException e) {
BeardAch.printError("There is a problem with the syntax of ach.json",e);
e.printStackTrace();
} catch (FileNotFoundException e) {
BeardAch.printError("ach.json not found",e);
} catch (IOException e) {
BeardAch.printError("An error occured reading ach.json",e);
e.printStackTrace();
}
}
| public static void loadAchievements(){
try {
//Load and create file
File file = new File(BeardAch.self.getDataFolder(),"ach.json");
file.createNewFile();
List<Achievement> achievements = loadAchievementsFromJSONFile(file);
if(achievements!=null){
//Run postLoad() on all achievements and add them to manager if successful
for(Achievement a : achievements){
if(a.postLoad()){
BeardAch.printDebugCon("Loading achievement " + a.getName());
BeardAch.self.getAchievementManager().addAchievement(a);
}
else
{
BeardAch.printCon("Could not load " + a.getName());
}
}
}
File achDir = new File(BeardAch.self.getDataFolder(),"config");
if(achDir.isDirectory() && achDir.exists()){
for(String f : achDir.list(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.endsWith(".json");
}
})){
achievements = loadAchievementsFromJSONFile(new File(achDir,f));
if(achievements!=null){
//Run postLoad() on all achievements and add them to manager if successful
for(Achievement a : achievements){
if(a==null){continue;}
if(a.postLoad()){
BeardAch.printDebugCon("Loading achievement " + a.getName());
BeardAch.self.getAchievementManager().addAchievement(a);
}
else
{
BeardAch.printCon("Could not load " + a.getName());
}
}
}
}
}
//TODO: Kill in 0.6
//old method to load achievements
List<Achievement> l = loadOldConfigAchievements();
boolean tripped = false;
for(Achievement a:l){
tripped = true;
BeardAch.printCon("Loading achievement " + a.getName());
BeardAch.self.getAchievementManager().addAchievement(a);
}
//convert old to new json awesomeness
if(tripped){
JsonWriter jw = new JsonWriter(new FileWriter(file));
jw.setIndent(" ");
gson.toJson(
BeardAch.self.getAchievementManager().getLoadedAchievements(),
new TypeToken<List<Achievement>>(){}.getType(),
jw
);
jw.flush();
jw.close();
Bukkit.getConsoleSender().sendMessage(ChatColor.RED + "[BEARDACH] CONVERTED ACHIEVEMENTS TO JSON, PLEASE CHECK CONVERSION WORKED AND REMOVE ACHIEVEMENTS ENTRY FROM config.yml");
}
} catch (JsonIOException e) {
BeardAch.printError("An error occured reading ach.json",e);
} catch (JsonSyntaxException e) {
BeardAch.printError("There is a problem with the syntax of ach.json",e);
e.printStackTrace();
} catch (FileNotFoundException e) {
BeardAch.printError("ach.json not found",e);
} catch (IOException e) {
BeardAch.printError("An error occured reading ach.json",e);
e.printStackTrace();
}
}
|
diff --git a/src/main/java/com/gemantic/killer/service/impl/MessageServiceSingleDroolsImpl.java b/src/main/java/com/gemantic/killer/service/impl/MessageServiceSingleDroolsImpl.java
index 7456816..1de1d6a 100644
--- a/src/main/java/com/gemantic/killer/service/impl/MessageServiceSingleDroolsImpl.java
+++ b/src/main/java/com/gemantic/killer/service/impl/MessageServiceSingleDroolsImpl.java
@@ -1,300 +1,300 @@
package com.gemantic.killer.service.impl;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.Resource;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.drools.runtime.StatefulKnowledgeSession;
import org.drools.runtime.rule.FactHandle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.gemantic.common.exception.ServiceDaoException;
import com.gemantic.common.exception.ServiceException;
import com.gemantic.killer.common.model.Message;
import com.gemantic.killer.common.model.Operater;
import com.gemantic.killer.model.Room;
import com.gemantic.killer.model.User;
import com.gemantic.killer.service.MessageService;
import com.gemantic.killer.service.RoomService;
import com.gemantic.killer.service.RoomTimerService;
import com.gemantic.killer.service.SessionService;
import com.gemantic.killer.util.MessageUtil;
import com.gemantic.labs.killer.model.Records;
import com.gemantic.labs.killer.service.RecordService;
import com.gemantic.labs.killer.service.UsersService;
//这段代码有点乱.有时间整理一下.
//太多需要重构的地方了.判断是哪一个Process启动.不应该通过配置文件.而是应该通过游戏房间的状态.
//用户名什么时候应该传进去.Snapshot应该如何处理.
@Component
public class MessageServiceSingleDroolsImpl implements MessageService {
private static final Log log = LogFactory.getLog(MessageServiceSingleDroolsImpl.class);
private static final Log recordLog = LogFactory.getLog("gameRecord");
@Autowired
private RoomTimerService roomTimerSevice;
@Autowired
private SessionService sessionService;
@Autowired
private UsersService userService;
@Autowired
private RoomService roomService;
@Autowired
private RecordService recordService;
@Resource(name = "roomAction")
private Set<String> roomAction = new HashSet();
public List<Message> generate(Message message, Room room) throws ServiceException, ServiceDaoException {
// 根据不同的房间ID创建不同的Session.这样怎么能支持扩展性呢.Session能否序列化.除非支持按房间分布Service的Session.
Long start=System.currentTimeMillis();
Operater operater = new Operater(message);
try{
process(operater, room);
}catch(Throwable t){
t.printStackTrace();
log.error(t);
log.error("error room is "+room +" message is "+message);
log.info("because room error so retract room ");
roomService.removeRoom(room.getId());
}
// 应该是开始游戏之后才记录.
if (CollectionUtils.isEmpty(operater.getTimerMessages())) {
log.info(message.getId() + " not have time ");
} else {
log.info(message.getId() + " have time " + operater.getTimerMessages());
roomTimerSevice.nextMessages(operater.getTimerMessages());
}
// 怎么对顺序排序
log.info(message.getId()+" user time is "+(System.currentTimeMillis()-start));
log.info(operater.getNextMessages());
return operater.getNextMessages();
}
private Operater process(Operater operater, Room r) throws ServiceException, ServiceDaoException {
Long roomID = Long.valueOf(operater.getMessage().getWhere());
// 大爷的.这个时候还没有Room
//log.info(operater + " =========== start,room ======================== " + r);
Long start = System.currentTimeMillis();
StatefulKnowledgeSession ksession = sessionService.getSesseion(operater.getMessage());
FactHandle fo = ksession.insert(operater);
//log.info(operater + " =========== after insert");
FactHandle fm = ksession.insert(operater.getMessage());
if (IsRoomMessage(operater.getMessage(), r)) {
//log.info("room operator " + operater.getMessage());
ksession.startProcess("room");
} else {
//log.info("game operator " + operater.getMessage());
ksession.startProcess("game");
}
ksession.fireAllRules();
ksession.retract(fo);
ksession.retract(fm);
// 什么时候关闭Session呢.规则里触发游戏结束的事件.
//log.info(" use time " + (System.currentTimeMillis() - start));
//log.info(operater + " =========== over");
List<Message> messages = new ArrayList();
messages = operater.getNextMessages();
if (operater.getGameStart()) {
// 创建的时候不会更新.因为创建的时候不会是Start
//log.info("game start");// 主要是在Session里.愁死我了.Gameover的时候不能把Session给Remove了.
r.setStartAt(operater.getMessage().getTime());
r.setStatus(Room.status_start);
r.setPlayers(operater.getPlayers());
this.roomService.updateRoom(r);
}
Long prevStart=r.getStartAt();
Long end=System.currentTimeMillis();
Long time=end-prevStart;
if (operater.getGameOver()) {
// log.info("game over");// 主要是在Session里.愁死我了.Gameover的时候不能把Session给Remove了.
this.roomTimerSevice.removeRoomTimer(Long.valueOf(operater.getMessage().getWhere()));
operater.getTimerMessages().clear();
r.setStartAt(System.currentTimeMillis() * 2);// 设置游戏的开始时间远远大于现在.
r.setStatus(Room.status_wait);
this.roomService.updateRoom(r);
// 从哪知道游戏里的玩家呢
- if(r.getVersion().equals("killer_police_1.0")){
+ if(r.getVersion().equals("killer_police_1.0")||r.getVersion().equals("ghost_simple_1.0")){
for (Message m : messages) {
if ("decryption" == m.getPredict()) {
Long uid = Long.valueOf(m.getSubject());
User u = this.userService.getObjectById(uid);
u.setMoney(u.getMoney() + 2000);//
this.userService.update(u);
}
}
}
if(r.getPlayers().size()>=6&&time>3*60*1000){
//六人局才发钱和超过三分钟才给钱存战例
for (Message m : messages) {
if ("decryption" == m.getPredict()) {
Long uid = Long.valueOf(m.getSubject());
User u = this.userService.getObjectById(uid);
u.setMoney(u.getMoney() + 1000);//
this.userService.update(u);
}
}
if(r.getVersion().equals("simple_1.0")){
// 更新战例记录
Records record = new Records();
record.setId(operater.getRecordID());
record.setPath("record/" + operater.getRecordID()+".txt");
record.setTime(time);
record.setRoom(r);
record.setVersion(r.getVersion());
List<Long> ls=r.getPlayers();
List<User> users=this.userService.getObjectsByIds(ls);
Map<Long,String> uid_names=new HashMap();
for(User user:users){
uid_names.put(user.getId(), user.getName());
}
record.setUid_names(uid_names);
this.recordService.insert(record);
// log.info(" insert record " + record);
}
}
}
// 开始之后就没有了计房间的状态了.
//log.info(roomID + " room is empty ? " + operater.getRoomEmpty());
if (operater.getRoomEmpty()) {
log.info("room empty ");
this.roomService.removeRoom(roomID);
this.sessionService.removeSession(operater.getMessage());
//log.info("room over ===================" + r);
}
return operater;
}
private boolean IsRoomMessage(Message message, Room r) {
if("video_1.0".equals(r.getVersion())){
return true;
}
if( (Room.status_start == r.getStatus() || "start".equals(message.getPredict()))){
return false;
}else {
return true;
}
/*
* String predict = message.getPredict();
*
* if (predict.equals("query") && !gameOver) { //
* 如果是查询,而且游戏又没有进行完.走的Game规则的查询接口. return false;
*
* }
*
* return this.roomAction.contains(message.getPredict());
*/
}
public Set<String> getRoomAction() {
return roomAction;
}
public void setRoomAction(Set<String> roomAction) {
this.roomAction = roomAction;
}
@Override
public String getSnapshots(Message queryMessage, Room room) throws ServiceException, ServiceDaoException {
Operater operator = new Operater(queryMessage);
// 这儿还是会是空的
process(operator, room);
return operator.getSnapshots();
}
@Override
public List<Message> createRoom(Room room) throws ServiceException, ServiceDaoException {
Message createMessage = MessageUtil.parse(room.getVersion(), room.getCreaterID() + ",create,-500,1000000,78," + room.getId(), "我创建了房间");
Operater operator = new Operater(createMessage);
operator.setSetting(room.getSetting());
process(operator, room);
if (CollectionUtils.isEmpty(operator.getTimerMessages())) {
} else {
roomTimerSevice.nextMessages(operator.getTimerMessages());
}
return operator.getNextMessages();
}
@Override
public List<Message> updateSetting(Room room) throws ServiceException, ServiceDaoException {
Message createMessage = MessageUtil.parse(room.getVersion(), room.getCreaterID() + ",setting,update,1000000,78," + room.getId(), "");
Operater operator = new Operater(createMessage);
operator.setSetting(room.getSetting());
process(operator, room);
// 怎么对顺序排序
return operator.getNextMessages();
}
}
| true | true | private Operater process(Operater operater, Room r) throws ServiceException, ServiceDaoException {
Long roomID = Long.valueOf(operater.getMessage().getWhere());
// 大爷的.这个时候还没有Room
//log.info(operater + " =========== start,room ======================== " + r);
Long start = System.currentTimeMillis();
StatefulKnowledgeSession ksession = sessionService.getSesseion(operater.getMessage());
FactHandle fo = ksession.insert(operater);
//log.info(operater + " =========== after insert");
FactHandle fm = ksession.insert(operater.getMessage());
if (IsRoomMessage(operater.getMessage(), r)) {
//log.info("room operator " + operater.getMessage());
ksession.startProcess("room");
} else {
//log.info("game operator " + operater.getMessage());
ksession.startProcess("game");
}
ksession.fireAllRules();
ksession.retract(fo);
ksession.retract(fm);
// 什么时候关闭Session呢.规则里触发游戏结束的事件.
//log.info(" use time " + (System.currentTimeMillis() - start));
//log.info(operater + " =========== over");
List<Message> messages = new ArrayList();
messages = operater.getNextMessages();
if (operater.getGameStart()) {
// 创建的时候不会更新.因为创建的时候不会是Start
//log.info("game start");// 主要是在Session里.愁死我了.Gameover的时候不能把Session给Remove了.
r.setStartAt(operater.getMessage().getTime());
r.setStatus(Room.status_start);
r.setPlayers(operater.getPlayers());
this.roomService.updateRoom(r);
}
Long prevStart=r.getStartAt();
Long end=System.currentTimeMillis();
Long time=end-prevStart;
if (operater.getGameOver()) {
// log.info("game over");// 主要是在Session里.愁死我了.Gameover的时候不能把Session给Remove了.
this.roomTimerSevice.removeRoomTimer(Long.valueOf(operater.getMessage().getWhere()));
operater.getTimerMessages().clear();
r.setStartAt(System.currentTimeMillis() * 2);// 设置游戏的开始时间远远大于现在.
r.setStatus(Room.status_wait);
this.roomService.updateRoom(r);
// 从哪知道游戏里的玩家呢
if(r.getVersion().equals("killer_police_1.0")){
for (Message m : messages) {
if ("decryption" == m.getPredict()) {
Long uid = Long.valueOf(m.getSubject());
User u = this.userService.getObjectById(uid);
u.setMoney(u.getMoney() + 2000);//
this.userService.update(u);
}
}
}
if(r.getPlayers().size()>=6&&time>3*60*1000){
//六人局才发钱和超过三分钟才给钱存战例
for (Message m : messages) {
if ("decryption" == m.getPredict()) {
Long uid = Long.valueOf(m.getSubject());
User u = this.userService.getObjectById(uid);
u.setMoney(u.getMoney() + 1000);//
this.userService.update(u);
}
}
if(r.getVersion().equals("simple_1.0")){
// 更新战例记录
Records record = new Records();
record.setId(operater.getRecordID());
record.setPath("record/" + operater.getRecordID()+".txt");
record.setTime(time);
record.setRoom(r);
record.setVersion(r.getVersion());
List<Long> ls=r.getPlayers();
List<User> users=this.userService.getObjectsByIds(ls);
Map<Long,String> uid_names=new HashMap();
for(User user:users){
uid_names.put(user.getId(), user.getName());
}
record.setUid_names(uid_names);
this.recordService.insert(record);
// log.info(" insert record " + record);
}
}
}
// 开始之后就没有了计房间的状态了.
//log.info(roomID + " room is empty ? " + operater.getRoomEmpty());
if (operater.getRoomEmpty()) {
log.info("room empty ");
this.roomService.removeRoom(roomID);
this.sessionService.removeSession(operater.getMessage());
//log.info("room over ===================" + r);
}
return operater;
}
| private Operater process(Operater operater, Room r) throws ServiceException, ServiceDaoException {
Long roomID = Long.valueOf(operater.getMessage().getWhere());
// 大爷的.这个时候还没有Room
//log.info(operater + " =========== start,room ======================== " + r);
Long start = System.currentTimeMillis();
StatefulKnowledgeSession ksession = sessionService.getSesseion(operater.getMessage());
FactHandle fo = ksession.insert(operater);
//log.info(operater + " =========== after insert");
FactHandle fm = ksession.insert(operater.getMessage());
if (IsRoomMessage(operater.getMessage(), r)) {
//log.info("room operator " + operater.getMessage());
ksession.startProcess("room");
} else {
//log.info("game operator " + operater.getMessage());
ksession.startProcess("game");
}
ksession.fireAllRules();
ksession.retract(fo);
ksession.retract(fm);
// 什么时候关闭Session呢.规则里触发游戏结束的事件.
//log.info(" use time " + (System.currentTimeMillis() - start));
//log.info(operater + " =========== over");
List<Message> messages = new ArrayList();
messages = operater.getNextMessages();
if (operater.getGameStart()) {
// 创建的时候不会更新.因为创建的时候不会是Start
//log.info("game start");// 主要是在Session里.愁死我了.Gameover的时候不能把Session给Remove了.
r.setStartAt(operater.getMessage().getTime());
r.setStatus(Room.status_start);
r.setPlayers(operater.getPlayers());
this.roomService.updateRoom(r);
}
Long prevStart=r.getStartAt();
Long end=System.currentTimeMillis();
Long time=end-prevStart;
if (operater.getGameOver()) {
// log.info("game over");// 主要是在Session里.愁死我了.Gameover的时候不能把Session给Remove了.
this.roomTimerSevice.removeRoomTimer(Long.valueOf(operater.getMessage().getWhere()));
operater.getTimerMessages().clear();
r.setStartAt(System.currentTimeMillis() * 2);// 设置游戏的开始时间远远大于现在.
r.setStatus(Room.status_wait);
this.roomService.updateRoom(r);
// 从哪知道游戏里的玩家呢
if(r.getVersion().equals("killer_police_1.0")||r.getVersion().equals("ghost_simple_1.0")){
for (Message m : messages) {
if ("decryption" == m.getPredict()) {
Long uid = Long.valueOf(m.getSubject());
User u = this.userService.getObjectById(uid);
u.setMoney(u.getMoney() + 2000);//
this.userService.update(u);
}
}
}
if(r.getPlayers().size()>=6&&time>3*60*1000){
//六人局才发钱和超过三分钟才给钱存战例
for (Message m : messages) {
if ("decryption" == m.getPredict()) {
Long uid = Long.valueOf(m.getSubject());
User u = this.userService.getObjectById(uid);
u.setMoney(u.getMoney() + 1000);//
this.userService.update(u);
}
}
if(r.getVersion().equals("simple_1.0")){
// 更新战例记录
Records record = new Records();
record.setId(operater.getRecordID());
record.setPath("record/" + operater.getRecordID()+".txt");
record.setTime(time);
record.setRoom(r);
record.setVersion(r.getVersion());
List<Long> ls=r.getPlayers();
List<User> users=this.userService.getObjectsByIds(ls);
Map<Long,String> uid_names=new HashMap();
for(User user:users){
uid_names.put(user.getId(), user.getName());
}
record.setUid_names(uid_names);
this.recordService.insert(record);
// log.info(" insert record " + record);
}
}
}
// 开始之后就没有了计房间的状态了.
//log.info(roomID + " room is empty ? " + operater.getRoomEmpty());
if (operater.getRoomEmpty()) {
log.info("room empty ");
this.roomService.removeRoom(roomID);
this.sessionService.removeSession(operater.getMessage());
//log.info("room over ===================" + r);
}
return operater;
}
|
diff --git a/RPG/src/RPGPersisted.java b/RPG/src/RPGPersisted.java
index c0a2689..558a50f 100644
--- a/RPG/src/RPGPersisted.java
+++ b/RPG/src/RPGPersisted.java
@@ -1,203 +1,212 @@
import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
public abstract class RPGPersisted
{
protected boolean dirty = false;
protected List<Field> fields = new ArrayList<Field>();
protected Field idField;
public RPGPersisted()
{
}
protected void onSave(PreparedStatement ps)
{
}
protected void onLoad(ResultSet rs)
{
}
protected void findFields()
{
idField = null;
for (Field field : this.getClass().getDeclaredFields())
{
RPGPersist persist = field.getAnnotation(RPGPersist.class);
if (persist != null)
{
fields.add(field);
if (persist.id())
{
idField = field;
}
}
}
}
public void load(Connection conn, String tableName, List<RPGPersisted> objects)
{
findFields();
if (fields.size() <= 0)
{
RPG.getRPG().log(Level.WARNING, "No fields defined for persisted class: " + getClass().getName());
return;
}
PreparedStatement ps = null;
ResultSet rs = null;
try
{
String sqlSelect = "SELECT ";
boolean first = true;
for (Field field : fields)
{
if (!first) sqlSelect += ", ";
first = false;
sqlSelect += field.getName();
}
sqlSelect += " FROM " + tableName;
ps = conn.prepareStatement(sqlSelect);
rs = ps.executeQuery();
while (rs.next())
{
RPGPersisted newObject = (RPGPersisted)this.getClass().newInstance();
for (Field field : fields)
{
field.set(newObject, rs.getObject(field.getName()));
}
newObject.onLoad(rs);
newObject.dirty = false;
objects.add(newObject);
}
}
catch (Exception ex)
{
RPG.getRPG().log(Level.SEVERE, "Error loading persisted class " + this.getClass().getName(), ex);
}
finally
{
try
{
if (ps != null)
{
ps.close();
}
if (rs != null)
{
rs.close();
}
}
catch (SQLException ex)
{
}
}
}
public void save(Connection conn, String tableName, List<RPGPersisted> objects)
{
findFields();
if (objects.size() <= 0) return;
if (fields.size() <= 0)
{
RPG.getRPG().log(Level.WARNING, "No fields defined for persisted class: " + this.getClass().getName());
return;
}
for(RPGPersisted object : objects)
{
if (object.dirty)
{
PreparedStatement ps = null;
ResultSet rs = null;
try
{
String fieldList = "";
String valueList = "";
String updateList = "";
boolean first = true;
for (Field field : fields)
{
if (!first)
{
fieldList += ", ";
valueList += ", ";
updateList += ", ";
}
first = false;
fieldList += field.getName();
valueList += "?";
updateList += field.getName() + " = ?";
}
String sqlUpdate =
"INSERT INTO "
+ tableName
+ " ("
+ fieldList
+ ") VALUES ("
+ valueList
+ ") ON DUPLICATE KEY UPDATE "
+ updateList;
ps = conn.prepareStatement(sqlUpdate);
- int index = 0;
+ int index = 1;
for (Field field : fields)
{
- Object value = field.get(field);
- ps.setObject(index, value);
- ps.setObject(index + fields.size(), value);
+ Object value = field.get(object);
+ if (value != null)
+ {
+ ps.setObject(index, value);
+ ps.setObject(index + fields.size(), value);
+ }
+ else
+ {
+ ps.setNull(index, java.sql.Types.NULL);
+ ps.setNull(index + fields.size(), java.sql.Types.NULL);
+ }
+ index++;
}
object.onSave(ps);
ps.executeUpdate();
object.dirty = false;
}
catch (Exception ex)
{
RPG.getRPG().log(Level.SEVERE, "Error updating or inserting persisted class " + getClass().getName(), ex);
}
finally
{
try
{
if (ps != null)
{
ps.close();
}
if (rs != null)
{
rs.close();
}
}
catch (SQLException ex)
{
}
}
}
}
}
public boolean isDirty()
{
return dirty;
}
public void setDirty(boolean dirty)
{
this.dirty = dirty;
}
}
| false | true | public void save(Connection conn, String tableName, List<RPGPersisted> objects)
{
findFields();
if (objects.size() <= 0) return;
if (fields.size() <= 0)
{
RPG.getRPG().log(Level.WARNING, "No fields defined for persisted class: " + this.getClass().getName());
return;
}
for(RPGPersisted object : objects)
{
if (object.dirty)
{
PreparedStatement ps = null;
ResultSet rs = null;
try
{
String fieldList = "";
String valueList = "";
String updateList = "";
boolean first = true;
for (Field field : fields)
{
if (!first)
{
fieldList += ", ";
valueList += ", ";
updateList += ", ";
}
first = false;
fieldList += field.getName();
valueList += "?";
updateList += field.getName() + " = ?";
}
String sqlUpdate =
"INSERT INTO "
+ tableName
+ " ("
+ fieldList
+ ") VALUES ("
+ valueList
+ ") ON DUPLICATE KEY UPDATE "
+ updateList;
ps = conn.prepareStatement(sqlUpdate);
int index = 0;
for (Field field : fields)
{
Object value = field.get(field);
ps.setObject(index, value);
ps.setObject(index + fields.size(), value);
}
object.onSave(ps);
ps.executeUpdate();
object.dirty = false;
}
catch (Exception ex)
{
RPG.getRPG().log(Level.SEVERE, "Error updating or inserting persisted class " + getClass().getName(), ex);
}
finally
{
try
{
if (ps != null)
{
ps.close();
}
if (rs != null)
{
rs.close();
}
}
catch (SQLException ex)
{
}
}
}
}
}
| public void save(Connection conn, String tableName, List<RPGPersisted> objects)
{
findFields();
if (objects.size() <= 0) return;
if (fields.size() <= 0)
{
RPG.getRPG().log(Level.WARNING, "No fields defined for persisted class: " + this.getClass().getName());
return;
}
for(RPGPersisted object : objects)
{
if (object.dirty)
{
PreparedStatement ps = null;
ResultSet rs = null;
try
{
String fieldList = "";
String valueList = "";
String updateList = "";
boolean first = true;
for (Field field : fields)
{
if (!first)
{
fieldList += ", ";
valueList += ", ";
updateList += ", ";
}
first = false;
fieldList += field.getName();
valueList += "?";
updateList += field.getName() + " = ?";
}
String sqlUpdate =
"INSERT INTO "
+ tableName
+ " ("
+ fieldList
+ ") VALUES ("
+ valueList
+ ") ON DUPLICATE KEY UPDATE "
+ updateList;
ps = conn.prepareStatement(sqlUpdate);
int index = 1;
for (Field field : fields)
{
Object value = field.get(object);
if (value != null)
{
ps.setObject(index, value);
ps.setObject(index + fields.size(), value);
}
else
{
ps.setNull(index, java.sql.Types.NULL);
ps.setNull(index + fields.size(), java.sql.Types.NULL);
}
index++;
}
object.onSave(ps);
ps.executeUpdate();
object.dirty = false;
}
catch (Exception ex)
{
RPG.getRPG().log(Level.SEVERE, "Error updating or inserting persisted class " + getClass().getName(), ex);
}
finally
{
try
{
if (ps != null)
{
ps.close();
}
if (rs != null)
{
rs.close();
}
}
catch (SQLException ex)
{
}
}
}
}
}
|
diff --git a/src/test/java/org/atlasapi/persistence/output/MongoAvailableItemsResolverTest.java b/src/test/java/org/atlasapi/persistence/output/MongoAvailableItemsResolverTest.java
index 029e5ff0..4bf32305 100644
--- a/src/test/java/org/atlasapi/persistence/output/MongoAvailableItemsResolverTest.java
+++ b/src/test/java/org/atlasapi/persistence/output/MongoAvailableItemsResolverTest.java
@@ -1,124 +1,125 @@
package org.atlasapi.persistence.output;
import static org.hamcrest.Matchers.hasItems;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import java.util.Set;
import org.atlasapi.application.v3.ApplicationConfiguration;
import org.atlasapi.media.entity.Brand;
import org.atlasapi.media.entity.ChildRef;
import org.atlasapi.media.entity.Encoding;
import org.atlasapi.media.entity.Episode;
import org.atlasapi.media.entity.Location;
import org.atlasapi.media.entity.LookupRef;
import org.atlasapi.media.entity.Policy;
import org.atlasapi.media.entity.Publisher;
import org.atlasapi.media.entity.Version;
import org.atlasapi.persistence.content.ContentWriter;
import org.atlasapi.persistence.content.mongo.MongoContentWriter;
import org.atlasapi.persistence.lookup.entry.LookupEntry;
import org.atlasapi.persistence.lookup.mongo.MongoLookupEntryStore;
import org.joda.time.DateTime;
import org.junit.Test;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.metabroadcast.common.persistence.MongoTestHelper;
import com.metabroadcast.common.persistence.mongo.DatabasedMongo;
import com.metabroadcast.common.time.DateTimeZones;
import com.metabroadcast.common.time.TimeMachine;
public class MongoAvailableItemsResolverTest {
private final DatabasedMongo mongo = MongoTestHelper.anEmptyTestDatabase();
private final TimeMachine clock = new TimeMachine();
private final MongoLookupEntryStore lookupStore
= new MongoLookupEntryStore(mongo.collection("lookup"));
private final MongoAvailableItemsResolver resolver
= new MongoAvailableItemsResolver(mongo, lookupStore, clock);
private final ContentWriter writer = new MongoContentWriter(mongo, lookupStore, clock);
@Test
public void testResolvesChildrenOfEquivalentBrandsAsTheItemsOfThePrimaryBrand() {
Brand primary = new Brand("primary", "primary", Publisher.BBC);
Brand equivalent = new Brand("equivalent", "equivalent", Publisher.PA);
Episode p1 = episode("p1", primary, location("p1l1", dateTime(0), dateTime(10)));
Episode p2 = episode("p2", primary);
Episode e1 = episode("e1", equivalent, location("e1l1", dateTime(0), dateTime(10)));
Episode e2 = episode("e2", equivalent, location("e2l2", dateTime(0), dateTime(10)));
writer.createOrUpdate(primary);
writer.createOrUpdate(equivalent);
writer.createOrUpdate(p1);
writer.createOrUpdate(p2);
writer.createOrUpdate(e1);
writer.createOrUpdate(e2);
writeEquivalences(p1, e1);
writeEquivalences(p2, e2);
primary.setEquivalentTo(ImmutableSet.of(LookupRef.from(equivalent)));
clock.jumpTo(dateTime(5));
ApplicationConfiguration noPaConfig = ApplicationConfiguration.defaultConfiguration();
Set<ChildRef> childRefs = ImmutableSet.copyOf(resolver.availableItemsFor(primary, noPaConfig));
ChildRef childRef = Iterables.getOnlyElement(childRefs);
assertEquals(p1.getCanonicalUri(), childRef.getUri());
ApplicationConfiguration withPaConfig = ApplicationConfiguration.defaultConfiguration()
+ .agreeLicense(Publisher.PA)
.enable(Publisher.PA);
childRefs = ImmutableSet.copyOf(resolver.availableItemsFor(primary, withPaConfig));
assertThat(childRefs.size(), is(2));
assertThat(Iterables.transform(childRefs, ChildRef.TO_URI), hasItems(p1.getCanonicalUri(), p2.getCanonicalUri()));
}
private void writeEquivalences(Episode a, Episode b) {
LookupEntry aEntry = LookupEntry.lookupEntryFrom(a)
.copyWithDirectEquivalents(ImmutableSet.of(LookupRef.from(b)))
.copyWithEquivalents(ImmutableSet.of(LookupRef.from(b)));
LookupEntry bEntry = LookupEntry.lookupEntryFrom(b)
.copyWithDirectEquivalents(ImmutableSet.of(LookupRef.from(a)))
.copyWithEquivalents(ImmutableSet.of(LookupRef.from(a)));
lookupStore.store(aEntry);
lookupStore.store(bEntry);
}
private Episode episode(String uri, Brand container, Location... locations) {
Episode episode = new Episode();
episode.setCanonicalUri(uri);
episode.setContainer(container);
episode.setPublisher(container.getPublisher());
Version version = new Version();
Encoding encoding = new Encoding();
encoding.setAvailableAt(ImmutableSet.copyOf(locations));
version.setManifestedAs(ImmutableSet.of(encoding));
episode.setVersions(ImmutableSet.of(version));
return episode;
}
private Location location(String uri, DateTime start, DateTime end) {
Location location = new Location();
location.setUri(uri);
Policy policy = new Policy();
policy.setAvailabilityStart(start);
policy.setAvailabilityEnd(end);
location.setPolicy(policy);
return location;
}
private DateTime dateTime(int millis) {
return new DateTime(millis,DateTimeZones.UTC);
}
}
| true | true | public void testResolvesChildrenOfEquivalentBrandsAsTheItemsOfThePrimaryBrand() {
Brand primary = new Brand("primary", "primary", Publisher.BBC);
Brand equivalent = new Brand("equivalent", "equivalent", Publisher.PA);
Episode p1 = episode("p1", primary, location("p1l1", dateTime(0), dateTime(10)));
Episode p2 = episode("p2", primary);
Episode e1 = episode("e1", equivalent, location("e1l1", dateTime(0), dateTime(10)));
Episode e2 = episode("e2", equivalent, location("e2l2", dateTime(0), dateTime(10)));
writer.createOrUpdate(primary);
writer.createOrUpdate(equivalent);
writer.createOrUpdate(p1);
writer.createOrUpdate(p2);
writer.createOrUpdate(e1);
writer.createOrUpdate(e2);
writeEquivalences(p1, e1);
writeEquivalences(p2, e2);
primary.setEquivalentTo(ImmutableSet.of(LookupRef.from(equivalent)));
clock.jumpTo(dateTime(5));
ApplicationConfiguration noPaConfig = ApplicationConfiguration.defaultConfiguration();
Set<ChildRef> childRefs = ImmutableSet.copyOf(resolver.availableItemsFor(primary, noPaConfig));
ChildRef childRef = Iterables.getOnlyElement(childRefs);
assertEquals(p1.getCanonicalUri(), childRef.getUri());
ApplicationConfiguration withPaConfig = ApplicationConfiguration.defaultConfiguration()
.enable(Publisher.PA);
childRefs = ImmutableSet.copyOf(resolver.availableItemsFor(primary, withPaConfig));
assertThat(childRefs.size(), is(2));
assertThat(Iterables.transform(childRefs, ChildRef.TO_URI), hasItems(p1.getCanonicalUri(), p2.getCanonicalUri()));
}
| public void testResolvesChildrenOfEquivalentBrandsAsTheItemsOfThePrimaryBrand() {
Brand primary = new Brand("primary", "primary", Publisher.BBC);
Brand equivalent = new Brand("equivalent", "equivalent", Publisher.PA);
Episode p1 = episode("p1", primary, location("p1l1", dateTime(0), dateTime(10)));
Episode p2 = episode("p2", primary);
Episode e1 = episode("e1", equivalent, location("e1l1", dateTime(0), dateTime(10)));
Episode e2 = episode("e2", equivalent, location("e2l2", dateTime(0), dateTime(10)));
writer.createOrUpdate(primary);
writer.createOrUpdate(equivalent);
writer.createOrUpdate(p1);
writer.createOrUpdate(p2);
writer.createOrUpdate(e1);
writer.createOrUpdate(e2);
writeEquivalences(p1, e1);
writeEquivalences(p2, e2);
primary.setEquivalentTo(ImmutableSet.of(LookupRef.from(equivalent)));
clock.jumpTo(dateTime(5));
ApplicationConfiguration noPaConfig = ApplicationConfiguration.defaultConfiguration();
Set<ChildRef> childRefs = ImmutableSet.copyOf(resolver.availableItemsFor(primary, noPaConfig));
ChildRef childRef = Iterables.getOnlyElement(childRefs);
assertEquals(p1.getCanonicalUri(), childRef.getUri());
ApplicationConfiguration withPaConfig = ApplicationConfiguration.defaultConfiguration()
.agreeLicense(Publisher.PA)
.enable(Publisher.PA);
childRefs = ImmutableSet.copyOf(resolver.availableItemsFor(primary, withPaConfig));
assertThat(childRefs.size(), is(2));
assertThat(Iterables.transform(childRefs, ChildRef.TO_URI), hasItems(p1.getCanonicalUri(), p2.getCanonicalUri()));
}
|
diff --git a/src/org/coode/dlquery/ResultsList.java b/src/org/coode/dlquery/ResultsList.java
index 0b26794..df99c23 100644
--- a/src/org/coode/dlquery/ResultsList.java
+++ b/src/org/coode/dlquery/ResultsList.java
@@ -1,301 +1,301 @@
package org.coode.dlquery;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.swing.JComponent;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import org.protege.editor.core.ui.list.MList;
import org.protege.editor.core.ui.list.MListButton;
import org.protege.editor.owl.OWLEditorKit;
import org.protege.editor.owl.ui.OWLClassExpressionComparator;
import org.protege.editor.owl.ui.framelist.ExplainButton;
import org.protege.editor.owl.ui.renderer.LinkedObjectComponent;
import org.protege.editor.owl.ui.renderer.LinkedObjectComponentMediator;
import org.protege.editor.owl.ui.view.Copyable;
import org.semanticweb.owlapi.model.OWLClass;
import org.semanticweb.owlapi.model.OWLClassExpression;
import org.semanticweb.owlapi.model.OWLIndividual;
import org.semanticweb.owlapi.model.OWLNamedIndividual;
import org.semanticweb.owlapi.model.OWLObject;
import org.semanticweb.owlapi.reasoner.Node;
import org.semanticweb.owlapi.reasoner.OWLReasoner;
/**
* Author: Matthew Horridge<br>
* The University Of Manchester<br>
* Bio-Health Informatics Group<br>
* Date: 27-Feb-2007<br><br>
*/
public class ResultsList extends MList implements LinkedObjectComponent, Copyable {
/**
*
*/
private static final long serialVersionUID = 8184853513690586368L;
private OWLEditorKit owlEditorKit;
private boolean showSuperClasses;
private boolean showAncestorClasses;
private boolean showDescendantClasses;
private boolean showSubClasses;
private boolean showInstances;
private boolean showEquivalentClasses;
private LinkedObjectComponentMediator mediator;
private List<ChangeListener> copyListeners = new ArrayList<ChangeListener>();
public ResultsList(OWLEditorKit owlEditorKit) {
this.owlEditorKit = owlEditorKit;
setCellRenderer(new DLQueryListCellRenderer(owlEditorKit));
explainButton.add(new ExplainButton(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
}));
mediator = new LinkedObjectComponentMediator(owlEditorKit, this);
getSelectionModel().addListSelectionListener(new ListSelectionListener(){
public void valueChanged(ListSelectionEvent event) {
ChangeEvent ev = new ChangeEvent(ResultsList.this);
for (ChangeListener l : copyListeners){
l.stateChanged(ev);
}
}
});
}
public boolean isShowAncestorClasses() {
return showAncestorClasses;
}
public void setShowAncestorClasses(boolean showAncestorClasses) {
this.showAncestorClasses = showAncestorClasses;
}
public boolean isShowDescendantClasses() {
return showDescendantClasses;
}
public void setShowDescendantClasses(boolean showDescendantClasses) {
this.showDescendantClasses = showDescendantClasses;
}
public boolean isShowInstances() {
return showInstances;
}
public void setShowInstances(boolean showInstances) {
this.showInstances = showInstances;
}
public boolean isShowSubClasses() {
return showSubClasses;
}
public void setShowSubClasses(boolean showSubClasses) {
this.showSubClasses = showSubClasses;
}
public boolean isShowSuperClasses() {
return showSuperClasses;
}
public void setShowSuperClasses(boolean showSuperClasses) {
this.showSuperClasses = showSuperClasses;
}
public boolean isShowEquivalentClasses() {
return showEquivalentClasses;
}
public void setShowEquivalentClasses(boolean showEquivalentClasses) {
this.showEquivalentClasses = showEquivalentClasses;
}
private List<OWLClass> toSortedList(Set<OWLClass> clses) {
OWLClassExpressionComparator descriptionComparator = new OWLClassExpressionComparator(owlEditorKit.getModelManager());
List<OWLClass> list = new ArrayList<OWLClass>(clses);
Collections.sort(list, descriptionComparator);
return list;
}
public void setOWLClassExpression(OWLClassExpression description) {
List<Object> data = new ArrayList<Object>();
OWLReasoner reasoner = owlEditorKit.getModelManager().getReasoner();
if (showEquivalentClasses) {
final List<OWLClass> results = toSortedList(reasoner.getEquivalentClasses(description).getEntities());
data.add(new DLQueryResultsSection("Equivalent classes (" + results.size() + ")"));
for (OWLClass cls : results) {
data.add(new DLQueryResultsSectionItem(cls));
}
}
if (showAncestorClasses) {
final List<OWLClass> results = toSortedList(reasoner.getSuperClasses(description, false).getFlattened());
data.add(new DLQueryResultsSection("Ancestor classes (" + results.size() + ")"));
for (OWLClass superClass : results) {
data.add(new DLQueryResultsSectionItem(superClass));
}
}
if (showSuperClasses) {
final List<OWLClass> results = toSortedList(reasoner.getSuperClasses(description, true).getFlattened());
data.add(new DLQueryResultsSection("Super classes (" + results.size() + ")"));
for (OWLClass superClass : results) {
data.add(new DLQueryResultsSectionItem(superClass));
}
}
if (showSubClasses) {
// flatten and filter out owl:Nothing
OWLClass owlNothing = owlEditorKit.getOWLModelManager().getOWLDataFactory().getOWLNothing();
final Set<OWLClass> resultSet = new HashSet<OWLClass>();
for (Node<OWLClass> clsSet : reasoner.getSubClasses(description, true)){
if (!clsSet.contains(owlNothing)){
resultSet.addAll(clsSet.getEntities());
}
}
final List<OWLClass> results = toSortedList(resultSet);
data.add(new DLQueryResultsSection("Sub classes (" + results.size() + ")"));
for (OWLClass subClass : results) {
data.add(new DLQueryResultsSectionItem(subClass));
}
}
if (showDescendantClasses) {
// flatten and filter out owl:Nothing
OWLClass owlNothing = owlEditorKit.getOWLModelManager().getOWLDataFactory().getOWLNothing();
final Set<OWLClass> resultSet = new HashSet<OWLClass>();
for (Node<OWLClass> clsSet : reasoner.getSubClasses(description, false)){
if (!clsSet.contains(owlNothing)){
resultSet.addAll(clsSet.getEntities());
}
}
final List<OWLClass> results = toSortedList(resultSet);
data.add(new DLQueryResultsSection("Descendant classes (" + results.size() + ")"));
for (OWLClass cls : results) {
data.add(new DLQueryResultsSectionItem(cls));
}
}
if (showInstances) {
- final Set<OWLNamedIndividual> results = reasoner.getInstances(description, true).getFlattened();
+ final Set<OWLNamedIndividual> results = reasoner.getInstances(description, false).getFlattened();
data.add(new DLQueryResultsSection("Instances (" + results.size() + ")"));
for (OWLIndividual ind : results) {
data.add(new DLQueryResultsSectionItem(ind));
}
}
setListData(data.toArray());
}
private List<MListButton> explainButton = new ArrayList<MListButton>();
protected List<MListButton> getButtons(Object value) {
if (value instanceof DLQueryResultsSectionItem) {
return explainButton;
}
else {
return Collections.emptyList();
}
}
public JComponent getComponent() {
return this;
}
public OWLObject getLinkedObject() {
return mediator.getLinkedObject();
}
public Point getMouseCellLocation() {
Rectangle r = getMouseCellRect();
if (r == null) {
return null;
}
Point mousePos = getMousePosition();
if (mousePos == null) {
return null;
}
return new Point(mousePos.x - r.x, mousePos.y - r.y);
}
public Rectangle getMouseCellRect() {
Point mousePos = getMousePosition();
if (mousePos == null) {
return null;
}
int sel = locationToIndex(mousePos);
if (sel == -1) {
return null;
}
return getCellBounds(sel, sel);
}
public void setLinkedObject(OWLObject object) {
mediator.setLinkedObject(object);
}
public boolean canCopy() {
return getSelectedIndices().length > 0;
}
public List<OWLObject> getObjectsToCopy() {
List<OWLObject> copyObjects = new ArrayList<OWLObject>();
for (Object sel : getSelectedValues()){
if (sel instanceof DLQueryResultsSectionItem){
copyObjects.add(((DLQueryResultsSectionItem)sel).getOWLObject());
}
}
return copyObjects;
}
public void addChangeListener(ChangeListener changeListener) {
copyListeners.add(changeListener);
}
public void removeChangeListener(ChangeListener changeListener) {
copyListeners.remove(changeListener);
}
}
| true | true | public void setOWLClassExpression(OWLClassExpression description) {
List<Object> data = new ArrayList<Object>();
OWLReasoner reasoner = owlEditorKit.getModelManager().getReasoner();
if (showEquivalentClasses) {
final List<OWLClass> results = toSortedList(reasoner.getEquivalentClasses(description).getEntities());
data.add(new DLQueryResultsSection("Equivalent classes (" + results.size() + ")"));
for (OWLClass cls : results) {
data.add(new DLQueryResultsSectionItem(cls));
}
}
if (showAncestorClasses) {
final List<OWLClass> results = toSortedList(reasoner.getSuperClasses(description, false).getFlattened());
data.add(new DLQueryResultsSection("Ancestor classes (" + results.size() + ")"));
for (OWLClass superClass : results) {
data.add(new DLQueryResultsSectionItem(superClass));
}
}
if (showSuperClasses) {
final List<OWLClass> results = toSortedList(reasoner.getSuperClasses(description, true).getFlattened());
data.add(new DLQueryResultsSection("Super classes (" + results.size() + ")"));
for (OWLClass superClass : results) {
data.add(new DLQueryResultsSectionItem(superClass));
}
}
if (showSubClasses) {
// flatten and filter out owl:Nothing
OWLClass owlNothing = owlEditorKit.getOWLModelManager().getOWLDataFactory().getOWLNothing();
final Set<OWLClass> resultSet = new HashSet<OWLClass>();
for (Node<OWLClass> clsSet : reasoner.getSubClasses(description, true)){
if (!clsSet.contains(owlNothing)){
resultSet.addAll(clsSet.getEntities());
}
}
final List<OWLClass> results = toSortedList(resultSet);
data.add(new DLQueryResultsSection("Sub classes (" + results.size() + ")"));
for (OWLClass subClass : results) {
data.add(new DLQueryResultsSectionItem(subClass));
}
}
if (showDescendantClasses) {
// flatten and filter out owl:Nothing
OWLClass owlNothing = owlEditorKit.getOWLModelManager().getOWLDataFactory().getOWLNothing();
final Set<OWLClass> resultSet = new HashSet<OWLClass>();
for (Node<OWLClass> clsSet : reasoner.getSubClasses(description, false)){
if (!clsSet.contains(owlNothing)){
resultSet.addAll(clsSet.getEntities());
}
}
final List<OWLClass> results = toSortedList(resultSet);
data.add(new DLQueryResultsSection("Descendant classes (" + results.size() + ")"));
for (OWLClass cls : results) {
data.add(new DLQueryResultsSectionItem(cls));
}
}
if (showInstances) {
final Set<OWLNamedIndividual> results = reasoner.getInstances(description, true).getFlattened();
data.add(new DLQueryResultsSection("Instances (" + results.size() + ")"));
for (OWLIndividual ind : results) {
data.add(new DLQueryResultsSectionItem(ind));
}
}
setListData(data.toArray());
}
| public void setOWLClassExpression(OWLClassExpression description) {
List<Object> data = new ArrayList<Object>();
OWLReasoner reasoner = owlEditorKit.getModelManager().getReasoner();
if (showEquivalentClasses) {
final List<OWLClass> results = toSortedList(reasoner.getEquivalentClasses(description).getEntities());
data.add(new DLQueryResultsSection("Equivalent classes (" + results.size() + ")"));
for (OWLClass cls : results) {
data.add(new DLQueryResultsSectionItem(cls));
}
}
if (showAncestorClasses) {
final List<OWLClass> results = toSortedList(reasoner.getSuperClasses(description, false).getFlattened());
data.add(new DLQueryResultsSection("Ancestor classes (" + results.size() + ")"));
for (OWLClass superClass : results) {
data.add(new DLQueryResultsSectionItem(superClass));
}
}
if (showSuperClasses) {
final List<OWLClass> results = toSortedList(reasoner.getSuperClasses(description, true).getFlattened());
data.add(new DLQueryResultsSection("Super classes (" + results.size() + ")"));
for (OWLClass superClass : results) {
data.add(new DLQueryResultsSectionItem(superClass));
}
}
if (showSubClasses) {
// flatten and filter out owl:Nothing
OWLClass owlNothing = owlEditorKit.getOWLModelManager().getOWLDataFactory().getOWLNothing();
final Set<OWLClass> resultSet = new HashSet<OWLClass>();
for (Node<OWLClass> clsSet : reasoner.getSubClasses(description, true)){
if (!clsSet.contains(owlNothing)){
resultSet.addAll(clsSet.getEntities());
}
}
final List<OWLClass> results = toSortedList(resultSet);
data.add(new DLQueryResultsSection("Sub classes (" + results.size() + ")"));
for (OWLClass subClass : results) {
data.add(new DLQueryResultsSectionItem(subClass));
}
}
if (showDescendantClasses) {
// flatten and filter out owl:Nothing
OWLClass owlNothing = owlEditorKit.getOWLModelManager().getOWLDataFactory().getOWLNothing();
final Set<OWLClass> resultSet = new HashSet<OWLClass>();
for (Node<OWLClass> clsSet : reasoner.getSubClasses(description, false)){
if (!clsSet.contains(owlNothing)){
resultSet.addAll(clsSet.getEntities());
}
}
final List<OWLClass> results = toSortedList(resultSet);
data.add(new DLQueryResultsSection("Descendant classes (" + results.size() + ")"));
for (OWLClass cls : results) {
data.add(new DLQueryResultsSectionItem(cls));
}
}
if (showInstances) {
final Set<OWLNamedIndividual> results = reasoner.getInstances(description, false).getFlattened();
data.add(new DLQueryResultsSection("Instances (" + results.size() + ")"));
for (OWLIndividual ind : results) {
data.add(new DLQueryResultsSectionItem(ind));
}
}
setListData(data.toArray());
}
|
diff --git a/src/main/java/com/hackeurope/feedspeak/ConcreteDBConnector.java b/src/main/java/com/hackeurope/feedspeak/ConcreteDBConnector.java
index aa4fa35..d5c57a4 100644
--- a/src/main/java/com/hackeurope/feedspeak/ConcreteDBConnector.java
+++ b/src/main/java/com/hackeurope/feedspeak/ConcreteDBConnector.java
@@ -1,125 +1,125 @@
package com.hackeurope.feedspeak;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Calum
*/
public class ConcreteDBConnector extends DatabaseConnector {
public void addUser(User newUser, boolean twitter, boolean bbc)
{
try {
Connection connection = getConnection();
String insertUsersString = "INSERT INTO "
+ "users (phone_number,name, oauth_token, oauth_token_secret) VALUES (?, ?, ?, ?);";
PreparedStatement prepUserStatement = connection.prepareStatement(insertUsersString, Statement.RETURN_GENERATED_KEYS);
prepUserStatement.setString(1, newUser.getPhoneNumber());
prepUserStatement.setString(2, newUser.getName());
prepUserStatement.setString(3, newUser.getOauthToken());
prepUserStatement.setString(4, newUser.getOauthTokenSecret());
prepUserStatement.executeUpdate();
int userID = Integer.MAX_VALUE;
ResultSet generatedKeys = prepUserStatement.getGeneratedKeys();
while (generatedKeys.next())
{
userID = generatedKeys.getInt(1);
}
//Insert user's sources
if (twitter)
{
String insertLinkString = "INSERT INTO user_sources (user_id, source_id) VALUES (?, ?);";
PreparedStatement prepLinkStatement = connection.prepareStatement(insertLinkString);
prepLinkStatement.setInt(1, userID);
- prepLinkStatement.setInt(2, 0);//Twitter
+ prepLinkStatement.setInt(2, 1);//Twitter
prepLinkStatement.executeUpdate();
}
if (bbc)
{
String insertLinkString = "INSERT INTO user_sources (user_id, source_id) VALUES (?, ?);";
PreparedStatement prepLinkStatement = connection.prepareStatement(insertLinkString);
prepLinkStatement.setInt(1, userID);
- prepLinkStatement.setInt(2, 1);//BBC
+ prepLinkStatement.setInt(2, 2);//BBC
prepLinkStatement.executeUpdate();
}
closeConnection();
} catch (SQLException ex) {
Logger.getLogger(ConcreteDBConnector.class.getName()).log(Level.SEVERE, null, ex);
}
}
public User getUserByPhoneNumber(String phoneNumber)
{
User newUser = new User();
try {
Connection connection = getConnection();
String selectString = "SELECT * FROM users WHERE phone_number = ?;";
PreparedStatement prepStatement = connection.prepareStatement(selectString);
prepStatement.setString(1, phoneNumber);
ResultSet resultSet = prepStatement.executeQuery();
while (resultSet.next())
{
newUser.setId(resultSet.getInt("id"));
newUser.setPhoneNumber(resultSet.getString("phone_number"));
newUser.setName(resultSet.getString("name"));
newUser.setOauthToken(resultSet.getString("oauth_token"));
newUser.setOauthTokenSecret(resultSet.getString("oauth_token_secret"));
}
closeConnection();
} catch (SQLException ex) {
Logger.getLogger(ConcreteDBConnector.class.getName()).log(Level.SEVERE, null, ex);
return null;
}
return newUser;
}
public List<String> getUsersSources(User user)
{
ArrayList<String> sources = new ArrayList<String>();
try {
Connection connection = getConnection();
String selectString = "SELECT * FROM users "
+ "JOIN user_sources ON users.user_id = user_sources.user_id "
+ "JOIN sources ON user_sources.source_id = sources.source_id "
+ "WHERE users.user_id = ?;";
PreparedStatement prepStatement = connection.prepareStatement(selectString);
prepStatement.setInt(1, user.getId());
ResultSet resultSet = prepStatement.executeQuery();
while (resultSet.next())
{
sources.add(resultSet.getString("source_name"));
}
closeConnection();
} catch (SQLException ex) {
Logger.getLogger(ConcreteDBConnector.class.getName()).log(Level.SEVERE, null, ex);
return null;
}
return sources;
}
}
| false | true | public void addUser(User newUser, boolean twitter, boolean bbc)
{
try {
Connection connection = getConnection();
String insertUsersString = "INSERT INTO "
+ "users (phone_number,name, oauth_token, oauth_token_secret) VALUES (?, ?, ?, ?);";
PreparedStatement prepUserStatement = connection.prepareStatement(insertUsersString, Statement.RETURN_GENERATED_KEYS);
prepUserStatement.setString(1, newUser.getPhoneNumber());
prepUserStatement.setString(2, newUser.getName());
prepUserStatement.setString(3, newUser.getOauthToken());
prepUserStatement.setString(4, newUser.getOauthTokenSecret());
prepUserStatement.executeUpdate();
int userID = Integer.MAX_VALUE;
ResultSet generatedKeys = prepUserStatement.getGeneratedKeys();
while (generatedKeys.next())
{
userID = generatedKeys.getInt(1);
}
//Insert user's sources
if (twitter)
{
String insertLinkString = "INSERT INTO user_sources (user_id, source_id) VALUES (?, ?);";
PreparedStatement prepLinkStatement = connection.prepareStatement(insertLinkString);
prepLinkStatement.setInt(1, userID);
prepLinkStatement.setInt(2, 0);//Twitter
prepLinkStatement.executeUpdate();
}
if (bbc)
{
String insertLinkString = "INSERT INTO user_sources (user_id, source_id) VALUES (?, ?);";
PreparedStatement prepLinkStatement = connection.prepareStatement(insertLinkString);
prepLinkStatement.setInt(1, userID);
prepLinkStatement.setInt(2, 1);//BBC
prepLinkStatement.executeUpdate();
}
closeConnection();
} catch (SQLException ex) {
Logger.getLogger(ConcreteDBConnector.class.getName()).log(Level.SEVERE, null, ex);
}
}
| public void addUser(User newUser, boolean twitter, boolean bbc)
{
try {
Connection connection = getConnection();
String insertUsersString = "INSERT INTO "
+ "users (phone_number,name, oauth_token, oauth_token_secret) VALUES (?, ?, ?, ?);";
PreparedStatement prepUserStatement = connection.prepareStatement(insertUsersString, Statement.RETURN_GENERATED_KEYS);
prepUserStatement.setString(1, newUser.getPhoneNumber());
prepUserStatement.setString(2, newUser.getName());
prepUserStatement.setString(3, newUser.getOauthToken());
prepUserStatement.setString(4, newUser.getOauthTokenSecret());
prepUserStatement.executeUpdate();
int userID = Integer.MAX_VALUE;
ResultSet generatedKeys = prepUserStatement.getGeneratedKeys();
while (generatedKeys.next())
{
userID = generatedKeys.getInt(1);
}
//Insert user's sources
if (twitter)
{
String insertLinkString = "INSERT INTO user_sources (user_id, source_id) VALUES (?, ?);";
PreparedStatement prepLinkStatement = connection.prepareStatement(insertLinkString);
prepLinkStatement.setInt(1, userID);
prepLinkStatement.setInt(2, 1);//Twitter
prepLinkStatement.executeUpdate();
}
if (bbc)
{
String insertLinkString = "INSERT INTO user_sources (user_id, source_id) VALUES (?, ?);";
PreparedStatement prepLinkStatement = connection.prepareStatement(insertLinkString);
prepLinkStatement.setInt(1, userID);
prepLinkStatement.setInt(2, 2);//BBC
prepLinkStatement.executeUpdate();
}
closeConnection();
} catch (SQLException ex) {
Logger.getLogger(ConcreteDBConnector.class.getName()).log(Level.SEVERE, null, ex);
}
}
|
diff --git a/api/src/main/java/org/openmrs/module/chartsearch/GeneratingJson.java b/api/src/main/java/org/openmrs/module/chartsearch/GeneratingJson.java
index 0e48587..39a2345 100644
--- a/api/src/main/java/org/openmrs/module/chartsearch/GeneratingJson.java
+++ b/api/src/main/java/org/openmrs/module/chartsearch/GeneratingJson.java
@@ -1,247 +1,247 @@
package org.openmrs.module.chartsearch;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.openmrs.*;
import org.openmrs.api.context.Context;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Created by Eli on 16/03/14.
*/
public class GeneratingJson {
public static String generateJson() {
JSONObject jsonToReturn = new JSONObject(); //returning this object
JSONArray arr_of_groups = new JSONArray();
Set<Set<Obs>> setOfObsGroups = generateObsGroupFromSearchResults();
for (Set<Obs> obsGrpSet : setOfObsGroups) { //for each obs group we go through it's obs
JSONArray arr_of_obs = new JSONArray(); //array of all the obs in a given obs group
JSONObject jsonObs = null;
JSONObject jsonGrp = new JSONObject();
for (Obs obs : obsGrpSet) { //for each obs in a group we create the single obs and add it to the obs array
if (obs != null) {
jsonObs = createJsonObservation(obs);
}
arr_of_obs.add(jsonObs);
}
int obsGrpId = -1; //init the obs grp id to -1, if there is a grp in
if (obsGrpSet.iterator().hasNext()) { //check inside of group an individual obs, if available, what its grp id
Obs obsFromObsGrp = obsGrpSet.iterator().next();
Obs obsGrp = obsFromObsGrp.getObsGroup();
obsGrpId = obsGrp.getObsId();
jsonGrp.put("group_Id", obsGrpId);
jsonGrp.put("group_name", obsGrp.getConcept().getDisplayString());
Date obsDate = obsGrp.getObsDatetime() == null ? new Date() : obsGrp.getObsDatetime();
- SimpleDateFormat formatDateJava = new SimpleDateFormat("dd/MM/yyyy");
+ SimpleDateFormat formatDateJava = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
String obsDateStr = formatDateJava.format(obsDate);
jsonGrp.put("last_taken_date", obsDateStr);
jsonGrp.put("observations", arr_of_obs);
arr_of_groups.add(jsonGrp);
}
}
jsonToReturn.put("obs_groups", arr_of_groups); //add the obs groups array to the json
JSONObject jsonObs = null;
JSONArray arr_of_obs = new JSONArray();
for (Obs obsSingle : generateObsSinglesFromSearchResults()) {
if (obsSingle != null) {
jsonObs = createJsonObservation(obsSingle);
}
arr_of_obs.add(jsonObs);
}
jsonToReturn.put("obs_singles", arr_of_obs);
JSONObject jsonForms = null;
JSONArray arr_of_forms = new JSONArray();
for (Form form : generateFormsFromSearchResults()) {
if (form != null) {
jsonForms = createJsonForm(form);
}
arr_of_forms.add(jsonForms);
}
jsonToReturn.put("froms", arr_of_forms);
JSONObject jsonEncounters = null;
JSONArray arr_of_encounterss = new JSONArray();
for (Encounter encounter : generateEncountersFromSearchResults()) {
if (encounter != null) {
jsonEncounters = createJsonEncounter(encounter);
}
arr_of_forms.add(jsonEncounters);
}
jsonToReturn.put("encounters", arr_of_encounterss);
String searchPhrase = SearchAPI.getInstance().getSearchPhrase().getPhrase();
jsonToReturn.put("search_phrase", searchPhrase);
return jsonToReturn.toString();
}
private static JSONObject createJsonObservation(Obs obs) {
JSONObject jsonObs = new JSONObject();
jsonObs.put("observation_id", obs.getObsId());
jsonObs.put("concept_name", obs.getConcept().getDisplayString());
Date obsDate = obs.getDateCreated() == null ? new Date() : obs.getDateCreated();
SimpleDateFormat formatDateJava = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
String dateStr = formatDateJava.format(obsDate);
jsonObs.put("date", dateStr);
if (obs.getConcept().getDatatype().isNumeric()) { // ADD MORE DATATYPES
jsonObs.put("value_type", obs.getConcept().getDatatype().getName());
ConceptNumeric conceptNumeric = Context.getConceptService().getConceptNumeric(obs.getConcept().getId());
jsonObs.put("units_of_measurement", conceptNumeric.getUnits());
jsonObs.put("absolute_high", conceptNumeric.getHiAbsolute());
jsonObs.put("absolute_low", conceptNumeric.getLowAbsolute());
jsonObs.put("critical_high", conceptNumeric.getHiCritical());
jsonObs.put("critical_low", conceptNumeric.getLowCritical());
jsonObs.put("normal_high", conceptNumeric.getHiNormal());
jsonObs.put("normal_low", conceptNumeric.getLowNormal());
}
else jsonObs.put("value_type", obs.getConcept().getDatatype().getName());
jsonObs.put("value", obs.getValueAsString(Context.getLocale()));
jsonObs.put("location", obs.getLocation().getDisplayString());
return jsonObs;
}
private static JSONObject createJsonForm(Form form) {
JSONObject jsonForm = new JSONObject();
jsonForm.put("form_id", form.getFormId());
Date formDate = form.getDateCreated() == null ? new Date() : form.getDateCreated();
SimpleDateFormat formatDateJava = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
String dateStr = formatDateJava.format(formDate);
jsonForm.put("date", dateStr);
jsonForm.put("encounter_type", form.getEncounterType().getName());
jsonForm.put("creator",form.getCreator().getName());
formDate = form.getDateChanged() == null ? new Date() : form.getDateChanged();
dateStr = formatDateJava.format(formDate);
jsonForm.put("last_changed_date",dateStr);
jsonForm.put("last_changed_by", form.getChangedBy().getName());
/* for(FormField formField : form.getOrderedFormFields()){
jsonForm.put(formField.getName(),formField.getDescription());
}*/
return jsonForm;
}
private static JSONObject createJsonEncounter(Encounter encounter) {
JSONObject jsonEncounter = new JSONObject();
jsonEncounter.put("encounter_id", encounter.getEncounterId());
return jsonEncounter;
}
public static Set<Set<Obs>> generateObsGroupFromSearchResults() {
Set<Set<Obs>> obsGroups = new HashSet<Set<Obs>>();
SearchAPI searchAPI = SearchAPI.getInstance();
List<ChartListItem> searchResultsList = searchAPI.getResults();
for (ChartListItem item : searchResultsList) { //for each item in results we classify it by its obsGroup, and add all of the group.
if (item != null && item instanceof ObsItem && ((ObsItem) item).getObsId() != null) {
int itemObsId = ((ObsItem) item).getObsId();
Obs obsGrp = Context.getObsService().getObs(itemObsId).getObsGroup();
if (obsGrp != null) {
int groupId = obsGrp.getId();
Set<Obs> obsGroup = obsGrp.getGroupMembers();
boolean found = false; //if found == ture then we don't need to add the group.
for (Set<Obs> grp : obsGroups) {
Obs ob = new Obs(-1);
if (grp.iterator().hasNext()) {
ob = grp.iterator().next();
}
if (ob.getObsGroup() != null && ob.getObsGroup().getId() != null) {
if (ob.getObsGroup().getId() == groupId) {
found = true;
}
}
}
if (!found) {
obsGroups.add(obsGroup);
}
}
}
}
return obsGroups;
}
public static Set<Obs> generateObsSinglesFromSearchResults() {
SearchAPI searchAPI = SearchAPI.getInstance();
Set<Obs> obsSingles = new HashSet<Obs>();
for (ChartListItem item : searchAPI.getResults()) {
if (item != null && item instanceof ObsItem && ((ObsItem) item).getObsId() != null) {
int itemObsId = ((ObsItem) item).getObsId();
Obs obs = Context.getObsService().getObs(itemObsId);
if (obs != null && obs.getObsGroup() == null && !obs.isObsGrouping()) {
obsSingles.add(Context.getObsService().getObs(itemObsId));
}
}
}
return obsSingles;
}
public static Set<Form> generateFormsFromSearchResults() {
SearchAPI searchAPI = SearchAPI.getInstance();
Set<Form> forms = new HashSet<Form>();
for (ChartListItem item : searchAPI.getResults()) {
if (item != null && item instanceof FormItem && ((FormItem) item).getFormId() != null) {
int itemFormId = ((FormItem) item).getFormId();
Form form = Context.getFormService().getForm(itemFormId);
if (form != null) {
forms.add(Context.getFormService().getForm(itemFormId));
}
}
}
return forms;
}
public static Set<Encounter> generateEncountersFromSearchResults() {
SearchAPI searchAPI = SearchAPI.getInstance();
Set<Encounter> encounters = new HashSet<Encounter>();
for (ChartListItem item : searchAPI.getResults()) {
if (item != null && item instanceof EncounterItem && ((EncounterItem) item).getEncounterId() != null) {
int itemEncounterId = ((EncounterItem) item).getEncounterId();
Encounter encounter = Context.getEncounterService().getEncounter(itemEncounterId);
if (encounter != null) {
encounters.add(Context.getEncounterService().getEncounter(itemEncounterId));
}
}
}
return encounters;
}
}
| true | true | public static String generateJson() {
JSONObject jsonToReturn = new JSONObject(); //returning this object
JSONArray arr_of_groups = new JSONArray();
Set<Set<Obs>> setOfObsGroups = generateObsGroupFromSearchResults();
for (Set<Obs> obsGrpSet : setOfObsGroups) { //for each obs group we go through it's obs
JSONArray arr_of_obs = new JSONArray(); //array of all the obs in a given obs group
JSONObject jsonObs = null;
JSONObject jsonGrp = new JSONObject();
for (Obs obs : obsGrpSet) { //for each obs in a group we create the single obs and add it to the obs array
if (obs != null) {
jsonObs = createJsonObservation(obs);
}
arr_of_obs.add(jsonObs);
}
int obsGrpId = -1; //init the obs grp id to -1, if there is a grp in
if (obsGrpSet.iterator().hasNext()) { //check inside of group an individual obs, if available, what its grp id
Obs obsFromObsGrp = obsGrpSet.iterator().next();
Obs obsGrp = obsFromObsGrp.getObsGroup();
obsGrpId = obsGrp.getObsId();
jsonGrp.put("group_Id", obsGrpId);
jsonGrp.put("group_name", obsGrp.getConcept().getDisplayString());
Date obsDate = obsGrp.getObsDatetime() == null ? new Date() : obsGrp.getObsDatetime();
SimpleDateFormat formatDateJava = new SimpleDateFormat("dd/MM/yyyy");
String obsDateStr = formatDateJava.format(obsDate);
jsonGrp.put("last_taken_date", obsDateStr);
jsonGrp.put("observations", arr_of_obs);
arr_of_groups.add(jsonGrp);
}
}
jsonToReturn.put("obs_groups", arr_of_groups); //add the obs groups array to the json
JSONObject jsonObs = null;
JSONArray arr_of_obs = new JSONArray();
for (Obs obsSingle : generateObsSinglesFromSearchResults()) {
if (obsSingle != null) {
jsonObs = createJsonObservation(obsSingle);
}
arr_of_obs.add(jsonObs);
}
jsonToReturn.put("obs_singles", arr_of_obs);
JSONObject jsonForms = null;
JSONArray arr_of_forms = new JSONArray();
for (Form form : generateFormsFromSearchResults()) {
if (form != null) {
jsonForms = createJsonForm(form);
}
arr_of_forms.add(jsonForms);
}
jsonToReturn.put("froms", arr_of_forms);
JSONObject jsonEncounters = null;
JSONArray arr_of_encounterss = new JSONArray();
for (Encounter encounter : generateEncountersFromSearchResults()) {
if (encounter != null) {
jsonEncounters = createJsonEncounter(encounter);
}
arr_of_forms.add(jsonEncounters);
}
jsonToReturn.put("encounters", arr_of_encounterss);
String searchPhrase = SearchAPI.getInstance().getSearchPhrase().getPhrase();
jsonToReturn.put("search_phrase", searchPhrase);
return jsonToReturn.toString();
}
| public static String generateJson() {
JSONObject jsonToReturn = new JSONObject(); //returning this object
JSONArray arr_of_groups = new JSONArray();
Set<Set<Obs>> setOfObsGroups = generateObsGroupFromSearchResults();
for (Set<Obs> obsGrpSet : setOfObsGroups) { //for each obs group we go through it's obs
JSONArray arr_of_obs = new JSONArray(); //array of all the obs in a given obs group
JSONObject jsonObs = null;
JSONObject jsonGrp = new JSONObject();
for (Obs obs : obsGrpSet) { //for each obs in a group we create the single obs and add it to the obs array
if (obs != null) {
jsonObs = createJsonObservation(obs);
}
arr_of_obs.add(jsonObs);
}
int obsGrpId = -1; //init the obs grp id to -1, if there is a grp in
if (obsGrpSet.iterator().hasNext()) { //check inside of group an individual obs, if available, what its grp id
Obs obsFromObsGrp = obsGrpSet.iterator().next();
Obs obsGrp = obsFromObsGrp.getObsGroup();
obsGrpId = obsGrp.getObsId();
jsonGrp.put("group_Id", obsGrpId);
jsonGrp.put("group_name", obsGrp.getConcept().getDisplayString());
Date obsDate = obsGrp.getObsDatetime() == null ? new Date() : obsGrp.getObsDatetime();
SimpleDateFormat formatDateJava = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
String obsDateStr = formatDateJava.format(obsDate);
jsonGrp.put("last_taken_date", obsDateStr);
jsonGrp.put("observations", arr_of_obs);
arr_of_groups.add(jsonGrp);
}
}
jsonToReturn.put("obs_groups", arr_of_groups); //add the obs groups array to the json
JSONObject jsonObs = null;
JSONArray arr_of_obs = new JSONArray();
for (Obs obsSingle : generateObsSinglesFromSearchResults()) {
if (obsSingle != null) {
jsonObs = createJsonObservation(obsSingle);
}
arr_of_obs.add(jsonObs);
}
jsonToReturn.put("obs_singles", arr_of_obs);
JSONObject jsonForms = null;
JSONArray arr_of_forms = new JSONArray();
for (Form form : generateFormsFromSearchResults()) {
if (form != null) {
jsonForms = createJsonForm(form);
}
arr_of_forms.add(jsonForms);
}
jsonToReturn.put("froms", arr_of_forms);
JSONObject jsonEncounters = null;
JSONArray arr_of_encounterss = new JSONArray();
for (Encounter encounter : generateEncountersFromSearchResults()) {
if (encounter != null) {
jsonEncounters = createJsonEncounter(encounter);
}
arr_of_forms.add(jsonEncounters);
}
jsonToReturn.put("encounters", arr_of_encounterss);
String searchPhrase = SearchAPI.getInstance().getSearchPhrase().getPhrase();
jsonToReturn.put("search_phrase", searchPhrase);
return jsonToReturn.toString();
}
|
diff --git a/maven-scm-providers/maven-scm-providers-cvs/maven-scm-provider-cvsexe/src/main/java/org/apache/maven/scm/provider/cvslib/cvsexe/command/changelog/CvsExeChangeLogCommand.java b/maven-scm-providers/maven-scm-providers-cvs/maven-scm-provider-cvsexe/src/main/java/org/apache/maven/scm/provider/cvslib/cvsexe/command/changelog/CvsExeChangeLogCommand.java
index 7d1b196a..5e0e2d67 100644
--- a/maven-scm-providers/maven-scm-providers-cvs/maven-scm-provider-cvsexe/src/main/java/org/apache/maven/scm/provider/cvslib/cvsexe/command/changelog/CvsExeChangeLogCommand.java
+++ b/maven-scm-providers/maven-scm-providers-cvs/maven-scm-provider-cvsexe/src/main/java/org/apache/maven/scm/provider/cvslib/cvsexe/command/changelog/CvsExeChangeLogCommand.java
@@ -1,71 +1,71 @@
package org.apache.maven.scm.provider.cvslib.cvsexe.command.changelog;
/*
* 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.
*/
import org.apache.maven.scm.ScmException;
import org.apache.maven.scm.ScmVersion;
import org.apache.maven.scm.command.changelog.ChangeLogScmResult;
import org.apache.maven.scm.command.changelog.ChangeLogSet;
import org.apache.maven.scm.provider.cvslib.command.changelog.AbstractCvsChangeLogCommand;
import org.apache.maven.scm.provider.cvslib.command.changelog.CvsChangeLogConsumer;
import org.codehaus.plexus.util.cli.CommandLineException;
import org.codehaus.plexus.util.cli.CommandLineUtils;
import org.codehaus.plexus.util.cli.Commandline;
import java.util.Date;
/**
* @author <a href="mailto:[email protected]">Emmanuel Venisse</a>
* @version $Id$
*/
public class CvsExeChangeLogCommand
extends AbstractCvsChangeLogCommand
{
- protected ChangeLogScmResult executeCvsCommand( Commandline cl, Date startDate, Date endDate, String datePattern,
- ScmVersion startVersion, ScmVersion endVersion )
+ protected ChangeLogScmResult executeCvsCommand( Commandline cl, Date startDate, Date endDate,
+ ScmVersion startVersion, ScmVersion endVersion, String datePattern )
throws ScmException
{
CvsChangeLogConsumer consumer = new CvsChangeLogConsumer( getLogger(), datePattern );
CommandLineUtils.StringStreamConsumer stderr = new CommandLineUtils.StringStreamConsumer();
int exitCode;
try
{
exitCode = CommandLineUtils.executeCommandLine( cl, consumer, stderr );
}
catch ( CommandLineException ex )
{
throw new ScmException( "Error while executing cvs command.", ex );
}
if ( exitCode != 0 )
{
return new ChangeLogScmResult( cl.toString(), "The cvs command failed.", stderr.getOutput(), false );
}
ChangeLogSet changeLogSet = new ChangeLogSet( consumer.getModifications(), startDate, endDate );
changeLogSet.setStartVersion( startVersion );
changeLogSet.setEndVersion( endVersion );
return new ChangeLogScmResult( cl.toString(), changeLogSet );
}
}
| true | true | protected ChangeLogScmResult executeCvsCommand( Commandline cl, Date startDate, Date endDate, String datePattern,
ScmVersion startVersion, ScmVersion endVersion )
throws ScmException
{
CvsChangeLogConsumer consumer = new CvsChangeLogConsumer( getLogger(), datePattern );
CommandLineUtils.StringStreamConsumer stderr = new CommandLineUtils.StringStreamConsumer();
int exitCode;
try
{
exitCode = CommandLineUtils.executeCommandLine( cl, consumer, stderr );
}
catch ( CommandLineException ex )
{
throw new ScmException( "Error while executing cvs command.", ex );
}
if ( exitCode != 0 )
{
return new ChangeLogScmResult( cl.toString(), "The cvs command failed.", stderr.getOutput(), false );
}
ChangeLogSet changeLogSet = new ChangeLogSet( consumer.getModifications(), startDate, endDate );
changeLogSet.setStartVersion( startVersion );
changeLogSet.setEndVersion( endVersion );
return new ChangeLogScmResult( cl.toString(), changeLogSet );
}
| protected ChangeLogScmResult executeCvsCommand( Commandline cl, Date startDate, Date endDate,
ScmVersion startVersion, ScmVersion endVersion, String datePattern )
throws ScmException
{
CvsChangeLogConsumer consumer = new CvsChangeLogConsumer( getLogger(), datePattern );
CommandLineUtils.StringStreamConsumer stderr = new CommandLineUtils.StringStreamConsumer();
int exitCode;
try
{
exitCode = CommandLineUtils.executeCommandLine( cl, consumer, stderr );
}
catch ( CommandLineException ex )
{
throw new ScmException( "Error while executing cvs command.", ex );
}
if ( exitCode != 0 )
{
return new ChangeLogScmResult( cl.toString(), "The cvs command failed.", stderr.getOutput(), false );
}
ChangeLogSet changeLogSet = new ChangeLogSet( consumer.getModifications(), startDate, endDate );
changeLogSet.setStartVersion( startVersion );
changeLogSet.setEndVersion( endVersion );
return new ChangeLogScmResult( cl.toString(), changeLogSet );
}
|
diff --git a/RecordIndexer/mccord/client/DownloadBatchGUI.java b/RecordIndexer/mccord/client/DownloadBatchGUI.java
index 0049f33..697f6d8 100644
--- a/RecordIndexer/mccord/client/DownloadBatchGUI.java
+++ b/RecordIndexer/mccord/client/DownloadBatchGUI.java
@@ -1,209 +1,209 @@
package client;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import models.FailedResult;
import models.Fields;
import server.ClientCommunicator;
import communicator.DownloadBatchParams;
import communicator.DownloadBatchResult;
import communicator.GetProjectsResult;
import communicator.ValidateUserParams;
public class DownloadBatchGUI {
private static final long serialVersionUID = 8227044344356048883L;
private ClientGUI cg;
private Integer projectId;
private ArrayList<GetProjectsResult> projects;
private JComboBox projectList;
private JDialog dbDialog;
public JDialog makeDownloadBatchGUI(){
JFrame frame = new JFrame("Download Batch");
this.dbDialog = new JDialog(frame, "Download Batch", true);
this.dbDialog.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
Dimension panelSize = new Dimension(400, 200);
this.dbDialog.setSize(panelSize);
this.dbDialog.setMinimumSize(panelSize);
this.dbDialog.setMaximumSize(panelSize);
Container pane = this.dbDialog.getContentPane();
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
pane.setLayout(new GridBagLayout());
JLabel label = new JLabel("Project: ");
c.weightx = 1;
c.gridx = 0;
c.gridy = 0;
label.setVisible(true);
pane.add(label, c);
projects = this.getProjects();
System.out.println(projects.size());
String[] names = new String[projects.size()];
for(int i = 0; i < projects.size(); i++){
names[i] = projects.get(i).getTitle();
}
projectList = new JComboBox(names);
projectId = -1;
projectList.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
if(projectList.getSelectedIndex() == -1){
// nothing selected
}else{
projectId = projects.get(projectList.getSelectedIndex()).getId();
System.out.println("projectid is now: " + projectId);
}
}
});
projectList.setSelectedIndex(0);// load initial thing
c.weightx = 1;
c.gridx = 1;
c.gridy = 0;
pane.add(projectList, c);
JButton viewSampleButton = new JButton("View Sample");
c.weightx = 1;
c.gridx = 2;
c.gridy = 0;
viewSampleButton.setVisible(true);
viewSampleButton.addMouseListener(new MouseListener(){
@Override
public void mouseClicked(MouseEvent e) {
SampleImage si = new SampleImage(cg);
JDialog dialog = si.makeSampleImage(projects.get(projectList.getSelectedIndex()).getTitle(), projectId);
dialog.setVisible(true);
}
@Override public void mousePressed(MouseEvent e) {}
@Override public void mouseReleased(MouseEvent e) {}
@Override public void mouseEntered(MouseEvent e) {}
@Override public void mouseExited(MouseEvent e) {}
});
pane.add(viewSampleButton, c);
- JButton cancelButton = new JButton("Download");
+ JButton downloadButton = new JButton("Download");
c.weightx = 1;
- c.gridx = 0;
+ c.gridx = 1;
c.gridy = 1;
- cancelButton.setVisible(true);
- cancelButton.addMouseListener(new MouseListener(){
+ downloadButton.setVisible(true);
+ downloadButton.addMouseListener(new MouseListener(){
@Override
public void mouseClicked(MouseEvent e) {
if(projectId != -1){
cg.downloadedBatch(downloadBatch(projectId));
dbDialog.setVisible(false);
}
}
@Override public void mousePressed(MouseEvent e) {}
@Override public void mouseReleased(MouseEvent e) {}
@Override public void mouseEntered(MouseEvent e) {}
@Override public void mouseExited(MouseEvent e) {}
});
- pane.add(cancelButton, c);
+ pane.add(downloadButton, c);
- JButton downloadButton = new JButton("Cancel");
+ JButton cancelButton = new JButton("Cancel");
c.weightx = 1;
c.gridx = 0;
c.gridy = 1;
- downloadButton.setVisible(true);
- downloadButton.addMouseListener(new MouseListener(){
+ cancelButton.setVisible(true);
+ cancelButton.addMouseListener(new MouseListener(){
@Override
public void mouseClicked(MouseEvent e) {
cg.closeDownloadBatchGUI();
}
@Override public void mousePressed(MouseEvent e) {}
@Override public void mouseReleased(MouseEvent e) {}
@Override public void mouseEntered(MouseEvent e) {}
@Override public void mouseExited(MouseEvent e) {}
});
- pane.add(downloadButton, c);
+ pane.add(cancelButton, c);
return this.dbDialog;
}
public DownloadBatchGUI(final ClientGUI cg){
// super("Download Batch");
this.cg = cg;
}
@SuppressWarnings("finally")
private DownloadBatchResult downloadBatch(int projectId) {
ClientCommunicator cc = new ClientCommunicator();
DownloadBatchParams var = new DownloadBatchParams();
DownloadBatchResult result = null;
var.setUsername(cg.username);
var.setPassword(cg.password);
var.setProjectId(projectId);
try {
System.out.println("making request");
Object response = cc.downloadBatch(var, cg.host, cg.port);
System.out.println("got a response");
if(response instanceof DownloadBatchResult){
((DownloadBatchResult)response).setImageUrl("http://" + cg.host + ":" + cg.port + "/" + ((DownloadBatchResult)response).getImageUrl());
for(Fields f : ((DownloadBatchResult)response).getFields()){
if(f.getHelpHtml() != null)
f.setHelpHtml("http://" + cg.host + ":" + cg.port + "/" + f.getHelpHtml());
if(f.getKnownData() != null)
f.setKnownData("http://" + cg.host + ":" + cg.port + "/" + f.getKnownData());
}
System.out.println("setting response");
result = (DownloadBatchResult)response;
}else if(response instanceof FailedResult){
System.out.println("failed to get batch");
}else
System.out.println("something else" + response.getClass());
} catch (Exception e) {
}finally{
System.out.println("returning result");
return result;
}
}
@SuppressWarnings({ "finally", "unchecked" })
private ArrayList<GetProjectsResult> getProjects() {
ArrayList<GetProjectsResult> result = null;
ClientCommunicator cc = new ClientCommunicator();
ValidateUserParams vup = new ValidateUserParams();
vup.setPassword(cg.password);
vup.setUsername(cg.username);
try {
Object response = cc.getProjects(vup, cg.host, cg.port);
if(response instanceof ArrayList){
System.out.println("is array list");
result = (ArrayList<GetProjectsResult>)response;
}else if(response instanceof FailedResult){
System.out.println("failedResult");
// result = ((FailedResult)response).toString();
}else
System.out.println("something selse");
// else
// result = "something else" + response.getClass();
// getView().setResponse(result);
} catch (Exception e) {
System.out.println("exception");
e.printStackTrace();
// result = "FAILED";
}finally{
// getView().setResponse(result);
System.out.println("finally");
return result;
}
}
}
| false | true | public JDialog makeDownloadBatchGUI(){
JFrame frame = new JFrame("Download Batch");
this.dbDialog = new JDialog(frame, "Download Batch", true);
this.dbDialog.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
Dimension panelSize = new Dimension(400, 200);
this.dbDialog.setSize(panelSize);
this.dbDialog.setMinimumSize(panelSize);
this.dbDialog.setMaximumSize(panelSize);
Container pane = this.dbDialog.getContentPane();
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
pane.setLayout(new GridBagLayout());
JLabel label = new JLabel("Project: ");
c.weightx = 1;
c.gridx = 0;
c.gridy = 0;
label.setVisible(true);
pane.add(label, c);
projects = this.getProjects();
System.out.println(projects.size());
String[] names = new String[projects.size()];
for(int i = 0; i < projects.size(); i++){
names[i] = projects.get(i).getTitle();
}
projectList = new JComboBox(names);
projectId = -1;
projectList.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
if(projectList.getSelectedIndex() == -1){
// nothing selected
}else{
projectId = projects.get(projectList.getSelectedIndex()).getId();
System.out.println("projectid is now: " + projectId);
}
}
});
projectList.setSelectedIndex(0);// load initial thing
c.weightx = 1;
c.gridx = 1;
c.gridy = 0;
pane.add(projectList, c);
JButton viewSampleButton = new JButton("View Sample");
c.weightx = 1;
c.gridx = 2;
c.gridy = 0;
viewSampleButton.setVisible(true);
viewSampleButton.addMouseListener(new MouseListener(){
@Override
public void mouseClicked(MouseEvent e) {
SampleImage si = new SampleImage(cg);
JDialog dialog = si.makeSampleImage(projects.get(projectList.getSelectedIndex()).getTitle(), projectId);
dialog.setVisible(true);
}
@Override public void mousePressed(MouseEvent e) {}
@Override public void mouseReleased(MouseEvent e) {}
@Override public void mouseEntered(MouseEvent e) {}
@Override public void mouseExited(MouseEvent e) {}
});
pane.add(viewSampleButton, c);
JButton cancelButton = new JButton("Download");
c.weightx = 1;
c.gridx = 0;
c.gridy = 1;
cancelButton.setVisible(true);
cancelButton.addMouseListener(new MouseListener(){
@Override
public void mouseClicked(MouseEvent e) {
if(projectId != -1){
cg.downloadedBatch(downloadBatch(projectId));
dbDialog.setVisible(false);
}
}
@Override public void mousePressed(MouseEvent e) {}
@Override public void mouseReleased(MouseEvent e) {}
@Override public void mouseEntered(MouseEvent e) {}
@Override public void mouseExited(MouseEvent e) {}
});
pane.add(cancelButton, c);
JButton downloadButton = new JButton("Cancel");
c.weightx = 1;
c.gridx = 0;
c.gridy = 1;
downloadButton.setVisible(true);
downloadButton.addMouseListener(new MouseListener(){
@Override
public void mouseClicked(MouseEvent e) {
cg.closeDownloadBatchGUI();
}
@Override public void mousePressed(MouseEvent e) {}
@Override public void mouseReleased(MouseEvent e) {}
@Override public void mouseEntered(MouseEvent e) {}
@Override public void mouseExited(MouseEvent e) {}
});
pane.add(downloadButton, c);
return this.dbDialog;
}
| public JDialog makeDownloadBatchGUI(){
JFrame frame = new JFrame("Download Batch");
this.dbDialog = new JDialog(frame, "Download Batch", true);
this.dbDialog.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
Dimension panelSize = new Dimension(400, 200);
this.dbDialog.setSize(panelSize);
this.dbDialog.setMinimumSize(panelSize);
this.dbDialog.setMaximumSize(panelSize);
Container pane = this.dbDialog.getContentPane();
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
pane.setLayout(new GridBagLayout());
JLabel label = new JLabel("Project: ");
c.weightx = 1;
c.gridx = 0;
c.gridy = 0;
label.setVisible(true);
pane.add(label, c);
projects = this.getProjects();
System.out.println(projects.size());
String[] names = new String[projects.size()];
for(int i = 0; i < projects.size(); i++){
names[i] = projects.get(i).getTitle();
}
projectList = new JComboBox(names);
projectId = -1;
projectList.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
if(projectList.getSelectedIndex() == -1){
// nothing selected
}else{
projectId = projects.get(projectList.getSelectedIndex()).getId();
System.out.println("projectid is now: " + projectId);
}
}
});
projectList.setSelectedIndex(0);// load initial thing
c.weightx = 1;
c.gridx = 1;
c.gridy = 0;
pane.add(projectList, c);
JButton viewSampleButton = new JButton("View Sample");
c.weightx = 1;
c.gridx = 2;
c.gridy = 0;
viewSampleButton.setVisible(true);
viewSampleButton.addMouseListener(new MouseListener(){
@Override
public void mouseClicked(MouseEvent e) {
SampleImage si = new SampleImage(cg);
JDialog dialog = si.makeSampleImage(projects.get(projectList.getSelectedIndex()).getTitle(), projectId);
dialog.setVisible(true);
}
@Override public void mousePressed(MouseEvent e) {}
@Override public void mouseReleased(MouseEvent e) {}
@Override public void mouseEntered(MouseEvent e) {}
@Override public void mouseExited(MouseEvent e) {}
});
pane.add(viewSampleButton, c);
JButton downloadButton = new JButton("Download");
c.weightx = 1;
c.gridx = 1;
c.gridy = 1;
downloadButton.setVisible(true);
downloadButton.addMouseListener(new MouseListener(){
@Override
public void mouseClicked(MouseEvent e) {
if(projectId != -1){
cg.downloadedBatch(downloadBatch(projectId));
dbDialog.setVisible(false);
}
}
@Override public void mousePressed(MouseEvent e) {}
@Override public void mouseReleased(MouseEvent e) {}
@Override public void mouseEntered(MouseEvent e) {}
@Override public void mouseExited(MouseEvent e) {}
});
pane.add(downloadButton, c);
JButton cancelButton = new JButton("Cancel");
c.weightx = 1;
c.gridx = 0;
c.gridy = 1;
cancelButton.setVisible(true);
cancelButton.addMouseListener(new MouseListener(){
@Override
public void mouseClicked(MouseEvent e) {
cg.closeDownloadBatchGUI();
}
@Override public void mousePressed(MouseEvent e) {}
@Override public void mouseReleased(MouseEvent e) {}
@Override public void mouseEntered(MouseEvent e) {}
@Override public void mouseExited(MouseEvent e) {}
});
pane.add(cancelButton, c);
return this.dbDialog;
}
|
diff --git a/src/brown/puzzles/liarliar/AccuserInputParser.java b/src/brown/puzzles/liarliar/AccuserInputParser.java
index f52f652..6d0634e 100644
--- a/src/brown/puzzles/liarliar/AccuserInputParser.java
+++ b/src/brown/puzzles/liarliar/AccuserInputParser.java
@@ -1,68 +1,70 @@
package brown.puzzles.liarliar;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import brown.puzzles.InputParser;
/**
* @author Matt Brown
* @date Feb 18, 2010
*/
public class AccuserInputParser implements InputParser<Collection<Accuser>> {
/*
* (non-Javadoc)
*
* @see brown.puzzles.InputParser#parseFile(java.io.File)
*/
public Collection<Accuser> parseFile(File file) throws IOException {
Scanner sc = null;
Collection<Accuser> parsed = null;
try {
sc = new Scanner(file);
parsed = parse(sc);
}
finally {
if (sc != null) sc.close();
}
return parsed;
}
private Collection<Accuser> parse(Scanner sc) {
Collection<Accuser> parsed = new ArrayList<Accuser>();
Map<String, Accuser> map = new HashMap<String, Accuser>();
final int numLines = sc.nextInt();
for (int i = 0; i < numLines; i++) {
final String name = sc.next();
final int accusations = sc.nextInt();
- Accuser acc = new Accuser(name);
- map.put(name, acc);
+ if (!map.containsKey(name)) {
+ map.put(name, new Accuser(name));
+ }
+ Accuser acc = map.get(name);
for (int j = 0; j < accusations; j++) {
String newAccusedName = sc.next();
if (!map.containsKey(newAccusedName)) {
map.put(newAccusedName, new Accuser(newAccusedName));
}
acc.accuse(map.get(newAccusedName));
}
parsed.add(acc);
}
return parsed;
}
}
| true | true | private Collection<Accuser> parse(Scanner sc) {
Collection<Accuser> parsed = new ArrayList<Accuser>();
Map<String, Accuser> map = new HashMap<String, Accuser>();
final int numLines = sc.nextInt();
for (int i = 0; i < numLines; i++) {
final String name = sc.next();
final int accusations = sc.nextInt();
Accuser acc = new Accuser(name);
map.put(name, acc);
for (int j = 0; j < accusations; j++) {
String newAccusedName = sc.next();
if (!map.containsKey(newAccusedName)) {
map.put(newAccusedName, new Accuser(newAccusedName));
}
acc.accuse(map.get(newAccusedName));
}
parsed.add(acc);
}
return parsed;
}
| private Collection<Accuser> parse(Scanner sc) {
Collection<Accuser> parsed = new ArrayList<Accuser>();
Map<String, Accuser> map = new HashMap<String, Accuser>();
final int numLines = sc.nextInt();
for (int i = 0; i < numLines; i++) {
final String name = sc.next();
final int accusations = sc.nextInt();
if (!map.containsKey(name)) {
map.put(name, new Accuser(name));
}
Accuser acc = map.get(name);
for (int j = 0; j < accusations; j++) {
String newAccusedName = sc.next();
if (!map.containsKey(newAccusedName)) {
map.put(newAccusedName, new Accuser(newAccusedName));
}
acc.accuse(map.get(newAccusedName));
}
parsed.add(acc);
}
return parsed;
}
|
diff --git a/CG7/src/util/Util.java b/CG7/src/util/Util.java
index 984a0d1..0fbada1 100644
--- a/CG7/src/util/Util.java
+++ b/CG7/src/util/Util.java
@@ -1,735 +1,737 @@
package util;
import static opengl.GL.*;
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import main.SolSystem;
import opengl.GL;
import org.lwjgl.BufferUtils;
import org.lwjgl.util.vector.Matrix4f;
import org.lwjgl.util.vector.Vector2f;
import org.lwjgl.util.vector.Vector3f;
import org.lwjgl.util.vector.Vector4f;
/**
*
* @author Sascha Kolodzey, Nico Marniok
*/
public class Util {
public static final FloatBuffer MAT_BUFFER = BufferUtils.createFloatBuffer(16);
public static final float PI = (float)Math.PI;
public static final float PI_DIV2 = 0.5f * (float)Math.PI;
public static final float PI_DIV4 = 0.25f * (float)Math.PI;
public static final float PI_MUL2 = 2.0f * (float)Math.PI;
/**
* Erzeugt eine Viewmatrix aus Augenposition und Fokuspunkt.
* @param eye Die Position des Auges
* @param at Anvisierter Punkt
* @param up Up Vektor des Auges
* @param dst Matrix, in die das Ergebnis gespeichert wird. Wenn null wird
* eine neue erstellt.
* @return Ergebnismatrix
*/
public static Matrix4f lookAtRH(Vector3f eye, Vector3f at, Vector3f up, Matrix4f dst) {
if(dst == null) dst = new Matrix4f();
Vector3f viewDir = Vector3f.sub(at, eye, null);
viewDir.normalise();
Vector3f side = Vector3f.cross(viewDir, up, null);
side.normalise();
Vector3f newUp = Vector3f.cross(side, viewDir, null);
newUp.normalise();
dst.m00 = side.x; dst.m10 = side.y; dst.m20 = side.z; dst.m30 = -Vector3f.dot(eye, side);
dst.m01 = newUp.x; dst.m11 = newUp.y; dst.m21 = newUp.z; dst.m31 = -Vector3f.dot(eye, newUp);
dst.m02 = -viewDir.x; dst.m12 = -viewDir.y; dst.m22 = -viewDir.z; dst.m32 = Vector3f.dot(eye, viewDir);
dst.m03 = 0.0f; dst.m13 = 0.0f; dst.m23 = 0.0f; dst.m33 = 1.0f;
return dst;
}
/**
* Erzeugt eine perspektivische Projektionsmatrix, die dem zweiten Ansatz
* der Vorlesung entspricht. (Vorl. vom 29.05.2012, Folie 16)
* @param l -x Wert der Viewpane
* @param r +x Wert der Viewpane
* @param b -y Wert der Viewpane
* @param t +y Wert der Viewpane
* @param n -z Wert der Viewpane
* @param f +z Wert der Viewpane
* @param dst Matrix, in die das Ergebnis gespeichert wird. Wenn null wird
* eine neue erstellt.
* @return Ergebnismatrix
*/
public static Matrix4f frustum(float l, float r, float b, float t, float n, float f, Matrix4f dst) {
if(dst == null) dst = new Matrix4f();
dst.m00 = 2.0f*n/(r-l); dst.m10 = 0.0f; dst.m20 = (r+l)/(r-l); dst.m30 = 0.0f;
dst.m01 = 0.0f; dst.m11 = 2.0f*n/(t-b); dst.m21 = (t+b)/(t-b); dst.m31 = 0.0f;
dst.m02 = 0.0f; dst.m12 = 0.0f; dst.m22 = -(f+n)/(f-n); dst.m32 = -2.0f*n*f/(f-n);
dst.m03 = 0.0f; dst.m13 = 0.0f; dst.m23 = -1.0f; dst.m33 = 0.0f;
return dst;
}
/**
* Erzeugt die orthogonale Projektionsmatrix, die dem klassichen Ansatz
* entspricht.
* @param dst Matrix, in die das Ergebnis gespeichert wird. Wenn null wird
* eine neue erstellt.
* @return Ergebnismatrix
*/
public static Matrix4f ortho(Matrix4f dst) {
if(dst == null) dst = new Matrix4f();
dst.setIdentity();
dst.m22 = 0.0f;
return dst;
}
/**
* Erzeugt eine orthogonal Projektionsmatrix, die dem zweiten Ansatz der
* Vorlesung entspricht. (Vorl. vom 29.05.2012, Folie 10)
* @param l minimaler Wert in x-Richtung
* @param r maximaler Wert in x-Richtung
* @param b minimaler Wert in y-Richtung
* @param t maximaler Wert in y-Richtung
* @param n minimaler Wert in z-Richtung
* @param f maximaler Wert in z-Richtung
* @param dst Matrix, in die das Ergebnis gespeichert wird. Wenn null wird
* eine neue erstellt.
* @return Ergebnismatrix
*/
public static Matrix4f ortho(float l, float r, float b, float t, float n, float f, Matrix4f dst) {
return Util.mul(dst, Util.scale(new Vector3f(2.0f / (r - l), 2.0f / (t - b), -2.0f / (f - n)), null),
Util.translation(new Vector3f(-0.5f * (r + l), -0.5f * (t + b), 0.5f * (f + n)), null));
}
/**
* Erzeugt eine Rotationsmatrix um die x-Achse.
* @param angle Winkel in Bogenass
* @param dst Matrix, in die das Ergebnis gespeichert wird. Wenn null wird
* eine neue erstellt.
* @return Ergebnismatrix
*/
public static Matrix4f rotationX(float angle, Matrix4f dst) {
if(dst == null) dst = new Matrix4f();
dst.setIdentity();
dst.m11 = dst.m22 = (float)Math.cos(angle);
dst.m21 = -(dst.m12 = (float)Math.sin(angle));
return dst;
}
/**
* Erzeugt eine Rotationsmatrix um die y-Achse.
* @param angle Winkel in Bogenass
* @param dst Matrix, in die das Ergebnis gespeichert wird. Wenn null wird
* eine neue erstellt.
* @return Ergebnismatrix
*/
public static Matrix4f rotationY(float angle, Matrix4f dst) {
if(dst == null) dst = new Matrix4f();
dst.setIdentity();
dst.m00 = dst.m22 = (float)Math.cos(angle);
dst.m02 = -(dst.m20 = (float)Math.sin(angle));
return dst;
}
/**
* Erzeugt eine Rotationsmatrix um die z-Achse.
* @param angle Winkel in Bogenass
* @param dst Matrix, in die das Ergebnis gespeichert wird. Wenn null wird
* eine neue erstellt.
* @return Ergebnismatrix
*/
public static Matrix4f rotationZ(float angle, Matrix4f dst) {
if(dst == null) dst = new Matrix4f();
dst.setIdentity();
dst.m00 = dst.m11 = (float)Math.cos(angle);
dst.m10 = -(dst.m01 = (float)Math.sin(angle));
return dst;
}
/**
* Erzeugt eine Translationsmatrix.
* @param translation Der Translationsvektor
* @param dst Matrix, in die das Ergebnis gespeichert wird. Wenn null wird
* eine neue erstellt.
* @return Ergebnismatrix
*/
public static Matrix4f translation(Vector3f translation, Matrix4f dst) {
if(dst == null) dst = new Matrix4f();
dst.setIdentity();
dst.m30 = translation.x;
dst.m31 = translation.y;
dst.m32 = translation.z;
return dst;
}
/**
* Erzeugt eine Translationsmatrix in x-Richtung.
* @param x Der Translationslaenge
* @param dst Matrix, in die das Ergebnis gespeichert wird. Wenn null wird
* eine neue erstellt.
* @return Ergebnismatrix
*/
public static Matrix4f translationX(float x, Matrix4f dst) {
if(dst == null) dst = new Matrix4f();
dst.setIdentity();
dst.m30 = x;
return dst;
}
/**
* Erzeugt eine Translationsmatrix in y-Richtung.
* @param y Der Translationslaenge
* @param dst Matrix, in die das Ergebnis gespeichert wird. Wenn null wird
* eine neue erstellt.
* @return Ergebnismatrix
*/
public static Matrix4f translationY(float y, Matrix4f dst) {
if(dst == null) dst = new Matrix4f();
dst.setIdentity();
dst.m31 = y;
return dst;
}
/**
* Erzeugt eine Translationsmatrix in z-Richtung.
* @param z Der Translationslaenge
* @param dst Matrix, in die das Ergebnis gespeichert wird. Wenn null wird
* eine neue erstellt.
* @return Ergebnismatrix
*/
public static Matrix4f translationZ(float z, Matrix4f dst) {
if(dst == null) dst = new Matrix4f();
dst.setIdentity();
dst.m32 = z;
return dst;
}
/**
* Erzeugt eine Skalierungsmatrix.
* @param scale Skalierungskomponente
* @param dst Matrix, in die das Ergebnis gespeichert wird. Wenn null wird
* eine neue erstellt.
* @return Ergebnismatrix
*/
public static Matrix4f scale(Vector3f scale, Matrix4f dst) {
if(dst == null) dst = new Matrix4f();
dst.setIdentity();
dst.m00 = scale.x;
dst.m11 = scale.y;
dst.m22 = scale.z;
return dst;
}
/**
* Erzeugt eine gleichmaessige Skalierungsmatrix.
* @param scale Skalierungskomponente
* @param dst Matrix, in die das Ergebnis gespeichert wird. Wenn null wird
* eine neue erstellt.
* @return Ergebnismatrix
*/
public static Matrix4f scale(float scale, Matrix4f dst) {
return Util.scale(new Vector3f(scale, scale, scale), dst);
}
/**
* Transformiert einen Vector3f mittels einer Matrix4f. Der Vektor wird um
* die homogene Koordinate 1 erweitert und anschliessend homogenisiert.
* @param left Trabsformationsmatrix
* @param right Zu transformierender Vektor
* @param dst Vektor, in den das Ergebnis gespeichert wird. Wenn null wird
* ein neuer erstellt.
* @return Ergebnisvektor
*/
public static Vector3f transformCoord(Matrix4f left, Vector3f right, Vector3f dst) {
if(dst == null) dst = new Vector3f();
Vector4f vec = Matrix4f.transform(left, new Vector4f(right.x, right.y, right.z, 1.0f), null);
vec.scale(1.0f / vec.w);
dst.set(vec.x, vec.y, vec.z);
return dst;
}
/**
* Transformiert einen Vector3f mittels einer Matrix4f. Der Vektor wird um
* die homogene Koordinate 0 erweitert.
* @param left Trabsformationsmatrix
* @param right Zu transformierender Vektor
* @param dst Vektor, in den das Ergebnis gespeichert wird. Wenn null wird
* ein neuer erstellt.
* @return Ergebnisvektor
*/
public static Vector3f transformDir(Matrix4f left, Vector3f right, Vector3f dst) {
if(dst == null) dst = new Vector3f();
Vector4f vec = Matrix4f.transform(left, new Vector4f(right.x, right.y, right.z, 0.0f), null);
dst.set(vec.x, vec.y, vec.z);
return dst;
}
/**
* Multipliziert beliebig viele Matrizen miteinander.
* @param dst Matrix, in die das Ergebnis gespeichert wird. Wenn null wird
* eine neue erstellt.
* @param factors Matrizen, die multipliziert werden sollen
* @return Ergebnismatrix
*/
public static Matrix4f mul(Matrix4f dst, Matrix4f ...factors) {
if(dst == null) dst = new Matrix4f();
dst.setIdentity();
for(Matrix4f mat : factors) {
Matrix4f.mul(dst, mat, dst);
}
return dst;
}
/**
* Schneidet einen Wert zurecht.
* @param val Wert
* @param min minimaler Wert
* @param max maximaler Wert
* @return Falls val < min, dann min. Falls val > max, dann max. sonst
* val.
*/
public static float clamp(float val, float min, float max) {
return Math.max(min, Math.min(val, max));
}
/**
* Schneidet einen Vektor komponentenweise zurecht.
* @param val Wert
* @param min minimaler Wert
* @param max maximaler Wert
* @param dst Vektor, in den das Ergebnis gespeichert wird. Wenn null wird
* ein neuer erstellt.
* @return Ergebnisvektor
*/
public static Vector2f clamp(Vector2f val, Vector2f min, Vector2f max, Vector2f dst) {
if(dst == null) dst = new Vector2f();
dst.x = clamp(val.x, min.x, max.x);
dst.y = clamp(val.y, min.y, max.y);
return dst;
}
/**
* Schneidet einen Vektor zurecht.
* @param val Wert
* @param min minimaler Wert
* @param max maximaler Wert
* @param dst Vektor, in den das Ergebnis gespeichert wird. Wenn null wird
* ein neuer erstellt.
* @return Ergebnisvektor
*/
public static Vector2f clamp(Vector2f val, float min, float max, Vector2f dst) {
return clamp(val, new Vector2f(min, min), new Vector2f(max, max), dst);
}
/**
* Schneidet einen Vektor komponentenweise zurecht.
* @param val Wert
* @param min minimaler Wert
* @param max maximaler Wert
* @param dst Vektor, in den das Ergebnis gespeichert wird. Wenn null wird
* ein neuer erstellt.
* @return Ergebnisvektor
*/
public static Vector3f clamp(Vector3f val, Vector3f min, Vector3f max, Vector3f dst) {
if(dst == null) dst = new Vector3f();
dst.x = clamp(val.x, min.x, max.x);
dst.y = clamp(val.y, min.y, max.y);
dst.z = clamp(val.z, min.z, max.z);
return dst;
}
/**
* Schneidet einen Vektor zurecht.
* @param val Wert
* @param min minimaler Wert
* @param max maximaler Wert
* @param dst Vektor, in den das Ergebnis gespeichert wird. Wenn null wird
* ein neuer erstellt.
* @return Ergebnisvektor
*/
public static Vector3f clamp(Vector3f val, float min, float max, Vector3f dst) {
return clamp(val, new Vector3f(min, min, min), new Vector3f(max, max, max), dst);
}
/**
* Schneidet einen Vektor komponentenweise zurecht.
* @param val Wert
* @param min minimaler Wert
* @param max maximaler Wert
* @param dst Vektor, in den das Ergebnis gespeichert wird. Wenn null wird
* ein neuer erstellt.
* @return Ergebnisvektor
*/
public static Vector4f clamp(Vector4f val, Vector4f min, Vector4f max, Vector4f dst) {
if(dst == null) dst = new Vector4f();
dst.x = clamp(val.x, min.x, max.x);
dst.y = clamp(val.y, min.y, max.y);
dst.z = clamp(val.z, min.z, max.z);
dst.w = clamp(val.w, min.w, max.w);
return dst;
}
/**
* Schneidet einen Vektor zurecht.
* @param val Wert
* @param min minimaler Wert
* @param max maximaler Wert
* @param dst Vektor, in den das Ergebnis gespeichert wird. Wenn null wird
* ein neuer erstellt.
* @return Ergebnisvektor
*/
public static Vector4f clamp(Vector4f val, float min, float max, Vector4f dst) {
return clamp(val, new Vector4f(min, min, min, min), new Vector4f(max, max, max, max), dst);
}
/**
* Erzeugt ein gleichmaessiges 2D n-Eck in der xy-Ebene. (n Indizes, als
* GL_LINE_LOOP)
* @param n Anzahl der Ecken
* @return VertexArrayObject ID
*/
public static int createNGon(int n) {
int vaid = glGenVertexArrays();
glBindVertexArray(vaid);
// indexbuffer
IntBuffer indexData = BufferUtils.createIntBuffer(n);
for(int i=0; i < n; ++i) {
indexData.put(i);
}
indexData.flip();
int indexBufferID = glGenBuffers();
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBufferID);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indexData, GL_STATIC_DRAW);
// vertexbuffer
FloatBuffer vertexData = BufferUtils.createFloatBuffer(3*n + 3*n); // world coords + normal coords
double phi = 0;
double deltaPhi = 2.0*Math.PI / (double)n;
for(int i=0; i < n; ++i) {
vertexData.put(0.5f*(float)Math.cos(phi)); // position x
vertexData.put(0.5f*(float)Math.sin(phi)); // position y
vertexData.put(0.5f*0.0f); // position z
vertexData.put((float)Math.cos(phi)); // normal x
vertexData.put((float)Math.sin(phi)); // normal y
vertexData.put(0.0f); // normal z
phi += deltaPhi;
}
vertexData.position(0);
int vertexBufferID = glGenBuffers();
glBindBuffer(GL_ARRAY_BUFFER, vertexBufferID);
glBufferData(GL_ARRAY_BUFFER, vertexData, GL_STATIC_DRAW);
// vs_in_pos
glEnableVertexAttribArray(ATTR_POS);
glVertexAttribPointer(ATTR_POS, 3, GL_FLOAT, false, 24, 0);
// vs_in_normal
glEnableVertexAttribArray(ATTR_NORMAL);
glVertexAttribPointer(ATTR_NORMAL, 3, GL_FLOAT, false, 24, 12);
return vaid;
}
/**
* Erzeugt ein Dreieck in der xy-Ebene. (3 Indizes)
* @return VertexArrayObject ID
*/
public static int createTriangle() {
int vaid = glGenVertexArrays();
glBindVertexArray(vaid);
// vertexbuffer
FloatBuffer vertexData = BufferUtils.createFloatBuffer((3+4)*3); // color, world coords
vertexData.put(new float[] {
0.4f, 1.0f, 1.0f, 1.0f, -1.0f, -1.0f, 0.0f,
0.4f, 1.0f, 1.0f, 1.0f, +1.0f, -1.0f, 0.0f,
0.4f, 0.4f, 1.0f, 1.0f, 0.0f, +1.0f, 0.0f,
});
vertexData.position(0);
int vertexBufferID = glGenBuffers();
glBindBuffer(GL_ARRAY_BUFFER, vertexBufferID);
glBufferData(GL_ARRAY_BUFFER, vertexData, GL_STATIC_DRAW);
// vs_in_color
glEnableVertexAttribArray(ATTR_COLOR);
glVertexAttribPointer(ATTR_COLOR, 4, GL_FLOAT, false, (3+4)*4, 0);
// vs_in_pos
glEnableVertexAttribArray(ATTR_POS);
glVertexAttribPointer(ATTR_POS, 3, GL_FLOAT, false, (3+4)*4, 4*4);
return vaid;
}
/**
* Erzeugt ein Vierexk in der xy-Ebene. (4 Indizes)
* @return VertexArrayObject ID
*/
public static int createQuad() {
int vaid = glGenVertexArrays();
glBindVertexArray(vaid);
// vertexbuffer
FloatBuffer vertexData = BufferUtils.createFloatBuffer((3+4)*4); // world coords, color
vertexData.put(new float[] {
-1.0f, -1.0f, 0.0f, 1.0f, 1.0f, 0.4f, 1.0f,
+1.0f, -1.0f, 0.0f, 0.4f, 1.0f, 0.4f, 1.0f,
+1.0f, +1.0f, 0.0f, 1.0f, 1.0f, 0.4f, 1.0f,
-1.0f, +1.0f, 0.0f, 0.4f, 1.0f, 0.4f, 1.0f,
});
vertexData.position(0);
int vertexBufferID = glGenBuffers();
glBindBuffer(GL_ARRAY_BUFFER, vertexBufferID);
glBufferData(GL_ARRAY_BUFFER, vertexData, GL_STATIC_DRAW);
// vs_in_pos
glEnableVertexAttribArray(ATTR_POS);
glVertexAttribPointer(ATTR_POS, 3, GL_FLOAT, false, (3+4)*4, 0);
// vs_in_color
glEnableVertexAttribArray(ATTR_COLOR);
glVertexAttribPointer(ATTR_COLOR, 4, GL_FLOAT, false, (3+4)*4, 3*4);
return vaid;
}
/**
* Erzeugt eine Kugel.
* @param r Radius der Kugel
* @param n vertikale Unterteilung
* @param k horizontale Unterteilung
* @param imageFile Pfad zu einer Bilddatei
* @return Geometrie der Kugel
*/
public static Geometry createSphere(float r, int n, int k, String imageFile) {
Geometry sphere = new Geometry(); //create new Geormetry for the sphere
float[] vertices= new float[(k*n+2)*6]; // k*n vertices *6 floats per vertex and north and south pole vertices
float[][][] image = getImageContents(imageFile); //[y][x][color] 0 < y < image.height 0 < x < image.width
float dTheta = Util.PI / (k+1); //angle between z and horizontal scale
float dPhi = Util.PI_MUL2 / (n); //angle between x and vetical scale
int xcol = 0, ycol = 0, count = 0; //xcol/ycol = x/y coordinate for color
float x = 0f, y = 0f, z = 0f, red = 0f, green = 0f, blue = 0f; //coordinates and color attributes
/*
* x = r*sin(theta)*cos(phi)
* y = r*cos(theta)
* z = r*sin(theta)*sin(phi)
*
* 0 <= theta <= pi ; 0 <= phi < 2*pi
* theta = angle between z-Axis and r (k)
* phi = angle between pos. x-axis and r (n)
*
*/
float xcolscale = image[0].length / (float)n;
float ycolscale = image.length / (float)k;
int countindex = 0;
vertices[count++] = 0; //northpole vertex
vertices[count++] = r;
vertices[count++] = 0;
vertices[count++] = image[0][0][0];
vertices[count++] = image[0][0][1];
vertices[count++] = image[0][0][2];
- int[] index = new int[k*n*2+k+2];
+ int[] index = new int[k*n*2+k*4];
for(int i = 0; i < k; i++)
{
+ index[countindex++] = 0;
for(int j = 0; j < n; j++)
{
x = (float) (r*Math.sin(dTheta+dTheta*j)*Math.cos(dPhi*i));
y = (float) (r*Math.cos(dTheta+dTheta*j));
z = (float) (r*Math.sin(dTheta+dTheta*j)*Math.sin(dPhi*i));
xcol = (int)(xcolscale * i);
ycol = (int)(ycolscale * j);
red = image[ycol][xcol][0];
green = image[ycol][xcol][1];
blue = image[ycol][xcol][2];
vertices[count++] = x;
vertices[count++] = y;
vertices[count++] = z;
vertices[count++] = red;
vertices[count++] = green;
vertices[count++] = blue;
//TODO: Index isn't quite correct
- index[countindex++] = j + n*i;
+ index[countindex++] = j + n*i +1;
if(i < (k-1)){
- index[countindex++] = j + n*(i+1);
+ index[countindex++] = j + n*(i+1) +1;
}
else{
- index[countindex++] = j;
+ index[countindex++] = j +1;
}
}
+ index[countindex++] = k*n+1;
index[countindex++] = -1;
}
vertices[k*n*6+6] = 0; //southpole vertex
vertices[k*n*6+7] = -r;
vertices[k*n*6+8] = 0;
vertices[k*n*6+9] = image[image.length-1][image[0].length-1][0];
vertices[k*n*6+10] = image[image.length-1][image[0].length-1][1];
vertices[k*n*6+11] = image[image.length-1][image[0].length-1][2];
// TODO: Add right indexbuffer for triangles
/*for(int i = 0; i < k*n+2; i++)
{
index[i] = i;
}*/
FloatBuffer indiBuffer = BufferUtils.createFloatBuffer(n*k*6+2*6);
- IntBuffer indexBuffer = BufferUtils.createIntBuffer(k*n*2+k+2);
+ IntBuffer indexBuffer = BufferUtils.createIntBuffer(k*n*2+k*4);
indexBuffer.put(index);
indexBuffer.position(0);
indiBuffer.put(vertices);
indiBuffer.position(0);
sphere.setVertices(indiBuffer);
sphere.setIndexBuffer(indexBuffer, GL.GL_TRIANGLE_STRIP);
return sphere;
}
/**
* Liest den Inhalt einer Datei und liefert ihn als String zurueck.
* @param filename Pfad der Datei
* @return Inhalt der Datei
*/
private static String getFileContents(String filename) {
BufferedReader reader = null;
String source = null;
try {
reader = new BufferedReader(new FileReader(filename));
source = "";
String line = null;
while((line = reader.readLine()) != null) {
source += line + "\n";
}
} catch (IOException ex) {
Logger.getLogger(Util.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
reader.close();
} catch (IOException ex) {
Logger.getLogger(Util.class.getName()).log(Level.SEVERE, null, ex);
}
}
return source;
}
/**
* Attribut Index von vs_in_pos
*/
public static final int ATTR_POS = 0;
/**
* Attribut Index von vs_in_normal
*/
public static final int ATTR_NORMAL = 1;
/**
* Attribut Index von vs_in_color
*/
public static final int ATTR_COLOR = 2;
/**
* Erzeugt ein ShaderProgram aus einem Vertex- und Fragmentshader.
* @param vs Pfad zum Vertexshader
* @param fs Pfad zum Fragmentshader
* @return ShaderProgram ID
*/
public static int createShaderProgram(String vs, String fs) {
int programID = glCreateProgram();
int vsID = glCreateShader(GL_VERTEX_SHADER);
int fsID = glCreateShader(GL_FRAGMENT_SHADER);
glAttachShader(programID, vsID);
glAttachShader(programID, fsID);
String vertexShaderContents = Util.getFileContents(vs);
String fragmentShaderContents = Util.getFileContents(fs);
glShaderSource(vsID, vertexShaderContents);
glShaderSource(fsID, fragmentShaderContents);
glCompileShader(vsID);
glCompileShader(fsID);
String log;
log = glGetShaderInfoLog(vsID, 1024);
System.out.print(log);
log = glGetShaderInfoLog(fsID, 1024);
System.out.print(log);
glBindAttribLocation(programID, ATTR_POS, "vs_in_pos");
glBindAttribLocation(programID, ATTR_NORMAL, "vs_in_normal");
glBindAttribLocation(programID, ATTR_COLOR, "vs_in_color");
glLinkProgram(programID);
log = glGetProgramInfoLog(programID, 1024);
System.out.print(log);
return programID;
}
/**
* Laedt ein Bild und speichert die einzelnen Bildpunke in einem
* 2-dimensionalen float-Array. Die erste Koordinate ist die y-Position und
* liegt zwischen 0 und der Hoehe des Bildes - 1. Die zweite Koordinate ist
* die x-Position und liegt zwischen 0 und der Breite des Bildes. Die dritte
* Koordinate ist die Farbkomponente des Bildpunktes und ist 0 (rot), 1
* (gruen) oder 2 (blau).
* @param imageFile Pfad zur Bilddatei
* @return Bild enthaltendes float-Array
*/
public static float[][][] getImageContents(String imageFile) {
File file = new File(imageFile);
if(!file.exists()) {
throw new IllegalArgumentException(imageFile + " does not exist");
}
try {
BufferedImage image = ImageIO.read(file);
float[][][] result = new float[image.getHeight()][image.getWidth()][3];
for(int y=0; y < image.getHeight(); ++y) {
for(int x=0; x < image.getWidth(); ++x) {
Color c = new Color(image.getRGB(image.getWidth() - 1 - x, y));
result[y][x][0] = (float)c.getRed() / 255.0f;
result[y][x][1] = (float)c.getGreen() / 255.0f;
result[y][x][2] = (float)c.getBlue() / 255.0f;
}
}
return result;
} catch (IOException ex) {
Logger.getLogger(Util.class.getName()).log(Level.SEVERE, null, ex);
return null;
}
}
}
| false | true | public static Geometry createSphere(float r, int n, int k, String imageFile) {
Geometry sphere = new Geometry(); //create new Geormetry for the sphere
float[] vertices= new float[(k*n+2)*6]; // k*n vertices *6 floats per vertex and north and south pole vertices
float[][][] image = getImageContents(imageFile); //[y][x][color] 0 < y < image.height 0 < x < image.width
float dTheta = Util.PI / (k+1); //angle between z and horizontal scale
float dPhi = Util.PI_MUL2 / (n); //angle between x and vetical scale
int xcol = 0, ycol = 0, count = 0; //xcol/ycol = x/y coordinate for color
float x = 0f, y = 0f, z = 0f, red = 0f, green = 0f, blue = 0f; //coordinates and color attributes
/*
* x = r*sin(theta)*cos(phi)
* y = r*cos(theta)
* z = r*sin(theta)*sin(phi)
*
* 0 <= theta <= pi ; 0 <= phi < 2*pi
* theta = angle between z-Axis and r (k)
* phi = angle between pos. x-axis and r (n)
*
*/
float xcolscale = image[0].length / (float)n;
float ycolscale = image.length / (float)k;
int countindex = 0;
vertices[count++] = 0; //northpole vertex
vertices[count++] = r;
vertices[count++] = 0;
vertices[count++] = image[0][0][0];
vertices[count++] = image[0][0][1];
vertices[count++] = image[0][0][2];
int[] index = new int[k*n*2+k+2];
for(int i = 0; i < k; i++)
{
for(int j = 0; j < n; j++)
{
x = (float) (r*Math.sin(dTheta+dTheta*j)*Math.cos(dPhi*i));
y = (float) (r*Math.cos(dTheta+dTheta*j));
z = (float) (r*Math.sin(dTheta+dTheta*j)*Math.sin(dPhi*i));
xcol = (int)(xcolscale * i);
ycol = (int)(ycolscale * j);
red = image[ycol][xcol][0];
green = image[ycol][xcol][1];
blue = image[ycol][xcol][2];
vertices[count++] = x;
vertices[count++] = y;
vertices[count++] = z;
vertices[count++] = red;
vertices[count++] = green;
vertices[count++] = blue;
//TODO: Index isn't quite correct
index[countindex++] = j + n*i;
if(i < (k-1)){
index[countindex++] = j + n*(i+1);
}
else{
index[countindex++] = j;
}
}
index[countindex++] = -1;
}
vertices[k*n*6+6] = 0; //southpole vertex
vertices[k*n*6+7] = -r;
vertices[k*n*6+8] = 0;
vertices[k*n*6+9] = image[image.length-1][image[0].length-1][0];
vertices[k*n*6+10] = image[image.length-1][image[0].length-1][1];
vertices[k*n*6+11] = image[image.length-1][image[0].length-1][2];
// TODO: Add right indexbuffer for triangles
/*for(int i = 0; i < k*n+2; i++)
{
index[i] = i;
}*/
FloatBuffer indiBuffer = BufferUtils.createFloatBuffer(n*k*6+2*6);
IntBuffer indexBuffer = BufferUtils.createIntBuffer(k*n*2+k+2);
indexBuffer.put(index);
indexBuffer.position(0);
indiBuffer.put(vertices);
indiBuffer.position(0);
sphere.setVertices(indiBuffer);
sphere.setIndexBuffer(indexBuffer, GL.GL_TRIANGLE_STRIP);
return sphere;
}
| public static Geometry createSphere(float r, int n, int k, String imageFile) {
Geometry sphere = new Geometry(); //create new Geormetry for the sphere
float[] vertices= new float[(k*n+2)*6]; // k*n vertices *6 floats per vertex and north and south pole vertices
float[][][] image = getImageContents(imageFile); //[y][x][color] 0 < y < image.height 0 < x < image.width
float dTheta = Util.PI / (k+1); //angle between z and horizontal scale
float dPhi = Util.PI_MUL2 / (n); //angle between x and vetical scale
int xcol = 0, ycol = 0, count = 0; //xcol/ycol = x/y coordinate for color
float x = 0f, y = 0f, z = 0f, red = 0f, green = 0f, blue = 0f; //coordinates and color attributes
/*
* x = r*sin(theta)*cos(phi)
* y = r*cos(theta)
* z = r*sin(theta)*sin(phi)
*
* 0 <= theta <= pi ; 0 <= phi < 2*pi
* theta = angle between z-Axis and r (k)
* phi = angle between pos. x-axis and r (n)
*
*/
float xcolscale = image[0].length / (float)n;
float ycolscale = image.length / (float)k;
int countindex = 0;
vertices[count++] = 0; //northpole vertex
vertices[count++] = r;
vertices[count++] = 0;
vertices[count++] = image[0][0][0];
vertices[count++] = image[0][0][1];
vertices[count++] = image[0][0][2];
int[] index = new int[k*n*2+k*4];
for(int i = 0; i < k; i++)
{
index[countindex++] = 0;
for(int j = 0; j < n; j++)
{
x = (float) (r*Math.sin(dTheta+dTheta*j)*Math.cos(dPhi*i));
y = (float) (r*Math.cos(dTheta+dTheta*j));
z = (float) (r*Math.sin(dTheta+dTheta*j)*Math.sin(dPhi*i));
xcol = (int)(xcolscale * i);
ycol = (int)(ycolscale * j);
red = image[ycol][xcol][0];
green = image[ycol][xcol][1];
blue = image[ycol][xcol][2];
vertices[count++] = x;
vertices[count++] = y;
vertices[count++] = z;
vertices[count++] = red;
vertices[count++] = green;
vertices[count++] = blue;
//TODO: Index isn't quite correct
index[countindex++] = j + n*i +1;
if(i < (k-1)){
index[countindex++] = j + n*(i+1) +1;
}
else{
index[countindex++] = j +1;
}
}
index[countindex++] = k*n+1;
index[countindex++] = -1;
}
vertices[k*n*6+6] = 0; //southpole vertex
vertices[k*n*6+7] = -r;
vertices[k*n*6+8] = 0;
vertices[k*n*6+9] = image[image.length-1][image[0].length-1][0];
vertices[k*n*6+10] = image[image.length-1][image[0].length-1][1];
vertices[k*n*6+11] = image[image.length-1][image[0].length-1][2];
// TODO: Add right indexbuffer for triangles
/*for(int i = 0; i < k*n+2; i++)
{
index[i] = i;
}*/
FloatBuffer indiBuffer = BufferUtils.createFloatBuffer(n*k*6+2*6);
IntBuffer indexBuffer = BufferUtils.createIntBuffer(k*n*2+k*4);
indexBuffer.put(index);
indexBuffer.position(0);
indiBuffer.put(vertices);
indiBuffer.position(0);
sphere.setVertices(indiBuffer);
sphere.setIndexBuffer(indexBuffer, GL.GL_TRIANGLE_STRIP);
return sphere;
}
|
diff --git a/src/main/java/simulation/beefs/model/DataServer.java b/src/main/java/simulation/beefs/model/DataServer.java
index 687517c..4b91f10 100644
--- a/src/main/java/simulation/beefs/model/DataServer.java
+++ b/src/main/java/simulation/beefs/model/DataServer.java
@@ -1,46 +1,46 @@
package simulation.beefs.model;
import manelsim.EventScheduler;
public class DataServer {
private long freeSpace;
private final Machine host;
private static final int NUMBER_OF_CHANGES_BEFORE_LOG = 1000;
private int numberOfChanges = 0;
public DataServer(Machine host, long freeSpace) {
this.host = host;
this.freeSpace = freeSpace;
}
public long freeSpace() {
return freeSpace;
}
public void useDisk(long bytes) {
freeSpace -= bytes;
notifyChange();
}
public void cleanSpace(long bytes) {
freeSpace += bytes;
notifyChange();
}
public Machine getHost() {
return host;
}
private void notifyChange() {
numberOfChanges++;
if(numberOfChanges > NUMBER_OF_CHANGES_BEFORE_LOG) {
- String msg = String.format("%s\t%d\t%d", host.getName(), EventScheduler.now(), freeSpace());
+ String msg = String.format("%s\t%s\t%d", host.getName(), EventScheduler.now(), freeSpace());
System.out.println(msg);
numberOfChanges = 0;
}
}
}
| true | true | private void notifyChange() {
numberOfChanges++;
if(numberOfChanges > NUMBER_OF_CHANGES_BEFORE_LOG) {
String msg = String.format("%s\t%d\t%d", host.getName(), EventScheduler.now(), freeSpace());
System.out.println(msg);
numberOfChanges = 0;
}
}
| private void notifyChange() {
numberOfChanges++;
if(numberOfChanges > NUMBER_OF_CHANGES_BEFORE_LOG) {
String msg = String.format("%s\t%s\t%d", host.getName(), EventScheduler.now(), freeSpace());
System.out.println(msg);
numberOfChanges = 0;
}
}
|
diff --git a/tests/org.jboss.tools.esb.ui.bot.test/src/org/jboss/tools/esb/ui/bot/tests/CreateRuntimeFromESB.java b/tests/org.jboss.tools.esb.ui.bot.test/src/org/jboss/tools/esb/ui/bot/tests/CreateRuntimeFromESB.java
index 8636a538f..1a670cf6b 100644
--- a/tests/org.jboss.tools.esb.ui.bot.test/src/org/jboss/tools/esb/ui/bot/tests/CreateRuntimeFromESB.java
+++ b/tests/org.jboss.tools.esb.ui.bot.test/src/org/jboss/tools/esb/ui/bot/tests/CreateRuntimeFromESB.java
@@ -1,39 +1,39 @@
package org.jboss.tools.esb.ui.bot.tests;
import org.eclipse.swtbot.swt.finder.SWTBot;
import org.jboss.tools.ui.bot.ext.SWTTestExt;
import org.jboss.tools.ui.bot.ext.config.TestConfigurator;
import org.jboss.tools.ui.bot.ext.config.Annotations.*;
import org.jboss.tools.ui.bot.ext.gen.ActionItem;
import org.jboss.tools.ui.bot.ext.types.IDELabel;
import org.junit.Test;
@Require(esb=@ESB())
public class CreateRuntimeFromESB extends SWTTestExt {
@Test
public void createESBRuntime() {
SWTBot wiz = open.preferenceOpen(ActionItem.Preference.JBossToolsJBossESBRuntimes.LABEL);
wiz.button("Add").click();
bot.shell(IDELabel.Shell.NEW_ESB_RUNTIME).activate();
assertFalse("Finish button must not be enabled when no home dir is defined",bot.button(IDELabel.Button.FINISH).isEnabled());
bot.text(1).setText(TestConfigurator.currentConfig.getEsb().runtimeHome);
bot.sleep (3000l, "3 sleeping - " + TestConfigurator.currentConfig.getEsb().runtimeHome + " " + TestConfigurator.currentConfig.getEsb().version + " " + bot.comboBox().selection().toString());
/* ldimaggi - Oct 2011 - https://issues.jboss.org/browse/JBDS-1886 - this test fails for ESB 4.10 */
- //assertTrue("JBDS-1886 - Version was not automatically selected by setting ESB home dir",bot.comboBox().selection().equals(TestConfigurator.currentConfig.getEsb().version));
+ assertTrue("JBDS-1886 - Version was not automatically selected by setting ESB home dir",bot.comboBox().selection().equals(TestConfigurator.currentConfig.getEsb().version));
/* ldimaggi - Oct 2011 */
bot.text(0).setText("123_TheName");
//System.out.println ("[" + bot.textWithLabel("JBoss ESB Runtime").getText() +"]");
assertTrue ("Runtime name cannot start with a number", bot.textWithLabel("JBoss ESB Runtime").getText().equals(" Runtime name is not correct") );
bot.text(0).setText("runtime");
String name = bot.text(0).getText();
assertFalse("Runtime name was not automaticly set by setting ESB home dir",name.equals(""));
assertTrue("Finish button must be enabled when valid home dir is defined",bot.button(IDELabel.Button.FINISH).isEnabled());
open.finish(bot.activeShell().bot());
open.finish(wiz, IDELabel.Button.OK);
eclipse.removeESBRuntime(name);
}
}
| true | true | public void createESBRuntime() {
SWTBot wiz = open.preferenceOpen(ActionItem.Preference.JBossToolsJBossESBRuntimes.LABEL);
wiz.button("Add").click();
bot.shell(IDELabel.Shell.NEW_ESB_RUNTIME).activate();
assertFalse("Finish button must not be enabled when no home dir is defined",bot.button(IDELabel.Button.FINISH).isEnabled());
bot.text(1).setText(TestConfigurator.currentConfig.getEsb().runtimeHome);
bot.sleep (3000l, "3 sleeping - " + TestConfigurator.currentConfig.getEsb().runtimeHome + " " + TestConfigurator.currentConfig.getEsb().version + " " + bot.comboBox().selection().toString());
/* ldimaggi - Oct 2011 - https://issues.jboss.org/browse/JBDS-1886 - this test fails for ESB 4.10 */
//assertTrue("JBDS-1886 - Version was not automatically selected by setting ESB home dir",bot.comboBox().selection().equals(TestConfigurator.currentConfig.getEsb().version));
/* ldimaggi - Oct 2011 */
bot.text(0).setText("123_TheName");
//System.out.println ("[" + bot.textWithLabel("JBoss ESB Runtime").getText() +"]");
assertTrue ("Runtime name cannot start with a number", bot.textWithLabel("JBoss ESB Runtime").getText().equals(" Runtime name is not correct") );
bot.text(0).setText("runtime");
String name = bot.text(0).getText();
assertFalse("Runtime name was not automaticly set by setting ESB home dir",name.equals(""));
assertTrue("Finish button must be enabled when valid home dir is defined",bot.button(IDELabel.Button.FINISH).isEnabled());
open.finish(bot.activeShell().bot());
open.finish(wiz, IDELabel.Button.OK);
eclipse.removeESBRuntime(name);
}
| public void createESBRuntime() {
SWTBot wiz = open.preferenceOpen(ActionItem.Preference.JBossToolsJBossESBRuntimes.LABEL);
wiz.button("Add").click();
bot.shell(IDELabel.Shell.NEW_ESB_RUNTIME).activate();
assertFalse("Finish button must not be enabled when no home dir is defined",bot.button(IDELabel.Button.FINISH).isEnabled());
bot.text(1).setText(TestConfigurator.currentConfig.getEsb().runtimeHome);
bot.sleep (3000l, "3 sleeping - " + TestConfigurator.currentConfig.getEsb().runtimeHome + " " + TestConfigurator.currentConfig.getEsb().version + " " + bot.comboBox().selection().toString());
/* ldimaggi - Oct 2011 - https://issues.jboss.org/browse/JBDS-1886 - this test fails for ESB 4.10 */
assertTrue("JBDS-1886 - Version was not automatically selected by setting ESB home dir",bot.comboBox().selection().equals(TestConfigurator.currentConfig.getEsb().version));
/* ldimaggi - Oct 2011 */
bot.text(0).setText("123_TheName");
//System.out.println ("[" + bot.textWithLabel("JBoss ESB Runtime").getText() +"]");
assertTrue ("Runtime name cannot start with a number", bot.textWithLabel("JBoss ESB Runtime").getText().equals(" Runtime name is not correct") );
bot.text(0).setText("runtime");
String name = bot.text(0).getText();
assertFalse("Runtime name was not automaticly set by setting ESB home dir",name.equals(""));
assertTrue("Finish button must be enabled when valid home dir is defined",bot.button(IDELabel.Button.FINISH).isEnabled());
open.finish(bot.activeShell().bot());
open.finish(wiz, IDELabel.Button.OK);
eclipse.removeESBRuntime(name);
}
|
diff --git a/src/java/com/threerings/ezgame/server/persist/GameCookieRepository.java b/src/java/com/threerings/ezgame/server/persist/GameCookieRepository.java
index fdbaefc1..99ab51e8 100644
--- a/src/java/com/threerings/ezgame/server/persist/GameCookieRepository.java
+++ b/src/java/com/threerings/ezgame/server/persist/GameCookieRepository.java
@@ -1,133 +1,133 @@
//
// $Id$
//
// Vilya library - tools for developing networked games
// Copyright (C) 2002-2006 Three Rings Design, Inc., All Rights Reserved
// http://www.threerings.net/code/vilya/
//
// 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 com.threerings.ezgame.server.persist;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import com.samskivert.io.PersistenceException;
import com.samskivert.jdbc.ConnectionProvider;
import com.samskivert.jdbc.DatabaseLiaison;
import com.samskivert.jdbc.JDBCUtil;
import com.samskivert.jdbc.JORARepository;
import com.samskivert.jdbc.SimpleRepository;
import com.samskivert.jdbc.TransitionRepository;
/**
* Provides storage services for user cookies used in games.
*/
public class GameCookieRepository extends SimpleRepository
{
/** The database identifier used when establishing a connection. */
public static final String COOKIE_DB_IDENT = "gameCookiedb";
public GameCookieRepository (ConnectionProvider conprov)
throws PersistenceException
{
super(conprov, COOKIE_DB_IDENT);
maintenance("analyze", "GAME_COOKIES");
}
@Override
protected void migrateSchema (Connection conn, DatabaseLiaison liaison)
throws SQLException, PersistenceException
{
super.migrateSchema(conn, liaison);
JDBCUtil.createTableIfMissing(conn, "GAME_COOKIES", new String[] {
"GAME_ID integer not null",
"USER_ID integer not null",
"COOKIE blob not null",
"primary key (GAME_ID, USER_ID)" }, "");
}
/**
* Get the specified game cookie, or null if none.
*/
public byte[] getCookie (final int gameId, final int userId)
throws PersistenceException
{
return execute(new Operation<byte[]>() {
public byte[] invoke (Connection conn, DatabaseLiaison liaison)
throws SQLException, PersistenceException
{
Statement stmt = conn.createStatement();
try {
ResultSet rs = stmt.executeQuery("select COOKIE " +
"from GAME_COOKIES where GAME_ID=" + gameId +
" and USER_ID=" + userId);
if (rs.next()) {
return rs.getBytes(1);
}
return null;
} finally {
JDBCUtil.close(stmt);
}
}
});
}
/**
* Set the specified user's game cookie.
*/
public void setCookie (
final int gameId, final int userId, final byte[] cookie)
throws PersistenceException
{
executeUpdate(new Operation<Void>() {
public Void invoke (Connection conn, DatabaseLiaison liaison)
throws SQLException, PersistenceException
{
if (cookie == null) {
Statement stmt = conn.createStatement();
try {
stmt.executeUpdate("delete from GAME_COOKIES" +
" where GAME_ID=" + gameId +
" and USER_ID=" + userId);
return null;
} finally {
JDBCUtil.close(stmt);
}
} else {
PreparedStatement stmt = conn.prepareStatement(
- "update GAME_COOKIES set COOKIE=?" +
- " where GAME_ID=" + gameId +
- " and USER_ID=" + userId);
+ "insert into GAME_COOKIES (GAME_ID, USER_ID, COOKIE) " +
+ "values (" + gameId + "," + userId + ",?) " +
+ "on duplicate key update COOKIE=values(COOKIE)");
try {
stmt.setBytes(1, cookie);
stmt.executeUpdate();
return null;
} finally {
JDBCUtil.close(stmt);
}
}
}
});
}
}
| true | true | protected void migrateSchema (Connection conn, DatabaseLiaison liaison)
throws SQLException, PersistenceException
{
super.migrateSchema(conn, liaison);
JDBCUtil.createTableIfMissing(conn, "GAME_COOKIES", new String[] {
"GAME_ID integer not null",
"USER_ID integer not null",
"COOKIE blob not null",
"primary key (GAME_ID, USER_ID)" }, "");
}
/**
* Get the specified game cookie, or null if none.
*/
public byte[] getCookie (final int gameId, final int userId)
throws PersistenceException
{
return execute(new Operation<byte[]>() {
public byte[] invoke (Connection conn, DatabaseLiaison liaison)
throws SQLException, PersistenceException
{
Statement stmt = conn.createStatement();
try {
ResultSet rs = stmt.executeQuery("select COOKIE " +
"from GAME_COOKIES where GAME_ID=" + gameId +
" and USER_ID=" + userId);
if (rs.next()) {
return rs.getBytes(1);
}
return null;
} finally {
JDBCUtil.close(stmt);
}
}
});
}
/**
* Set the specified user's game cookie.
*/
public void setCookie (
final int gameId, final int userId, final byte[] cookie)
throws PersistenceException
{
executeUpdate(new Operation<Void>() {
public Void invoke (Connection conn, DatabaseLiaison liaison)
throws SQLException, PersistenceException
{
if (cookie == null) {
Statement stmt = conn.createStatement();
try {
stmt.executeUpdate("delete from GAME_COOKIES" +
" where GAME_ID=" + gameId +
" and USER_ID=" + userId);
return null;
} finally {
JDBCUtil.close(stmt);
}
} else {
PreparedStatement stmt = conn.prepareStatement(
"update GAME_COOKIES set COOKIE=?" +
" where GAME_ID=" + gameId +
" and USER_ID=" + userId);
try {
stmt.setBytes(1, cookie);
stmt.executeUpdate();
return null;
} finally {
JDBCUtil.close(stmt);
}
}
}
});
}
}
| protected void migrateSchema (Connection conn, DatabaseLiaison liaison)
throws SQLException, PersistenceException
{
super.migrateSchema(conn, liaison);
JDBCUtil.createTableIfMissing(conn, "GAME_COOKIES", new String[] {
"GAME_ID integer not null",
"USER_ID integer not null",
"COOKIE blob not null",
"primary key (GAME_ID, USER_ID)" }, "");
}
/**
* Get the specified game cookie, or null if none.
*/
public byte[] getCookie (final int gameId, final int userId)
throws PersistenceException
{
return execute(new Operation<byte[]>() {
public byte[] invoke (Connection conn, DatabaseLiaison liaison)
throws SQLException, PersistenceException
{
Statement stmt = conn.createStatement();
try {
ResultSet rs = stmt.executeQuery("select COOKIE " +
"from GAME_COOKIES where GAME_ID=" + gameId +
" and USER_ID=" + userId);
if (rs.next()) {
return rs.getBytes(1);
}
return null;
} finally {
JDBCUtil.close(stmt);
}
}
});
}
/**
* Set the specified user's game cookie.
*/
public void setCookie (
final int gameId, final int userId, final byte[] cookie)
throws PersistenceException
{
executeUpdate(new Operation<Void>() {
public Void invoke (Connection conn, DatabaseLiaison liaison)
throws SQLException, PersistenceException
{
if (cookie == null) {
Statement stmt = conn.createStatement();
try {
stmt.executeUpdate("delete from GAME_COOKIES" +
" where GAME_ID=" + gameId +
" and USER_ID=" + userId);
return null;
} finally {
JDBCUtil.close(stmt);
}
} else {
PreparedStatement stmt = conn.prepareStatement(
"insert into GAME_COOKIES (GAME_ID, USER_ID, COOKIE) " +
"values (" + gameId + "," + userId + ",?) " +
"on duplicate key update COOKIE=values(COOKIE)");
try {
stmt.setBytes(1, cookie);
stmt.executeUpdate();
return null;
} finally {
JDBCUtil.close(stmt);
}
}
}
});
}
}
|
diff --git a/classpath/java/io/ObjectInputStream.java b/classpath/java/io/ObjectInputStream.java
index a0390465..45bacc73 100644
--- a/classpath/java/io/ObjectInputStream.java
+++ b/classpath/java/io/ObjectInputStream.java
@@ -1,234 +1,234 @@
/* Copyright (c) 2008-2010, Avian Contributors
Permission to use, copy, modify, and/or distribute this software
for any purpose with or without fee is hereby granted, provided
that the above copyright notice and this permission notice appear
in all copies.
There is NO WARRANTY for this software. See license.txt for
details. */
package java.io;
import avian.VMClass;
import java.util.HashMap;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
public class ObjectInputStream extends InputStream {
private final InputStream in;
private final PushbackReader r;
public ObjectInputStream(InputStream in) {
this.in = in;
this.r = new PushbackReader(new InputStreamReader(in));
}
public int read() throws IOException {
return in.read();
}
public int read(byte[] b, int offset, int length) throws IOException {
return in.read(b, offset, length);
}
public void close() throws IOException {
in.close();
}
public Object readObject() throws IOException, ClassNotFoundException {
return readObject(new HashMap());
}
public boolean readBoolean() throws IOException {
read('z');
return readLongToken() != 0;
}
public byte readByte() throws IOException {
read('b');
return (byte) readLongToken();
}
public char readChar() throws IOException {
read('c');
return (char) readLongToken();
}
public short readShort() throws IOException {
read('s');
return (short) readLongToken();
}
public int readInt() throws IOException {
read('i');
return (int) readLongToken();
}
public long readLong() throws IOException {
read('j');
return readLongToken();
}
public float readFloat() throws IOException {
read('f');
return (float) readDoubleToken();
}
public double readDouble() throws IOException {
read('d');
return readDoubleToken();
}
public void defaultReadObject() throws IOException {
throw new UnsupportedOperationException();
}
private void skipSpace() throws IOException {
int c;
while ((c = r.read()) != -1 && Character.isWhitespace((char) c));
if (c != -1) {
r.unread(c);
}
}
private void read(char v) throws IOException {
skipSpace();
int c = r.read();
if (c != v) {
if (c == -1) {
throw new EOFException();
} else {
throw new StreamCorruptedException();
}
}
}
private String readStringToken() throws IOException {
skipSpace();
StringBuilder sb = new StringBuilder();
int c;
while ((c = r.read()) != -1 && ! Character.isWhitespace((char) c) && c != ')') {
sb.append((char) c);
}
if (c != -1) {
r.unread(c);
}
return sb.toString();
}
private long readLongToken() throws IOException {
return Long.parseLong(readStringToken());
}
private double readDoubleToken() throws IOException {
return Double.parseDouble(readStringToken());
}
private Object readObject(HashMap<Integer, Object> map)
throws IOException, ClassNotFoundException
{
skipSpace();
switch (r.read()) {
case 'a':
return deserializeArray(map);
case 'l':
return deserializeObject(map);
case 'n':
return null;
case -1:
throw new EOFException();
default:
throw new StreamCorruptedException();
}
}
private Object deserialize(HashMap<Integer, Object> map)
throws IOException, ClassNotFoundException
{
skipSpace();
switch (r.read()) {
case 'a':
return deserializeArray(map);
case 'l':
return deserializeObject(map);
case 'r':
return map.get((int) readLongToken());
case 'n':
return null;
case 'z':
- return (readLongToken() == 0);
+ return (readLongToken() != 0);
case 'b':
return (byte) readLongToken();
case 'c':
return (char) readLongToken();
case 's':
return (short) readLongToken();
case 'i':
return (int) readLongToken();
case 'j':
return readLongToken();
case 'f':
return (float) readDoubleToken();
case 'd':
return readDoubleToken();
case -1:
throw new EOFException();
default:
throw new StreamCorruptedException();
}
}
private Object deserializeArray(HashMap<Integer, Object> map)
throws IOException, ClassNotFoundException
{
read('(');
int id = (int) readLongToken();
Class c = Class.forName(readStringToken());
int length = (int) readLongToken();
Class t = c.getComponentType();
Object o = Array.newInstance(t, length);
map.put(id, o);
for (int i = 0; i < length; ++i) {
Array.set(o, i, deserialize(map));
}
read(')');
return o;
}
private static native Object makeInstance(VMClass c);
private Object deserializeObject(HashMap<Integer, Object> map)
throws IOException, ClassNotFoundException
{
read('(');
int id = (int) readLongToken();
Class c = Class.forName(readStringToken());
Object o = makeInstance(c.vmClass);
map.put(id, o);
for (Field f: c.getAllFields()) {
int modifiers = f.getModifiers();
if ((modifiers & (Modifier.TRANSIENT | Modifier.STATIC)) == 0) {
try {
f.set(o, deserialize(map));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
read(')');
return o;
}
}
| true | true | private Object deserialize(HashMap<Integer, Object> map)
throws IOException, ClassNotFoundException
{
skipSpace();
switch (r.read()) {
case 'a':
return deserializeArray(map);
case 'l':
return deserializeObject(map);
case 'r':
return map.get((int) readLongToken());
case 'n':
return null;
case 'z':
return (readLongToken() == 0);
case 'b':
return (byte) readLongToken();
case 'c':
return (char) readLongToken();
case 's':
return (short) readLongToken();
case 'i':
return (int) readLongToken();
case 'j':
return readLongToken();
case 'f':
return (float) readDoubleToken();
case 'd':
return readDoubleToken();
case -1:
throw new EOFException();
default:
throw new StreamCorruptedException();
}
}
| private Object deserialize(HashMap<Integer, Object> map)
throws IOException, ClassNotFoundException
{
skipSpace();
switch (r.read()) {
case 'a':
return deserializeArray(map);
case 'l':
return deserializeObject(map);
case 'r':
return map.get((int) readLongToken());
case 'n':
return null;
case 'z':
return (readLongToken() != 0);
case 'b':
return (byte) readLongToken();
case 'c':
return (char) readLongToken();
case 's':
return (short) readLongToken();
case 'i':
return (int) readLongToken();
case 'j':
return readLongToken();
case 'f':
return (float) readDoubleToken();
case 'd':
return readDoubleToken();
case -1:
throw new EOFException();
default:
throw new StreamCorruptedException();
}
}
|
diff --git a/teams/team298/ChainerPlayer.java b/teams/team298/ChainerPlayer.java
index 9afccd4..2f8a7de 100644
--- a/teams/team298/ChainerPlayer.java
+++ b/teams/team298/ChainerPlayer.java
@@ -1,54 +1,53 @@
package team298;
import battlecode.common.*;
import static battlecode.common.GameConstants.*;
import java.util.*;
public class ChainerPlayer extends AttackPlayer {
public ChainerPlayer(RobotController controller) {
super(controller);
}
public void step() {
MapLocation location = sensing.senseClosestArchon();
int distance = location.distanceSquaredTo(controller.getLocation());
if(energon.isEnergonLow() || energon.isFluxFull() || distance > 34) {
navigation.changeToArchonGoal(true);
if(distance < 3) {
- energon.transferFlux(location);
energon.requestEnergonTransfer();
controller.yield();
} else {
navigation.moveOnce(false);
}
return;
}
processEnemies();
sortEnemies();
EnemyInfo enemy = mode.getEnemyToAttack();
if(enemy != null) {
// attack
if(!controller.canAttackSquare(enemy.location)) {
navigation.faceLocation(enemy.location);
processEnemies();
}
executeAttack(enemy.location, enemy.type.isAirborne() ? RobotLevel.IN_AIR : RobotLevel.ON_GROUND);
processEnemies();
attackLocation = enemy.location;
} else {
if(outOfRangeEnemies.size() > 0) {
// only move if we can do it in 1 turn or less
if(controller.getRoundsUntilMovementIdle() < 2) {
moveToAttack();
}
} else {
navigation.changeToMoveableDirectionGoal(true);
navigation.moveOnce(true);
}
}
}
}
| true | true | public void step() {
MapLocation location = sensing.senseClosestArchon();
int distance = location.distanceSquaredTo(controller.getLocation());
if(energon.isEnergonLow() || energon.isFluxFull() || distance > 34) {
navigation.changeToArchonGoal(true);
if(distance < 3) {
energon.transferFlux(location);
energon.requestEnergonTransfer();
controller.yield();
} else {
navigation.moveOnce(false);
}
return;
}
processEnemies();
sortEnemies();
EnemyInfo enemy = mode.getEnemyToAttack();
if(enemy != null) {
// attack
if(!controller.canAttackSquare(enemy.location)) {
navigation.faceLocation(enemy.location);
processEnemies();
}
executeAttack(enemy.location, enemy.type.isAirborne() ? RobotLevel.IN_AIR : RobotLevel.ON_GROUND);
processEnemies();
attackLocation = enemy.location;
} else {
if(outOfRangeEnemies.size() > 0) {
// only move if we can do it in 1 turn or less
if(controller.getRoundsUntilMovementIdle() < 2) {
moveToAttack();
}
} else {
navigation.changeToMoveableDirectionGoal(true);
navigation.moveOnce(true);
}
}
}
| public void step() {
MapLocation location = sensing.senseClosestArchon();
int distance = location.distanceSquaredTo(controller.getLocation());
if(energon.isEnergonLow() || energon.isFluxFull() || distance > 34) {
navigation.changeToArchonGoal(true);
if(distance < 3) {
energon.requestEnergonTransfer();
controller.yield();
} else {
navigation.moveOnce(false);
}
return;
}
processEnemies();
sortEnemies();
EnemyInfo enemy = mode.getEnemyToAttack();
if(enemy != null) {
// attack
if(!controller.canAttackSquare(enemy.location)) {
navigation.faceLocation(enemy.location);
processEnemies();
}
executeAttack(enemy.location, enemy.type.isAirborne() ? RobotLevel.IN_AIR : RobotLevel.ON_GROUND);
processEnemies();
attackLocation = enemy.location;
} else {
if(outOfRangeEnemies.size() > 0) {
// only move if we can do it in 1 turn or less
if(controller.getRoundsUntilMovementIdle() < 2) {
moveToAttack();
}
} else {
navigation.changeToMoveableDirectionGoal(true);
navigation.moveOnce(true);
}
}
}
|
diff --git a/src/cs/c301/project/PhotoReview.java b/src/cs/c301/project/PhotoReview.java
index c966e45..2601dca 100644
--- a/src/cs/c301/project/PhotoReview.java
+++ b/src/cs/c301/project/PhotoReview.java
@@ -1,147 +1,147 @@
package cs.c301.project;
import java.util.Date;
import java.util.Vector;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import cs.c301.project.Data.PhotoEntry;
import cs.c301.project.Listeners.PhotoModelListener;
/**
* Take recent taken photo from the sd card and draws the photo up on screen
* for the user to review and decide whether to put into group and then keep
* the photo or user can discard the photo if it is unwanted
*
*/
public class PhotoReview extends Activity implements PhotoModelListener {
ListView partlist;
Button keepButton;
ProgressDialog p;
private String groupName;
private PhotoEntry photoEntry;
@Override
/**
* Method called upon activity creation
*/
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.review);
ImageView reviewPhoto = (ImageView) findViewById(R.id.review_photo);
- reviewPhoto.setImageDrawable(Drawable.createFromPath(photoEntry.getFilePath()));
+// reviewPhoto.setImageDrawable(Drawable.createFromPath(photoEntry.getFilePath()));
//ImageView comparePhoto = (ImageView) findViewById(R.id.review_photoCompare);
/**
* Discard button to allow the user to discard unwanted photos
*/
Button discardButton = (Button) findViewById(R.id.review_disc);
discardButton.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
PhotoApplication.removePhoto(photoEntry.getID());
}
});
keepButton = (Button) findViewById(R.id.review_keep);
keepButton.setText("Select Group");
keepButton.setOnClickListener(new Button.OnClickListener(){
public void onClick(View v) {
Intent intent = new Intent(getApplication(), GroupList.class);
intent.putExtra("isUnderReview", true);
startActivityForResult(intent, 0);
}
});
PhotoApplication.addPhotoModelListener(this);
}
/**
* Grab the group name of the photo from the group list intent
* @param a
* @param b
* @param intent extra data from the intent
*/
@Override
protected void onActivityResult(int a, int b, Intent intent) {
Bundle extra = intent.getExtras();
groupName = extra.getString("groupname");
photoEntry.setGroup(groupName);
}
/**
* Grab the latest photo from the sd card and give the global
* variable the string path
*
* @param photos vector list of photos in the sd card
*/
public void photosChanged(Vector<PhotoEntry> photos) {
int id = -1;
Date latestDate = null;
for (int i = 0; i < photos.size(); i++) {
if (latestDate == null) {
photos.elementAt(i).getDate();
id = i;
} else {
Date tempDate = photos.elementAt(i).getDate();
if (tempDate.compareTo(latestDate) > 0) {
id = i;
latestDate = tempDate;
}
}
}
if (id != -1) {
photoEntry = photos.elementAt(id);
onStart();
}
}
/**
* Show the review photo page and draw the photo on screen
*/
protected void onStart() {
super.onStart();
ImageView reviewPhoto = (ImageView) findViewById(R.id.review_photo);
reviewPhoto.setImageDrawable(Drawable.createFromPath(photoEntry.getFilePath()));
}
/**
* (non-Javadoc)
* @see cs.c301.project.Listeners.PhotoModelListener#tagsChanged(java.util.Vector)
*/
public void tagsChanged(Vector<String> tags) {
// TODO Auto-generated method stub
}
/**
* (non-Javadoc)
* @see cs.c301.project.Listeners.PhotoModelListener#groupsChanged(Vector)
*/
public void groupsChanged(Vector<String> groups) {
// TODO Auto-generated method stub
}
}
| true | true | public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.review);
ImageView reviewPhoto = (ImageView) findViewById(R.id.review_photo);
reviewPhoto.setImageDrawable(Drawable.createFromPath(photoEntry.getFilePath()));
//ImageView comparePhoto = (ImageView) findViewById(R.id.review_photoCompare);
/**
* Discard button to allow the user to discard unwanted photos
*/
Button discardButton = (Button) findViewById(R.id.review_disc);
discardButton.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
PhotoApplication.removePhoto(photoEntry.getID());
}
});
keepButton = (Button) findViewById(R.id.review_keep);
keepButton.setText("Select Group");
keepButton.setOnClickListener(new Button.OnClickListener(){
public void onClick(View v) {
Intent intent = new Intent(getApplication(), GroupList.class);
intent.putExtra("isUnderReview", true);
startActivityForResult(intent, 0);
}
});
PhotoApplication.addPhotoModelListener(this);
}
| public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.review);
ImageView reviewPhoto = (ImageView) findViewById(R.id.review_photo);
// reviewPhoto.setImageDrawable(Drawable.createFromPath(photoEntry.getFilePath()));
//ImageView comparePhoto = (ImageView) findViewById(R.id.review_photoCompare);
/**
* Discard button to allow the user to discard unwanted photos
*/
Button discardButton = (Button) findViewById(R.id.review_disc);
discardButton.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
PhotoApplication.removePhoto(photoEntry.getID());
}
});
keepButton = (Button) findViewById(R.id.review_keep);
keepButton.setText("Select Group");
keepButton.setOnClickListener(new Button.OnClickListener(){
public void onClick(View v) {
Intent intent = new Intent(getApplication(), GroupList.class);
intent.putExtra("isUnderReview", true);
startActivityForResult(intent, 0);
}
});
PhotoApplication.addPhotoModelListener(this);
}
|
diff --git a/minecraft/entanglecraft/items/EntangleCraftItems.java b/minecraft/entanglecraft/items/EntangleCraftItems.java
index 134b6c0..684d125 100644
--- a/minecraft/entanglecraft/items/EntangleCraftItems.java
+++ b/minecraft/entanglecraft/items/EntangleCraftItems.java
@@ -1,141 +1,141 @@
package entanglecraft.items;
import cpw.mods.fml.common.registry.GameRegistry;
import cpw.mods.fml.common.registry.LanguageRegistry;
import net.minecraft.block.Block;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.src.ModLoader;
import entanglecraft.blocks.EntangleCraftBlocks;
public class EntangleCraftItems {
public static final Item ItemNetherEssence = new ItemLambda(8600).setIconIndex(87).setItemName("ItemNetherEssence");
public static final Item ItemDeviceG = new ItemDevice(8601).setIconIndex(90).setItemName("ItemDeviceG");
public static final Item ItemDeviceR = new ItemDevice(8602).setIconIndex(91).setItemName("ItemDeviceR");
public static final Item ItemDeviceY = new ItemDevice(8603).setIconIndex(92).setItemName("ItemDeviceY");
public static final Item ItemDeviceB = new ItemDevice(8604).setIconIndex(93).setItemName("ItemDeviceB");
public static final Item ItemNethermonicDiamond = new ItemLambda(8605).setIconIndex(88).setItemName("ItemNethermonicDiamond");
public static final Item ItemLambdaCore = new ItemLambda(8606).setIconIndex(89).setItemName("ItemLambdaCore");
public static final Item ItemTransformer = new ItemLambda(8607).setIconIndex(80).setItemName("ItemTransformer");
public static final Item ItemReverseTransformer = new ItemLambda(8608).setIconIndex(81).setItemName("ItemReverseTransformer");
public static final Item ItemTransmitter = new ItemLambda(8609).setIconIndex(82).setItemName("ItemTransmitter");
public static final Item ItemFrShard = new ItemLambda(8610).setIconIndex(86).setItemName("ItemFrShard");
public static final Item ItemBlueShard = new ItemShard(8611,0).setIconIndex(83).setItemName("ItemBlueShard").setMaxDamage(256);
public static final Item ItemRedShard = new ItemShard(8612,1).setIconIndex(84).setItemName("ItemRedShard").setMaxDamage(256);
public static final Item ItemYelShard = new ItemShard(8613,2).setIconIndex(85).setItemName("ItemYelShard").setMaxDamage(256);
public static final Item ItemImbuedShard = new ItemShard(8614,4).setIconIndex(94).setItemName("ItemImbuedShard");
public static final Item ItemInductionCircuit = new ItemLambda(8615).setIconIndex(95).setItemName("ItemInductionCircuit").setMaxStackSize(1);
public static final Item ItemCircuit = new ItemLambda(8616).setIconIndex(96).setItemName("ItemCircuit");
public static final Item ItemInclusiveFilter = new ItemLambda(8617).setIconIndex(97).setItemName("ItemInclusiveFilter").setMaxStackSize(1);
public static final Item ItemExclusiveFilter = new ItemLambda(8618).setIconIndex(98).setItemName("ItemExclusiveFilter").setMaxStackSize(1);
public static final Item ItemDestroyFilter = new ItemLambda(8625).setIconIndex(97+16).setItemName("ItemDestroyFilter").setMaxStackSize(1);
public static final Item ItemDontDestroyFilter = new ItemLambda(8626).setIconIndex(97+17).setItemName("ItemDontDestroyFilter").setMaxStackSize(1);
public static final Item ItemSuperInductionCircuit = new ItemLambda(8619).setIconIndex(99).setItemName("ItemSuperInductionCircuit").setMaxStackSize(1);
public static final Item ItemTPScroll = new ItemShard(8620,3).setIconIndex(101).setItemName("ItemTPScroll").setMaxDamage(1);
public static final Item ItemShardPickG = new ItemShardPick(8621).setIconIndex(102).setItemName("ItemShardPickG").setMaxDamage(0);
public static final Item ItemShardPickR = new ItemShardPick(8622).setIconIndex(103).setItemName("ItemShardPickR").setMaxDamage(0);
public static final Item ItemShardPickY = new ItemShardPick(8623).setIconIndex(104).setItemName("ItemShardPickY").setMaxDamage(0);
public static final Item ItemShardPickB = new ItemShardPick(8624).setIconIndex(105).setItemName("ItemShardPickB").setMaxDamage(0);
public static void addItems(){
itemInitializing();
LanguageRegistry.addName(ItemDeviceG, "Lambda Device : G");
LanguageRegistry.addName(ItemDeviceR, "Lambda Device : R");
LanguageRegistry.addName(ItemDeviceY, "Lambda Device : Y");
LanguageRegistry.addName(ItemDeviceB, "Lambda Device : B");
LanguageRegistry.addName(ItemLambdaCore, "Lambda Core");
LanguageRegistry.addName(ItemNetherEssence, "Nethermonic Essence");
LanguageRegistry.addName(ItemNethermonicDiamond, "Nethermonic Diamond");
LanguageRegistry.addName(ItemTransformer, "Displacement Flat-rate Transformer");
LanguageRegistry.addName(ItemReverseTransformer, "Entanglement Flat-rate Transformer");
LanguageRegistry.addName(ItemTransmitter,"Transmitter");
LanguageRegistry.addName(ItemInductionCircuit, "Induction Circuit");
LanguageRegistry.addName(ItemSuperInductionCircuit, "Forerunner Induction Circuit");
LanguageRegistry.addName(ItemFrShard, "Forerunner Obsidian Shard");
LanguageRegistry.addName(ItemBlueShard, "Mysterious Blue Shard");
LanguageRegistry.addName(ItemRedShard, "Mysterious Red Shard");
LanguageRegistry.addName(ItemYelShard, "Mysterious Yellow Shard");
LanguageRegistry.addName(ItemImbuedShard, "Legendary Tri-Shard");
LanguageRegistry.addName(ItemCircuit,"Circuit");
LanguageRegistry.addName(ItemInclusiveFilter,"'Mine only x' Filter Device");
LanguageRegistry.addName(ItemExclusiveFilter, "Exclusive Filter Device");
LanguageRegistry.addName(ItemDestroyFilter, "'Destroy x' Filter Device");
LanguageRegistry.addName(ItemDontDestroyFilter, "'Do not destroy x' Filter Device");
LanguageRegistry.addName(ItemTPScroll, "TP Scroll");
LanguageRegistry.addName(ItemShardPickG, "Displacement Pick : G");
LanguageRegistry.addName(ItemShardPickR, "Displacement Pick : R");
LanguageRegistry.addName(ItemShardPickY, "Displacement Pick : Y");
LanguageRegistry.addName(ItemShardPickB, "Displacement Pick : B");
GameRegistry.addSmelting(Block.netherrack.blockID, new ItemStack(ItemNetherEssence, 1),1F);
GameRegistry.addRecipe(new ItemStack(EntangleCraftBlocks.BlockRLD, 1), new Object[] { "NRN", "NGN", "NDN", Character.valueOf('D'), ItemNethermonicDiamond, Character.valueOf('N'), ItemNetherEssence, Character.valueOf('G'), EntangleCraftBlocks.BlockGLD, Character.valueOf('R'), Item.redstone });
GameRegistry.addRecipe(new ItemStack(EntangleCraftBlocks.BlockYLD, 1), new Object[] { "NSN", "NGN", "NDN", Character.valueOf('D'), ItemNethermonicDiamond, Character.valueOf('N'), ItemNetherEssence, Character.valueOf('G'), EntangleCraftBlocks.BlockGLD, Character.valueOf('S'), Item.lightStoneDust });
GameRegistry.addRecipe(new ItemStack(EntangleCraftBlocks.BlockBLD, 1), new Object[] { "NSN", "NGN", "NDN", Character.valueOf('D'), ItemNethermonicDiamond, Character.valueOf('N'), ItemNetherEssence, Character.valueOf('G'), EntangleCraftBlocks.BlockGLD, Character.valueOf('S'), new ItemStack(Item.dyePowder, 1, 4) });
GameRegistry.addRecipe(new ItemStack(EntangleCraftBlocks.BlockFObsidian,8), new Object[] {"OOO","OSO","OOO", Character.valueOf('O'),Block.obsidian, Character.valueOf('S'),ItemFrShard});
GameRegistry.addRecipe(new ItemStack(ItemDeviceG, 1), new Object[] { "SOO", "OLO", "OXO", Character.valueOf('O'), Block.obsidian, Character.valueOf('L'), ItemLambdaCore, Character.valueOf('S'), Item.lightStoneDust, Character.valueOf('X'), Item.map});
GameRegistry.addRecipe(new ItemStack(EntangleCraftBlocks.BlockGLD, 1), new Object[] { "FFF", "FLF", "FFF", Character.valueOf('F'), Block.obsidian, Character.valueOf('L'), ItemLambdaCore });
//GameRegistry.addRecipe(new ItemStack(EntangleCraftBlocks.BlockGenericDestination, 1), new Object[] { " D"," ", " ", Character.valueOf('D'), Block.dirt});
GameRegistry.addRecipe(new ItemStack(ItemNethermonicDiamond, 1), new Object[] { "NNN", "NDN", "NNN", Character.valueOf('N'), ItemNetherEssence, Character.valueOf('D'), Item.diamond });
GameRegistry.addRecipe(new ItemStack(ItemNethermonicDiamond,12), new Object[] {"DDD","DID","DDD", Character.valueOf('D'), ItemNethermonicDiamond, Character.valueOf('I'), ItemImbuedShard});
GameRegistry.addRecipe(new ItemStack(ItemLambdaCore, 1), new Object[] { "FBF", "SNS", "FBF", Character.valueOf('S'), Item.lightStoneDust, Character.valueOf('F'), Block.obsidian, Character.valueOf('N'), ItemNethermonicDiamond, Character.valueOf('B'), new ItemStack(Item.dyePowder, 1, 4) });
GameRegistry.addRecipe(new ItemStack(ItemTransformer, 1), new Object[] { "RNL", "NIN", "GNR", Character.valueOf('N'), ItemNetherEssence, Character.valueOf('R'), Item.redstone, Character.valueOf('L'), new ItemStack(Item.dyePowder, 1, 4), Character.valueOf('G'), Item.lightStoneDust, Character.valueOf('I'), Item.ingotIron });
GameRegistry.addRecipe(new ItemStack(ItemReverseTransformer, 1), new Object[] { "NLN", "RIR", "NGN", Character.valueOf('N'), ItemNetherEssence, Character.valueOf('R'), Item.redstone, Character.valueOf('L'), new ItemStack(Item.dyePowder, 1, 4), Character.valueOf('G'), Item.lightStoneDust, Character.valueOf('I'), Item.ingotIron });
GameRegistry.addRecipe(new ItemStack(ItemTransmitter,1), new Object[] {"IBI","ICI","INI", Character.valueOf('I'), Item.ingotIron,Character.valueOf('B'), new ItemStack(Item.dyePowder,1,4), Character.valueOf('N'),Item.compass, Character.valueOf('C'),ItemCircuit});
GameRegistry.addRecipe(new ItemStack(ItemCircuit,1), new Object[] {"FIF","ISI","FIF", Character.valueOf('F'), ItemFrShard,Character.valueOf('I'), Item.ingotIron, Character.valueOf('S'), ItemImbuedShard});
GameRegistry.addRecipe(new ItemStack(ItemInductionCircuit,1), new Object[] {"IRI","ISI"," C ", Character.valueOf('C'), ItemCircuit, Character.valueOf('I'), Item.ingotIron, Character.valueOf('R'), Item.redstone, Character.valueOf('S'),ItemFrShard});
GameRegistry.addRecipe(new ItemStack(ItemSuperInductionCircuit,1), new Object[] {"FDF","FDF"," I ", Character.valueOf('F'), EntangleCraftBlocks.BlockFObsidian, Character.valueOf('D'), Item.diamond, Character.valueOf('I'), ItemInductionCircuit});
GameRegistry.addRecipe(new ItemStack(EntangleCraftBlocks.BlockGLM,1), new Object[] {"FCF","TLT","FDF",Character.valueOf('D'), ItemShardPickG, Character.valueOf('F'), EntangleCraftBlocks.BlockFObsidian,Character.valueOf('L'), ItemLambdaCore, Character.valueOf('C'), ItemCircuit, Character.valueOf('T'), ItemTransmitter});
GameRegistry.addRecipe(new ItemStack(EntangleCraftBlocks.BlockRLM,1), new Object[] {"FCF","TLT","FDF",Character.valueOf('D'), ItemShardPickR, Character.valueOf('F'), EntangleCraftBlocks.BlockFObsidian,Character.valueOf('L'), ItemLambdaCore, Character.valueOf('C'), ItemCircuit, Character.valueOf('T'), ItemTransmitter});
GameRegistry.addRecipe(new ItemStack(EntangleCraftBlocks.BlockYLM,1), new Object[] {"FCF","TLT","FDF",Character.valueOf('D'), ItemShardPickY, Character.valueOf('F'), EntangleCraftBlocks.BlockFObsidian,Character.valueOf('L'), ItemLambdaCore, Character.valueOf('C'), ItemCircuit, Character.valueOf('T'), ItemTransmitter});
GameRegistry.addRecipe(new ItemStack(EntangleCraftBlocks.BlockBLM,1), new Object[] {"FCF","TLT","FDF",Character.valueOf('D'), ItemShardPickB, Character.valueOf('F'), EntangleCraftBlocks.BlockFObsidian,Character.valueOf('L'), ItemLambdaCore, Character.valueOf('C'), ItemCircuit, Character.valueOf('T'), ItemTransmitter});
GameRegistry.addRecipe(new ItemStack(ItemInclusiveFilter,1), new Object[] {"GTG","GCG","GTG", Character.valueOf('G'), Block.glass, Character.valueOf('C'),ItemCircuit,Character.valueOf('T'), ItemTransmitter});
GameRegistry.addRecipe(new ItemStack(ItemExclusiveFilter,1), new Object[] {"GGG","TCT","GGG", Character.valueOf('G'), Block.glass, Character.valueOf('C'),ItemCircuit,Character.valueOf('T'), ItemTransmitter});
- GameRegistry.addRecipe(new ItemStack(ItemDestroyFilter,1), new Object[] {"GTG","GCG","GRG", Character.valueOf('G'), Block.glass, Character.valueOf('C'), ItemCircuit,Character.valueOf('T'), ItemTransmitter, Character.valueOf('R'), Item.redstone});
- GameRegistry.addRecipe(new ItemStack(ItemDestroyFilter,1), new Object[] {"GRG","GCG","GTG", Character.valueOf('G'), Block.glass, Character.valueOf('C'), ItemCircuit,Character.valueOf('T'), ItemTransmitter, Character.valueOf('R'), Item.redstone});
+ GameRegistry.addRecipe(new ItemStack(ItemDestroyFilter,1), new Object[] {"GTG","GCG","GRG", Character.valueOf('G'), Block.glass, Character.valueOf('C'), ItemCircuit,Character.valueOf('T'), ItemTransmitter, Character.valueOf('R'), new ItemStack(Block.torchRedstoneActive,1)});
+ GameRegistry.addRecipe(new ItemStack(ItemDontDestroyFilter,1), new Object[] {"GRG","GCG","GTG", Character.valueOf('G'), Block.glass, Character.valueOf('C'), ItemCircuit,Character.valueOf('T'), ItemTransmitter, Character.valueOf('R'), new ItemStack(Block.torchRedstoneActive,1)});
GameRegistry.addShapelessRecipe(new ItemStack(ItemFrShard,1), new Object[]{Block.obsidian}); // THIS RECIPE IS TEMPORARY, SHOULD BE BlockFObsidian AFTER WORLD GENEREATION RE-IMPLEMENTED AND SHOULD GRANT 8 INSTEAD OF 1
GameRegistry.addShapelessRecipe(new ItemStack(ItemRedShard,1), new Object[]{ItemFrShard,Item.redstone});
GameRegistry.addShapelessRecipe(new ItemStack(ItemYelShard,1), new Object[]{ItemFrShard,Item.lightStoneDust});
GameRegistry.addShapelessRecipe(new ItemStack(ItemBlueShard,1), new Object[]{ItemFrShard,new ItemStack(Item.dyePowder,1,4)});
GameRegistry.addShapelessRecipe(new ItemStack(ItemImbuedShard), new Object[]{ItemYelShard,ItemBlueShard,ItemRedShard});
GameRegistry.addShapelessRecipe(new ItemStack(ItemTPScroll,8), new Object[]{Item.enderPearl,Item.spiderEye,Item.gunpowder,Item.bone,Item.paper});
GameRegistry.addShapelessRecipe(new ItemStack(ItemShardPickG), new Object[] {Item.pickaxeDiamond, ItemDeviceG});
GameRegistry.addShapelessRecipe(new ItemStack(ItemShardPickR), new Object[] {Item.pickaxeDiamond, ItemDeviceR});
GameRegistry.addShapelessRecipe(new ItemStack(ItemShardPickY), new Object[] {Item.pickaxeDiamond, ItemDeviceY});
GameRegistry.addShapelessRecipe(new ItemStack(ItemShardPickB), new Object[] {Item.pickaxeDiamond, ItemDeviceB});
}
private static void itemInitializing()
{
Item[] availableChannelsDevices = new Item[] {
EntangleCraftItems.ItemDeviceG,
EntangleCraftItems.ItemDeviceR,
EntangleCraftItems.ItemDeviceY,
EntangleCraftItems.ItemDeviceB};
Item[] availableChannelsPicks = new Item[] {EntangleCraftItems.ItemShardPickG,
EntangleCraftItems.ItemShardPickR,
EntangleCraftItems.ItemShardPickY,
EntangleCraftItems.ItemShardPickB};
Item[][] classOfChannel = new Item[][] {availableChannelsDevices, availableChannelsPicks};
for(Object obj : classOfChannel)
{
Item[] thisClassOfChannels = (Item[])obj;
int i = 0;
for(Object o : thisClassOfChannels)
{
IChanneled thisItemChanneled = (IChanneled)o;
thisItemChanneled.setAvailableChannels(thisClassOfChannels);
thisItemChanneled.setChannel(i);
i += 1;
}
}
}
}
| true | true | public static void addItems(){
itemInitializing();
LanguageRegistry.addName(ItemDeviceG, "Lambda Device : G");
LanguageRegistry.addName(ItemDeviceR, "Lambda Device : R");
LanguageRegistry.addName(ItemDeviceY, "Lambda Device : Y");
LanguageRegistry.addName(ItemDeviceB, "Lambda Device : B");
LanguageRegistry.addName(ItemLambdaCore, "Lambda Core");
LanguageRegistry.addName(ItemNetherEssence, "Nethermonic Essence");
LanguageRegistry.addName(ItemNethermonicDiamond, "Nethermonic Diamond");
LanguageRegistry.addName(ItemTransformer, "Displacement Flat-rate Transformer");
LanguageRegistry.addName(ItemReverseTransformer, "Entanglement Flat-rate Transformer");
LanguageRegistry.addName(ItemTransmitter,"Transmitter");
LanguageRegistry.addName(ItemInductionCircuit, "Induction Circuit");
LanguageRegistry.addName(ItemSuperInductionCircuit, "Forerunner Induction Circuit");
LanguageRegistry.addName(ItemFrShard, "Forerunner Obsidian Shard");
LanguageRegistry.addName(ItemBlueShard, "Mysterious Blue Shard");
LanguageRegistry.addName(ItemRedShard, "Mysterious Red Shard");
LanguageRegistry.addName(ItemYelShard, "Mysterious Yellow Shard");
LanguageRegistry.addName(ItemImbuedShard, "Legendary Tri-Shard");
LanguageRegistry.addName(ItemCircuit,"Circuit");
LanguageRegistry.addName(ItemInclusiveFilter,"'Mine only x' Filter Device");
LanguageRegistry.addName(ItemExclusiveFilter, "Exclusive Filter Device");
LanguageRegistry.addName(ItemDestroyFilter, "'Destroy x' Filter Device");
LanguageRegistry.addName(ItemDontDestroyFilter, "'Do not destroy x' Filter Device");
LanguageRegistry.addName(ItemTPScroll, "TP Scroll");
LanguageRegistry.addName(ItemShardPickG, "Displacement Pick : G");
LanguageRegistry.addName(ItemShardPickR, "Displacement Pick : R");
LanguageRegistry.addName(ItemShardPickY, "Displacement Pick : Y");
LanguageRegistry.addName(ItemShardPickB, "Displacement Pick : B");
GameRegistry.addSmelting(Block.netherrack.blockID, new ItemStack(ItemNetherEssence, 1),1F);
GameRegistry.addRecipe(new ItemStack(EntangleCraftBlocks.BlockRLD, 1), new Object[] { "NRN", "NGN", "NDN", Character.valueOf('D'), ItemNethermonicDiamond, Character.valueOf('N'), ItemNetherEssence, Character.valueOf('G'), EntangleCraftBlocks.BlockGLD, Character.valueOf('R'), Item.redstone });
GameRegistry.addRecipe(new ItemStack(EntangleCraftBlocks.BlockYLD, 1), new Object[] { "NSN", "NGN", "NDN", Character.valueOf('D'), ItemNethermonicDiamond, Character.valueOf('N'), ItemNetherEssence, Character.valueOf('G'), EntangleCraftBlocks.BlockGLD, Character.valueOf('S'), Item.lightStoneDust });
GameRegistry.addRecipe(new ItemStack(EntangleCraftBlocks.BlockBLD, 1), new Object[] { "NSN", "NGN", "NDN", Character.valueOf('D'), ItemNethermonicDiamond, Character.valueOf('N'), ItemNetherEssence, Character.valueOf('G'), EntangleCraftBlocks.BlockGLD, Character.valueOf('S'), new ItemStack(Item.dyePowder, 1, 4) });
GameRegistry.addRecipe(new ItemStack(EntangleCraftBlocks.BlockFObsidian,8), new Object[] {"OOO","OSO","OOO", Character.valueOf('O'),Block.obsidian, Character.valueOf('S'),ItemFrShard});
GameRegistry.addRecipe(new ItemStack(ItemDeviceG, 1), new Object[] { "SOO", "OLO", "OXO", Character.valueOf('O'), Block.obsidian, Character.valueOf('L'), ItemLambdaCore, Character.valueOf('S'), Item.lightStoneDust, Character.valueOf('X'), Item.map});
GameRegistry.addRecipe(new ItemStack(EntangleCraftBlocks.BlockGLD, 1), new Object[] { "FFF", "FLF", "FFF", Character.valueOf('F'), Block.obsidian, Character.valueOf('L'), ItemLambdaCore });
//GameRegistry.addRecipe(new ItemStack(EntangleCraftBlocks.BlockGenericDestination, 1), new Object[] { " D"," ", " ", Character.valueOf('D'), Block.dirt});
GameRegistry.addRecipe(new ItemStack(ItemNethermonicDiamond, 1), new Object[] { "NNN", "NDN", "NNN", Character.valueOf('N'), ItemNetherEssence, Character.valueOf('D'), Item.diamond });
GameRegistry.addRecipe(new ItemStack(ItemNethermonicDiamond,12), new Object[] {"DDD","DID","DDD", Character.valueOf('D'), ItemNethermonicDiamond, Character.valueOf('I'), ItemImbuedShard});
GameRegistry.addRecipe(new ItemStack(ItemLambdaCore, 1), new Object[] { "FBF", "SNS", "FBF", Character.valueOf('S'), Item.lightStoneDust, Character.valueOf('F'), Block.obsidian, Character.valueOf('N'), ItemNethermonicDiamond, Character.valueOf('B'), new ItemStack(Item.dyePowder, 1, 4) });
GameRegistry.addRecipe(new ItemStack(ItemTransformer, 1), new Object[] { "RNL", "NIN", "GNR", Character.valueOf('N'), ItemNetherEssence, Character.valueOf('R'), Item.redstone, Character.valueOf('L'), new ItemStack(Item.dyePowder, 1, 4), Character.valueOf('G'), Item.lightStoneDust, Character.valueOf('I'), Item.ingotIron });
GameRegistry.addRecipe(new ItemStack(ItemReverseTransformer, 1), new Object[] { "NLN", "RIR", "NGN", Character.valueOf('N'), ItemNetherEssence, Character.valueOf('R'), Item.redstone, Character.valueOf('L'), new ItemStack(Item.dyePowder, 1, 4), Character.valueOf('G'), Item.lightStoneDust, Character.valueOf('I'), Item.ingotIron });
GameRegistry.addRecipe(new ItemStack(ItemTransmitter,1), new Object[] {"IBI","ICI","INI", Character.valueOf('I'), Item.ingotIron,Character.valueOf('B'), new ItemStack(Item.dyePowder,1,4), Character.valueOf('N'),Item.compass, Character.valueOf('C'),ItemCircuit});
GameRegistry.addRecipe(new ItemStack(ItemCircuit,1), new Object[] {"FIF","ISI","FIF", Character.valueOf('F'), ItemFrShard,Character.valueOf('I'), Item.ingotIron, Character.valueOf('S'), ItemImbuedShard});
GameRegistry.addRecipe(new ItemStack(ItemInductionCircuit,1), new Object[] {"IRI","ISI"," C ", Character.valueOf('C'), ItemCircuit, Character.valueOf('I'), Item.ingotIron, Character.valueOf('R'), Item.redstone, Character.valueOf('S'),ItemFrShard});
GameRegistry.addRecipe(new ItemStack(ItemSuperInductionCircuit,1), new Object[] {"FDF","FDF"," I ", Character.valueOf('F'), EntangleCraftBlocks.BlockFObsidian, Character.valueOf('D'), Item.diamond, Character.valueOf('I'), ItemInductionCircuit});
GameRegistry.addRecipe(new ItemStack(EntangleCraftBlocks.BlockGLM,1), new Object[] {"FCF","TLT","FDF",Character.valueOf('D'), ItemShardPickG, Character.valueOf('F'), EntangleCraftBlocks.BlockFObsidian,Character.valueOf('L'), ItemLambdaCore, Character.valueOf('C'), ItemCircuit, Character.valueOf('T'), ItemTransmitter});
GameRegistry.addRecipe(new ItemStack(EntangleCraftBlocks.BlockRLM,1), new Object[] {"FCF","TLT","FDF",Character.valueOf('D'), ItemShardPickR, Character.valueOf('F'), EntangleCraftBlocks.BlockFObsidian,Character.valueOf('L'), ItemLambdaCore, Character.valueOf('C'), ItemCircuit, Character.valueOf('T'), ItemTransmitter});
GameRegistry.addRecipe(new ItemStack(EntangleCraftBlocks.BlockYLM,1), new Object[] {"FCF","TLT","FDF",Character.valueOf('D'), ItemShardPickY, Character.valueOf('F'), EntangleCraftBlocks.BlockFObsidian,Character.valueOf('L'), ItemLambdaCore, Character.valueOf('C'), ItemCircuit, Character.valueOf('T'), ItemTransmitter});
GameRegistry.addRecipe(new ItemStack(EntangleCraftBlocks.BlockBLM,1), new Object[] {"FCF","TLT","FDF",Character.valueOf('D'), ItemShardPickB, Character.valueOf('F'), EntangleCraftBlocks.BlockFObsidian,Character.valueOf('L'), ItemLambdaCore, Character.valueOf('C'), ItemCircuit, Character.valueOf('T'), ItemTransmitter});
GameRegistry.addRecipe(new ItemStack(ItemInclusiveFilter,1), new Object[] {"GTG","GCG","GTG", Character.valueOf('G'), Block.glass, Character.valueOf('C'),ItemCircuit,Character.valueOf('T'), ItemTransmitter});
GameRegistry.addRecipe(new ItemStack(ItemExclusiveFilter,1), new Object[] {"GGG","TCT","GGG", Character.valueOf('G'), Block.glass, Character.valueOf('C'),ItemCircuit,Character.valueOf('T'), ItemTransmitter});
GameRegistry.addRecipe(new ItemStack(ItemDestroyFilter,1), new Object[] {"GTG","GCG","GRG", Character.valueOf('G'), Block.glass, Character.valueOf('C'), ItemCircuit,Character.valueOf('T'), ItemTransmitter, Character.valueOf('R'), Item.redstone});
GameRegistry.addRecipe(new ItemStack(ItemDestroyFilter,1), new Object[] {"GRG","GCG","GTG", Character.valueOf('G'), Block.glass, Character.valueOf('C'), ItemCircuit,Character.valueOf('T'), ItemTransmitter, Character.valueOf('R'), Item.redstone});
GameRegistry.addShapelessRecipe(new ItemStack(ItemFrShard,1), new Object[]{Block.obsidian}); // THIS RECIPE IS TEMPORARY, SHOULD BE BlockFObsidian AFTER WORLD GENEREATION RE-IMPLEMENTED AND SHOULD GRANT 8 INSTEAD OF 1
GameRegistry.addShapelessRecipe(new ItemStack(ItemRedShard,1), new Object[]{ItemFrShard,Item.redstone});
GameRegistry.addShapelessRecipe(new ItemStack(ItemYelShard,1), new Object[]{ItemFrShard,Item.lightStoneDust});
GameRegistry.addShapelessRecipe(new ItemStack(ItemBlueShard,1), new Object[]{ItemFrShard,new ItemStack(Item.dyePowder,1,4)});
GameRegistry.addShapelessRecipe(new ItemStack(ItemImbuedShard), new Object[]{ItemYelShard,ItemBlueShard,ItemRedShard});
GameRegistry.addShapelessRecipe(new ItemStack(ItemTPScroll,8), new Object[]{Item.enderPearl,Item.spiderEye,Item.gunpowder,Item.bone,Item.paper});
GameRegistry.addShapelessRecipe(new ItemStack(ItemShardPickG), new Object[] {Item.pickaxeDiamond, ItemDeviceG});
GameRegistry.addShapelessRecipe(new ItemStack(ItemShardPickR), new Object[] {Item.pickaxeDiamond, ItemDeviceR});
GameRegistry.addShapelessRecipe(new ItemStack(ItemShardPickY), new Object[] {Item.pickaxeDiamond, ItemDeviceY});
GameRegistry.addShapelessRecipe(new ItemStack(ItemShardPickB), new Object[] {Item.pickaxeDiamond, ItemDeviceB});
}
| public static void addItems(){
itemInitializing();
LanguageRegistry.addName(ItemDeviceG, "Lambda Device : G");
LanguageRegistry.addName(ItemDeviceR, "Lambda Device : R");
LanguageRegistry.addName(ItemDeviceY, "Lambda Device : Y");
LanguageRegistry.addName(ItemDeviceB, "Lambda Device : B");
LanguageRegistry.addName(ItemLambdaCore, "Lambda Core");
LanguageRegistry.addName(ItemNetherEssence, "Nethermonic Essence");
LanguageRegistry.addName(ItemNethermonicDiamond, "Nethermonic Diamond");
LanguageRegistry.addName(ItemTransformer, "Displacement Flat-rate Transformer");
LanguageRegistry.addName(ItemReverseTransformer, "Entanglement Flat-rate Transformer");
LanguageRegistry.addName(ItemTransmitter,"Transmitter");
LanguageRegistry.addName(ItemInductionCircuit, "Induction Circuit");
LanguageRegistry.addName(ItemSuperInductionCircuit, "Forerunner Induction Circuit");
LanguageRegistry.addName(ItemFrShard, "Forerunner Obsidian Shard");
LanguageRegistry.addName(ItemBlueShard, "Mysterious Blue Shard");
LanguageRegistry.addName(ItemRedShard, "Mysterious Red Shard");
LanguageRegistry.addName(ItemYelShard, "Mysterious Yellow Shard");
LanguageRegistry.addName(ItemImbuedShard, "Legendary Tri-Shard");
LanguageRegistry.addName(ItemCircuit,"Circuit");
LanguageRegistry.addName(ItemInclusiveFilter,"'Mine only x' Filter Device");
LanguageRegistry.addName(ItemExclusiveFilter, "Exclusive Filter Device");
LanguageRegistry.addName(ItemDestroyFilter, "'Destroy x' Filter Device");
LanguageRegistry.addName(ItemDontDestroyFilter, "'Do not destroy x' Filter Device");
LanguageRegistry.addName(ItemTPScroll, "TP Scroll");
LanguageRegistry.addName(ItemShardPickG, "Displacement Pick : G");
LanguageRegistry.addName(ItemShardPickR, "Displacement Pick : R");
LanguageRegistry.addName(ItemShardPickY, "Displacement Pick : Y");
LanguageRegistry.addName(ItemShardPickB, "Displacement Pick : B");
GameRegistry.addSmelting(Block.netherrack.blockID, new ItemStack(ItemNetherEssence, 1),1F);
GameRegistry.addRecipe(new ItemStack(EntangleCraftBlocks.BlockRLD, 1), new Object[] { "NRN", "NGN", "NDN", Character.valueOf('D'), ItemNethermonicDiamond, Character.valueOf('N'), ItemNetherEssence, Character.valueOf('G'), EntangleCraftBlocks.BlockGLD, Character.valueOf('R'), Item.redstone });
GameRegistry.addRecipe(new ItemStack(EntangleCraftBlocks.BlockYLD, 1), new Object[] { "NSN", "NGN", "NDN", Character.valueOf('D'), ItemNethermonicDiamond, Character.valueOf('N'), ItemNetherEssence, Character.valueOf('G'), EntangleCraftBlocks.BlockGLD, Character.valueOf('S'), Item.lightStoneDust });
GameRegistry.addRecipe(new ItemStack(EntangleCraftBlocks.BlockBLD, 1), new Object[] { "NSN", "NGN", "NDN", Character.valueOf('D'), ItemNethermonicDiamond, Character.valueOf('N'), ItemNetherEssence, Character.valueOf('G'), EntangleCraftBlocks.BlockGLD, Character.valueOf('S'), new ItemStack(Item.dyePowder, 1, 4) });
GameRegistry.addRecipe(new ItemStack(EntangleCraftBlocks.BlockFObsidian,8), new Object[] {"OOO","OSO","OOO", Character.valueOf('O'),Block.obsidian, Character.valueOf('S'),ItemFrShard});
GameRegistry.addRecipe(new ItemStack(ItemDeviceG, 1), new Object[] { "SOO", "OLO", "OXO", Character.valueOf('O'), Block.obsidian, Character.valueOf('L'), ItemLambdaCore, Character.valueOf('S'), Item.lightStoneDust, Character.valueOf('X'), Item.map});
GameRegistry.addRecipe(new ItemStack(EntangleCraftBlocks.BlockGLD, 1), new Object[] { "FFF", "FLF", "FFF", Character.valueOf('F'), Block.obsidian, Character.valueOf('L'), ItemLambdaCore });
//GameRegistry.addRecipe(new ItemStack(EntangleCraftBlocks.BlockGenericDestination, 1), new Object[] { " D"," ", " ", Character.valueOf('D'), Block.dirt});
GameRegistry.addRecipe(new ItemStack(ItemNethermonicDiamond, 1), new Object[] { "NNN", "NDN", "NNN", Character.valueOf('N'), ItemNetherEssence, Character.valueOf('D'), Item.diamond });
GameRegistry.addRecipe(new ItemStack(ItemNethermonicDiamond,12), new Object[] {"DDD","DID","DDD", Character.valueOf('D'), ItemNethermonicDiamond, Character.valueOf('I'), ItemImbuedShard});
GameRegistry.addRecipe(new ItemStack(ItemLambdaCore, 1), new Object[] { "FBF", "SNS", "FBF", Character.valueOf('S'), Item.lightStoneDust, Character.valueOf('F'), Block.obsidian, Character.valueOf('N'), ItemNethermonicDiamond, Character.valueOf('B'), new ItemStack(Item.dyePowder, 1, 4) });
GameRegistry.addRecipe(new ItemStack(ItemTransformer, 1), new Object[] { "RNL", "NIN", "GNR", Character.valueOf('N'), ItemNetherEssence, Character.valueOf('R'), Item.redstone, Character.valueOf('L'), new ItemStack(Item.dyePowder, 1, 4), Character.valueOf('G'), Item.lightStoneDust, Character.valueOf('I'), Item.ingotIron });
GameRegistry.addRecipe(new ItemStack(ItemReverseTransformer, 1), new Object[] { "NLN", "RIR", "NGN", Character.valueOf('N'), ItemNetherEssence, Character.valueOf('R'), Item.redstone, Character.valueOf('L'), new ItemStack(Item.dyePowder, 1, 4), Character.valueOf('G'), Item.lightStoneDust, Character.valueOf('I'), Item.ingotIron });
GameRegistry.addRecipe(new ItemStack(ItemTransmitter,1), new Object[] {"IBI","ICI","INI", Character.valueOf('I'), Item.ingotIron,Character.valueOf('B'), new ItemStack(Item.dyePowder,1,4), Character.valueOf('N'),Item.compass, Character.valueOf('C'),ItemCircuit});
GameRegistry.addRecipe(new ItemStack(ItemCircuit,1), new Object[] {"FIF","ISI","FIF", Character.valueOf('F'), ItemFrShard,Character.valueOf('I'), Item.ingotIron, Character.valueOf('S'), ItemImbuedShard});
GameRegistry.addRecipe(new ItemStack(ItemInductionCircuit,1), new Object[] {"IRI","ISI"," C ", Character.valueOf('C'), ItemCircuit, Character.valueOf('I'), Item.ingotIron, Character.valueOf('R'), Item.redstone, Character.valueOf('S'),ItemFrShard});
GameRegistry.addRecipe(new ItemStack(ItemSuperInductionCircuit,1), new Object[] {"FDF","FDF"," I ", Character.valueOf('F'), EntangleCraftBlocks.BlockFObsidian, Character.valueOf('D'), Item.diamond, Character.valueOf('I'), ItemInductionCircuit});
GameRegistry.addRecipe(new ItemStack(EntangleCraftBlocks.BlockGLM,1), new Object[] {"FCF","TLT","FDF",Character.valueOf('D'), ItemShardPickG, Character.valueOf('F'), EntangleCraftBlocks.BlockFObsidian,Character.valueOf('L'), ItemLambdaCore, Character.valueOf('C'), ItemCircuit, Character.valueOf('T'), ItemTransmitter});
GameRegistry.addRecipe(new ItemStack(EntangleCraftBlocks.BlockRLM,1), new Object[] {"FCF","TLT","FDF",Character.valueOf('D'), ItemShardPickR, Character.valueOf('F'), EntangleCraftBlocks.BlockFObsidian,Character.valueOf('L'), ItemLambdaCore, Character.valueOf('C'), ItemCircuit, Character.valueOf('T'), ItemTransmitter});
GameRegistry.addRecipe(new ItemStack(EntangleCraftBlocks.BlockYLM,1), new Object[] {"FCF","TLT","FDF",Character.valueOf('D'), ItemShardPickY, Character.valueOf('F'), EntangleCraftBlocks.BlockFObsidian,Character.valueOf('L'), ItemLambdaCore, Character.valueOf('C'), ItemCircuit, Character.valueOf('T'), ItemTransmitter});
GameRegistry.addRecipe(new ItemStack(EntangleCraftBlocks.BlockBLM,1), new Object[] {"FCF","TLT","FDF",Character.valueOf('D'), ItemShardPickB, Character.valueOf('F'), EntangleCraftBlocks.BlockFObsidian,Character.valueOf('L'), ItemLambdaCore, Character.valueOf('C'), ItemCircuit, Character.valueOf('T'), ItemTransmitter});
GameRegistry.addRecipe(new ItemStack(ItemInclusiveFilter,1), new Object[] {"GTG","GCG","GTG", Character.valueOf('G'), Block.glass, Character.valueOf('C'),ItemCircuit,Character.valueOf('T'), ItemTransmitter});
GameRegistry.addRecipe(new ItemStack(ItemExclusiveFilter,1), new Object[] {"GGG","TCT","GGG", Character.valueOf('G'), Block.glass, Character.valueOf('C'),ItemCircuit,Character.valueOf('T'), ItemTransmitter});
GameRegistry.addRecipe(new ItemStack(ItemDestroyFilter,1), new Object[] {"GTG","GCG","GRG", Character.valueOf('G'), Block.glass, Character.valueOf('C'), ItemCircuit,Character.valueOf('T'), ItemTransmitter, Character.valueOf('R'), new ItemStack(Block.torchRedstoneActive,1)});
GameRegistry.addRecipe(new ItemStack(ItemDontDestroyFilter,1), new Object[] {"GRG","GCG","GTG", Character.valueOf('G'), Block.glass, Character.valueOf('C'), ItemCircuit,Character.valueOf('T'), ItemTransmitter, Character.valueOf('R'), new ItemStack(Block.torchRedstoneActive,1)});
GameRegistry.addShapelessRecipe(new ItemStack(ItemFrShard,1), new Object[]{Block.obsidian}); // THIS RECIPE IS TEMPORARY, SHOULD BE BlockFObsidian AFTER WORLD GENEREATION RE-IMPLEMENTED AND SHOULD GRANT 8 INSTEAD OF 1
GameRegistry.addShapelessRecipe(new ItemStack(ItemRedShard,1), new Object[]{ItemFrShard,Item.redstone});
GameRegistry.addShapelessRecipe(new ItemStack(ItemYelShard,1), new Object[]{ItemFrShard,Item.lightStoneDust});
GameRegistry.addShapelessRecipe(new ItemStack(ItemBlueShard,1), new Object[]{ItemFrShard,new ItemStack(Item.dyePowder,1,4)});
GameRegistry.addShapelessRecipe(new ItemStack(ItemImbuedShard), new Object[]{ItemYelShard,ItemBlueShard,ItemRedShard});
GameRegistry.addShapelessRecipe(new ItemStack(ItemTPScroll,8), new Object[]{Item.enderPearl,Item.spiderEye,Item.gunpowder,Item.bone,Item.paper});
GameRegistry.addShapelessRecipe(new ItemStack(ItemShardPickG), new Object[] {Item.pickaxeDiamond, ItemDeviceG});
GameRegistry.addShapelessRecipe(new ItemStack(ItemShardPickR), new Object[] {Item.pickaxeDiamond, ItemDeviceR});
GameRegistry.addShapelessRecipe(new ItemStack(ItemShardPickY), new Object[] {Item.pickaxeDiamond, ItemDeviceY});
GameRegistry.addShapelessRecipe(new ItemStack(ItemShardPickB), new Object[] {Item.pickaxeDiamond, ItemDeviceB});
}
|
diff --git a/src/main/java/org/sagebionetworks/web/server/servlet/SynapseClientImpl.java b/src/main/java/org/sagebionetworks/web/server/servlet/SynapseClientImpl.java
index 201213f87..7ba1e124f 100644
--- a/src/main/java/org/sagebionetworks/web/server/servlet/SynapseClientImpl.java
+++ b/src/main/java/org/sagebionetworks/web/server/servlet/SynapseClientImpl.java
@@ -1,906 +1,905 @@
package org.sagebionetworks.web.server.servlet;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.logging.Logger;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONException;
import org.json.JSONObject;
import org.sagebionetworks.client.Synapse;
import org.sagebionetworks.client.exceptions.SynapseException;
import org.sagebionetworks.repo.model.ACCESS_TYPE;
import org.sagebionetworks.repo.model.AccessApproval;
import org.sagebionetworks.repo.model.AccessControlList;
import org.sagebionetworks.repo.model.AccessRequirement;
import org.sagebionetworks.repo.model.Annotations;
import org.sagebionetworks.repo.model.AutoGenFactory;
import org.sagebionetworks.repo.model.BatchResults;
import org.sagebionetworks.repo.model.Entity;
import org.sagebionetworks.repo.model.EntityBundle;
import org.sagebionetworks.repo.model.EntityHeader;
import org.sagebionetworks.repo.model.EntityPath;
import org.sagebionetworks.repo.model.EntityType;
import org.sagebionetworks.repo.model.Locationable;
import org.sagebionetworks.repo.model.PaginatedResults;
import org.sagebionetworks.repo.model.UserGroup;
import org.sagebionetworks.repo.model.UserGroupHeaderResponsePage;
import org.sagebionetworks.repo.model.UserProfile;
import org.sagebionetworks.repo.model.VariableContentPaginatedResults;
import org.sagebionetworks.repo.model.VersionInfo;
import org.sagebionetworks.repo.model.attachment.AttachmentData;
import org.sagebionetworks.repo.model.attachment.PresignedUrl;
import org.sagebionetworks.repo.model.auth.UserEntityPermissions;
import org.sagebionetworks.repo.model.search.SearchResults;
import org.sagebionetworks.repo.model.search.query.SearchQuery;
import org.sagebionetworks.repo.model.storage.StorageUsage;
import org.sagebionetworks.schema.adapter.AdapterFactory;
import org.sagebionetworks.schema.adapter.JSONArrayAdapter;
import org.sagebionetworks.schema.adapter.JSONEntity;
import org.sagebionetworks.schema.adapter.JSONObjectAdapter;
import org.sagebionetworks.schema.adapter.JSONObjectAdapterException;
import org.sagebionetworks.schema.adapter.org.json.AdapterFactoryImpl;
import org.sagebionetworks.schema.adapter.org.json.EntityFactory;
import org.sagebionetworks.schema.adapter.org.json.JSONArrayAdapterImpl;
import org.sagebionetworks.schema.adapter.org.json.JSONObjectAdapterImpl;
import org.sagebionetworks.web.client.DisplayConstants;
import org.sagebionetworks.web.client.SynapseClient;
import org.sagebionetworks.web.client.transform.JSONEntityFactory;
import org.sagebionetworks.web.client.transform.JSONEntityFactoryImpl;
import org.sagebionetworks.web.server.ServerMarkdownUtils;
import org.sagebionetworks.web.shared.AccessRequirementsTransport;
import org.sagebionetworks.web.shared.EntityBundleTransport;
import org.sagebionetworks.web.shared.EntityConstants;
import org.sagebionetworks.web.shared.EntityWrapper;
import org.sagebionetworks.web.shared.SerializableWhitelist;
import org.sagebionetworks.web.shared.exceptions.BadRequestException;
import org.sagebionetworks.web.shared.exceptions.ExceptionUtil;
import org.sagebionetworks.web.shared.exceptions.RestServiceException;
import org.sagebionetworks.web.shared.exceptions.UnknownErrorException;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.google.inject.Inject;
import com.petebevin.markdown.MarkdownProcessor;
@SuppressWarnings("serial")
public class SynapseClientImpl extends RemoteServiceServlet implements
SynapseClient, TokenProvider {
static private Log log = LogFactory.getLog(SynapseClientImpl.class);
@SuppressWarnings("unused")
private static Logger logger = Logger.getLogger(SynapseClientImpl.class
.getName());
private TokenProvider tokenProvider = this;
AdapterFactory adapterFactory = new AdapterFactoryImpl();
AutoGenFactory entityFactory = new AutoGenFactory();
MarkdownProcessor markdownProcessor = new MarkdownProcessor();
/**
* Injected with Gin
*/
private ServiceUrlProvider urlProvider;
/**
* Essentially the constructor. Setup synapse client.
*
* @param provider
*/
@Inject
public void setServiceUrlProvider(ServiceUrlProvider provider) {
this.urlProvider = provider;
}
/**
* Injected with Gin
*/
private SynapseProvider synapseProvider = new SynapseProviderImpl();
/**
* This allows tests provide mock Synapse ojbects
*
* @param provider
*/
public void setSynapseProvider(SynapseProvider provider) {
this.synapseProvider = provider;
}
/**
* This allows integration tests to override the token provider.
*
* @param tokenProvider
*/
public void setTokenProvider(TokenProvider tokenProvider) {
this.tokenProvider = tokenProvider;
}
/**
* Validate that the service is ready to go. If any of the injected data is
* missing then it cannot run. Public for tests.
*/
public void validateService() {
if (synapseProvider == null)
throw new IllegalStateException("The SynapseProvider was not set");
if (tokenProvider == null) {
throw new IllegalStateException("The token provider was not set");
}
}
@Override
public String getSessionToken() {
// By default, we get the token from the request cookies.
return UserDataProvider.getThreadLocalUserToken(this
.getThreadLocalRequest());
}
/*
* SynapseClient Service Methods
*/
/**
* Get an Entity by its id
*/
@Override
public EntityWrapper getEntity(String entityId) {
return getEntityForVersion(entityId, null);
}
@Override
public EntityWrapper getEntityForVersion(String entityId, Long versionNumber) {
Synapse synapseClient = createSynapseClient();
try {
Entity entity;
if(versionNumber == null) {
entity = synapseClient.getEntityById(entityId);
} else {
entity = synapseClient.getEntityByIdForVersion(entityId, versionNumber);
}
JSONObjectAdapter entityJson = entity
.writeToJSONObject(adapterFactory.createNew());
return new EntityWrapper(entityJson.toJSONString(), entity
.getClass().getName(), null);
} catch (SynapseException e) {
// Since we are not throwing errors, log them
log.error(e);
return new EntityWrapper(null, null,
ExceptionUtil.convertSynapseException(e));
} catch (JSONObjectAdapterException e) {
// Since we are not throwing errors, log them
log.error(e);
return new EntityWrapper(null, null, new UnknownErrorException(
e.getMessage()));
}
}
@Override
public EntityBundleTransport getEntityBundle(String entityId, int partsMask)
throws RestServiceException {
try {
Synapse synapseClient = createSynapseClient();
EntityBundle eb = synapseClient.getEntityBundle(entityId, partsMask);
return convertBundleToTransport(entityId, eb, partsMask);
} catch (SynapseException e) {
throw ExceptionUtil.convertSynapseException(e);
}
}
@Override
public EntityBundleTransport getEntityBundleForVersion(String entityId,
Long versionNumber, int partsMask) throws RestServiceException {
try {
Synapse synapseClient = createSynapseClient();
EntityBundle eb = synapseClient.getEntityBundle(entityId, versionNumber, partsMask);
return convertBundleToTransport(entityId, eb, partsMask);
} catch (SynapseException e) {
throw ExceptionUtil.convertSynapseException(e);
}
}
@Override
public String getEntityVersions(String entityId, int offset, int limit)
throws RestServiceException {
Synapse synapseClient = createSynapseClient();
try {
PaginatedResults<VersionInfo> versions = synapseClient.getEntityVersions(entityId, offset, limit);
JSONObjectAdapter entityJson = versions.writeToJSONObject(adapterFactory.createNew());
return entityJson.toJSONString();
} catch (SynapseException e) {
log.error(e);
throw ExceptionUtil.convertSynapseException(e);
} catch (JSONObjectAdapterException e) {
// Since we are not throwing errors, log them
log.error(e);
throw new UnknownErrorException(e.getMessage());
}
}
@Override
public String getEntityTypeRegistryJSON() {
return SynapseClientImpl.getEntityTypeRegistryJson();
}
@Override
public EntityWrapper getEntityPath(String entityId) {
Synapse synapseClient = createSynapseClient();
try {
EntityPath entityPath = synapseClient.getEntityPath(entityId);
JSONObjectAdapter entityPathJson = entityPath
.writeToJSONObject(adapterFactory.createNew());
return new EntityWrapper(entityPathJson.toJSONString(), entityPath
.getClass().getName(), null);
} catch (SynapseException e) {
return new EntityWrapper(null, null,
ExceptionUtil.convertSynapseException(e));
} catch (JSONObjectAdapterException e) {
// Since we are not throwing errors, log them
log.error(e);
return new EntityWrapper(null, null, new UnknownErrorException(
e.getMessage()));
}
}
@Override
public EntityWrapper search(String searchQueryJson) {
Synapse synapseClient = createSynapseClient();
try {
JSONObjectAdapter adapter = new JSONObjectAdapterImpl();
SearchResults searchResults = synapseClient.search(new SearchQuery(
adapter.createNew(searchQueryJson)));
searchResults.writeToJSONObject(adapter);
return new EntityWrapper(adapter.toJSONString(),
SearchResults.class.getName(), null);
} catch (SynapseException e) {
return new EntityWrapper(null, null,
ExceptionUtil.convertSynapseException(e));
} catch (JSONObjectAdapterException e) {
// Since we are not throwing errors, log them
log.error(e);
return new EntityWrapper(null, null, new UnknownErrorException(
e.getMessage()));
} catch (UnsupportedEncodingException e) {
// Since we are not throwing errors, log them
log.error(e);
return new EntityWrapper(null, null, new UnknownErrorException(
e.getMessage()));
}
}
@Override
public Long getStorageUsage(String entityId) throws RestServiceException{
//direct call to the Synapse Client (made available there)
Synapse synapseClient = createSynapseClient();
Long size = -1l;
try {
PaginatedResults<StorageUsage> usageResults = synapseClient.getItemizedStorageUsageForNode(entityId, 0, 1);
if (usageResults.getResults().size() > 0)
size = usageResults.getResults().get(0).getContentSize();
} catch (SynapseException e) {
log.error(e);
throw ExceptionUtil.convertSynapseException(e);
}
if (size < 0)
throw new RuntimeException(DisplayConstants.ENTITY_STORAGE_NOT_FOUND_ERROR + entityId);
return size;
}
/*
* Private Methods
*/
// Convert repo-side EntityBundle to serializable EntityBundleTransport
private EntityBundleTransport convertBundleToTransport(String entityId,
EntityBundle eb, int partsMask) throws RestServiceException {
EntityBundleTransport ebt = new EntityBundleTransport();
try {
if ((EntityBundleTransport.ENTITY & partsMask) > 0) {
Entity e = eb.getEntity();
ebt.setEntityJson(EntityFactory.createJSONStringForEntity(e));
}
if ((EntityBundleTransport.ANNOTATIONS & partsMask) > 0) {
Annotations a = eb.getAnnotations();
ebt.setAnnotationsJson(EntityFactory.createJSONStringForEntity(a));
}
if ((EntityBundleTransport.PERMISSIONS & partsMask) > 0) {
UserEntityPermissions uep = eb.getPermissions();
ebt.setPermissionsJson(EntityFactory.createJSONStringForEntity(uep));
}
if ((EntityBundleTransport.ENTITY_PATH & partsMask) > 0) {
EntityPath path = eb.getPath();
ebt.setEntityPathJson(EntityFactory.createJSONStringForEntity(path));
}
if ((EntityBundleTransport.ENTITY_REFERENCEDBY & partsMask) > 0) {
PaginatedResults<EntityHeader> rb = eb.getReferencedBy();
ebt.setEntityReferencedByJson(EntityFactory.createJSONStringForEntity(rb));
}
if ((EntityBundleTransport.HAS_CHILDREN & partsMask) > 0) {
Boolean hasChildren = eb.getHasChildren();
ebt.setHashChildren(hasChildren);
}
if ((EntityBundleTransport.ACL & partsMask) > 0) {
AccessControlList acl = eb.getAccessControlList();
if (acl == null) {
// ACL is inherited; fetch benefactor ACL.
try {
acl = getAcl(entityId);
} catch (SynapseException e) {
e.printStackTrace();
}
}
ebt.setAclJson(EntityFactory.createJSONStringForEntity(acl));
}
if ((EntityBundleTransport.ACCESS_REQUIREMENTS & partsMask)!=0) {
ebt.setAccessRequirementsJson(createJSONStringFromArray(eb.getAccessRequirements()));
}
if ((EntityBundleTransport.UNMET_ACCESS_REQUIREMENTS & partsMask)!=0) {
ebt.setUnmetAccessRequirementsJson(createJSONStringFromArray(eb.getUnmetAccessRequirements()));
}
} catch (JSONObjectAdapterException e) {
throw new UnknownErrorException(e.getMessage());
}
return ebt;
}
public static String createJSONStringFromArray(List<? extends JSONEntity> list) throws JSONObjectAdapterException {
JSONArrayAdapter aa = new JSONArrayAdapterImpl();
for (int i=0; i<list.size(); i++) {
JSONObjectAdapter oa = new JSONObjectAdapterImpl();
list.get(i).writeToJSONObject(oa);
aa.put(i, oa);
}
return aa.toJSONString();
}
/**
* The synapse client is stateful so we must create a new one for each
* request
*/
private Synapse createSynapseClient() {
// Create a new syanpse
Synapse synapseClient = synapseProvider.createNewClient();
synapseClient.setSessionToken(tokenProvider.getSessionToken());
synapseClient.setRepositoryEndpoint(urlProvider
.getRepositoryServiceUrl());
synapseClient.setAuthEndpoint(urlProvider.getPublicAuthBaseUrl());
return synapseClient;
}
/**
* Read an input stream into a string.
*
* @param in
* @return
* @throws IOException
*/
private static String readToString(InputStream in) throws IOException {
try {
BufferedInputStream bufferd = new BufferedInputStream(in);
byte[] buffer = new byte[1024];
StringBuilder builder = new StringBuilder();
int index = -1;
while ((index = bufferd.read(buffer, 0, buffer.length)) > 0) {
builder.append(new String(buffer, 0, index, "UTF-8"));
}
return builder.toString();
} finally {
in.close();
}
}
@Override
public SerializableWhitelist junk(SerializableWhitelist l) {
return null;
}
public static String getEntityTypeRegistryJson() {
ClassLoader classLoader = EntityType.class.getClassLoader();
InputStream in = classLoader
.getResourceAsStream(EntityType.REGISTER_JSON_FILE_NAME);
if (in == null)
throw new IllegalStateException("Cannot find the "
+ EntityType.REGISTER_JSON_FILE_NAME
+ " file on the classpath");
String jsonString = "";
try {
jsonString = readToString(in);
} catch (IOException e) {
log.error(e);
// error reading file
}
return jsonString;
}
private static final int USER_PAGINATION_OFFSET = 0;
// before we hit this limit we will use another mechanism to find users
private static final int USER_PAGINATION_LIMIT = 1000;
private static final int GROUPS_PAGINATION_OFFSET = 0;
// before we hit this limit we will use another mechanism to find groups
private static final int GROUPS_PAGINATION_LIMIT = 1000;
@Override
public String getEntityReferencedBy(String entityId)
throws RestServiceException {
try {
Synapse synapseClient = createSynapseClient();
PaginatedResults<EntityHeader> results = synapseClient
.getEntityReferencedBy(entityId, null);
return EntityFactory.createJSONStringForEntity(results);
} catch (SynapseException e) {
throw ExceptionUtil.convertSynapseException(e);
} catch (JSONObjectAdapterException e) {
throw new UnknownErrorException(e.getMessage());
}
}
@Override
public void logDebug(String message) {
log.debug(message);
}
@Override
public void logError(String message) {
log.error(message);
}
@Override
public void logInfo(String message) {
log.info(message);
}
@Override
public String getRepositoryServiceUrl() {
return urlProvider.getRepositoryServiceUrl();
}
/**
* Update entity
*/
@Override
public EntityWrapper updateEntity(String entityJson) throws RestServiceException {
try {
// update
Entity entity = parseEntityFromJson(entityJson);
Synapse synapseClient = createSynapseClient();
entity = synapseClient.putEntity(entity);
EntityWrapper wrapper = new EntityWrapper();
wrapper.setEntityClassName(entity.getClass().getName());
wrapper.setEntityJson(entity.writeToJSONObject(adapterFactory.createNew()).toJSONString());
return wrapper;
} catch (JSONObjectAdapterException e) {
throw new BadRequestException(e.getMessage());
} catch (SynapseException e) {
throw ExceptionUtil.convertSynapseException(e);
}
}
@Override
public String createOrUpdateEntity(String entityJson, String annoJson,
boolean isNew) throws RestServiceException {
// First read the entity
try {
Entity entity = parseEntityFromJson(entityJson);
Annotations annos = null;
if (annoJson != null) {
annos = EntityFactory.createEntityFromJSONString(annoJson,
Annotations.class);
}
return createOrUpdateEntity(entity, annos, isNew);
} catch (JSONObjectAdapterException e) {
throw new BadRequestException(e.getMessage());
}
}
/**
* Create or update an entity
*
* @param entity
* @param annos
* @param isNew
* @return
* @throws RestServiceException
*/
public String createOrUpdateEntity(Entity entity, Annotations annos,
boolean isNew) throws RestServiceException {
// First read the entity
try {
Synapse synapseClient = createSynapseClient();
if (isNew) {
// This is a create
entity = synapseClient.createEntity(entity);
} else {
// This is an update
entity = synapseClient.putEntity(entity);
}
// Update the annotations
if (annos != null) {
annos.setEtag(entity.getEtag());
annos.setId(entity.getId());
synapseClient.updateAnnotations(entity.getId(), annos);
}
return entity.getId();
} catch (SynapseException e) {
throw ExceptionUtil.convertSynapseException(e);
}
}
/**
* Parse an entity from its json.
*
* @param json
* @return
* @throws JSONObjectAdapterException
*/
public Entity parseEntityFromJson(String json)
throws JSONObjectAdapterException {
if (json == null)
throw new IllegalArgumentException("Entity cannot be null");
// Create an adapter
JSONObjectAdapter adapter = adapterFactory.createNew(json);
// Extrat the entity type.
if (!adapter.has(EntityConstants.ENTITY_TYPE)
|| adapter.isNull(EntityConstants.ENTITY_TYPE)) {
throw new IllegalArgumentException("JSON does not contain: "
+ EntityConstants.ENTITY_TYPE);
}
String entityType = adapter.getString(EntityConstants.ENTITY_TYPE);
Entity entity = (Entity) entityFactory.newInstance(entityType);
entity.initializeFromJSONObject(adapter);
return entity;
}
@Override
public String getEntityTypeBatch(List<String> entityIds)
throws RestServiceException {
try {
Synapse synapseClient = createSynapseClient();
BatchResults<EntityHeader> results = synapseClient
.getEntityTypeBatch(entityIds);
return EntityFactory.createJSONStringForEntity(results);
} catch (SynapseException e) {
throw ExceptionUtil.convertSynapseException(e);
} catch (JSONObjectAdapterException e) {
throw new UnknownErrorException(e.getMessage());
}
}
@Override
public void deleteEntity(String entityId) throws RestServiceException {
try {
Synapse synapseClient = createSynapseClient();
synapseClient.deleteEntityById(entityId);
} catch (SynapseException e) {
throw ExceptionUtil.convertSynapseException(e);
}
}
@Override
public String getUserProfile() throws RestServiceException {
try {
//cached, in a cookie?
UserProfile profile = UserDataProvider.getThreadLocalUserProfile(this.getThreadLocalRequest());
if (profile == null){
Synapse synapseClient = createSynapseClient();
profile = synapseClient.getMyProfile();
}
return EntityFactory.createJSONStringForEntity(profile);
} catch (JSONObjectAdapterException e) {
throw new UnknownErrorException(e.getMessage());
} catch (SynapseException e) {
throw ExceptionUtil.convertSynapseException(e);
}
}
@Override
public String getUserProfile(String userId) throws RestServiceException {
try {
Synapse synapseClient = createSynapseClient();
String targetUserId = userId == null ? "" : "/"+userId;
JSONObject userProfile = synapseClient.getSynapseEntity(urlProvider.getRepositoryServiceUrl(), "/userProfile"+targetUserId);
return userProfile.toString();
} catch (SynapseException e) {
throw ExceptionUtil.convertSynapseException(e);
}
}
@Override
public EntityWrapper getUserGroupHeadersById(List<String> ids)
throws RestServiceException {
try {
Synapse synapseClient = createSynapseClient();
UserGroupHeaderResponsePage response = synapseClient.getUserGroupHeadersByIds(ids);
JSONObjectAdapter responseJSON = response
.writeToJSONObject(adapterFactory.createNew());
return new EntityWrapper(responseJSON.toJSONString(), responseJSON
.getClass().getName(), null);
} catch (SynapseException e) {
throw ExceptionUtil.convertSynapseException(e);
} catch (JSONObjectAdapterException e) {
throw new UnknownErrorException(e.getMessage());
}
}
@Override
public void updateUserProfile(String userProfileJson)
throws RestServiceException {
try {
Synapse synapseClient = createSynapseClient();
JSONObject userProfileJSONObject = new JSONObject(userProfileJson);
UserProfile profile = EntityFactory.createEntityFromJSONObject(userProfileJSONObject, UserProfile.class);
AttachmentData pic = profile.getPic();
if (pic != null && pic.getTokenId() == null && pic.getUrl() != null){
//special case, client provided just enough information to pull the pic from an external location (so try to store in s3 before updating the profile).
log.info("Downloading picture from url: " + pic.getUrl());
URL url = new URL(pic.getUrl());
pic.setUrl(null);
File temp = null;
URLConnection conn = null;
try
{
conn = url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(false);
temp = ServiceUtils.writeToTempFile(conn.getInputStream(), UserProfileAttachmentServlet.MAX_ATTACHMENT_SIZE_IN_BYTES);
// Now upload the file
String contentType = conn.getContentType();
String fileName = temp.getName();
if (contentType != null && contentType.equalsIgnoreCase("image/jpeg") && !fileName.toLowerCase().endsWith(".jpg"))
fileName = profile.getOwnerId() + ".jpg";
pic = synapseClient.uploadUserProfileAttachmentToSynapse(profile.getOwnerId(), temp, fileName);
} catch (Throwable t){
//couldn't pull the picture from the external server. log and move on with the update
t.printStackTrace();
} finally{
// Unconditionally delete the tmp file and close the input stream
if (temp != null)
temp.delete();
try {
conn.getInputStream().close();
} catch (Throwable t) {
t.printStackTrace();
}
}
profile.setPic(pic);
userProfileJSONObject = EntityFactory.createJSONObjectForEntity(profile);
}
- //DO NOT TAKE THIS PARTICULAR CHANGE! TAKE THE OTHER VERSION
- //synapseClient.putEntity("/userProfile", userProfileJSONObject);
-// } catch (SynapseException e) {
-// throw ExceptionUtil.convertSynapseException(e);
+ synapseClient.putEntity("/userProfile", userProfileJSONObject);
+ } catch (SynapseException e) {
+ throw ExceptionUtil.convertSynapseException(e);
} catch (JSONException e) {
throw new UnknownErrorException(e.getMessage());
} catch (JSONObjectAdapterException e) {
throw new UnknownErrorException(e.getMessage());
} catch (IOException e) {
throw new UnknownErrorException(e.getMessage());
}
}
public AccessControlList getAcl(String id) throws SynapseException {
Synapse synapseClient = createSynapseClient();
EntityHeader benefactor = synapseClient.getEntityBenefactor(id);
String benefactorId = benefactor.getId();
return synapseClient.getACL(benefactorId);
}
@Override
public EntityWrapper getNodeAcl(String id) throws RestServiceException {
try {
AccessControlList acl = getAcl(id);
JSONObjectAdapter aclJson = acl
.writeToJSONObject(adapterFactory.createNew());
return new EntityWrapper(aclJson.toJSONString(), aclJson
.getClass().getName(), null);
} catch (SynapseException e) {
throw ExceptionUtil.convertSynapseException(e);
} catch (JSONObjectAdapterException e) {
throw new UnknownErrorException(e.getMessage());
}
}
@Override
public EntityWrapper createAcl(EntityWrapper aclEW) throws RestServiceException {
Synapse synapseClient = createSynapseClient();
try {
JSONEntityFactory jsonEntityFactory = new JSONEntityFactoryImpl(adapterFactory);
AccessControlList acl = jsonEntityFactory.createEntity(aclEW.getEntityJson(), AccessControlList.class);
acl = synapseClient.createACL(acl);
JSONObjectAdapter aclJson = acl
.writeToJSONObject(adapterFactory.createNew());
return new EntityWrapper(aclJson.toJSONString(), aclJson
.getClass().getName(), null);
} catch (SynapseException e) {
throw ExceptionUtil.convertSynapseException(e);
} catch (JSONObjectAdapterException e) {
throw new UnknownErrorException(e.getMessage());
}
}
@Override
public EntityWrapper updateAcl(EntityWrapper aclEW) throws RestServiceException {
return updateAcl(aclEW, false);
}
@Override
public EntityWrapper updateAcl(EntityWrapper aclEW, boolean recursive) throws RestServiceException {
Synapse synapseClient = createSynapseClient();
try {
JSONEntityFactory jsonEntityFactory = new JSONEntityFactoryImpl(adapterFactory);
AccessControlList acl = jsonEntityFactory.createEntity(aclEW.getEntityJson(), AccessControlList.class);
acl = synapseClient.updateACL(acl, recursive);
JSONObjectAdapter aclJson = acl
.writeToJSONObject(adapterFactory.createNew());
return new EntityWrapper(aclJson.toJSONString(), aclJson
.getClass().getName(), null);
} catch (SynapseException e) {
throw ExceptionUtil.convertSynapseException(e);
} catch (JSONObjectAdapterException e) {
throw new UnknownErrorException(e.getMessage());
}
}
@Override
public EntityWrapper deleteAcl(String ownerEntityId) throws RestServiceException {
Synapse synapseClient = createSynapseClient();
try {
// first delete the ACL
synapseClient.deleteACL(ownerEntityId);
// now get the ACL governing this entity, which will be some ancestor, the 'permissions benefactor'
AccessControlList acl = getAcl(ownerEntityId);
JSONObjectAdapter aclJson = acl
.writeToJSONObject(adapterFactory.createNew());
return new EntityWrapper(aclJson.toJSONString(), aclJson
.getClass().getName(), null);
} catch (SynapseException e) {
throw ExceptionUtil.convertSynapseException(e);
} catch (JSONObjectAdapterException e) {
throw new UnknownErrorException(e.getMessage());
}
}
@Override
public boolean hasAccess(String ownerEntityId, String accessType) throws RestServiceException {
Synapse synapseClient = createSynapseClient();
try {
return synapseClient.canAccess(ownerEntityId, ACCESS_TYPE.valueOf(accessType));
} catch (SynapseException e) {
throw ExceptionUtil.convertSynapseException(e);
}
}
@Override
public EntityWrapper getAllUsers() throws RestServiceException {
Synapse synapseClient = createSynapseClient();
try {
PaginatedResults<UserProfile> userProfiles = synapseClient.getUsers(USER_PAGINATION_OFFSET, USER_PAGINATION_LIMIT);
JSONObjectAdapter upJson = userProfiles.writeToJSONObject(adapterFactory.createNew());
return new EntityWrapper(upJson.toJSONString(), upJson.getClass().getName(), null);
} catch (SynapseException e) {
throw ExceptionUtil.convertSynapseException(e);
} catch (JSONObjectAdapterException e) {
throw new UnknownErrorException(e.getMessage());
}
}
@Override
public EntityWrapper getAllGroups() throws RestServiceException {
Synapse synapseClient = createSynapseClient();
try {
PaginatedResults<UserGroup> userGroups = synapseClient.getGroups(GROUPS_PAGINATION_OFFSET, GROUPS_PAGINATION_LIMIT);
JSONObjectAdapter ugJson = userGroups.writeToJSONObject(adapterFactory.createNew());
return new EntityWrapper(ugJson.toJSONString(), ugJson.getClass().getName(), null);
} catch (SynapseException e) {
throw ExceptionUtil.convertSynapseException(e);
} catch (JSONObjectAdapterException e) {
throw new UnknownErrorException(e.getMessage());
}
}
@Override
public String createUserProfileAttachmentPresignedUrl(String id,
String tokenOrPreviewId) throws RestServiceException {
Synapse synapseClient = createSynapseClient();
try {
PresignedUrl url = synapseClient.createUserProfileAttachmentPresignedUrl(id, tokenOrPreviewId);
return EntityFactory.createJSONStringForEntity(url);
} catch (SynapseException e) {
throw ExceptionUtil.convertSynapseException(e);
} catch (JSONObjectAdapterException e) {
throw new UnknownErrorException(e.getMessage());
}
}
@Override
public EntityWrapper createAccessRequirement(EntityWrapper arEW) throws RestServiceException {
Synapse synapseClient = createSynapseClient();
try {
JSONEntityFactory jsonEntityFactory = new JSONEntityFactoryImpl(adapterFactory);
@SuppressWarnings("unchecked")
AccessRequirement ar = jsonEntityFactory.createEntity(arEW.getEntityJson(),
(Class<AccessRequirement>)Class.forName(arEW.getEntityClassName()));
AccessRequirement result = synapseClient.createAccessRequirement(ar);
JSONObjectAdapter arJson = result.writeToJSONObject(adapterFactory.createNew());
return new EntityWrapper(arJson.toJSONString(), arJson.getClass().getName(), null);
} catch (SynapseException e) {
throw ExceptionUtil.convertSynapseException(e);
} catch (JSONObjectAdapterException e) {
throw new UnknownErrorException(e.getMessage());
} catch (ClassNotFoundException e) {
throw new UnknownErrorException(e.getMessage());
}
}
@Override
public AccessRequirementsTransport getUnmetAccessRequirements(String entityId) throws RestServiceException {
Synapse synapseClient = createSynapseClient();
try {
VariableContentPaginatedResults<AccessRequirement> accessRequirements =
synapseClient.getUnmetAccessReqAccessRequirements(entityId);
JSONObjectAdapter arJson = accessRequirements.writeToJSONObject(adapterFactory.createNew());
AccessRequirementsTransport transport = new AccessRequirementsTransport();
transport.setAccessRequirementsString(arJson.toJSONString());
Entity e = synapseClient.getEntityById(entityId);
transport.setEntityString(EntityFactory.createJSONStringForEntity(e));
transport.setEntityClassAsString(e.getClass().getName());
transport.setUserProfileString(getUserProfile());
return transport;
} catch (SynapseException e) {
throw ExceptionUtil.convertSynapseException(e);
} catch (JSONObjectAdapterException e) {
throw new UnknownErrorException(e.getMessage());
}
}
@Override
public EntityWrapper createAccessApproval(EntityWrapper aaEW) throws RestServiceException {
Synapse synapseClient = createSynapseClient();
try {
JSONEntityFactory jsonEntityFactory = new JSONEntityFactoryImpl(adapterFactory);
@SuppressWarnings("unchecked")
AccessApproval aa = jsonEntityFactory.createEntity(aaEW.getEntityJson(),
(Class<AccessApproval>)Class.forName(aaEW.getEntityClassName()));
AccessApproval result = synapseClient.createAccessApproval(aa);
JSONObjectAdapter aaJson = result.writeToJSONObject(adapterFactory.createNew());
return new EntityWrapper(aaJson.toJSONString(), aaJson.getClass().getName(), null);
} catch (SynapseException e) {
throw ExceptionUtil.convertSynapseException(e);
} catch (ClassNotFoundException e) {
throw new UnknownErrorException(e.getMessage());
} catch (JSONObjectAdapterException e) {
throw new UnknownErrorException(e.getMessage());
}
}
@Override
public EntityWrapper updateExternalLocationable(String entityId, String externalUrl) throws RestServiceException {
Synapse synapseClient = createSynapseClient();
try {
Entity locationable = synapseClient.getEntityById(entityId);
if(!(locationable instanceof Locationable)) {
throw new RuntimeException("Upload failed. Entity id: " + locationable.getId() + " is not Locationable.");
}
Locationable result = synapseClient.updateExternalLocationableToSynapse((Locationable)locationable, externalUrl);
JSONObjectAdapter aaJson = result.writeToJSONObject(adapterFactory.createNew());
return new EntityWrapper(aaJson.toJSONString(), aaJson.getClass().getName(), null);
} catch (SynapseException e) {
throw ExceptionUtil.convertSynapseException(e);
} catch (JSONObjectAdapterException e) {
throw new UnknownErrorException(e.getMessage());
}
}
@Override
public String markdown2Html(String markdown, String attachmentUrl) {
return ServerMarkdownUtils.markdown2Html(markdown, attachmentUrl, markdownProcessor);
}
}
| true | true | public void updateUserProfile(String userProfileJson)
throws RestServiceException {
try {
Synapse synapseClient = createSynapseClient();
JSONObject userProfileJSONObject = new JSONObject(userProfileJson);
UserProfile profile = EntityFactory.createEntityFromJSONObject(userProfileJSONObject, UserProfile.class);
AttachmentData pic = profile.getPic();
if (pic != null && pic.getTokenId() == null && pic.getUrl() != null){
//special case, client provided just enough information to pull the pic from an external location (so try to store in s3 before updating the profile).
log.info("Downloading picture from url: " + pic.getUrl());
URL url = new URL(pic.getUrl());
pic.setUrl(null);
File temp = null;
URLConnection conn = null;
try
{
conn = url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(false);
temp = ServiceUtils.writeToTempFile(conn.getInputStream(), UserProfileAttachmentServlet.MAX_ATTACHMENT_SIZE_IN_BYTES);
// Now upload the file
String contentType = conn.getContentType();
String fileName = temp.getName();
if (contentType != null && contentType.equalsIgnoreCase("image/jpeg") && !fileName.toLowerCase().endsWith(".jpg"))
fileName = profile.getOwnerId() + ".jpg";
pic = synapseClient.uploadUserProfileAttachmentToSynapse(profile.getOwnerId(), temp, fileName);
} catch (Throwable t){
//couldn't pull the picture from the external server. log and move on with the update
t.printStackTrace();
} finally{
// Unconditionally delete the tmp file and close the input stream
if (temp != null)
temp.delete();
try {
conn.getInputStream().close();
} catch (Throwable t) {
t.printStackTrace();
}
}
profile.setPic(pic);
userProfileJSONObject = EntityFactory.createJSONObjectForEntity(profile);
}
//DO NOT TAKE THIS PARTICULAR CHANGE! TAKE THE OTHER VERSION
//synapseClient.putEntity("/userProfile", userProfileJSONObject);
// } catch (SynapseException e) {
// throw ExceptionUtil.convertSynapseException(e);
} catch (JSONException e) {
throw new UnknownErrorException(e.getMessage());
} catch (JSONObjectAdapterException e) {
throw new UnknownErrorException(e.getMessage());
} catch (IOException e) {
throw new UnknownErrorException(e.getMessage());
}
}
| public void updateUserProfile(String userProfileJson)
throws RestServiceException {
try {
Synapse synapseClient = createSynapseClient();
JSONObject userProfileJSONObject = new JSONObject(userProfileJson);
UserProfile profile = EntityFactory.createEntityFromJSONObject(userProfileJSONObject, UserProfile.class);
AttachmentData pic = profile.getPic();
if (pic != null && pic.getTokenId() == null && pic.getUrl() != null){
//special case, client provided just enough information to pull the pic from an external location (so try to store in s3 before updating the profile).
log.info("Downloading picture from url: " + pic.getUrl());
URL url = new URL(pic.getUrl());
pic.setUrl(null);
File temp = null;
URLConnection conn = null;
try
{
conn = url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(false);
temp = ServiceUtils.writeToTempFile(conn.getInputStream(), UserProfileAttachmentServlet.MAX_ATTACHMENT_SIZE_IN_BYTES);
// Now upload the file
String contentType = conn.getContentType();
String fileName = temp.getName();
if (contentType != null && contentType.equalsIgnoreCase("image/jpeg") && !fileName.toLowerCase().endsWith(".jpg"))
fileName = profile.getOwnerId() + ".jpg";
pic = synapseClient.uploadUserProfileAttachmentToSynapse(profile.getOwnerId(), temp, fileName);
} catch (Throwable t){
//couldn't pull the picture from the external server. log and move on with the update
t.printStackTrace();
} finally{
// Unconditionally delete the tmp file and close the input stream
if (temp != null)
temp.delete();
try {
conn.getInputStream().close();
} catch (Throwable t) {
t.printStackTrace();
}
}
profile.setPic(pic);
userProfileJSONObject = EntityFactory.createJSONObjectForEntity(profile);
}
synapseClient.putEntity("/userProfile", userProfileJSONObject);
} catch (SynapseException e) {
throw ExceptionUtil.convertSynapseException(e);
} catch (JSONException e) {
throw new UnknownErrorException(e.getMessage());
} catch (JSONObjectAdapterException e) {
throw new UnknownErrorException(e.getMessage());
} catch (IOException e) {
throw new UnknownErrorException(e.getMessage());
}
}
|
diff --git a/nexus/nexus-rest-api/src/main/java/org/sonatype/nexus/rest/feeds/AbstractNexusFeedSource.java b/nexus/nexus-rest-api/src/main/java/org/sonatype/nexus/rest/feeds/AbstractNexusFeedSource.java
index e8309942f..aef6fb0e9 100644
--- a/nexus/nexus-rest-api/src/main/java/org/sonatype/nexus/rest/feeds/AbstractNexusFeedSource.java
+++ b/nexus/nexus-rest-api/src/main/java/org/sonatype/nexus/rest/feeds/AbstractNexusFeedSource.java
@@ -1,332 +1,332 @@
/*
* Nexus: Maven Repository Manager
* Copyright (C) 2008 Sonatype Inc.
*
* This file is part of Nexus.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see http://www.gnu.org/licenses/.
*
*/
package org.sonatype.nexus.rest.feeds;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.codehaus.plexus.component.annotations.Requirement;
import org.codehaus.plexus.util.StringUtils;
import org.restlet.data.MediaType;
import org.sonatype.nexus.artifact.Gav;
import org.sonatype.nexus.artifact.NexusItemInfo;
import org.sonatype.nexus.feeds.NexusArtifactEvent;
import org.sonatype.nexus.proxy.NoSuchRepositoryException;
import org.sonatype.nexus.proxy.access.AccessManager;
import org.sonatype.nexus.proxy.access.Action;
import org.sonatype.nexus.proxy.access.NexusItemAuthorizer;
import org.sonatype.nexus.proxy.item.RepositoryItemUid;
import org.sonatype.nexus.proxy.maven.MavenRepository;
import org.sonatype.nexus.proxy.repository.Repository;
import com.sun.syndication.feed.synd.SyndContent;
import com.sun.syndication.feed.synd.SyndContentImpl;
import com.sun.syndication.feed.synd.SyndEntry;
import com.sun.syndication.feed.synd.SyndEntryImpl;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.feed.synd.SyndFeedImpl;
/**
* And abstract class for NexusArtifactEvent based feeds. This class implements all needed to create a feed,
* implementors needs only to implement 3 abtract classes.
*
* @author cstamas
*/
public abstract class AbstractNexusFeedSource
extends AbstractFeedSource
{
@Requirement
private NexusItemAuthorizer nexusItemAuthorizer;
/**
* Creates/formats GAV strings from ArtifactInfo.
*
* @param ai
* @return
*/
protected String getGav( NexusItemInfo ai )
{
if ( ai == null )
{
return "unknown : unknown : unknown";
}
else
{
try
{
Repository repo = getNexus().getRepository( ai.getRepositoryId() );
if ( MavenRepository.class.isAssignableFrom( repo.getClass() ) )
{
Gav gav = ( (MavenRepository) repo ).getGavCalculator().pathToGav( ai.getPath() );
if ( gav != null )
{
StringBuffer result = new StringBuffer( gav.getGroupId() ).append( " : " ).append(
gav.getArtifactId() ).append( " : " ).append(
gav.getVersion() != null ? gav.getVersion() : "unknown" );
if ( gav.getClassifier() != null )
{
result.append( " : " ).append( gav.getClassifier() );
}
return result.toString();
}
else
{
return ai.getPath();
}
}
else
{
return ai.getPath();
}
}
catch ( NoSuchRepositoryException e )
{
return ai.getPath();
}
}
}
protected Set<String> getRepoIdsFromParams( Map<String, String> params )
{
if ( params != null && params.containsKey( "r" ) )
{
HashSet<String> result = new HashSet<String>();
String value = params.get( "r" );
if ( value.contains( "," ) )
{
String[] values = StringUtils.split( value, "," );
result.addAll( Arrays.asList( values ) );
}
else
{
result.add( value );
}
return result;
}
else
{
return null;
}
}
public abstract List<NexusArtifactEvent> getEventList( Integer from, Integer count, Map<String, String> params );
public abstract String getTitle();
public abstract String getDescription();
public SyndFeed getFeed( Integer from, Integer count, Map<String, String> params )
{
List<NexusArtifactEvent> items = getEventList( from, count, params );
SyndFeedImpl feed = new SyndFeedImpl();
feed.setTitle( getTitle() );
feed.setDescription( getDescription() );
feed.setAuthor( "Nexus " + getNexus().getSystemStatus().getVersion() );
feed.setPublishedDate( new Date() );
List<SyndEntry> entries = new ArrayList<SyndEntry>( items.size() );
SyndEntry entry = null;
SyndContent content = null;
String gav = null;
String username = null;
String ipAddress = null;
String itemLink = null;
for ( NexusArtifactEvent item : items )
{
if ( item.getEventContext().containsKey( AccessManager.REQUEST_USER ) )
{
username = (String) item.getEventContext().get( AccessManager.REQUEST_USER );
}
else
{
username = null;
}
if ( item.getEventContext().containsKey( AccessManager.REQUEST_REMOTE_ADDRESS ) )
{
ipAddress = (String) item.getEventContext().get( AccessManager.REQUEST_REMOTE_ADDRESS );
}
else
{
ipAddress = null;
}
try
{
Repository repo = getNexus().getRepository( item.getNexusItemInfo().getRepositoryId() );
RepositoryItemUid uid = repo.createUid( item.getNexusItemInfo().getPath() );
if ( nexusItemAuthorizer.authorizePath( uid, null, Action.read ) )
{
gav = getGav( item.getNexusItemInfo() );
StringBuffer msg = new StringBuffer( "The " )
.append( gav ).append( " artifact in repository " ).append(
item.getNexusItemInfo().getRepositoryId() ).append( " is " );
if ( NexusArtifactEvent.ACTION_CACHED.equals( item.getAction() ) )
{
msg
.append( "cached by Nexus from remote URL " ).append(
item.getNexusItemInfo().getRemoteUrl() ).append( "." );
if ( username != null )
{
msg
.append( " Caching happened to fulfill a request from user " ).append( username )
.append( "." );
}
}
else if ( NexusArtifactEvent.ACTION_DEPLOYED.equals( item.getAction() ) )
{
- msg.append( "deployed onto Nexus." );
+ msg.append( "deployed into Nexus." );
if ( username != null )
{
msg.append( " Deployment was initiated by user " ).append( username ).append( "." );
}
}
else if ( NexusArtifactEvent.ACTION_DELETED.equals( item.getAction() ) )
{
msg.append( "deleted from Nexus." );
if ( username != null )
{
msg.append( " Deletion was initiated by user " ).append( username ).append( "." );
}
}
else if ( NexusArtifactEvent.ACTION_BROKEN.equals( item.getAction() ) )
{
msg.append( "broken." );
if ( item.getMessage() != null )
{
msg.append( " Details: \n" );
msg.append( item.getMessage() );
msg.append( "\n" );
}
if ( username != null )
{
msg.append( " Processing was initiated by user " ).append( username ).append( "." );
}
}
else if ( NexusArtifactEvent.ACTION_BROKEN_WRONG_REMOTE_CHECKSUM.equals( item.getAction() ) )
{
msg.append( "proxied, and the remote repository contains wrong checksum for it." );
if ( item.getMessage() != null )
{
msg.append( " Details: \n" );
msg.append( item.getMessage() );
msg.append( "\n" );
}
if ( username != null )
{
msg.append( " Processing was initiated by user " ).append( username ).append( "." );
}
}
else if ( NexusArtifactEvent.ACTION_RETRIEVED.equals( item.getAction() ) )
{
msg.append( "served by Nexus." );
if ( username != null )
{
msg.append( " Request was initiated by user " ).append( username ).append( "." );
}
}
if ( ipAddress != null )
{
msg.append( " The request was originated from IP address " ).append( ipAddress ).append( "." );
}
StringBuffer uriToAppend = new StringBuffer( "content/repositories/" ).append(
item.getNexusItemInfo().getRepositoryId() ).append( item.getNexusItemInfo().getPath() );
itemLink = uriToAppend.toString();
entry = new SyndEntryImpl();
entry.setTitle( getGav( item.getNexusItemInfo() ) );
entry.setLink( itemLink );
entry.setPublishedDate( item.getEventDate() );
entry.setAuthor( username );
content = new SyndContentImpl();
content.setType( MediaType.TEXT_PLAIN.toString() );
content.setValue( msg.toString() );
entry.setDescription( content );
entries.add( entry );
}
}
catch ( NoSuchRepositoryException e )
{
// Can't get repository for artifact, therefore we can't authorize access, therefore you dont see it
getLogger().error(
"Feed entry contained invalid repository id " + item.getNexusItemInfo().getRepositoryId(),
e );
}
}
feed.setEntries( entries );
return feed;
}
}
| true | true | public SyndFeed getFeed( Integer from, Integer count, Map<String, String> params )
{
List<NexusArtifactEvent> items = getEventList( from, count, params );
SyndFeedImpl feed = new SyndFeedImpl();
feed.setTitle( getTitle() );
feed.setDescription( getDescription() );
feed.setAuthor( "Nexus " + getNexus().getSystemStatus().getVersion() );
feed.setPublishedDate( new Date() );
List<SyndEntry> entries = new ArrayList<SyndEntry>( items.size() );
SyndEntry entry = null;
SyndContent content = null;
String gav = null;
String username = null;
String ipAddress = null;
String itemLink = null;
for ( NexusArtifactEvent item : items )
{
if ( item.getEventContext().containsKey( AccessManager.REQUEST_USER ) )
{
username = (String) item.getEventContext().get( AccessManager.REQUEST_USER );
}
else
{
username = null;
}
if ( item.getEventContext().containsKey( AccessManager.REQUEST_REMOTE_ADDRESS ) )
{
ipAddress = (String) item.getEventContext().get( AccessManager.REQUEST_REMOTE_ADDRESS );
}
else
{
ipAddress = null;
}
try
{
Repository repo = getNexus().getRepository( item.getNexusItemInfo().getRepositoryId() );
RepositoryItemUid uid = repo.createUid( item.getNexusItemInfo().getPath() );
if ( nexusItemAuthorizer.authorizePath( uid, null, Action.read ) )
{
gav = getGav( item.getNexusItemInfo() );
StringBuffer msg = new StringBuffer( "The " )
.append( gav ).append( " artifact in repository " ).append(
item.getNexusItemInfo().getRepositoryId() ).append( " is " );
if ( NexusArtifactEvent.ACTION_CACHED.equals( item.getAction() ) )
{
msg
.append( "cached by Nexus from remote URL " ).append(
item.getNexusItemInfo().getRemoteUrl() ).append( "." );
if ( username != null )
{
msg
.append( " Caching happened to fulfill a request from user " ).append( username )
.append( "." );
}
}
else if ( NexusArtifactEvent.ACTION_DEPLOYED.equals( item.getAction() ) )
{
msg.append( "deployed onto Nexus." );
if ( username != null )
{
msg.append( " Deployment was initiated by user " ).append( username ).append( "." );
}
}
else if ( NexusArtifactEvent.ACTION_DELETED.equals( item.getAction() ) )
{
msg.append( "deleted from Nexus." );
if ( username != null )
{
msg.append( " Deletion was initiated by user " ).append( username ).append( "." );
}
}
else if ( NexusArtifactEvent.ACTION_BROKEN.equals( item.getAction() ) )
{
msg.append( "broken." );
if ( item.getMessage() != null )
{
msg.append( " Details: \n" );
msg.append( item.getMessage() );
msg.append( "\n" );
}
if ( username != null )
{
msg.append( " Processing was initiated by user " ).append( username ).append( "." );
}
}
else if ( NexusArtifactEvent.ACTION_BROKEN_WRONG_REMOTE_CHECKSUM.equals( item.getAction() ) )
{
msg.append( "proxied, and the remote repository contains wrong checksum for it." );
if ( item.getMessage() != null )
{
msg.append( " Details: \n" );
msg.append( item.getMessage() );
msg.append( "\n" );
}
if ( username != null )
{
msg.append( " Processing was initiated by user " ).append( username ).append( "." );
}
}
else if ( NexusArtifactEvent.ACTION_RETRIEVED.equals( item.getAction() ) )
{
msg.append( "served by Nexus." );
if ( username != null )
{
msg.append( " Request was initiated by user " ).append( username ).append( "." );
}
}
if ( ipAddress != null )
{
msg.append( " The request was originated from IP address " ).append( ipAddress ).append( "." );
}
StringBuffer uriToAppend = new StringBuffer( "content/repositories/" ).append(
item.getNexusItemInfo().getRepositoryId() ).append( item.getNexusItemInfo().getPath() );
itemLink = uriToAppend.toString();
entry = new SyndEntryImpl();
entry.setTitle( getGav( item.getNexusItemInfo() ) );
entry.setLink( itemLink );
entry.setPublishedDate( item.getEventDate() );
entry.setAuthor( username );
content = new SyndContentImpl();
content.setType( MediaType.TEXT_PLAIN.toString() );
content.setValue( msg.toString() );
entry.setDescription( content );
entries.add( entry );
}
}
catch ( NoSuchRepositoryException e )
{
// Can't get repository for artifact, therefore we can't authorize access, therefore you dont see it
getLogger().error(
"Feed entry contained invalid repository id " + item.getNexusItemInfo().getRepositoryId(),
e );
}
}
feed.setEntries( entries );
return feed;
}
| public SyndFeed getFeed( Integer from, Integer count, Map<String, String> params )
{
List<NexusArtifactEvent> items = getEventList( from, count, params );
SyndFeedImpl feed = new SyndFeedImpl();
feed.setTitle( getTitle() );
feed.setDescription( getDescription() );
feed.setAuthor( "Nexus " + getNexus().getSystemStatus().getVersion() );
feed.setPublishedDate( new Date() );
List<SyndEntry> entries = new ArrayList<SyndEntry>( items.size() );
SyndEntry entry = null;
SyndContent content = null;
String gav = null;
String username = null;
String ipAddress = null;
String itemLink = null;
for ( NexusArtifactEvent item : items )
{
if ( item.getEventContext().containsKey( AccessManager.REQUEST_USER ) )
{
username = (String) item.getEventContext().get( AccessManager.REQUEST_USER );
}
else
{
username = null;
}
if ( item.getEventContext().containsKey( AccessManager.REQUEST_REMOTE_ADDRESS ) )
{
ipAddress = (String) item.getEventContext().get( AccessManager.REQUEST_REMOTE_ADDRESS );
}
else
{
ipAddress = null;
}
try
{
Repository repo = getNexus().getRepository( item.getNexusItemInfo().getRepositoryId() );
RepositoryItemUid uid = repo.createUid( item.getNexusItemInfo().getPath() );
if ( nexusItemAuthorizer.authorizePath( uid, null, Action.read ) )
{
gav = getGav( item.getNexusItemInfo() );
StringBuffer msg = new StringBuffer( "The " )
.append( gav ).append( " artifact in repository " ).append(
item.getNexusItemInfo().getRepositoryId() ).append( " is " );
if ( NexusArtifactEvent.ACTION_CACHED.equals( item.getAction() ) )
{
msg
.append( "cached by Nexus from remote URL " ).append(
item.getNexusItemInfo().getRemoteUrl() ).append( "." );
if ( username != null )
{
msg
.append( " Caching happened to fulfill a request from user " ).append( username )
.append( "." );
}
}
else if ( NexusArtifactEvent.ACTION_DEPLOYED.equals( item.getAction() ) )
{
msg.append( "deployed into Nexus." );
if ( username != null )
{
msg.append( " Deployment was initiated by user " ).append( username ).append( "." );
}
}
else if ( NexusArtifactEvent.ACTION_DELETED.equals( item.getAction() ) )
{
msg.append( "deleted from Nexus." );
if ( username != null )
{
msg.append( " Deletion was initiated by user " ).append( username ).append( "." );
}
}
else if ( NexusArtifactEvent.ACTION_BROKEN.equals( item.getAction() ) )
{
msg.append( "broken." );
if ( item.getMessage() != null )
{
msg.append( " Details: \n" );
msg.append( item.getMessage() );
msg.append( "\n" );
}
if ( username != null )
{
msg.append( " Processing was initiated by user " ).append( username ).append( "." );
}
}
else if ( NexusArtifactEvent.ACTION_BROKEN_WRONG_REMOTE_CHECKSUM.equals( item.getAction() ) )
{
msg.append( "proxied, and the remote repository contains wrong checksum for it." );
if ( item.getMessage() != null )
{
msg.append( " Details: \n" );
msg.append( item.getMessage() );
msg.append( "\n" );
}
if ( username != null )
{
msg.append( " Processing was initiated by user " ).append( username ).append( "." );
}
}
else if ( NexusArtifactEvent.ACTION_RETRIEVED.equals( item.getAction() ) )
{
msg.append( "served by Nexus." );
if ( username != null )
{
msg.append( " Request was initiated by user " ).append( username ).append( "." );
}
}
if ( ipAddress != null )
{
msg.append( " The request was originated from IP address " ).append( ipAddress ).append( "." );
}
StringBuffer uriToAppend = new StringBuffer( "content/repositories/" ).append(
item.getNexusItemInfo().getRepositoryId() ).append( item.getNexusItemInfo().getPath() );
itemLink = uriToAppend.toString();
entry = new SyndEntryImpl();
entry.setTitle( getGav( item.getNexusItemInfo() ) );
entry.setLink( itemLink );
entry.setPublishedDate( item.getEventDate() );
entry.setAuthor( username );
content = new SyndContentImpl();
content.setType( MediaType.TEXT_PLAIN.toString() );
content.setValue( msg.toString() );
entry.setDescription( content );
entries.add( entry );
}
}
catch ( NoSuchRepositoryException e )
{
// Can't get repository for artifact, therefore we can't authorize access, therefore you dont see it
getLogger().error(
"Feed entry contained invalid repository id " + item.getNexusItemInfo().getRepositoryId(),
e );
}
}
feed.setEntries( entries );
return feed;
}
|
diff --git a/modules/foundation/appbase/src/classes/org/jdesktop/wonderland/modules/appbase/client/HUDDisplayer.java b/modules/foundation/appbase/src/classes/org/jdesktop/wonderland/modules/appbase/client/HUDDisplayer.java
index 97252aa35..bd370053a 100644
--- a/modules/foundation/appbase/src/classes/org/jdesktop/wonderland/modules/appbase/client/HUDDisplayer.java
+++ b/modules/foundation/appbase/src/classes/org/jdesktop/wonderland/modules/appbase/client/HUDDisplayer.java
@@ -1,100 +1,102 @@
/**
* Project Wonderland
*
* Copyright (c) 2004-2009, Sun Microsystems, Inc., All Rights Reserved
*
* Redistributions in source code form must reproduce the above
* copyright and this condition.
*
* The contents of this file are subject to the GNU General Public
* License, Version 2 (the "License"); you may not use this file
* except in compliance with the License. A copy of the License is
* available at http://www.opensource.org/licenses/gpl-license.php.
*
* Sun designates this particular file as subject to the "Classpath"
* exception as provided by Sun in the License file that accompanied
* this code.
*/
package org.jdesktop.wonderland.modules.appbase.client;
import java.util.Iterator;
import java.util.LinkedList;
import org.jdesktop.wonderland.client.hud.CompassLayout.Layout;
import org.jdesktop.wonderland.client.hud.HUD;
import org.jdesktop.wonderland.client.hud.HUDComponent;
import org.jdesktop.wonderland.client.hud.HUDEvent;
import org.jdesktop.wonderland.client.hud.HUDEventListener;
import org.jdesktop.wonderland.client.hud.HUDManagerFactory;
import org.jdesktop.wonderland.common.ExperimentalAPI;
import org.jdesktop.wonderland.modules.appbase.client.view.View2D;
import org.jdesktop.wonderland.modules.appbase.client.view.View2DDisplayer;
import org.jdesktop.wonderland.modules.appbase.client.view.WindowSwingHeader;
@ExperimentalAPI
public class HUDDisplayer implements View2DDisplayer {
/** The app displayed by this displayer. */
private App2D app;
/** The HUD. */
private HUD mainHUD;
/** HUD components for windows shown in the HUD. */
private LinkedList<HUDComponent> hudComponents;
public HUDDisplayer (App2D app) {
this.app = app;
mainHUD = HUDManagerFactory.getHUDManager().getHUD("main");
hudComponents = new LinkedList<HUDComponent>();
}
public void cleanup () {
if (hudComponents != null) {
HUD mainHUD = HUDManagerFactory.getHUDManager().getHUD("main");
for (HUDComponent component : hudComponents) {
component.setVisible(false);
mainHUD.removeComponent(component);
}
hudComponents.clear();
hudComponents = null;
}
mainHUD = null;
app = null;
}
public View2D createView (Window2D window) {
// Don't ever show frame headers in the HUD
if (window instanceof WindowSwingHeader) return null;
HUDComponent component = mainHUD.createComponent(window);
component.setName(app.getName());
component.setPreferredLocation(Layout.NORTH);
hudComponents.add(component);
component.addEventListener(new HUDEventListener() {
public void HUDObjectChanged(HUDEvent e) {
if (e.getEventType().equals(HUDEvent.HUDEventType.CLOSED)) {
// TODO: currently we take the entire app off the HUD when
// any HUD view of any app window is quit
- app.setShowInHUD(false);
+ if (app != null) {
+ app.setShowInHUD(false);
+ }
}
}
});
mainHUD.addComponent(component);
component.setVisible(true);
// TODO: get the view from the HUD component and return it?
return null;
}
public void destroyView (View2D view) {
}
public void destroyAllViews () {
}
public Iterator<? extends View2D> getViews () {
return null;
}
}
| true | true | public View2D createView (Window2D window) {
// Don't ever show frame headers in the HUD
if (window instanceof WindowSwingHeader) return null;
HUDComponent component = mainHUD.createComponent(window);
component.setName(app.getName());
component.setPreferredLocation(Layout.NORTH);
hudComponents.add(component);
component.addEventListener(new HUDEventListener() {
public void HUDObjectChanged(HUDEvent e) {
if (e.getEventType().equals(HUDEvent.HUDEventType.CLOSED)) {
// TODO: currently we take the entire app off the HUD when
// any HUD view of any app window is quit
app.setShowInHUD(false);
}
}
});
mainHUD.addComponent(component);
component.setVisible(true);
// TODO: get the view from the HUD component and return it?
return null;
}
| public View2D createView (Window2D window) {
// Don't ever show frame headers in the HUD
if (window instanceof WindowSwingHeader) return null;
HUDComponent component = mainHUD.createComponent(window);
component.setName(app.getName());
component.setPreferredLocation(Layout.NORTH);
hudComponents.add(component);
component.addEventListener(new HUDEventListener() {
public void HUDObjectChanged(HUDEvent e) {
if (e.getEventType().equals(HUDEvent.HUDEventType.CLOSED)) {
// TODO: currently we take the entire app off the HUD when
// any HUD view of any app window is quit
if (app != null) {
app.setShowInHUD(false);
}
}
}
});
mainHUD.addComponent(component);
component.setVisible(true);
// TODO: get the view from the HUD component and return it?
return null;
}
|
diff --git a/src/java/main/esg/node/filters/MountedPathResolver.java b/src/java/main/esg/node/filters/MountedPathResolver.java
index b863df5..8b5caac 100644
--- a/src/java/main/esg/node/filters/MountedPathResolver.java
+++ b/src/java/main/esg/node/filters/MountedPathResolver.java
@@ -1,137 +1,136 @@
/***************************************************************************
* *
* Organization: Earth System Grid Federation *
* *
****************************************************************************
* *
* Copyright (c) 2009, Lawrence Livermore National Security, LLC. *
* Produced at the Lawrence Livermore National Laboratory *
* Written by: Gavin M. Bell ([email protected]) *
* LLNL-CODE-420962 *
* *
* All rights reserved. This file is part of the: *
* Earth System Grid Federation (ESGF) Data Node Software Stack *
* *
* For details, see http://esgf.org/ *
* Please also read this link *
* http://esgf.org/LICENSE *
* *
* * 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 disclaimer below. *
* *
* * Redistributions in binary form must reproduce the above copyright *
* notice, this list of conditions and the disclaimer (as noted below) *
* in the documentation and/or other materials provided with the *
* distribution. *
* *
* Neither the name of the LLNS/LLNL 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 LAWRENCE *
* LIVERMORE NATIONAL SECURITY, LLC, THE U.S. DEPARTMENT OF ENERGY 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. *
* *
***************************************************************************/
/**
Description:
**/
package esg.node.filters;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.TreeSet;
import java.util.Comparator;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.logging.impl.*;
public class MountedPathResolver implements esg.common.Resolver {
private List<MountPoint> mountPoints = null;
public MountedPathResolver() {
this.mountPoints = new ArrayList<MountPoint>(5);
}
public MountedPathResolver(Map<String,String> readMountpoints) {
this();
addMountPoints(readMountpoints);
}
//Up-front loading, getting data into the resolver
//adding an unordered mountpoint map
public void addMountPoints(Map<String,String> readMountpoints) {
this.mountPoints.clear();
Comparator<? super String> stringLengthComparator = new Comparator<String>() {
public int compare(String o1, String o2) {
- if(o1.length() > o2.length()) { return -1; }
- else if(o1.length() < o2.length()) { return 1;}
- else { return 0; }
+ if(o1.length() >= o2.length()) { return -1; }
+ else { return 1; }
}
};
//Just sort the keys in length order.
TreeSet<String> rmpSorted = new TreeSet<String>(stringLengthComparator);
rmpSorted.addAll(readMountpoints.keySet());
for(String key : rmpSorted) {
addMountPoint(key,readMountpoints.get(key));
}
}
private synchronized void addMountPoint(String mountpoint, String localpath) {
System.out.println("Adding mountpoint: "+mountpoint+" --> "+localpath);
this.mountPoints.add(new MountPoint(Pattern.compile("/"+mountpoint+"/(.*$)").matcher(""),localpath));
}
public String resolve(String input) {
String out = null;
System.out.println("Resolving "+input);
System.out.println("Scanning over ["+mountPoints.size()+"] mounts");
for(MountPoint mp : mountPoints) {
mp.mountmatcher.reset(input);
if(mp.mountmatcher.find()) {
System.out.print("+");
out = mp.localpath+java.io.File.separator+mp.mountmatcher.group(1);
break;
}
System.out.print("-");
}
System.out.println("Resolved to local path: ["+out+"]");
return out;
}
private class MountPoint {
Matcher mountmatcher = null;
String localpath = null;
MountPoint(Matcher mountmatcher, String localpath) {
this.mountmatcher = mountmatcher;
this.localpath = localpath;
}
}
public String toString() { return mountPoints.toString(); }
}
| true | true | public void addMountPoints(Map<String,String> readMountpoints) {
this.mountPoints.clear();
Comparator<? super String> stringLengthComparator = new Comparator<String>() {
public int compare(String o1, String o2) {
if(o1.length() > o2.length()) { return -1; }
else if(o1.length() < o2.length()) { return 1;}
else { return 0; }
}
};
//Just sort the keys in length order.
TreeSet<String> rmpSorted = new TreeSet<String>(stringLengthComparator);
rmpSorted.addAll(readMountpoints.keySet());
for(String key : rmpSorted) {
addMountPoint(key,readMountpoints.get(key));
}
}
| public void addMountPoints(Map<String,String> readMountpoints) {
this.mountPoints.clear();
Comparator<? super String> stringLengthComparator = new Comparator<String>() {
public int compare(String o1, String o2) {
if(o1.length() >= o2.length()) { return -1; }
else { return 1; }
}
};
//Just sort the keys in length order.
TreeSet<String> rmpSorted = new TreeSet<String>(stringLengthComparator);
rmpSorted.addAll(readMountpoints.keySet());
for(String key : rmpSorted) {
addMountPoint(key,readMountpoints.get(key));
}
}
|
diff --git a/de.walware.statet.r.console.ui/src/de/walware/statet/r/internal/console/ui/launching/RJEngineLaunchDelegate.java b/de.walware.statet.r.console.ui/src/de/walware/statet/r/internal/console/ui/launching/RJEngineLaunchDelegate.java
index ccc9d79e..5169dca0 100644
--- a/de.walware.statet.r.console.ui/src/de/walware/statet/r/internal/console/ui/launching/RJEngineLaunchDelegate.java
+++ b/de.walware.statet.r.console.ui/src/de/walware/statet/r/internal/console/ui/launching/RJEngineLaunchDelegate.java
@@ -1,279 +1,279 @@
/*******************************************************************************
* Copyright (c) 2008-2011 WalWare/StatET-Project (www.walware.de/goto/statet).
* 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:
* Stephan Wahlbrink - initial API and implementation
*******************************************************************************/
package de.walware.statet.r.internal.console.ui.launching;
import static de.walware.rj.server.srvext.ServerUtil.RJ_DATA_ID;
import static de.walware.rj.server.srvext.ServerUtil.RJ_SERVER_ID;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.regex.Pattern;
import org.eclipse.core.filesystem.EFS;
import org.eclipse.core.filesystem.IFileStore;
import org.eclipse.core.filesystem.URIUtil;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Status;
import org.eclipse.debug.core.ILaunch;
import org.eclipse.debug.core.ILaunchConfiguration;
import org.eclipse.debug.core.ILaunchManager;
import org.eclipse.jdt.launching.IVMInstall;
import org.eclipse.jdt.launching.IVMInstall3;
import org.eclipse.jdt.launching.JavaLaunchDelegate;
import de.walware.ecommons.debug.ui.LaunchConfigUtil;
import de.walware.ecommons.net.RMIAddress;
import de.walware.statet.nico.core.runtime.ToolRunner;
import de.walware.rj.server.srvext.EServerUtil;
import de.walware.rj.server.srvext.ServerUtil;
import de.walware.statet.r.core.renv.IREnvConfiguration;
import de.walware.statet.r.internal.console.ui.RConsoleUIPlugin;
import de.walware.statet.r.launching.ui.REnvTab;
/**
* Launches RJ Server using JDT java launch mechanism
*/
public class RJEngineLaunchDelegate extends JavaLaunchDelegate {
private static final String[] CLASSPATH_LIBS = new String[] {
RJ_SERVER_ID, RJ_DATA_ID, "org.eclipse.swt", //$NON-NLS-1$
};
private static final String[] CODEBASE_LIBS = new String[] {
RJ_SERVER_ID,
};
private static final Pattern PATH_PATTERN = Pattern.compile("\\" + File.pathSeparatorChar);
private final String fAddress;
private final IREnvConfiguration fRenv;
private final String[] fCodebaseLibs;
private File fWorkingDirectory;
private IProgressMonitor fMonitor;
private String fLibPreloadVar;
private String fLibPreloadFile;
public RJEngineLaunchDelegate(final String address, final boolean requireCodebase,
final IREnvConfiguration renv) throws CoreException {
fAddress = address;
fRenv = renv;
fCodebaseLibs = (requireCodebase) ? CODEBASE_LIBS : null;
setLibPreload(true);
}
@Override
public void launch(final ILaunchConfiguration configuration, String mode,
final ILaunch launch, final IProgressMonitor monitor) throws CoreException {
fMonitor = (monitor != null) ? monitor : new NullProgressMonitor();
if (mode.equals(ILaunchManager.DEBUG_MODE)) {
// TODO add configuration option (-> source lookup support for Java)
mode = ILaunchManager.RUN_MODE;
}
super.launch(configuration, mode, launch, fMonitor);
}
@Override
public IPath getWorkingDirectoryPath(final ILaunchConfiguration configuration) throws CoreException {
final IFileStore workingDirectory = REnvTab.getWorkingDirectory(configuration);
return URIUtil.toPath(workingDirectory.toURI());
}
@Override
public File verifyWorkingDirectory(final ILaunchConfiguration configuration) throws CoreException {
return fWorkingDirectory = super.verifyWorkingDirectory(configuration);
}
public IFileStore getWorkingDirectory() {
if (fWorkingDirectory != null) {
return EFS.getLocalFileSystem().fromLocalFile(fWorkingDirectory);
}
return null;
}
public void setLibPreload(final boolean enable) {
if (enable) {
if (Platform.getOS().equals(Platform.OS_WIN32)) {
fLibPreloadVar = null;
fLibPreloadFile = null;
}
else if (Platform.getOS().equals(Platform.OS_MACOSX)) {
fLibPreloadVar = null;
// fLibPreloadFile = "DYLD_INSERT_LIBRARIES"; //$NON-NLS-1$
fLibPreloadFile = "libjsig.dylib"; //$NON-NLS-1$
}
else { // *nix
fLibPreloadVar = "LD_PRELOAD"; //$NON-NLS-1$
fLibPreloadFile = "libjsig.so"; //$NON-NLS-1$
}
}
else {
fLibPreloadVar = null;
fLibPreloadFile = null;
}
}
@Override
public String[] getEnvironment(final ILaunchConfiguration configuration) throws CoreException {
final IVMInstall vmInstall = getVMInstall(configuration); // already verified
final Map<String, String> additional = new HashMap<String, String>();
final File location = vmInstall.getInstallLocation();
if (location != null) {
additional.put("JAVA_HOME", location.getAbsolutePath()); //$NON-NLS-1$
}
@SuppressWarnings("unchecked")
final Map<String, String> envp = LaunchConfigUtil.createEnvironment(configuration,
new Map[] { additional, fRenv.getEnvironmentsVariables() });
if (fLibPreloadVar != null) {
String value = envp.get(fLibPreloadVar);
if (value == null || !value.contains("libjsig")) { //$NON-NLS-1$
final String path = (String) ((IVMInstall3) vmInstall).evaluateSystemProperties(
new String[] { "java.library.path" }, fMonitor).get("java.library.path"); //$NON-NLS-1$ //$NON-NLS-2$
if (path != null) {
final String[] pathList = PATH_PATTERN.split(path);
for (int i = 0; i < pathList.length; i++) {
final File file = new File(pathList[i], fLibPreloadFile);
if (file.exists()) {
final String s = file.getAbsolutePath();
if (s.indexOf(' ') < 0) { // whitespace is separator char
if (value != null && value.length() > 0) {
value = s + ' ' + value;
}
else {
value = s;
}
envp.put(fLibPreloadVar, value);
}
break;
}
}
}
}
}
return LaunchConfigUtil.toKeyValueStrings(envp);
}
@Override
public String[] getClasspath(final ILaunchConfiguration configuration) throws CoreException {
final String[] rjLibs = EServerUtil.searchRJLibsInPlatform(CLASSPATH_LIBS);
final LinkedHashSet<String> classpath = new LinkedHashSet<String>();
classpath.addAll(Arrays.asList(super.getClasspath(configuration)));
classpath.addAll(Arrays.asList(rjLibs));
return classpath.toArray(new String[classpath.size()]);
}
@Override
public String getVMArguments(final ILaunchConfiguration configuration) throws CoreException {
final String args = super.getVMArguments(configuration);
final StringBuilder s = new StringBuilder(" "); //$NON-NLS-1$
if (args != null) {
s.append(args);
}
if (s.indexOf(" -Djava.security.policy=") < 0) { //$NON-NLS-1$
try {
final URL intern = Platform.getBundle(RJ_SERVER_ID).getEntry("/localhost.policy"); //$NON-NLS-1$
final URL java = FileLocator.resolve(intern);
s.append(" -Djava.security.policy="); //$NON-NLS-1$
s.append('"');
s.append(java.toString());
s.append('"');
}
catch (final IOException e) {
RConsoleUIPlugin.log(new Status(IStatus.ERROR, RConsoleUIPlugin.PLUGIN_ID, -1,
"An error trying to resolve path to security policy", e )); //$NON-NLS-1$
}
}
if (s.indexOf(" -Djava.rmi.server.hostname=") < 0) { //$NON-NLS-1$
s.append(" -Djava.rmi.server.hostname="); //$NON-NLS-1$
s.append(RMIAddress.LOOPBACK.getHostAddress());
}
if (fCodebaseLibs != null && s.indexOf(" -Djava.rmi.server.codebase=") < 0) { //$NON-NLS-1$
s.append(" -Djava.rmi.server.codebase=\""); //$NON-NLS-1$
final String[] rjLibs = EServerUtil.searchRJLibsInPlatform(fCodebaseLibs);
s.append(ServerUtil.concatCodebase(rjLibs));
s.append("\""); //$NON-NLS-1$
}
if (!ToolRunner.captureLogOnly(configuration)
&& s.indexOf(" -Dde.walware.rj.verbose=") < 0 ) { //$NON-NLS-1$
s.append(" -Dde.walware.rj.verbose=true"); //$NON-NLS-1$
}
if (Platform.getOS().equals(Platform.OS_MACOSX)
&& s.indexOf(" -d32") < 0 && s.indexOf(" -d64") < 0) { //$NON-NLS-1$ //$NON-NLS-2$
final String rArch = fRenv.getSubArch();
if (rArch != null) {
if (rArch.equals("i386") || rArch.equals("i586") || rArch.equals("i686")) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- s.append("-d32"); //$NON-NLS-1$
+ s.append(" -d32"); //$NON-NLS-1$
}
else if (rArch.equals("x86_64")) { //$NON-NLS-1$
- s.append("-d64"); //$NON-NLS-1$
+ s.append(" -d64"); //$NON-NLS-1$
}
}
}
return s.substring(1);
}
@Override
public String getMainTypeName(final ILaunchConfiguration configuration) throws CoreException {
return "de.walware.rj.server.RMIServerControl"; //$NON-NLS-1$
}
@Override
public String getProgramArguments(final ILaunchConfiguration configuration) throws CoreException {
final StringBuilder args = new StringBuilder("start"); //$NON-NLS-1$
args.append(' ');
args.append(fAddress);
args.append(" -auth=none"); //$NON-NLS-1$
args.append(" -embedded");
args.append(" -plugins="); //$NON-NLS-1$
args.append("awt,"); //$NON-NLS-1$
if (Platform.getOS().equals(Platform.OS_WIN32)) {
args.append("swt,"); //$NON-NLS-1$
}
return args.toString();
}
@Override
protected void prepareStopInMain(final ILaunchConfiguration configuration) throws CoreException {
}
}
| false | true | public String[] getEnvironment(final ILaunchConfiguration configuration) throws CoreException {
final IVMInstall vmInstall = getVMInstall(configuration); // already verified
final Map<String, String> additional = new HashMap<String, String>();
final File location = vmInstall.getInstallLocation();
if (location != null) {
additional.put("JAVA_HOME", location.getAbsolutePath()); //$NON-NLS-1$
}
@SuppressWarnings("unchecked")
final Map<String, String> envp = LaunchConfigUtil.createEnvironment(configuration,
new Map[] { additional, fRenv.getEnvironmentsVariables() });
if (fLibPreloadVar != null) {
String value = envp.get(fLibPreloadVar);
if (value == null || !value.contains("libjsig")) { //$NON-NLS-1$
final String path = (String) ((IVMInstall3) vmInstall).evaluateSystemProperties(
new String[] { "java.library.path" }, fMonitor).get("java.library.path"); //$NON-NLS-1$ //$NON-NLS-2$
if (path != null) {
final String[] pathList = PATH_PATTERN.split(path);
for (int i = 0; i < pathList.length; i++) {
final File file = new File(pathList[i], fLibPreloadFile);
if (file.exists()) {
final String s = file.getAbsolutePath();
if (s.indexOf(' ') < 0) { // whitespace is separator char
if (value != null && value.length() > 0) {
value = s + ' ' + value;
}
else {
value = s;
}
envp.put(fLibPreloadVar, value);
}
break;
}
}
}
}
}
return LaunchConfigUtil.toKeyValueStrings(envp);
}
@Override
public String[] getClasspath(final ILaunchConfiguration configuration) throws CoreException {
final String[] rjLibs = EServerUtil.searchRJLibsInPlatform(CLASSPATH_LIBS);
final LinkedHashSet<String> classpath = new LinkedHashSet<String>();
classpath.addAll(Arrays.asList(super.getClasspath(configuration)));
classpath.addAll(Arrays.asList(rjLibs));
return classpath.toArray(new String[classpath.size()]);
}
@Override
public String getVMArguments(final ILaunchConfiguration configuration) throws CoreException {
final String args = super.getVMArguments(configuration);
final StringBuilder s = new StringBuilder(" "); //$NON-NLS-1$
if (args != null) {
s.append(args);
}
if (s.indexOf(" -Djava.security.policy=") < 0) { //$NON-NLS-1$
try {
final URL intern = Platform.getBundle(RJ_SERVER_ID).getEntry("/localhost.policy"); //$NON-NLS-1$
final URL java = FileLocator.resolve(intern);
s.append(" -Djava.security.policy="); //$NON-NLS-1$
s.append('"');
s.append(java.toString());
s.append('"');
}
catch (final IOException e) {
RConsoleUIPlugin.log(new Status(IStatus.ERROR, RConsoleUIPlugin.PLUGIN_ID, -1,
"An error trying to resolve path to security policy", e )); //$NON-NLS-1$
}
}
if (s.indexOf(" -Djava.rmi.server.hostname=") < 0) { //$NON-NLS-1$
s.append(" -Djava.rmi.server.hostname="); //$NON-NLS-1$
s.append(RMIAddress.LOOPBACK.getHostAddress());
}
if (fCodebaseLibs != null && s.indexOf(" -Djava.rmi.server.codebase=") < 0) { //$NON-NLS-1$
s.append(" -Djava.rmi.server.codebase=\""); //$NON-NLS-1$
final String[] rjLibs = EServerUtil.searchRJLibsInPlatform(fCodebaseLibs);
s.append(ServerUtil.concatCodebase(rjLibs));
s.append("\""); //$NON-NLS-1$
}
if (!ToolRunner.captureLogOnly(configuration)
&& s.indexOf(" -Dde.walware.rj.verbose=") < 0 ) { //$NON-NLS-1$
s.append(" -Dde.walware.rj.verbose=true"); //$NON-NLS-1$
}
if (Platform.getOS().equals(Platform.OS_MACOSX)
&& s.indexOf(" -d32") < 0 && s.indexOf(" -d64") < 0) { //$NON-NLS-1$ //$NON-NLS-2$
final String rArch = fRenv.getSubArch();
if (rArch != null) {
if (rArch.equals("i386") || rArch.equals("i586") || rArch.equals("i686")) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
s.append("-d32"); //$NON-NLS-1$
}
else if (rArch.equals("x86_64")) { //$NON-NLS-1$
s.append("-d64"); //$NON-NLS-1$
}
}
}
return s.substring(1);
}
@Override
public String getMainTypeName(final ILaunchConfiguration configuration) throws CoreException {
return "de.walware.rj.server.RMIServerControl"; //$NON-NLS-1$
}
@Override
public String getProgramArguments(final ILaunchConfiguration configuration) throws CoreException {
final StringBuilder args = new StringBuilder("start"); //$NON-NLS-1$
args.append(' ');
args.append(fAddress);
args.append(" -auth=none"); //$NON-NLS-1$
args.append(" -embedded");
args.append(" -plugins="); //$NON-NLS-1$
args.append("awt,"); //$NON-NLS-1$
if (Platform.getOS().equals(Platform.OS_WIN32)) {
args.append("swt,"); //$NON-NLS-1$
}
return args.toString();
}
@Override
protected void prepareStopInMain(final ILaunchConfiguration configuration) throws CoreException {
}
}
| public String[] getEnvironment(final ILaunchConfiguration configuration) throws CoreException {
final IVMInstall vmInstall = getVMInstall(configuration); // already verified
final Map<String, String> additional = new HashMap<String, String>();
final File location = vmInstall.getInstallLocation();
if (location != null) {
additional.put("JAVA_HOME", location.getAbsolutePath()); //$NON-NLS-1$
}
@SuppressWarnings("unchecked")
final Map<String, String> envp = LaunchConfigUtil.createEnvironment(configuration,
new Map[] { additional, fRenv.getEnvironmentsVariables() });
if (fLibPreloadVar != null) {
String value = envp.get(fLibPreloadVar);
if (value == null || !value.contains("libjsig")) { //$NON-NLS-1$
final String path = (String) ((IVMInstall3) vmInstall).evaluateSystemProperties(
new String[] { "java.library.path" }, fMonitor).get("java.library.path"); //$NON-NLS-1$ //$NON-NLS-2$
if (path != null) {
final String[] pathList = PATH_PATTERN.split(path);
for (int i = 0; i < pathList.length; i++) {
final File file = new File(pathList[i], fLibPreloadFile);
if (file.exists()) {
final String s = file.getAbsolutePath();
if (s.indexOf(' ') < 0) { // whitespace is separator char
if (value != null && value.length() > 0) {
value = s + ' ' + value;
}
else {
value = s;
}
envp.put(fLibPreloadVar, value);
}
break;
}
}
}
}
}
return LaunchConfigUtil.toKeyValueStrings(envp);
}
@Override
public String[] getClasspath(final ILaunchConfiguration configuration) throws CoreException {
final String[] rjLibs = EServerUtil.searchRJLibsInPlatform(CLASSPATH_LIBS);
final LinkedHashSet<String> classpath = new LinkedHashSet<String>();
classpath.addAll(Arrays.asList(super.getClasspath(configuration)));
classpath.addAll(Arrays.asList(rjLibs));
return classpath.toArray(new String[classpath.size()]);
}
@Override
public String getVMArguments(final ILaunchConfiguration configuration) throws CoreException {
final String args = super.getVMArguments(configuration);
final StringBuilder s = new StringBuilder(" "); //$NON-NLS-1$
if (args != null) {
s.append(args);
}
if (s.indexOf(" -Djava.security.policy=") < 0) { //$NON-NLS-1$
try {
final URL intern = Platform.getBundle(RJ_SERVER_ID).getEntry("/localhost.policy"); //$NON-NLS-1$
final URL java = FileLocator.resolve(intern);
s.append(" -Djava.security.policy="); //$NON-NLS-1$
s.append('"');
s.append(java.toString());
s.append('"');
}
catch (final IOException e) {
RConsoleUIPlugin.log(new Status(IStatus.ERROR, RConsoleUIPlugin.PLUGIN_ID, -1,
"An error trying to resolve path to security policy", e )); //$NON-NLS-1$
}
}
if (s.indexOf(" -Djava.rmi.server.hostname=") < 0) { //$NON-NLS-1$
s.append(" -Djava.rmi.server.hostname="); //$NON-NLS-1$
s.append(RMIAddress.LOOPBACK.getHostAddress());
}
if (fCodebaseLibs != null && s.indexOf(" -Djava.rmi.server.codebase=") < 0) { //$NON-NLS-1$
s.append(" -Djava.rmi.server.codebase=\""); //$NON-NLS-1$
final String[] rjLibs = EServerUtil.searchRJLibsInPlatform(fCodebaseLibs);
s.append(ServerUtil.concatCodebase(rjLibs));
s.append("\""); //$NON-NLS-1$
}
if (!ToolRunner.captureLogOnly(configuration)
&& s.indexOf(" -Dde.walware.rj.verbose=") < 0 ) { //$NON-NLS-1$
s.append(" -Dde.walware.rj.verbose=true"); //$NON-NLS-1$
}
if (Platform.getOS().equals(Platform.OS_MACOSX)
&& s.indexOf(" -d32") < 0 && s.indexOf(" -d64") < 0) { //$NON-NLS-1$ //$NON-NLS-2$
final String rArch = fRenv.getSubArch();
if (rArch != null) {
if (rArch.equals("i386") || rArch.equals("i586") || rArch.equals("i686")) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
s.append(" -d32"); //$NON-NLS-1$
}
else if (rArch.equals("x86_64")) { //$NON-NLS-1$
s.append(" -d64"); //$NON-NLS-1$
}
}
}
return s.substring(1);
}
@Override
public String getMainTypeName(final ILaunchConfiguration configuration) throws CoreException {
return "de.walware.rj.server.RMIServerControl"; //$NON-NLS-1$
}
@Override
public String getProgramArguments(final ILaunchConfiguration configuration) throws CoreException {
final StringBuilder args = new StringBuilder("start"); //$NON-NLS-1$
args.append(' ');
args.append(fAddress);
args.append(" -auth=none"); //$NON-NLS-1$
args.append(" -embedded");
args.append(" -plugins="); //$NON-NLS-1$
args.append("awt,"); //$NON-NLS-1$
if (Platform.getOS().equals(Platform.OS_WIN32)) {
args.append("swt,"); //$NON-NLS-1$
}
return args.toString();
}
@Override
protected void prepareStopInMain(final ILaunchConfiguration configuration) throws CoreException {
}
}
|
diff --git a/src/main/java/com/lordralex/totalpermissions/commands/subcommands/DebugCommand.java b/src/main/java/com/lordralex/totalpermissions/commands/subcommands/DebugCommand.java
index 4e32a59..43c1235 100644
--- a/src/main/java/com/lordralex/totalpermissions/commands/subcommands/DebugCommand.java
+++ b/src/main/java/com/lordralex/totalpermissions/commands/subcommands/DebugCommand.java
@@ -1,76 +1,76 @@
/*
* Copyright (C) 2013 LordRalex
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.lordralex.totalpermissions.commands.subcommands;
import com.lordralex.totalpermissions.TotalPermissions;
import com.lordralex.totalpermissions.permission.PermissionUser;
import org.bukkit.command.CommandSender;
/**
* @since 0.1
* @author Joshua
* @version 0.1
*/
public class DebugCommand implements SubCommand {
@Override
public String getName() {
return "debug";
}
@Override
public void execute(CommandSender sender, String[] args) {
if (args.length == 0) {
sender.sendMessage("No target specified, for help, use /totalperms help debug");
return;
}
- PermissionUser target = TotalPermissions.getPlugin().getManager().getUser(args[0]);
+ PermissionUser target = TotalPermissions.getPlugin().getManager().getUser(args[1]);
if (target == null) {
sender.sendMessage("Target user (" + args[0] + ") was not found");
return;
}
- boolean newState = true;
+ boolean newState = false;
if (args.length == 2) {
if (args[1].equalsIgnoreCase("on") || args[1].equalsIgnoreCase("enable") || args[1].equalsIgnoreCase("true")) {
newState = true;
} else if (args[1].equalsIgnoreCase("toggle")) {
newState = !target.getDebugState();
} else {
newState = false;
}
}
target.setDebug(newState);
if (target.getDebugState()) {
sender.sendMessage("Debug turned on for " + target.getName());
} else {
sender.sendMessage("Debug turned off for " + target.getName());
}
}
@Override
public String getPerm() {
return "totalpermissions.cmd.debug";
}
public String[] getHelp() {
return new String[]{
"Usage: /totalperms debug <user name>",
"This turns on debug mode for a user, which shows perms "
+ "needed to use commands by them and the permissions they have"
};
}
}
| false | true | public void execute(CommandSender sender, String[] args) {
if (args.length == 0) {
sender.sendMessage("No target specified, for help, use /totalperms help debug");
return;
}
PermissionUser target = TotalPermissions.getPlugin().getManager().getUser(args[0]);
if (target == null) {
sender.sendMessage("Target user (" + args[0] + ") was not found");
return;
}
boolean newState = true;
if (args.length == 2) {
if (args[1].equalsIgnoreCase("on") || args[1].equalsIgnoreCase("enable") || args[1].equalsIgnoreCase("true")) {
newState = true;
} else if (args[1].equalsIgnoreCase("toggle")) {
newState = !target.getDebugState();
} else {
newState = false;
}
}
target.setDebug(newState);
if (target.getDebugState()) {
sender.sendMessage("Debug turned on for " + target.getName());
} else {
sender.sendMessage("Debug turned off for " + target.getName());
}
}
| public void execute(CommandSender sender, String[] args) {
if (args.length == 0) {
sender.sendMessage("No target specified, for help, use /totalperms help debug");
return;
}
PermissionUser target = TotalPermissions.getPlugin().getManager().getUser(args[1]);
if (target == null) {
sender.sendMessage("Target user (" + args[0] + ") was not found");
return;
}
boolean newState = false;
if (args.length == 2) {
if (args[1].equalsIgnoreCase("on") || args[1].equalsIgnoreCase("enable") || args[1].equalsIgnoreCase("true")) {
newState = true;
} else if (args[1].equalsIgnoreCase("toggle")) {
newState = !target.getDebugState();
} else {
newState = false;
}
}
target.setDebug(newState);
if (target.getDebugState()) {
sender.sendMessage("Debug turned on for " + target.getName());
} else {
sender.sendMessage("Debug turned off for " + target.getName());
}
}
|
diff --git a/src/java/org/apache/fop/render/ps/PSDocumentGraphics2D.java b/src/java/org/apache/fop/render/ps/PSDocumentGraphics2D.java
index f462b8873..ebed0f7c6 100644
--- a/src/java/org/apache/fop/render/ps/PSDocumentGraphics2D.java
+++ b/src/java/org/apache/fop/render/ps/PSDocumentGraphics2D.java
@@ -1,288 +1,288 @@
/*
* $Id: PDFDocumentGraphics2D.java,v 1.27 2003/03/07 09:51:26 jeremias Exp $
* ============================================================================
* The Apache Software License, Version 1.1
* ============================================================================
*
* Copyright (C) 1999-2003 The Apache Software Foundation. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modifica-
* tion, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. The end-user documentation included with the redistribution, if any, must
* include the following acknowledgment: "This product includes software
* developed by the Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself, if
* and wherever such third-party acknowledgments normally appear.
*
* 4. The names "FOP" and "Apache Software Foundation" must not be used to
* endorse or promote products derived from this software without prior
* written permission. For written permission, please contact
* [email protected].
*
* 5. Products derived from this software may not be called "Apache", nor may
* "Apache" appear in their name, without prior written permission of the
* Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
* DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* ============================================================================
*
* This software consists of voluntary contributions made by many individuals
* on behalf of the Apache Software Foundation and was originally created by
* James Tauber <[email protected]>. For more information on the Apache
* Software Foundation, please see <http://www.apache.org/>.
*/
package org.apache.fop.render.ps;
//Java
import java.awt.Graphics;
import java.awt.Font;
import java.awt.Color;
import java.awt.Shape;
import java.awt.font.FontRenderContext;
import java.awt.font.GlyphVector;
import java.io.OutputStream;
import java.io.IOException;
//FOP
import org.apache.fop.render.pdf.FontSetup;
import org.apache.fop.layout.FontInfo;
/**
* This class is a wrapper for the <tt>PSGraphics2D</tt> that
* is used to create a full document around the PostScript rendering from
* <tt>PSGraphics2D</tt>.
*
* @author <a href="mailto:[email protected]">Keiron Liddle</a>
* @author <a href="mailto:[email protected]">Jeremias Maerki</a>
* @version $Id: PDFDocumentGraphics2D.java,v 1.27 2003/03/07 09:51:26 jeremias Exp $
* @see org.apache.fop.svg.PSGraphics2D
*/
public class PSDocumentGraphics2D extends PSGraphics2D {
private int width;
private int height;
/**
* Create a new PSDocumentGraphics2D.
* This is used to create a new PostScript document, the height,
* width and output stream can be setup later.
* For use by the transcoder which needs font information
* for the bridge before the document size is known.
* The resulting document is written to the stream after rendering.
*
* @param textAsShapes set this to true so that text will be rendered
* using curves and not the font.
*/
PSDocumentGraphics2D(boolean textAsShapes) {
super(textAsShapes);
if (!textAsShapes) {
fontInfo = new FontInfo();
FontSetup.setup(fontInfo, null);
//FontState fontState = new FontState("Helvetica", "normal",
// FontInfo.NORMAL, 12, 0);
}
currentFontName = "";
currentFontSize = 0;
}
/**
* Setup the document.
* @param stream the output stream to write the document
* @param width the width of the page
* @param height the height of the page
* @throws IOException an io exception if there is a problem
* writing to the output stream
*/
public void setupDocument(OutputStream stream, int width, int height) throws IOException {
this.width = width;
this.height = height;
final Integer zero = new Integer(0);
final Long pagewidth = new Long(this.width);
final Long pageheight = new Long(this.height);
//Setup for PostScript generation
setPSGenerator(new PSGenerator(stream));
//PostScript Header
gen.writeln(DSCConstants.PS_ADOBE_30);
gen.writeDSCComment(DSCConstants.CREATOR,
new String[] {"FOP PostScript Transcoder for SVG"});
gen.writeDSCComment(DSCConstants.CREATION_DATE,
new Object[] {new java.util.Date()});
gen.writeDSCComment(DSCConstants.PAGES, new Object[] {new Integer(1)});
gen.writeDSCComment(DSCConstants.BBOX, new Object[]
{zero, zero, pagewidth, pageheight});
gen.writeDSCComment(DSCConstants.END_COMMENTS);
//Defaults
gen.writeDSCComment(DSCConstants.BEGIN_DEFAULTS);
gen.writeDSCComment(DSCConstants.END_DEFAULTS);
//Prolog
gen.writeDSCComment(DSCConstants.BEGIN_PROLOG);
gen.writeDSCComment(DSCConstants.END_PROLOG);
//Setup
gen.writeDSCComment(DSCConstants.BEGIN_SETUP);
PSProcSets.writeFOPStdProcSet(gen);
PSProcSets.writeFOPEPSProcSet(gen);
- PSRenderer.writeFontDict(gen, fontInfo);
+ PSProcSets.writeFontDict(gen, fontInfo);
gen.writeDSCComment(DSCConstants.END_SETUP);
//Start page
Integer pageNumber = new Integer(1);
gen.writeDSCComment(DSCConstants.PAGE, new Object[]
{pageNumber.toString(), pageNumber});
gen.writeDSCComment(DSCConstants.PAGE_BBOX, new Object[]
{zero, zero, pagewidth, pageheight});
gen.writeDSCComment(DSCConstants.BEGIN_PAGE_SETUP);
gen.writeln("FOPFonts begin");
gen.writeln("0.001 0.001 scale");
gen.concatMatrix(1, 0, 0, -1, 0, pageheight.doubleValue() * 1000);
gen.writeDSCComment(DSCConstants.END_PAGE_SETUP);
}
/**
* Create a new PSDocumentGraphics2D.
* This is used to create a new PostScript document of the given height
* and width.
* The resulting document is written to the stream after rendering.
*
* @param textAsShapes set this to true so that text will be rendered
* using curves and not the font.
* @param stream the stream that the final document should be written to.
* @param width the width of the document
* @param height the height of the document
* @throws IOException an io exception if there is a problem
* writing to the output stream
*/
public PSDocumentGraphics2D(boolean textAsShapes, OutputStream stream,
int width, int height) throws IOException {
this(textAsShapes);
setupDocument(stream, width, height);
}
/**
* Get the font info for this PostScript document.
* @return the font information
*/
public FontInfo getFontInfo() {
return fontInfo;
}
/**
* Set the dimensions of the SVG document that will be drawn.
* This is useful if the dimensions of the SVG document are different
* from the PostScript document that is to be created.
* The result is scaled so that the SVG fits correctly inside the
* PostScript document.
* @param w the width of the page
* @param h the height of the page
* @throws IOException in case of an I/O problem
*/
public void setSVGDimension(float w, float h) throws IOException {
gen.concatMatrix(width / w, 0, 0, height / h, 0, 0);
}
/**
* Set the background of the PostScript document.
* This is used to set the background for the PostScript document
* Rather than leaving it as the default white.
* @param col the background colour to fill
*/
public void setBackgroundColor(Color col) {
/**@todo Implement this */
/*
Color c = col;
PDFColor currentColour = new PDFColor(c.getRed(), c.getGreen(), c.getBlue());
currentStream.write("q\n");
currentStream.write(currentColour.getColorSpaceOut(true));
currentStream.write("0 0 " + width + " " + height + " re\n");
currentStream.write("f\n");
currentStream.write("Q\n");
*/
}
/**
* The rendering process has finished.
* This should be called after the rendering has completed as there is
* no other indication it is complete.
* This will then write the results to the output stream.
* @throws IOException an io exception if there is a problem
* writing to the output stream
*/
public void finish() throws IOException {
//Finish page
gen.writeln("showpage");
gen.writeDSCComment(DSCConstants.PAGE_TRAILER);
gen.writeDSCComment(DSCConstants.END_PAGE);
//Finish document
gen.writeDSCComment(DSCConstants.TRAILER);
gen.writeDSCComment(DSCConstants.EOF);
gen.flush();
}
/**
* This constructor supports the create method
* @param g the PostScript document graphics to make a copy of
*/
public PSDocumentGraphics2D(PSDocumentGraphics2D g) {
super(g);
}
/**
* Creates a new <code>Graphics</code> object that is
* a copy of this <code>Graphics</code> object.
* @return a new graphics context that is a copy of
* this graphics context.
*/
public Graphics create() {
return new PSDocumentGraphics2D(this);
}
/**
* Draw a string to the PostScript document.
* This either draws the string directly or if drawing text as
* shapes it converts the string into shapes and draws that.
* @param s the string to draw
* @param x the x position
* @param y the y position
*/
public void drawString(String s, float x, float y) {
if (super.textAsShapes) {
Font font = super.getFont();
FontRenderContext frc = super.getFontRenderContext();
GlyphVector gv = font.createGlyphVector(frc, s);
Shape glyphOutline = gv.getOutline(x, y);
super.fill(glyphOutline);
} else {
super.drawString(s, x, y);
}
}
}
| true | true | public void setupDocument(OutputStream stream, int width, int height) throws IOException {
this.width = width;
this.height = height;
final Integer zero = new Integer(0);
final Long pagewidth = new Long(this.width);
final Long pageheight = new Long(this.height);
//Setup for PostScript generation
setPSGenerator(new PSGenerator(stream));
//PostScript Header
gen.writeln(DSCConstants.PS_ADOBE_30);
gen.writeDSCComment(DSCConstants.CREATOR,
new String[] {"FOP PostScript Transcoder for SVG"});
gen.writeDSCComment(DSCConstants.CREATION_DATE,
new Object[] {new java.util.Date()});
gen.writeDSCComment(DSCConstants.PAGES, new Object[] {new Integer(1)});
gen.writeDSCComment(DSCConstants.BBOX, new Object[]
{zero, zero, pagewidth, pageheight});
gen.writeDSCComment(DSCConstants.END_COMMENTS);
//Defaults
gen.writeDSCComment(DSCConstants.BEGIN_DEFAULTS);
gen.writeDSCComment(DSCConstants.END_DEFAULTS);
//Prolog
gen.writeDSCComment(DSCConstants.BEGIN_PROLOG);
gen.writeDSCComment(DSCConstants.END_PROLOG);
//Setup
gen.writeDSCComment(DSCConstants.BEGIN_SETUP);
PSProcSets.writeFOPStdProcSet(gen);
PSProcSets.writeFOPEPSProcSet(gen);
PSRenderer.writeFontDict(gen, fontInfo);
gen.writeDSCComment(DSCConstants.END_SETUP);
//Start page
Integer pageNumber = new Integer(1);
gen.writeDSCComment(DSCConstants.PAGE, new Object[]
{pageNumber.toString(), pageNumber});
gen.writeDSCComment(DSCConstants.PAGE_BBOX, new Object[]
{zero, zero, pagewidth, pageheight});
gen.writeDSCComment(DSCConstants.BEGIN_PAGE_SETUP);
gen.writeln("FOPFonts begin");
gen.writeln("0.001 0.001 scale");
gen.concatMatrix(1, 0, 0, -1, 0, pageheight.doubleValue() * 1000);
gen.writeDSCComment(DSCConstants.END_PAGE_SETUP);
}
| public void setupDocument(OutputStream stream, int width, int height) throws IOException {
this.width = width;
this.height = height;
final Integer zero = new Integer(0);
final Long pagewidth = new Long(this.width);
final Long pageheight = new Long(this.height);
//Setup for PostScript generation
setPSGenerator(new PSGenerator(stream));
//PostScript Header
gen.writeln(DSCConstants.PS_ADOBE_30);
gen.writeDSCComment(DSCConstants.CREATOR,
new String[] {"FOP PostScript Transcoder for SVG"});
gen.writeDSCComment(DSCConstants.CREATION_DATE,
new Object[] {new java.util.Date()});
gen.writeDSCComment(DSCConstants.PAGES, new Object[] {new Integer(1)});
gen.writeDSCComment(DSCConstants.BBOX, new Object[]
{zero, zero, pagewidth, pageheight});
gen.writeDSCComment(DSCConstants.END_COMMENTS);
//Defaults
gen.writeDSCComment(DSCConstants.BEGIN_DEFAULTS);
gen.writeDSCComment(DSCConstants.END_DEFAULTS);
//Prolog
gen.writeDSCComment(DSCConstants.BEGIN_PROLOG);
gen.writeDSCComment(DSCConstants.END_PROLOG);
//Setup
gen.writeDSCComment(DSCConstants.BEGIN_SETUP);
PSProcSets.writeFOPStdProcSet(gen);
PSProcSets.writeFOPEPSProcSet(gen);
PSProcSets.writeFontDict(gen, fontInfo);
gen.writeDSCComment(DSCConstants.END_SETUP);
//Start page
Integer pageNumber = new Integer(1);
gen.writeDSCComment(DSCConstants.PAGE, new Object[]
{pageNumber.toString(), pageNumber});
gen.writeDSCComment(DSCConstants.PAGE_BBOX, new Object[]
{zero, zero, pagewidth, pageheight});
gen.writeDSCComment(DSCConstants.BEGIN_PAGE_SETUP);
gen.writeln("FOPFonts begin");
gen.writeln("0.001 0.001 scale");
gen.concatMatrix(1, 0, 0, -1, 0, pageheight.doubleValue() * 1000);
gen.writeDSCComment(DSCConstants.END_PAGE_SETUP);
}
|
diff --git a/src/dk/dbc/opensearch/components/datadock/DatadockPool.java b/src/dk/dbc/opensearch/components/datadock/DatadockPool.java
index 3f41fcaf..27eca965 100644
--- a/src/dk/dbc/opensearch/components/datadock/DatadockPool.java
+++ b/src/dk/dbc/opensearch/components/datadock/DatadockPool.java
@@ -1,165 +1,168 @@
/**
* \file DatadockPool.java
* \brief The DatadockPool class
* \package datadock;
*/
package dk.dbc.opensearch.components.datadock;
import dk.dbc.opensearch.common.types.DatadockJob;
import dk.dbc.opensearch.common.types.CompletedTask;
import dk.dbc.opensearch.common.statistics.Estimate;
import dk.dbc.opensearch.common.db.Processqueue;
import dk.dbc.opensearch.common.fedora.FedoraHandler;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.ClassNotFoundException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.Vector;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.log4j.Logger;
/**
* \ingroup datadock
*
* \brief The datadockPool manages the datadock threads and provides methods
* to add and check running jobs
*/
public class DatadockPool
{
static Logger log = Logger.getLogger("DatadockPool");
private Vector<FutureTask<DatadockThread>> jobs;
private final ThreadPoolExecutor threadpool;
private Estimate estimate;
private Processqueue processqueue;
private FedoraHandler fedoraHandler;
private int shutDownPollTime;
/**
* Constructs the the datadockPool instance
*
* @param threadpool The threadpool to submit jobs to
* @param estimate the estimation database handler
* @param processqueue the processqueue handler
* @param fedoraHandler the fedora repository handler
*/
public DatadockPool( ThreadPoolExecutor threadpool, Estimate estimate, Processqueue processqueue, FedoraHandler fedoraHandler )
{
log.debug( "Constructor( threadpool, estimat, processqueue, fedoraHandler ) called" );
this.threadpool = threadpool;
this.estimate = estimate;
this.processqueue = processqueue;
this.fedoraHandler = fedoraHandler;
jobs = new Vector<FutureTask<DatadockThread>>();
shutDownPollTime = 1000; // configuration file
}
/**
* submits a job to the threadpool for execution by a datadockThread.
*
* @param DatadockJob The job to start.
*
* @throws RejectedExecutionException Thrown if the threadpools jobqueue is full.
*/
public void submit( DatadockJob datadockJob ) throws RejectedExecutionException, ConfigurationException, ClassNotFoundException, FileNotFoundException, IOException
{
log.debug( String.format( "submit( path='%s', submitter='%s', format='%s' )",
datadockJob.getPath().getRawPath(), datadockJob.getSubmitter(), datadockJob.getFormat() ) );
FutureTask future = getTask( datadockJob );
threadpool.submit( future );
jobs.add( future );
}
public FutureTask getTask( DatadockJob datadockJob )throws ConfigurationException, ClassNotFoundException, FileNotFoundException, IOException
{
return new FutureTask( new DatadockThread( datadockJob, estimate, processqueue, fedoraHandler ) );
}
/**
* Checks the jobs submitted for execution, and return the number
* of active jobs.
*
* if a Job throws an exception it is written to the log and the
* datadock continues.
*
* @throws InterruptedException if the job.get() call is interrupted (by kill or otherwise).
*/
public Vector<CompletedTask> checkJobs() throws InterruptedException
{
log.debug( "checkJobs() called" );
Vector<CompletedTask> finishedJobs = new Vector<CompletedTask>();
for( FutureTask job : jobs )
{
if( job.isDone() )
{
+ Float f = -1f;
//log.fatal( "Catched exception from job" );
try
{
log.debug( "Checking job" );
- Float f = (Float) job.get();
- finishedJobs.add( new CompletedTask( job, f ) );
+ f = (Float) job.get();
}
catch( ExecutionException ee )
{
log.fatal( "Exception caught from job" );
//jobs.remove( job );
// getting exception from thread
Throwable cause = ee.getCause();
RuntimeException re = new RuntimeException( cause );
log.error( String.format( "Exception Caught: '%s'\n'%s'" , re.getMessage(), re.getStackTrace() ) );
// throw re; //shouldnt throw just because thread throw
}
+ log.debug( "adding to finished jobs" );
+ finishedJobs.add( new CompletedTask( job, f ) );
}
}
for( CompletedTask finishedJob : finishedJobs )
{
+ log.debug( "Removing Job" );
jobs.remove( finishedJob.getFuture() );
}
return finishedJobs;
}
/**
* Shuts down the datadockPool. it waits for all current jobs to
* finish before exiting.
*
* @throws InterruptedException if the checkJobs or sleep call is interrupted (by kill or otherwise).
*/
public void shutdown() throws InterruptedException
{
log.debug( "shutdown() called" );
boolean activeJobs = true;
while( activeJobs )
{
activeJobs = false;
for( FutureTask job : jobs )
{
if( ! job.isDone() )
{
activeJobs = true;
}
}
}
}
}
| false | true | public Vector<CompletedTask> checkJobs() throws InterruptedException
{
log.debug( "checkJobs() called" );
Vector<CompletedTask> finishedJobs = new Vector<CompletedTask>();
for( FutureTask job : jobs )
{
if( job.isDone() )
{
//log.fatal( "Catched exception from job" );
try
{
log.debug( "Checking job" );
Float f = (Float) job.get();
finishedJobs.add( new CompletedTask( job, f ) );
}
catch( ExecutionException ee )
{
log.fatal( "Exception caught from job" );
//jobs.remove( job );
// getting exception from thread
Throwable cause = ee.getCause();
RuntimeException re = new RuntimeException( cause );
log.error( String.format( "Exception Caught: '%s'\n'%s'" , re.getMessage(), re.getStackTrace() ) );
// throw re; //shouldnt throw just because thread throw
}
}
}
for( CompletedTask finishedJob : finishedJobs )
{
jobs.remove( finishedJob.getFuture() );
}
return finishedJobs;
}
| public Vector<CompletedTask> checkJobs() throws InterruptedException
{
log.debug( "checkJobs() called" );
Vector<CompletedTask> finishedJobs = new Vector<CompletedTask>();
for( FutureTask job : jobs )
{
if( job.isDone() )
{
Float f = -1f;
//log.fatal( "Catched exception from job" );
try
{
log.debug( "Checking job" );
f = (Float) job.get();
}
catch( ExecutionException ee )
{
log.fatal( "Exception caught from job" );
//jobs.remove( job );
// getting exception from thread
Throwable cause = ee.getCause();
RuntimeException re = new RuntimeException( cause );
log.error( String.format( "Exception Caught: '%s'\n'%s'" , re.getMessage(), re.getStackTrace() ) );
// throw re; //shouldnt throw just because thread throw
}
log.debug( "adding to finished jobs" );
finishedJobs.add( new CompletedTask( job, f ) );
}
}
for( CompletedTask finishedJob : finishedJobs )
{
log.debug( "Removing Job" );
jobs.remove( finishedJob.getFuture() );
}
return finishedJobs;
}
|
diff --git a/src/java/org/codehaus/groovy/grails/compiler/injection/GlobalPluginAwareEntityASTTransformation.java b/src/java/org/codehaus/groovy/grails/compiler/injection/GlobalPluginAwareEntityASTTransformation.java
index 0f8eb2604..5485b5da2 100644
--- a/src/java/org/codehaus/groovy/grails/compiler/injection/GlobalPluginAwareEntityASTTransformation.java
+++ b/src/java/org/codehaus/groovy/grails/compiler/injection/GlobalPluginAwareEntityASTTransformation.java
@@ -1,88 +1,89 @@
/* 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.compiler.injection;
import grails.util.PluginBuildSettings;
import org.codehaus.groovy.ast.ASTNode;
import org.codehaus.groovy.ast.AnnotationNode;
import org.codehaus.groovy.ast.ClassNode;
import org.codehaus.groovy.ast.ModuleNode;
import org.codehaus.groovy.ast.expr.ConstantExpression;
import org.codehaus.groovy.control.CompilePhase;
import org.codehaus.groovy.control.SourceUnit;
import org.codehaus.groovy.grails.plugins.GrailsPluginUtils;
import org.codehaus.groovy.grails.plugins.PluginInfo;
import org.codehaus.groovy.grails.plugins.metadata.GrailsPlugin;
import org.codehaus.groovy.transform.ASTTransformation;
import org.codehaus.groovy.transform.GroovyASTTransformation;
import java.io.File;
import java.io.IOException;
import java.util.List;
/**
* This AST transformation automatically annotates any class
* with @Plugin(name="foo") if it is a plugin resource
*
* @author Graeme Rocher
* @since 1.2
*/
@GroovyASTTransformation(phase = CompilePhase.CANONICALIZATION)
public class GlobalPluginAwareEntityASTTransformation implements ASTTransformation {
private boolean disableTransformation = Boolean.getBoolean("disable.grails.plugin.transform");
public void visit(ASTNode[] astNodes, SourceUnit sourceUnit) {
if(disableTransformation) return;
ASTNode astNode = astNodes[0];
if(astNode instanceof ModuleNode) {
ModuleNode moduleNode = (ModuleNode) astNode;
List classes = moduleNode.getClasses();
if(classes.size()>0) {
ClassNode classNode = (ClassNode) classes.get(0);
+ if(classNode.isAnnotationDefinition()) return;
File sourcePath = new File(sourceUnit.getName());
try {
String absolutePath = sourcePath.getCanonicalPath();
PluginBuildSettings pluginBuildSettings = GrailsPluginUtils.getPluginBuildSettings();
if(pluginBuildSettings!=null) {
PluginInfo info = pluginBuildSettings.getPluginInfoForSource(absolutePath);
if(info!=null) {
final ClassNode annotation = new ClassNode(GrailsPlugin.class);
final List list = classNode.getAnnotations(annotation);
if(list.size()==0) {
final AnnotationNode annotationNode = new AnnotationNode(annotation);
annotationNode.addMember(org.codehaus.groovy.grails.plugins.GrailsPlugin.NAME, new ConstantExpression(info.getName()));
annotationNode.addMember(org.codehaus.groovy.grails.plugins.GrailsPlugin.VERSION, new ConstantExpression(info.getVersion()));
annotationNode.setRuntimeRetention(true);
annotationNode.setClassRetention(true);
classNode.addAnnotation(annotationNode);
}
}
}
}
catch (IOException e) {
// ignore
}
}
}
}
}
| true | true | public void visit(ASTNode[] astNodes, SourceUnit sourceUnit) {
if(disableTransformation) return;
ASTNode astNode = astNodes[0];
if(astNode instanceof ModuleNode) {
ModuleNode moduleNode = (ModuleNode) astNode;
List classes = moduleNode.getClasses();
if(classes.size()>0) {
ClassNode classNode = (ClassNode) classes.get(0);
File sourcePath = new File(sourceUnit.getName());
try {
String absolutePath = sourcePath.getCanonicalPath();
PluginBuildSettings pluginBuildSettings = GrailsPluginUtils.getPluginBuildSettings();
if(pluginBuildSettings!=null) {
PluginInfo info = pluginBuildSettings.getPluginInfoForSource(absolutePath);
if(info!=null) {
final ClassNode annotation = new ClassNode(GrailsPlugin.class);
final List list = classNode.getAnnotations(annotation);
if(list.size()==0) {
final AnnotationNode annotationNode = new AnnotationNode(annotation);
annotationNode.addMember(org.codehaus.groovy.grails.plugins.GrailsPlugin.NAME, new ConstantExpression(info.getName()));
annotationNode.addMember(org.codehaus.groovy.grails.plugins.GrailsPlugin.VERSION, new ConstantExpression(info.getVersion()));
annotationNode.setRuntimeRetention(true);
annotationNode.setClassRetention(true);
classNode.addAnnotation(annotationNode);
}
}
}
}
catch (IOException e) {
// ignore
}
}
}
}
| public void visit(ASTNode[] astNodes, SourceUnit sourceUnit) {
if(disableTransformation) return;
ASTNode astNode = astNodes[0];
if(astNode instanceof ModuleNode) {
ModuleNode moduleNode = (ModuleNode) astNode;
List classes = moduleNode.getClasses();
if(classes.size()>0) {
ClassNode classNode = (ClassNode) classes.get(0);
if(classNode.isAnnotationDefinition()) return;
File sourcePath = new File(sourceUnit.getName());
try {
String absolutePath = sourcePath.getCanonicalPath();
PluginBuildSettings pluginBuildSettings = GrailsPluginUtils.getPluginBuildSettings();
if(pluginBuildSettings!=null) {
PluginInfo info = pluginBuildSettings.getPluginInfoForSource(absolutePath);
if(info!=null) {
final ClassNode annotation = new ClassNode(GrailsPlugin.class);
final List list = classNode.getAnnotations(annotation);
if(list.size()==0) {
final AnnotationNode annotationNode = new AnnotationNode(annotation);
annotationNode.addMember(org.codehaus.groovy.grails.plugins.GrailsPlugin.NAME, new ConstantExpression(info.getName()));
annotationNode.addMember(org.codehaus.groovy.grails.plugins.GrailsPlugin.VERSION, new ConstantExpression(info.getVersion()));
annotationNode.setRuntimeRetention(true);
annotationNode.setClassRetention(true);
classNode.addAnnotation(annotationNode);
}
}
}
}
catch (IOException e) {
// ignore
}
}
}
}
|
diff --git a/src/com/flashmath/activity/ResultActivity.java b/src/com/flashmath/activity/ResultActivity.java
index ac2d650..63d266a 100644
--- a/src/com/flashmath/activity/ResultActivity.java
+++ b/src/com/flashmath/activity/ResultActivity.java
@@ -1,303 +1,303 @@
package com.flashmath.activity;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Calendar;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ActionBar;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Gravity;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;
import com.codepath.oauth.OAuthLoginActivity;
import com.education.flashmath.R;
import com.flashmath.models.OfflineScore;
import com.flashmath.models.Question;
import com.flashmath.network.FlashMathClient;
import com.flashmath.network.TwitterClient;
import com.flashmath.util.ColorUtil;
import com.flashmath.util.ConnectivityUtil;
import com.flashmath.util.SoundUtil;
import com.jjoe64.graphview.CustomLabelFormatter;
import com.jjoe64.graphview.GraphView;
import com.jjoe64.graphview.GraphView.GraphViewData;
import com.jjoe64.graphview.GraphViewSeries;
import com.jjoe64.graphview.GraphViewSeries.GraphViewSeriesStyle;
import com.jjoe64.graphview.GraphViewStyle;
import com.jjoe64.graphview.LineGraphView;
import com.loopj.android.http.JsonHttpResponseHandler;
public class ResultActivity extends OAuthLoginActivity<TwitterClient> {
public static final String SUBJECT_INTENT_KEY = "subject";
private ArrayList<Question> resultList;
private int score = 0;
private String subject;
private LinearLayout llStats;
private TextView tvTotal;
private TextView tvScore;
private TextView tvSubject;
private Button btnMainMenu;
private boolean wentThroughTwitterFlow = false;
private boolean isMockQuiz;
@SuppressWarnings("unchecked")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.activity_result);
wentThroughTwitterFlow = false;
llStats = (LinearLayout) findViewById(R.id.llStats);
tvTotal = (TextView) findViewById(R.id.tvTotal);
tvScore = (TextView) findViewById(R.id.tvScore);
tvSubject = (TextView) findViewById(R.id.tvSubject);
btnMainMenu = (Button) findViewById(R.id.btnMainMenu);
if (savedInstanceState == null) {
resultList = (ArrayList<Question>) getIntent().getSerializableExtra("QUESTIONS_ANSWERED");
subject = getIntent().getStringExtra(SUBJECT_INTENT_KEY);
isMockQuiz = getIntent().getBooleanExtra(QuestionActivity.IS_MOCK_QUIZ_INTENT_KEY, true);
evaluate();
}
}
private void playSounds(float pc) {
if (pc >= .8) {
SoundUtil.playSound(this, 3);
} else if (pc >= .5) {
SoundUtil.playSound(this, 2);
} else {
SoundUtil.playSound(this, 1);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.result, menu);
return true;
}
public void evaluate(){
//if (resultList != null) {
ActionBar ab = getActionBar();
ab.setIcon(ColorUtil.getBarIcon(subject, this));
for(int i = 0; i < resultList.size(); i++){
String correctAnswer = resultList.get(i).getCorrectAnswer();
if (resultList.get(i).getUserAnswer().equals(correctAnswer)){
score++;
}
}
Button btnTweet = (Button) findViewById(R.id.btnTweet);
btnTweet.setBackground(ColorUtil.getButtonStyle(subject, this));
btnMainMenu.setBackground(ColorUtil.getButtonStyle(subject, this));
tvScore.setText(String.valueOf(score));
tvScore.setTextColor(ColorUtil.getScoreColor((float) score / resultList.size()));
tvTotal.setText("/ " + String.valueOf(resultList.size()));
String subjectTitle = Character.toUpperCase(subject.charAt(0))+subject.substring(1);
ab.setTitle(subjectTitle + " Results");
tvSubject.setText(" Score History for " + subjectTitle + " ");
tvSubject.setBackgroundColor(ColorUtil.subjectColorInt(subject));
tvSubject.setTextColor(Color.WHITE);
FlashMathClient client = FlashMathClient.getClient(this);
boolean isConnectionAvailable = ConnectivityUtil.isInternetConnectionAvailable(this.getApplicationContext());
//Real quiz && Internet is available
if (!isMockQuiz) {
if (isConnectionAvailable) {
setProgressBarIndeterminateVisibility(true);
btnMainMenu.setEnabled(false);
client.putScore(subject, String.valueOf(score), new JsonHttpResponseHandler() {
@Override
public void onSuccess(JSONArray jsonScores) {
if (jsonScores != null && jsonScores.length() > 1) {
GraphViewData[] data = new GraphViewData[jsonScores.length()];
int max_score = 1;
for (int i = 0; i < jsonScores.length(); i++) {
try {
int val = jsonScores.getJSONObject(i).getInt("value");
max_score = val > max_score ? val : max_score;
data[i] = (new GraphViewData(i + 1, val));
} catch (JSONException e) {
e.printStackTrace();
}
}
GraphView graphView = new LineGraphView(ResultActivity.this, "");
graphView.setCustomLabelFormatter(new CustomLabelFormatter.IntegerOnly());
GraphViewStyle style = new GraphViewStyle();
style.setVerticalLabelsColor(Color.BLACK);
style.setHorizontalLabelsColor(Color.BLACK);
style.setGridColor(Color.GRAY);
style.setNumVerticalLabels(4);
style.setNumHorizontalLabels(2);
GraphViewSeriesStyle lineStyle = new GraphViewSeriesStyle(ColorUtil.subjectColorInt(subject), 5);
graphView.addSeries(new GraphViewSeries("Scores", lineStyle, data));
graphView.addSeries(new GraphViewSeries(new GraphViewData[] { new GraphViewData(1, 0) }));
graphView.addSeries(new GraphViewSeries(new GraphViewData[] { new GraphViewData(2, 3) }));
graphView.setGraphViewStyle(style);
llStats.addView(graphView);
} else {
- showAlternativeTextForGraph("Not enough scores to show graph. Please do the quiz one more time!");
+ showAlternativeTextForGraph("You need to take more tests before we can make you a graph!");
}
setProgressBarIndeterminateVisibility(false);
btnMainMenu.setEnabled(true);
}
@Override
public void onFailure(Throwable arg0, JSONObject errorResponse) {
super.onFailure(arg0, errorResponse);
setProgressBarIndeterminateVisibility(false);
btnMainMenu.setEnabled(true);
showAlternativeTextForGraph("Could not load historical data. Please try again later!");
}
});
} else {
// Real quiz but no Internet
OfflineScore os = new OfflineScore();
os.setScore(score);
os.setSubject(subject);
Calendar c = Calendar.getInstance();
os.setTimeStampInSeconds(c.get(Calendar.SECOND));
//ConnectivityUtil.setUnsentScore(os);
os.save();
showAlternativeTextForGraph("Your results will be submitted when internet connection is back.");
}
} else {
if(!isConnectionAvailable) {
//Mock quiz and no Internet
showAlternativeTextForGraph("Thank you for completing the offline quiz! Your score will not be submitted.");
} else {
//Mock quiz and Internet
showAlternativeTextForGraph("Thank you for completing the offline quiz! You can try now real quiz in the Main Menu.");
}
}
playSounds((float) score / resultList.size());
}
public void tweetScore(View v) {
if (ConnectivityUtil.isInternetConnectionAvailable(this)) {
if (!getClient().isAuthenticated()) {
getClient().connect();
wentThroughTwitterFlow = true;
} else {
tweet();
}
} else {
Toast.makeText(this, ConnectivityUtil.INTERNET_CONNECTION_IS_NOT_AVAILABLE, Toast.LENGTH_SHORT).show();
}
}
private void tweet() {
getClient().sendTweetWithImage(new JsonHttpResponseHandler() {
@Override
public void onSuccess(JSONObject object) {
Toast.makeText(ResultActivity.this, "Sent tweet \"" + getTweet((float) score / resultList.size()) + "\"", Toast.LENGTH_LONG).show();
}
@Override
public void onFailure(Throwable e, JSONObject errorResponse) {
super.onFailure(e, errorResponse);
e.printStackTrace();
Toast.makeText(ResultActivity.this, errorResponse.toString(), Toast.LENGTH_SHORT).show();
}
}, getTweet((float) score / resultList.size()), getScreenShotFile()
);
}
private InputStream getScreenShotFile() {
// create bitmap screen capture
Bitmap bitmap;
View resultView = findViewById(R.id.rlResult).getRootView();
resultView.setDrawingCacheEnabled(true);
bitmap = Bitmap.createBitmap(resultView.getDrawingCache());
resultView.setDrawingCacheEnabled(false);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 100, stream);
InputStream is = new ByteArrayInputStream(stream.toByteArray());
return is;
}
public String getTweet(float pc) {
if (pc >= .8) {
return "Look Ma! I passed " + subject + " with a " + String.format("%.0f", pc * 100) + "%.";
} else if (pc >= .5) {
return "Alas, I am mortal! I barely passed " + subject + " with a " + String.format("%.0f", pc * 100) + "%.";
} else {
return "I have brought shame to my family. I failed " + subject + " with a " + String.format("%.0f", pc * 100) + "%.";
}
}
@Override
public void onLoginSuccess() {
if (wentThroughTwitterFlow) {
Toast.makeText(this, "Success! You can tweet your score now!", Toast.LENGTH_LONG).show();
}
}
@Override
public void onLoginFailure(Exception e) {
Toast.makeText(ResultActivity.this, "Error logging into Twitter!", Toast.LENGTH_SHORT).show();
}
public void onTakeQuizAgain(View v) {
Intent i = new Intent(this, QuestionActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.putExtra(SUBJECT_INTENT_KEY, subject);
startActivity(i);
}
public void onMainMenuSelected(View v) {
Intent i = new Intent(this, SubjectActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
@Override
public void onBackPressed() {
onMainMenuSelected(null);
}
public void showAlternativeTextForGraph(String textMessageToShow) {
TextView tvNoResult = new TextView(getApplicationContext());
tvNoResult.setText(textMessageToShow);
tvNoResult.setLayoutParams(new LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));
tvNoResult.setTextSize(23);
tvNoResult.setTextColor(Color.BLACK);
tvNoResult.setGravity(Gravity.CENTER_HORIZONTAL|Gravity.CENTER_VERTICAL);
llStats.addView(tvNoResult);
}
}
| true | true | public void evaluate(){
//if (resultList != null) {
ActionBar ab = getActionBar();
ab.setIcon(ColorUtil.getBarIcon(subject, this));
for(int i = 0; i < resultList.size(); i++){
String correctAnswer = resultList.get(i).getCorrectAnswer();
if (resultList.get(i).getUserAnswer().equals(correctAnswer)){
score++;
}
}
Button btnTweet = (Button) findViewById(R.id.btnTweet);
btnTweet.setBackground(ColorUtil.getButtonStyle(subject, this));
btnMainMenu.setBackground(ColorUtil.getButtonStyle(subject, this));
tvScore.setText(String.valueOf(score));
tvScore.setTextColor(ColorUtil.getScoreColor((float) score / resultList.size()));
tvTotal.setText("/ " + String.valueOf(resultList.size()));
String subjectTitle = Character.toUpperCase(subject.charAt(0))+subject.substring(1);
ab.setTitle(subjectTitle + " Results");
tvSubject.setText(" Score History for " + subjectTitle + " ");
tvSubject.setBackgroundColor(ColorUtil.subjectColorInt(subject));
tvSubject.setTextColor(Color.WHITE);
FlashMathClient client = FlashMathClient.getClient(this);
boolean isConnectionAvailable = ConnectivityUtil.isInternetConnectionAvailable(this.getApplicationContext());
//Real quiz && Internet is available
if (!isMockQuiz) {
if (isConnectionAvailable) {
setProgressBarIndeterminateVisibility(true);
btnMainMenu.setEnabled(false);
client.putScore(subject, String.valueOf(score), new JsonHttpResponseHandler() {
@Override
public void onSuccess(JSONArray jsonScores) {
if (jsonScores != null && jsonScores.length() > 1) {
GraphViewData[] data = new GraphViewData[jsonScores.length()];
int max_score = 1;
for (int i = 0; i < jsonScores.length(); i++) {
try {
int val = jsonScores.getJSONObject(i).getInt("value");
max_score = val > max_score ? val : max_score;
data[i] = (new GraphViewData(i + 1, val));
} catch (JSONException e) {
e.printStackTrace();
}
}
GraphView graphView = new LineGraphView(ResultActivity.this, "");
graphView.setCustomLabelFormatter(new CustomLabelFormatter.IntegerOnly());
GraphViewStyle style = new GraphViewStyle();
style.setVerticalLabelsColor(Color.BLACK);
style.setHorizontalLabelsColor(Color.BLACK);
style.setGridColor(Color.GRAY);
style.setNumVerticalLabels(4);
style.setNumHorizontalLabels(2);
GraphViewSeriesStyle lineStyle = new GraphViewSeriesStyle(ColorUtil.subjectColorInt(subject), 5);
graphView.addSeries(new GraphViewSeries("Scores", lineStyle, data));
graphView.addSeries(new GraphViewSeries(new GraphViewData[] { new GraphViewData(1, 0) }));
graphView.addSeries(new GraphViewSeries(new GraphViewData[] { new GraphViewData(2, 3) }));
graphView.setGraphViewStyle(style);
llStats.addView(graphView);
} else {
showAlternativeTextForGraph("Not enough scores to show graph. Please do the quiz one more time!");
}
setProgressBarIndeterminateVisibility(false);
btnMainMenu.setEnabled(true);
}
@Override
public void onFailure(Throwable arg0, JSONObject errorResponse) {
super.onFailure(arg0, errorResponse);
setProgressBarIndeterminateVisibility(false);
btnMainMenu.setEnabled(true);
showAlternativeTextForGraph("Could not load historical data. Please try again later!");
}
});
} else {
// Real quiz but no Internet
OfflineScore os = new OfflineScore();
os.setScore(score);
os.setSubject(subject);
Calendar c = Calendar.getInstance();
os.setTimeStampInSeconds(c.get(Calendar.SECOND));
//ConnectivityUtil.setUnsentScore(os);
os.save();
showAlternativeTextForGraph("Your results will be submitted when internet connection is back.");
}
} else {
if(!isConnectionAvailable) {
//Mock quiz and no Internet
showAlternativeTextForGraph("Thank you for completing the offline quiz! Your score will not be submitted.");
} else {
//Mock quiz and Internet
showAlternativeTextForGraph("Thank you for completing the offline quiz! You can try now real quiz in the Main Menu.");
}
}
playSounds((float) score / resultList.size());
}
| public void evaluate(){
//if (resultList != null) {
ActionBar ab = getActionBar();
ab.setIcon(ColorUtil.getBarIcon(subject, this));
for(int i = 0; i < resultList.size(); i++){
String correctAnswer = resultList.get(i).getCorrectAnswer();
if (resultList.get(i).getUserAnswer().equals(correctAnswer)){
score++;
}
}
Button btnTweet = (Button) findViewById(R.id.btnTweet);
btnTweet.setBackground(ColorUtil.getButtonStyle(subject, this));
btnMainMenu.setBackground(ColorUtil.getButtonStyle(subject, this));
tvScore.setText(String.valueOf(score));
tvScore.setTextColor(ColorUtil.getScoreColor((float) score / resultList.size()));
tvTotal.setText("/ " + String.valueOf(resultList.size()));
String subjectTitle = Character.toUpperCase(subject.charAt(0))+subject.substring(1);
ab.setTitle(subjectTitle + " Results");
tvSubject.setText(" Score History for " + subjectTitle + " ");
tvSubject.setBackgroundColor(ColorUtil.subjectColorInt(subject));
tvSubject.setTextColor(Color.WHITE);
FlashMathClient client = FlashMathClient.getClient(this);
boolean isConnectionAvailable = ConnectivityUtil.isInternetConnectionAvailable(this.getApplicationContext());
//Real quiz && Internet is available
if (!isMockQuiz) {
if (isConnectionAvailable) {
setProgressBarIndeterminateVisibility(true);
btnMainMenu.setEnabled(false);
client.putScore(subject, String.valueOf(score), new JsonHttpResponseHandler() {
@Override
public void onSuccess(JSONArray jsonScores) {
if (jsonScores != null && jsonScores.length() > 1) {
GraphViewData[] data = new GraphViewData[jsonScores.length()];
int max_score = 1;
for (int i = 0; i < jsonScores.length(); i++) {
try {
int val = jsonScores.getJSONObject(i).getInt("value");
max_score = val > max_score ? val : max_score;
data[i] = (new GraphViewData(i + 1, val));
} catch (JSONException e) {
e.printStackTrace();
}
}
GraphView graphView = new LineGraphView(ResultActivity.this, "");
graphView.setCustomLabelFormatter(new CustomLabelFormatter.IntegerOnly());
GraphViewStyle style = new GraphViewStyle();
style.setVerticalLabelsColor(Color.BLACK);
style.setHorizontalLabelsColor(Color.BLACK);
style.setGridColor(Color.GRAY);
style.setNumVerticalLabels(4);
style.setNumHorizontalLabels(2);
GraphViewSeriesStyle lineStyle = new GraphViewSeriesStyle(ColorUtil.subjectColorInt(subject), 5);
graphView.addSeries(new GraphViewSeries("Scores", lineStyle, data));
graphView.addSeries(new GraphViewSeries(new GraphViewData[] { new GraphViewData(1, 0) }));
graphView.addSeries(new GraphViewSeries(new GraphViewData[] { new GraphViewData(2, 3) }));
graphView.setGraphViewStyle(style);
llStats.addView(graphView);
} else {
showAlternativeTextForGraph("You need to take more tests before we can make you a graph!");
}
setProgressBarIndeterminateVisibility(false);
btnMainMenu.setEnabled(true);
}
@Override
public void onFailure(Throwable arg0, JSONObject errorResponse) {
super.onFailure(arg0, errorResponse);
setProgressBarIndeterminateVisibility(false);
btnMainMenu.setEnabled(true);
showAlternativeTextForGraph("Could not load historical data. Please try again later!");
}
});
} else {
// Real quiz but no Internet
OfflineScore os = new OfflineScore();
os.setScore(score);
os.setSubject(subject);
Calendar c = Calendar.getInstance();
os.setTimeStampInSeconds(c.get(Calendar.SECOND));
//ConnectivityUtil.setUnsentScore(os);
os.save();
showAlternativeTextForGraph("Your results will be submitted when internet connection is back.");
}
} else {
if(!isConnectionAvailable) {
//Mock quiz and no Internet
showAlternativeTextForGraph("Thank you for completing the offline quiz! Your score will not be submitted.");
} else {
//Mock quiz and Internet
showAlternativeTextForGraph("Thank you for completing the offline quiz! You can try now real quiz in the Main Menu.");
}
}
playSounds((float) score / resultList.size());
}
|
diff --git a/plugins/org.eclipse.m2m.atl.engine/src/org/eclipse/m2m/atl/engine/parser/AtlSourceManager.java b/plugins/org.eclipse.m2m.atl.engine/src/org/eclipse/m2m/atl/engine/parser/AtlSourceManager.java
index e038e0d1..62599dcf 100644
--- a/plugins/org.eclipse.m2m.atl.engine/src/org/eclipse/m2m/atl/engine/parser/AtlSourceManager.java
+++ b/plugins/org.eclipse.m2m.atl.engine/src/org/eclipse/m2m/atl/engine/parser/AtlSourceManager.java
@@ -1,461 +1,465 @@
/*******************************************************************************
* Copyright (c) 2008, 2009 Obeo.
* 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:
* Obeo - initial API and implementation
*******************************************************************************/
package org.eclipse.m2m.atl.engine.parser;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.EStructuralFeature;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.eclipse.emf.ecore.xmi.XMLResource;
import org.eclipse.emf.ecore.xmi.impl.XMIResourceFactoryImpl;
import org.eclipse.m2m.atl.core.ATLCoreException;
import org.eclipse.m2m.atl.engine.compiler.AtlCompiler;
/**
* ATL source inspector, used to catch main file informations. Also allows to update them.
*
* @author <a href="mailto:[email protected]">William Piers</a>
*/
public final class AtlSourceManager {
/** ATL compiler tag. */
public static final String COMPILER_TAG = "atlcompiler"; //$NON-NLS-1$
/** URI tag value. */
public static final String URI_TAG = "nsURI"; //$NON-NLS-1$
/** PATH tag value. */
public static final String PATH_TAG = "path"; //$NON-NLS-1$
// ATL File Type:
/** Undefined. */
public static final int ATL_FILE_TYPE_UNDEFINED = 0;
/** Module. */
public static final int ATL_FILE_TYPE_MODULE = 1;
/** Query. */
public static final int ATL_FILE_TYPE_QUERY = 3;
/** Library. */
public static final int ATL_FILE_TYPE_LIBRARY = 4;
// Metamodel filter types:
/** 0 : input + output metamodels. */
public static final int FILTER_ALL_METAMODELS = 0;
/** 1 : input metamodels. */
public static final int FILTER_INPUT_METAMODELS = 1;
/** 2 : OUTPUT metamodels. */
public static final int FILTER_OUTPUT_METAMODELS = 2;
private static final ResourceSet RESOURCE_SET = new ResourceSetImpl();
/** The detected metamodels Map[id,List[EPackage]]. */
private Map metamodelsPackages;
/** Input models / metamodels names Map. */
private Map inputModels;
/** Output models / metamodels names Map. */
private Map outputModels;
private List librariesImports;
private int atlFileType;
private String atlCompiler;
private boolean initialized;
private boolean isRefining;
private EObject model;
private Map metamodelLocations;
/**
* Creates an atl source manager.
*/
public AtlSourceManager() {
super();
}
/**
* Returns the ATL file type.
*
* @return the ATL file type
*/
public int getATLFileType() {
return atlFileType;
}
public Map getInputModels() {
return inputModels;
}
public Map getOutputModels() {
return outputModels;
}
public List getLibrariesImports() {
return librariesImports;
}
/**
* Update method : parsing and metamodel detection.
*
* @param content
* the content of the atl file
*/
public void updateDataSource(String content) {
parseMetamodels(content);
}
/**
* Update method : parsing and metamodel detection.
*
* @param inputStream
* the atl file input stream
*/
public void updateDataSource(InputStream inputStream) throws IOException {
String content = null;
byte[] bytes = new byte[inputStream.available()];
inputStream.read(bytes);
content = new String(bytes);
updateDataSource(content);
}
public boolean isRefining() {
return isRefining;
}
public EObject getModel() {
return model;
}
/**
* Metamodels access method.
*
* @param filter
* the metamodel filter
* @return the map of searched metamodels
*/
public Map getMetamodelPackages(int filter) {
if (inputModels == null && outputModels == null) {
return metamodelsPackages;
}
switch (filter) {
case FILTER_INPUT_METAMODELS:
Map inputres = new HashMap();
for (Iterator iterator = inputModels.values().iterator(); iterator.hasNext();) {
String id = (String)iterator.next();
inputres.put(id, metamodelsPackages.get(id));
}
return inputres;
case FILTER_OUTPUT_METAMODELS:
Map outputres = new HashMap();
for (Iterator iterator = outputModels.values().iterator(); iterator.hasNext();) {
String id = (String)iterator.next();
outputres.put(id, metamodelsPackages.get(id));
}
return outputres;
default:
return metamodelsPackages;
}
}
/**
* Access on a specific metamodel.
*
* @param metamodelId
* the metamodel id
* @return the metamodels list
*/
public List getMetamodelPackages(String metamodelId) {
return (List)metamodelsPackages.get(metamodelId);
}
/**
* Parsing method : detects uris and stores metamodels.
*
* @param text
* the atl file.
* @throws IOException
*/
private void parseMetamodels(String text) {
metamodelsPackages = new HashMap();
metamodelLocations = new HashMap();
inputModels = new LinkedHashMap();
outputModels = new LinkedHashMap();
librariesImports = new ArrayList();
List compilers = getTaggedInformations(text.getBytes(), COMPILER_TAG);
atlCompiler = getCompilerName(compilers);
List uris = getTaggedInformations(text.getBytes(), URI_TAG);
for (Iterator iterator = uris.iterator(); iterator.hasNext();) {
String line = (String)iterator.next();
if (line.split("=").length == 2) { //$NON-NLS-1$
String name = line.split("=")[0].trim(); //$NON-NLS-1$
String uri = line.split("=")[1].trim(); //$NON-NLS-1$
if (uri != null && uri.length() > 0) {
uri = uri.trim();
// EPackage registration
EPackage regValue = EPackage.Registry.INSTANCE.getEPackage(uri);
if (regValue != null) {
ArrayList list = new ArrayList();
list.add(regValue);
metamodelsPackages.put(name, list);
metamodelLocations.put(name, "uri:" + uri); //$NON-NLS-1$
}
}
}
}
List paths = getTaggedInformations(text.getBytes(), PATH_TAG);
for (Iterator iterator = paths.iterator(); iterator.hasNext();) {
String line = (String)iterator.next();
if (line.split("=").length == 2) { //$NON-NLS-1$
String name = line.split("=")[0].trim(); //$NON-NLS-1$
String path = line.split("=")[1].trim(); //$NON-NLS-1$
if (path != null && path.length() > 0) {
path = path.trim();
Resource resource = null;
try {
- resource = load(URI.createPlatformResourceURI(path, true), RESOURCE_SET);
+ if (path.startsWith("file:/")) { //$NON-NLS-1$
+ resource = load(URI.createURI(path, true), RESOURCE_SET);
+ } else {
+ resource = load(URI.createPlatformResourceURI(path, true), RESOURCE_SET);
+ }
} catch (IOException e) {
// TODO apply marker on the file
// Exceptions are detected by the compiler
// AtlUIPlugin.log(e);
}
if (resource != null) {
ArrayList list = new ArrayList();
for (Iterator it = resource.getContents().iterator(); it.hasNext();) {
Object object = it.next();
if (object instanceof EPackage) {
list.add(object);
}
}
metamodelsPackages.put(name, list);
metamodelLocations.put(name, path);
}
}
}
}
try {
model = AtlParser.getDefault().parse(new ByteArrayInputStream(text.getBytes()));
} catch (ATLCoreException e) {
// fail silently
}
if (model == null) {
inputModels = null;
outputModels = null;
return;
}
if (model.eClass().getName().equals("Module")) { //$NON-NLS-1$
atlFileType = ATL_FILE_TYPE_MODULE;
isRefining = ((Boolean)eGet(model, "isRefining")).booleanValue(); //$NON-NLS-1$
// input models computation
EList inModelsList = (EList)eGet(model, "inModels"); //$NON-NLS-1$
if (inModelsList != null) {
for (Iterator iterator = inModelsList.iterator(); iterator.hasNext();) {
EObject me = (EObject)iterator.next();
EObject mm = (EObject)eGet(me, "metamodel"); //$NON-NLS-1$
inputModels.put(eGet(me, "name"), eGet(mm, "name")); //$NON-NLS-1$ //$NON-NLS-2$
}
}
// output models computation
EList outModelsList = (EList)eGet(model, "outModels"); //$NON-NLS-1$
if (outModelsList != null) {
for (Iterator iterator = outModelsList.iterator(); iterator.hasNext();) {
EObject me = (EObject)iterator.next();
EObject mm = (EObject)eGet(me, "metamodel"); //$NON-NLS-1$
outputModels.put(eGet(me, "name"), eGet(mm, "name")); //$NON-NLS-1$ //$NON-NLS-2$
}
}
} else if (model.eClass().getName().equals("Query")) { //$NON-NLS-1$
atlFileType = ATL_FILE_TYPE_QUERY;
outputModels = null;
for (Iterator iterator = model.eResource().getAllContents(); iterator.hasNext();) {
EObject eo = (EObject)iterator.next();
if (eo.eClass().getName().equals("OclModel")) { //$NON-NLS-1$
String metamodelName = (String)eGet(eo, "name"); //$NON-NLS-1$
inputModels.put("IN", metamodelName); //$NON-NLS-1$
break;
}
}
} else if (model.eClass().getName().equals("Library")) { //$NON-NLS-1$
atlFileType = ATL_FILE_TYPE_LIBRARY;
}
// libraries computation
EList librariesList = (EList)eGet(model, "libraries"); //$NON-NLS-1$
if (librariesList != null) {
for (Iterator iterator = librariesList.iterator(); iterator.hasNext();) {
EObject lib = (EObject)iterator.next();
librariesImports.add(eGet(lib, "name")); //$NON-NLS-1$
}
}
initialized = true;
}
public String getAtlCompiler() {
return atlCompiler;
}
public Map getMetamodelLocations() {
return metamodelLocations;
}
/**
* Status method.
*
* @return <code>True</code> if the some metamodels have ever been detected , <code>False</code> if not.
*/
public boolean initialized() {
return initialized;
}
/**
* Returns the list of tagged informations (header).
*
* @param buffer
* the input
* @param tag
* the tag to search
* @return the tagged information
*/
public static List getTaggedInformations(byte[] buffer, String tag) {
List res = new ArrayList();
try {
int length = buffer.length;
BufferedReader reader = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(buffer,
0, length)));
while (reader.ready()) {
String line = reader.readLine();
// code begins, checking stops.
if (line == null || line.startsWith("library") //$NON-NLS-1$
|| line.startsWith("module") || line.startsWith("query")) { //$NON-NLS-1$ //$NON-NLS-2$
break;
} else {
if (line.trim().startsWith("-- @" + tag)) { //$NON-NLS-1$
line = line.replaceFirst("^\\p{Space}*--\\p{Space}*@" //$NON-NLS-1$
+ tag + "\\p{Space}+([^\\p{Space}]*)\\p{Space}*$", "$1"); //$NON-NLS-1$ //$NON-NLS-2$
res.add(line);
}
}
}
reader.close();
} catch (IOException e) {
// TODO apply marker on the file
// Exceptions are detected by the compiler
// AtlUIPlugin.log(e);
}
return res;
}
/**
* Returns the compiler name, or the default name if null.
*
* @param compilers
* the list of compilers
* @return the compiler name, or the default name if null
*/
public static String getCompilerName(List compilers) {
if (compilers.isEmpty()) {
return AtlCompiler.DEFAULT_COMPILER_NAME;
} else {
return compilers.get(0).toString();
}
}
/**
* Loads a model from an {@link org.eclipse.emf.common.util.URI URI} in a given {@link ResourceSet}.
*
* @param modelURI
* {@link org.eclipse.emf.common.util.URI URI} where the model is stored.
* @param resourceSet
* The {@link ResourceSet} to load the model in.
* @return The packages of the model loaded from the URI.
* @throws IOException
* If the given file does not exist.
*/
private static Resource load(URI modelURI, ResourceSet resourceSet) throws IOException {
String fileExtension = modelURI.fileExtension();
if (fileExtension == null || fileExtension.length() == 0) {
fileExtension = Resource.Factory.Registry.DEFAULT_EXTENSION;
}
final Resource.Factory.Registry reg = Resource.Factory.Registry.INSTANCE;
final Object resourceFactory = reg.getExtensionToFactoryMap().get(fileExtension);
if (resourceFactory != null) {
resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put(fileExtension,
resourceFactory);
} else {
resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put(fileExtension,
new XMIResourceFactoryImpl());
}
final Resource modelResource = resourceSet.createResource(modelURI);
final Map options = new HashMap();
options.put(XMLResource.OPTION_ENCODING, System.getProperty("file.encoding")); //$NON-NLS-1$
modelResource.load(options);
return modelResource;
}
/**
* Returns the value of a feature on an EObject.
*
* @param self
* the EObject
* @param featureName
* the feature name
* @return the feature value
*/
private static Object eGet(EObject self, String featureName) {
if (self != null) {
EStructuralFeature feature = self.eClass().getEStructuralFeature(featureName);
if (feature != null) {
return self.eGet(feature);
}
}
return null;
}
}
| true | true | private void parseMetamodels(String text) {
metamodelsPackages = new HashMap();
metamodelLocations = new HashMap();
inputModels = new LinkedHashMap();
outputModels = new LinkedHashMap();
librariesImports = new ArrayList();
List compilers = getTaggedInformations(text.getBytes(), COMPILER_TAG);
atlCompiler = getCompilerName(compilers);
List uris = getTaggedInformations(text.getBytes(), URI_TAG);
for (Iterator iterator = uris.iterator(); iterator.hasNext();) {
String line = (String)iterator.next();
if (line.split("=").length == 2) { //$NON-NLS-1$
String name = line.split("=")[0].trim(); //$NON-NLS-1$
String uri = line.split("=")[1].trim(); //$NON-NLS-1$
if (uri != null && uri.length() > 0) {
uri = uri.trim();
// EPackage registration
EPackage regValue = EPackage.Registry.INSTANCE.getEPackage(uri);
if (regValue != null) {
ArrayList list = new ArrayList();
list.add(regValue);
metamodelsPackages.put(name, list);
metamodelLocations.put(name, "uri:" + uri); //$NON-NLS-1$
}
}
}
}
List paths = getTaggedInformations(text.getBytes(), PATH_TAG);
for (Iterator iterator = paths.iterator(); iterator.hasNext();) {
String line = (String)iterator.next();
if (line.split("=").length == 2) { //$NON-NLS-1$
String name = line.split("=")[0].trim(); //$NON-NLS-1$
String path = line.split("=")[1].trim(); //$NON-NLS-1$
if (path != null && path.length() > 0) {
path = path.trim();
Resource resource = null;
try {
resource = load(URI.createPlatformResourceURI(path, true), RESOURCE_SET);
} catch (IOException e) {
// TODO apply marker on the file
// Exceptions are detected by the compiler
// AtlUIPlugin.log(e);
}
if (resource != null) {
ArrayList list = new ArrayList();
for (Iterator it = resource.getContents().iterator(); it.hasNext();) {
Object object = it.next();
if (object instanceof EPackage) {
list.add(object);
}
}
metamodelsPackages.put(name, list);
metamodelLocations.put(name, path);
}
}
}
}
try {
model = AtlParser.getDefault().parse(new ByteArrayInputStream(text.getBytes()));
} catch (ATLCoreException e) {
// fail silently
}
if (model == null) {
inputModels = null;
outputModels = null;
return;
}
if (model.eClass().getName().equals("Module")) { //$NON-NLS-1$
atlFileType = ATL_FILE_TYPE_MODULE;
isRefining = ((Boolean)eGet(model, "isRefining")).booleanValue(); //$NON-NLS-1$
// input models computation
EList inModelsList = (EList)eGet(model, "inModels"); //$NON-NLS-1$
if (inModelsList != null) {
for (Iterator iterator = inModelsList.iterator(); iterator.hasNext();) {
EObject me = (EObject)iterator.next();
EObject mm = (EObject)eGet(me, "metamodel"); //$NON-NLS-1$
inputModels.put(eGet(me, "name"), eGet(mm, "name")); //$NON-NLS-1$ //$NON-NLS-2$
}
}
// output models computation
EList outModelsList = (EList)eGet(model, "outModels"); //$NON-NLS-1$
if (outModelsList != null) {
for (Iterator iterator = outModelsList.iterator(); iterator.hasNext();) {
EObject me = (EObject)iterator.next();
EObject mm = (EObject)eGet(me, "metamodel"); //$NON-NLS-1$
outputModels.put(eGet(me, "name"), eGet(mm, "name")); //$NON-NLS-1$ //$NON-NLS-2$
}
}
} else if (model.eClass().getName().equals("Query")) { //$NON-NLS-1$
atlFileType = ATL_FILE_TYPE_QUERY;
outputModels = null;
for (Iterator iterator = model.eResource().getAllContents(); iterator.hasNext();) {
EObject eo = (EObject)iterator.next();
if (eo.eClass().getName().equals("OclModel")) { //$NON-NLS-1$
String metamodelName = (String)eGet(eo, "name"); //$NON-NLS-1$
inputModels.put("IN", metamodelName); //$NON-NLS-1$
break;
}
}
} else if (model.eClass().getName().equals("Library")) { //$NON-NLS-1$
atlFileType = ATL_FILE_TYPE_LIBRARY;
}
// libraries computation
EList librariesList = (EList)eGet(model, "libraries"); //$NON-NLS-1$
if (librariesList != null) {
for (Iterator iterator = librariesList.iterator(); iterator.hasNext();) {
EObject lib = (EObject)iterator.next();
librariesImports.add(eGet(lib, "name")); //$NON-NLS-1$
}
}
initialized = true;
}
| private void parseMetamodels(String text) {
metamodelsPackages = new HashMap();
metamodelLocations = new HashMap();
inputModels = new LinkedHashMap();
outputModels = new LinkedHashMap();
librariesImports = new ArrayList();
List compilers = getTaggedInformations(text.getBytes(), COMPILER_TAG);
atlCompiler = getCompilerName(compilers);
List uris = getTaggedInformations(text.getBytes(), URI_TAG);
for (Iterator iterator = uris.iterator(); iterator.hasNext();) {
String line = (String)iterator.next();
if (line.split("=").length == 2) { //$NON-NLS-1$
String name = line.split("=")[0].trim(); //$NON-NLS-1$
String uri = line.split("=")[1].trim(); //$NON-NLS-1$
if (uri != null && uri.length() > 0) {
uri = uri.trim();
// EPackage registration
EPackage regValue = EPackage.Registry.INSTANCE.getEPackage(uri);
if (regValue != null) {
ArrayList list = new ArrayList();
list.add(regValue);
metamodelsPackages.put(name, list);
metamodelLocations.put(name, "uri:" + uri); //$NON-NLS-1$
}
}
}
}
List paths = getTaggedInformations(text.getBytes(), PATH_TAG);
for (Iterator iterator = paths.iterator(); iterator.hasNext();) {
String line = (String)iterator.next();
if (line.split("=").length == 2) { //$NON-NLS-1$
String name = line.split("=")[0].trim(); //$NON-NLS-1$
String path = line.split("=")[1].trim(); //$NON-NLS-1$
if (path != null && path.length() > 0) {
path = path.trim();
Resource resource = null;
try {
if (path.startsWith("file:/")) { //$NON-NLS-1$
resource = load(URI.createURI(path, true), RESOURCE_SET);
} else {
resource = load(URI.createPlatformResourceURI(path, true), RESOURCE_SET);
}
} catch (IOException e) {
// TODO apply marker on the file
// Exceptions are detected by the compiler
// AtlUIPlugin.log(e);
}
if (resource != null) {
ArrayList list = new ArrayList();
for (Iterator it = resource.getContents().iterator(); it.hasNext();) {
Object object = it.next();
if (object instanceof EPackage) {
list.add(object);
}
}
metamodelsPackages.put(name, list);
metamodelLocations.put(name, path);
}
}
}
}
try {
model = AtlParser.getDefault().parse(new ByteArrayInputStream(text.getBytes()));
} catch (ATLCoreException e) {
// fail silently
}
if (model == null) {
inputModels = null;
outputModels = null;
return;
}
if (model.eClass().getName().equals("Module")) { //$NON-NLS-1$
atlFileType = ATL_FILE_TYPE_MODULE;
isRefining = ((Boolean)eGet(model, "isRefining")).booleanValue(); //$NON-NLS-1$
// input models computation
EList inModelsList = (EList)eGet(model, "inModels"); //$NON-NLS-1$
if (inModelsList != null) {
for (Iterator iterator = inModelsList.iterator(); iterator.hasNext();) {
EObject me = (EObject)iterator.next();
EObject mm = (EObject)eGet(me, "metamodel"); //$NON-NLS-1$
inputModels.put(eGet(me, "name"), eGet(mm, "name")); //$NON-NLS-1$ //$NON-NLS-2$
}
}
// output models computation
EList outModelsList = (EList)eGet(model, "outModels"); //$NON-NLS-1$
if (outModelsList != null) {
for (Iterator iterator = outModelsList.iterator(); iterator.hasNext();) {
EObject me = (EObject)iterator.next();
EObject mm = (EObject)eGet(me, "metamodel"); //$NON-NLS-1$
outputModels.put(eGet(me, "name"), eGet(mm, "name")); //$NON-NLS-1$ //$NON-NLS-2$
}
}
} else if (model.eClass().getName().equals("Query")) { //$NON-NLS-1$
atlFileType = ATL_FILE_TYPE_QUERY;
outputModels = null;
for (Iterator iterator = model.eResource().getAllContents(); iterator.hasNext();) {
EObject eo = (EObject)iterator.next();
if (eo.eClass().getName().equals("OclModel")) { //$NON-NLS-1$
String metamodelName = (String)eGet(eo, "name"); //$NON-NLS-1$
inputModels.put("IN", metamodelName); //$NON-NLS-1$
break;
}
}
} else if (model.eClass().getName().equals("Library")) { //$NON-NLS-1$
atlFileType = ATL_FILE_TYPE_LIBRARY;
}
// libraries computation
EList librariesList = (EList)eGet(model, "libraries"); //$NON-NLS-1$
if (librariesList != null) {
for (Iterator iterator = librariesList.iterator(); iterator.hasNext();) {
EObject lib = (EObject)iterator.next();
librariesImports.add(eGet(lib, "name")); //$NON-NLS-1$
}
}
initialized = true;
}
|
diff --git a/pace-ext-funcs/src/main/java/com/pace/ext/funcs/AllocFunc.java b/pace-ext-funcs/src/main/java/com/pace/ext/funcs/AllocFunc.java
index 282b9ee4..31b26082 100644
--- a/pace-ext-funcs/src/main/java/com/pace/ext/funcs/AllocFunc.java
+++ b/pace-ext-funcs/src/main/java/com/pace/ext/funcs/AllocFunc.java
@@ -1,684 +1,684 @@
package com.pace.ext.funcs;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.log4j.Logger;
import com.pace.base.PafErrSeverity;
import com.pace.base.PafException;
import com.pace.base.SortOrder;
import com.pace.base.data.EvalUtil;
import com.pace.base.data.IPafDataCache;
import com.pace.base.data.Intersection;
import com.pace.base.data.MemberTreeSet;
import com.pace.base.funcs.AbstractFunction;
import com.pace.base.mdb.PafDimMember;
import com.pace.base.mdb.PafDimTree;
import com.pace.base.state.IPafEvalState;
/**
* "Allocation" Custom Function -
*
* The calling signature of this function is '@ALLOC(msrToAllocate, [msrsToExclude*] )'.
* This function allocates the initial measure into the hierarchical children of the measure
* specified. A list of measures to be excluded can be optionally passed in.
* @version 2.8.2.0
* @author JWatkins
*
*/
public class AllocFunc extends AbstractFunction {
protected static int MEASURE_ARGS = 1; //, MAX_ARGS = 4;
protected static int REQUIRED_ARGS = 1;
protected String msrToAlloc = null;
protected List<String> targetMsrs = new ArrayList<String>(), validTargetMsrs = new ArrayList<String>();
protected Set<String> aggMsrs = new HashSet<String>();
protected List<Intersection> unlockIntersections = new ArrayList<Intersection>(10000);
protected List<String> excludedMsrs = new ArrayList<String>();
protected Set<Intersection> userLockTargets = new HashSet<Intersection>(10000); // Exploded measures
protected Set<Intersection> msrToAllocPreservedLocks = new HashSet<Intersection>(10000); // Original (non-exploded) measures
protected List<Intersection> sourceIsTargetCells = new ArrayList<Intersection>(10000);
private static Logger logger = Logger.getLogger(AllocFunc.class);
public double calculate(Intersection sourceIs, IPafDataCache dataCache, IPafEvalState evalState) throws PafException {
// This method uses allocation logic cloned from the Evaluation package. All
// locked or changed "msrToAllocate" intersections will be allocated in
// ascending intersection order. This allocation of multiple "msrToAllocate"
// intersections will be interleaved with the re-allocation of any impacted
// "msrToAllocate" component measure intersections, that are descendants
// of the next "msrToAllocate" to be calculated. (TTN-1743)
// Convenience variables
String msrDim = dataCache.getMeasureDim();
String[] axisSortSeq = evalState.getAxisSortPriority();
HashSet<Intersection> allocMsrComponentIntersections = new HashSet<Intersection>(evalState.getLoadFactor());
HashSet<Intersection> allocMsrIntersections = new HashSet<Intersection>(evalState.getLoadFactor());
PafDimTree measureTree = evalState.getClientState().getUowTrees().getTree(msrDim);
List<Intersection> allocCellList = new ArrayList<Intersection>(100);
// Validate function parameters
validateParms(evalState);
// targets holds all intersections to allocate into.
// The lists have been processed by validateParms
// Get the list of intersections to allocate. This would include the current
// intersection as well as any non-elapsed locked intersections for the
// "msrToAlloc" or any of its descendants along the measure hierarchy.
// (TTN-1743)
for (Intersection lockedCell : evalState.getCurrentLockedCells()) {
// Skip elapsed periods
if (EvalUtil.isElapsedIs(lockedCell, evalState)) continue;
// Split locked intersections into two groups by measure: the ones
// belonging to "msrToAlloc" and the ones belonging to the "msrToAlloc"
// components.
String measure = lockedCell.getCoordinate(msrDim);
if (this.aggMsrs.contains(measure)) {
if (!measure.equals(msrToAlloc)) {
allocMsrComponentIntersections.add(lockedCell);
} else {
allocMsrIntersections.add(lockedCell);
}
}
}
// Sort intersections to allocate in ascending, but interleaved order. All
// component measure intersections need to be allocated before any ancestor
// "msrToAlloc" intersections, but after any "msrToAlloc" intersection that
// contain any descendant targets.
//
// The one exception is that component intersections that are descendants to
// the first "msrToAlloc" intersection, are not re-allocated, since there is
// no need reason to recalculate them.
// (TTN-1743)
Intersection[] allocComponentCells = EvalUtil.sortIntersectionsByAxis(allocMsrComponentIntersections.toArray(new Intersection[0]),
evalState.getClientState().getMemberIndexLists(),axisSortSeq, SortOrder.Ascending);
List<Intersection> allocComponentCellList = new ArrayList<Intersection>(Arrays.asList(allocComponentCells));
Intersection[] allocMsrCells = EvalUtil.sortIntersectionsByAxis(allocMsrIntersections.toArray(new Intersection[0]),
evalState.getClientState().getMemberIndexLists(),axisSortSeq, SortOrder.Ascending);
boolean bFirstAllocMsrIs = true;
for (Intersection allocMsrIs : allocMsrCells) {
List<Intersection> processedCompIntersections = new ArrayList<Intersection>();
for (Intersection componentIs : allocComponentCellList) {
if (isDescendantIs(componentIs, allocMsrIs, evalState)) {
processedCompIntersections.add(componentIs);
if (!bFirstAllocMsrIs) {
allocCellList.add(componentIs);
}
} else {
// Since this is the first "msrToAllocate" intersection, skip
// any descendant component intersections.
break;
}
}
// Add "msrToAlloc" intersection to list after it's descendant component
// intersections.
allocCellList.add(allocMsrIs);
// Add any remaining component intersections
allocComponentCellList.removeAll(processedCompIntersections);
bFirstAllocMsrIs = false;
}
allocCellList.addAll(allocComponentCellList);
// Exit if we're already called this function on the current rule
Intersection topMsrToAllocIs = allocCellList.get(0);
- if (sourceIs.equals(topMsrToAllocIs)) {
+ if (!sourceIs.equals(topMsrToAllocIs)) {
// actual intersection in question should remain unchanged by this operation
return dataCache.getCellValue(sourceIs);
}
// Get the list of the source intersection target intersections. (TTN-1743)
sourceIsTargetCells.clear();
sourceIsTargetCells.addAll(EvalUtil.buildFloorIntersections(topMsrToAllocIs, evalState, true));
// Allocate the selected intersections in the optimal calculation order. This logic
// assumes that any component/descendant measures were already allocated in a
// previous rule step. (TTN-1743)
for (Intersection allocCell : allocCellList) {
// Find the targets of the cell to allocate
Set<Intersection> allocTargets = new HashSet<Intersection>();
String allocMeasure = allocCell.getCoordinate(msrDim);
List<String> descMeasures = measureTree.getLowestMemberNames(allocMeasure);
descMeasures.retainAll(this.targetMsrs);
for (String targetMeasure : descMeasures) {
Intersection targetCell = allocCell.clone();
targetCell.setCoordinate(msrDim, targetMeasure);
allocTargets.addAll(EvalUtil.buildFloorIntersections(targetCell, evalState));
}
// gather the user lock target intersections. These are user locks "only" and
// don't include elapsed period locks. Also gather the allocation locks that
// need to be preserved when performing the allocation of the "msrToAlloc" (TTN-1743)
userLockTargets.clear();
msrToAllocPreservedLocks.clear();
for (Intersection origLockedCell : evalState.getOrigLockedCells()) {
String measure = origLockedCell.getCoordinate(msrDim);
if (aggMsrs.contains(measure)) {
if (!EvalUtil.isElapsedIs(origLockedCell, evalState)) {
userLockTargets.addAll(EvalUtil.buildFloorIntersections(origLockedCell, evalState, true));
// Determine which locks need to be preserved when allocating the current
// "msrToAlloc" intersection. Pick all descendant locked intersections.
if (allocMeasure.equals(msrToAlloc) && isDescendantIs(origLockedCell, allocCell, evalState)) {
List<Intersection> floorLocks = EvalUtil.buildFloorIntersections(origLockedCell,evalState);
msrToAllocPreservedLocks.addAll(floorLocks);
}
}
}
}
// for (Intersection origChangedCell : evalState.getOrigChangedCells()) {
// String measure = origChangedCell.getCoordinate(msrDim);
// if (aggMsrs.contains(measure)) {
// userLockTargets.addAll(EvalUtil.buildFloorIntersections(origChangedCell, evalState, true));
// // Determine which locks need to be preserved when allocating the current
// // "msrToAlloc" intersection. Pick all descendant locked intersections.
// if (allocMeasure.equals(msrToAlloc) && isDescendantIs(origChangedCell, allocCell, evalState)) {
// List<Intersection> floorLocks = EvalUtil.buildFloorIntersections(origChangedCell,evalState);
// msrToAllocPreservedLocks.addAll(floorLocks);
// }
// }
// }
// Allocate cell
allocateChange(allocCell, allocTargets, evalState, dataCache);
}
// indicate additional aggregations required by this operation
evalState.getTriggeredAggMsrs().addAll(this.targetMsrs);
// actual intersection in question should remain unchanged by this operation
return dataCache.getCellValue(sourceIs);
}
/**
* Checks if one intersection is a descendant of the other intersection
*
* @param descendantIs Descendant intersection
* @param ancestorIs Ancestor intersection
* @param evalState Evaluation state
*
* @return true if the tested descendant intersection is a descendant of the ancestor intersection
*/
private boolean isDescendantIs(Intersection descendantIs, Intersection ancestorIs, IPafEvalState evalState) {
MemberTreeSet dimTrees = evalState.getClientState().getUowTrees();
// Cycle through each dimension and check each coordinate of the tested
// intersection.
for (String dim : descendantIs.getDimensions()) {
PafDimTree dimTree = dimTrees.getTree(dim);
String descCoord = descendantIs.getCoordinate(dim);
String ancestorCoord = ancestorIs.getCoordinate(dim);
List<String> descendantMbrs = PafDimTree.getMemberNames(dimTree.getIDescendants(ancestorCoord));
// If the tested intersection's dimension coordinate is not a descendant
// of the ancestor intersection, then return failure status
if (!descendantMbrs.contains(descCoord)) {
return false;
}
}
// Successful (tested intersection passed all tests)
return true;
}
/**
* Parse and validate function parameters
*
* @param evalState Evaluation state object
* @throws PafException
*/
protected void validateParms(IPafEvalState evalState) throws PafException {
int parmIndex = 0;
// quick check to get out if it looks like these have been validated already
// if (this.isValidated) return;
String errMsg = "Error in [" + this.getClass().getName() + "] - ";
String measureDim = evalState.getAppDef().getMdbDef().getMeasureDim();
// Check for existence of arguments
if (parms == null) {
errMsg += "[" + REQUIRED_ARGS + "] arguments are required, but none were provided.";
logger.error(errMsg);
throw new PafException(errMsg, PafErrSeverity.Error);
}
// Check for the correct number of arguments
if (parms.length < REQUIRED_ARGS) {
errMsg += "[" + REQUIRED_ARGS + "] arguments are required, but [" + parms.length + "] were provided.";
logger.error(errMsg);
throw new PafException(errMsg, PafErrSeverity.Error);
}
// Check validity of all arguments for existence in measures dimension
PafDimTree measureTree = evalState.getEvaluationTree(measureDim);
for (parmIndex = 0; parmIndex < parms.length; parmIndex++) {
String member = parms[parmIndex];
if (!measureTree.hasMember(member)){
errMsg += "[" + member + "] is not a valid member of the [" + measureDim + "] dimension.";
logger.error(errMsg);
throw new PafException(errMsg, PafErrSeverity.Error);
}
}
// Get required arguments
msrToAlloc = this.measureName;
// Check for optional parameters - if any other parameters
// then they represent children to be filtered out of the default children
int index = 1;
targetMsrs.clear();
// initialize with descendant floor measures
targetMsrs.addAll(measureTree.getLowestMemberNames(msrToAlloc));
// remove any measures specified as well as their descendants
if (parms.length > 1) {
// build excluded measures list
List<PafDimMember> desc = measureTree.getLowestMembers(parms[index]);
while (index<parms.length) {
if (desc == null || desc.size() == 0) {
excludedMsrs.add(parms[index]);
} else {
for (PafDimMember msrMbr : desc) {
excludedMsrs.add(msrMbr.getKey());
}
}
index++;
}
// now remove them from the list
// for (String excludedMsr : excludedMsrs) {
// targetMsrs.remove(excludedMsr);
// }
}
// create a set of members to aggregate after the allocation takes place. this should be the
// entire measure branch being allocated.
aggMsrs = new HashSet<String>(PafDimTree.getMemberNames(measureTree.getIDescendants(msrToAlloc)));
// create a set of members to aggregate after the allocation takes place. this should be the
// entire measure branch being allocated (TTN-1473)
validTargetMsrs.clear();
validTargetMsrs.addAll(targetMsrs);
validTargetMsrs.removeAll(excludedMsrs);
this.isValidated = true;
}
/* (non-Javadoc)
* @see com.pace.base.funcs.AbstractFunction#getTriggerIntersections(com.pace.base.state.IPafEvalState)
*/
public Set<Intersection> getTriggerIntersections(IPafEvalState evalState) throws PafException {
/*
* The trigger intersections for the @ALLOC function are:
*
* 1. Any changed intersection containing the alloc measure
*
*/
Set<Intersection> triggerIntersections = null; // = new HashSet<Intersection>(0);
Map<String, Set<Intersection>> changedCellsByMsr = evalState.getChangedCellsByMsr();
// Parse function parameters
validateParms(evalState);
// Add in alloc measure
Set<Intersection> allocIsxs = changedCellsByMsr.get(msrToAlloc);
if (allocIsxs == null) {
triggerIntersections = new HashSet<Intersection>(0);
}
else {
triggerIntersections = new HashSet<Intersection>( 2 * allocIsxs.size() );
triggerIntersections.addAll(allocIsxs);
}
return triggerIntersections;
}
/* (non-Javadoc)
* @see com.pace.base.funcs.AbstractFunction#changeTriggersFormula(com.pace.base.data.Intersection, com.pace.base.state.IPafEvalState)
*/
public boolean changeTriggersFormula(Intersection is, IPafEvalState evalState) {
/*
* A change to the allocation measure triggers this formula
*
*/
String measureDim = evalState.getAppDef().getMdbDef().getMeasureDim();
String measure = is.getCoordinate(measureDim);
if (measure.equals(msrToAlloc))
return true;
else
return false;
}
/* (non-Javadoc)
* @see com.pace.base.funcs.AbstractFunction#getMemberDependencyMap(com.pace.base.state.IPafEvalState)
*/
public Map<String, Set<String>> getMemberDependencyMap(IPafEvalState evalState) throws PafException {
Map<String, Set<String>> dependencyMap = new HashMap<String, Set<String>>();
String measureDim = evalState.getMsrDim();
// validate function parameters
validateParms(evalState);
// Add all parameters
Set<String> memberList = new HashSet<String>();
memberList.add(msrToAlloc);
memberList.addAll(targetMsrs);
dependencyMap.put(measureDim, memberList);
// Return member dependency map
return dependencyMap;
}
/**
* This takes an arbitrary intersection and allocates it across a potential pool of intersections. No restrictions are initially
* placed on the validity of this pool as it's used to do measure to measure allocations. The math however won't work if the parent
* doesn't total the children as thats assumed the base condition for allocation.
*
*
* @param intersection Intersection to allocate
* @param targetPoolIsxs Set of intersections that should total the parent intersection
* @param evalState State variable for current point in evaluation process
* @param dataCache Access to the data for updating values as a result of the allocation
* @return
* @throws PafException
*/
public IPafDataCache allocateChange(Intersection allocSrcIsx, Set<Intersection> targets, IPafEvalState evalState, IPafDataCache dataCache) throws PafException {
double allocTotal = dataCache.getCellValue(allocSrcIsx);
// if (logger.isDebugEnabled()) logger.debug("Allocating change for :" + intersection.toString() + " = " + allocTotal);
// convenience variables
String msrDim = evalState.getAppDef().getMdbDef().getMeasureDim();
String allocMeasure = allocSrcIsx.getCoordinate(msrDim);
long stepTime = System.currentTimeMillis();
// initial check, don't allocate any intersection that is "elapsed" during forward plannable sessions
// if current plan is forward plannable, also don't allow
// allocation into any intersections containing protected time periods
if (EvalUtil.isElapsedIs(allocSrcIsx, evalState)) return dataCache;
// total locked cells under intersection
stepTime = System.currentTimeMillis();
double lockedTotal = 0;
Set<Intersection> lockedTargets = new HashSet<Intersection>(evalState.getLoadFactor());
Set<Intersection> currentLockedCells = new HashSet<Intersection>(evalState.getLoadFactor());
// add up all locked cell values, this must include floors intersections of excluded measures
for (Intersection lockedCell : evalState.getCurrentLockedCells()) {
currentLockedCells.addAll(EvalUtil.buildFloorIntersections(lockedCell, evalState));
}
for (Intersection target : targets) {
if (currentLockedCells.contains(target) ||
// (lockedTimePeriods.contains(target.getCoordinate(timeDim)) &&
// target.getCoordinate(yearDim).equals(currentYear)) ||
(EvalUtil.isElapsedIs(target, evalState)) || // TTN-1595
excludedMsrs.contains(target.getCoordinate(msrDim))
) {
lockedTotal += dataCache.getCellValue(target);
lockedTargets.add(target);
}
}
double allocAvailable = 0;
// normal routine, remove locked intersections from available allocation targets
if (targets.size() != lockedTargets.size() || evalState.isRoundingResourcePass() ) {
targets.removeAll(lockedTargets);
allocAvailable = allocTotal - lockedTotal;
}
else { // all targets locked so special case
// if some of the locks are original user changes
ArrayList<Intersection> userLockedTargets = new ArrayList<Intersection>(evalState.getLoadFactor());
if (allocMeasure.equals(msrToAlloc)) {
userLockedTargets.addAll(msrToAllocPreservedLocks);
} else {
userLockedTargets.addAll(userLockTargets);
}
userLockedTargets.retainAll(targets);
ArrayList<Intersection> elapsedTargets = new ArrayList<Intersection>(evalState.getLoadFactor());
double elapsedTotal = 0;
for (Intersection target : targets) {
// total elapsed period locks and add them to a specific collection
// if (lockedTimePeriods.contains(target.getCoordinate(timeDim)) &&
// target.getCoordinate(yearDim).equals(currentYear) ) {
if (EvalUtil.isElapsedIs(target, evalState)) { // TTN-1595
elapsedTotal += dataCache.getCellValue(target);
elapsedTargets.add(target);
}
}
// always remove elapsed periods from the allocation
targets.removeAll(elapsedTargets);
allocAvailable = allocTotal - elapsedTotal;
userLockedTargets.removeAll(elapsedTargets);
// ensure that potential targets of the top allocation measure are preserved (TTN-1743)
Set<Intersection> msrToAllocTargets = null;
double msrToAllocTargetTotal = 0;
if (!allocMeasure.equals(msrToAlloc)) {
msrToAllocTargets = new HashSet<Intersection>(evalState.getLoadFactor());
for (Intersection target : targets) {
if (sourceIsTargetCells.contains(target)) {
msrToAllocTargets.add(target);
msrToAllocTargetTotal += dataCache.getCellValue(target);
}
}
targets.removeAll(msrToAllocTargets);
allocAvailable -= msrToAllocTargetTotal;
userLockedTargets.removeAll(msrToAllocTargets);
}
if (targets.size() != userLockedTargets.size()) {
// some targets are user locks so remove them and allocate into rest
for (Intersection userLockedTarget : userLockedTargets) {
if (targets.contains(userLockedTarget)) {
targets.remove(userLockedTarget);
allocAvailable -= dataCache.getCellValue(userLockedTarget);
}
}
}
// else { // all potential targets are user locks, so allocate evenly into them
// allocAvailable = allocAvailable;
// }
}
// if no quantity to allocate, dump out.
// if (allocAvailable == 0) return dataCache;
double origTargetSum = 0;
for (Intersection target : targets ) {
origTargetSum += dataCache.getCellValue(target);
}
// begin timing allocation step
stepTime = System.currentTimeMillis();
// logger.info("Allocating intersection: " + intersection);
// logger.info("Allocating into " + targets.size() + " targets" );
if (origTargetSum == 0 &&
evalState.getRule().getBaseAllocateMeasure() != null
&& !evalState.getRule().getBaseAllocateMeasure().equals("")) {
// in this case, perform the exact same logic as the normal allocation step, however, use the "shape"
// from base measure to determine the allocation percentages.
allocateToTargets(targets, evalState.getRule().getBaseAllocateMeasure(), allocAvailable, dataCache, evalState);
} else {
// normal allocation to open targets
allocateToTargets(targets, allocAvailable, origTargetSum, dataCache, evalState);
}
// logger.info(LogUtil.timedStep("Allocation completed ", stepTime));
// evalState.addAllAllocations(targets);
return dataCache;
}
protected void allocateToTargets(Set<Intersection> targets, double allocAvailable, double origTargetSum, IPafDataCache dataCache, IPafEvalState evalState) throws PafException {
double origValue = 0;
double allocValue = 0;
int places = 0;
long stepTime = System.currentTimeMillis();
for (Intersection target : targets ) {
origValue = dataCache.getCellValue(target);
if (origTargetSum == 0) {
allocValue = allocAvailable / targets.size();
}
else {
allocValue = ((origValue / origTargetSum) * (allocAvailable));
}
if (evalState.getAppDef().getAppSettings() != null && evalState.getAppDef().getAppSettings().isEnableRounding())
{
String currentMeasure = target.getCoordinate(evalState.getAppDef().getMdbDef().getMeasureDim());
if (evalState.getRoundingRules().containsKey(currentMeasure)){
places = evalState.getRoundingRules().get(currentMeasure).getDigits();
allocValue = EvalUtil.Round(allocValue, places);
evalState.getAllocatedLockedCells().add(target);
}
}
dataCache.setCellValue(target, allocValue);
// if (logger.isDebugEnabled()) logger.debug("Allocating " + target.toString() + " new value: " + allocValue);
// add cells to locks
evalState.getCurrentLockedCells().add(target);
// add to changed cell list
evalState.addChangedCell(target);
}
// // default is to lock the results of allocation, but can be overriden,
// // however unlocking can only occur at the end of the overall allocation pass
// if (!evalState.getRule().isLockAllocation())
// unlockIntersections.addAll(targets);
}
protected void allocateToTargets(Set<Intersection> targets, String baseMeasure, double allocAvailable, IPafDataCache dataCache, IPafEvalState evalState) throws PafException {
double baseValue = 0;
double allocValue = 0;
double baseTargetSum = 0;
int places = 0;
String msrDim = evalState.getAppDef().getMdbDef().getMeasureDim();
// find index of measure dimension in axis
int msrIndex = dataCache.getAxisIndex(msrDim);
String[] baseCoords;
String targetMsr;
// save off original measure from 1st target
if (targets.size() > 0)
targetMsr = targets.iterator().next().getCoordinate(msrDim);
else //just return if no targets, no work to do
return;
// recalculate origTargetSum over base measure intersections
for (Intersection target : targets ) {
baseCoords = target.getCoordinates();
baseCoords[msrIndex] = baseMeasure;
baseTargetSum += dataCache.getCellValue(target);
}
// if (logger.isDebugEnabled()) logger.debug("Original total of unlocked base measure targets: " + baseTargetSum);
// allocate into each target intersection, using the shape of the
for (Intersection target : targets ) {
// target coordinates have already been shifted by the
// addition operation above.
baseValue = dataCache.getCellValue(target);
if (baseTargetSum == 0) {
allocValue = allocAvailable / targets.size();
}
else {
allocValue = ((baseValue / baseTargetSum) * (allocAvailable));
}
if (evalState.getAppDef().getAppSettings() != null && evalState.getAppDef().getAppSettings().isEnableRounding())
{
if (evalState.getRoundingRules().containsKey(targetMsr)){
places = evalState.getRoundingRules().get(targetMsr).getDigits();
allocValue = EvalUtil.Round(allocValue, places);
evalState.getAllocatedLockedCells().add(target);
}
}
// put target msr coordinate back to original measure for assignment
target.setCoordinate(msrDim, targetMsr);
dataCache.setCellValue(target, allocValue);
// if (logger.isDebugEnabled()) logger.debug("Allocating " + target.toString() + " new value: " + allocValue);
// add cells to locks
evalState.getCurrentLockedCells().add(target);
// add to changed cell list
evalState.addChangedCell(target);
}
// // default is to lock the results of allocation, but can be overriden,
// // however unlocking can only occur at the end of the overall allocation pass
// if (!evalState.getRule().isLockAllocation())
// unlockIntersections.addAll(targets);
}
}
| true | true | public double calculate(Intersection sourceIs, IPafDataCache dataCache, IPafEvalState evalState) throws PafException {
// This method uses allocation logic cloned from the Evaluation package. All
// locked or changed "msrToAllocate" intersections will be allocated in
// ascending intersection order. This allocation of multiple "msrToAllocate"
// intersections will be interleaved with the re-allocation of any impacted
// "msrToAllocate" component measure intersections, that are descendants
// of the next "msrToAllocate" to be calculated. (TTN-1743)
// Convenience variables
String msrDim = dataCache.getMeasureDim();
String[] axisSortSeq = evalState.getAxisSortPriority();
HashSet<Intersection> allocMsrComponentIntersections = new HashSet<Intersection>(evalState.getLoadFactor());
HashSet<Intersection> allocMsrIntersections = new HashSet<Intersection>(evalState.getLoadFactor());
PafDimTree measureTree = evalState.getClientState().getUowTrees().getTree(msrDim);
List<Intersection> allocCellList = new ArrayList<Intersection>(100);
// Validate function parameters
validateParms(evalState);
// targets holds all intersections to allocate into.
// The lists have been processed by validateParms
// Get the list of intersections to allocate. This would include the current
// intersection as well as any non-elapsed locked intersections for the
// "msrToAlloc" or any of its descendants along the measure hierarchy.
// (TTN-1743)
for (Intersection lockedCell : evalState.getCurrentLockedCells()) {
// Skip elapsed periods
if (EvalUtil.isElapsedIs(lockedCell, evalState)) continue;
// Split locked intersections into two groups by measure: the ones
// belonging to "msrToAlloc" and the ones belonging to the "msrToAlloc"
// components.
String measure = lockedCell.getCoordinate(msrDim);
if (this.aggMsrs.contains(measure)) {
if (!measure.equals(msrToAlloc)) {
allocMsrComponentIntersections.add(lockedCell);
} else {
allocMsrIntersections.add(lockedCell);
}
}
}
// Sort intersections to allocate in ascending, but interleaved order. All
// component measure intersections need to be allocated before any ancestor
// "msrToAlloc" intersections, but after any "msrToAlloc" intersection that
// contain any descendant targets.
//
// The one exception is that component intersections that are descendants to
// the first "msrToAlloc" intersection, are not re-allocated, since there is
// no need reason to recalculate them.
// (TTN-1743)
Intersection[] allocComponentCells = EvalUtil.sortIntersectionsByAxis(allocMsrComponentIntersections.toArray(new Intersection[0]),
evalState.getClientState().getMemberIndexLists(),axisSortSeq, SortOrder.Ascending);
List<Intersection> allocComponentCellList = new ArrayList<Intersection>(Arrays.asList(allocComponentCells));
Intersection[] allocMsrCells = EvalUtil.sortIntersectionsByAxis(allocMsrIntersections.toArray(new Intersection[0]),
evalState.getClientState().getMemberIndexLists(),axisSortSeq, SortOrder.Ascending);
boolean bFirstAllocMsrIs = true;
for (Intersection allocMsrIs : allocMsrCells) {
List<Intersection> processedCompIntersections = new ArrayList<Intersection>();
for (Intersection componentIs : allocComponentCellList) {
if (isDescendantIs(componentIs, allocMsrIs, evalState)) {
processedCompIntersections.add(componentIs);
if (!bFirstAllocMsrIs) {
allocCellList.add(componentIs);
}
} else {
// Since this is the first "msrToAllocate" intersection, skip
// any descendant component intersections.
break;
}
}
// Add "msrToAlloc" intersection to list after it's descendant component
// intersections.
allocCellList.add(allocMsrIs);
// Add any remaining component intersections
allocComponentCellList.removeAll(processedCompIntersections);
bFirstAllocMsrIs = false;
}
allocCellList.addAll(allocComponentCellList);
// Exit if we're already called this function on the current rule
Intersection topMsrToAllocIs = allocCellList.get(0);
if (sourceIs.equals(topMsrToAllocIs)) {
// actual intersection in question should remain unchanged by this operation
return dataCache.getCellValue(sourceIs);
}
// Get the list of the source intersection target intersections. (TTN-1743)
sourceIsTargetCells.clear();
sourceIsTargetCells.addAll(EvalUtil.buildFloorIntersections(topMsrToAllocIs, evalState, true));
// Allocate the selected intersections in the optimal calculation order. This logic
// assumes that any component/descendant measures were already allocated in a
// previous rule step. (TTN-1743)
for (Intersection allocCell : allocCellList) {
// Find the targets of the cell to allocate
Set<Intersection> allocTargets = new HashSet<Intersection>();
String allocMeasure = allocCell.getCoordinate(msrDim);
List<String> descMeasures = measureTree.getLowestMemberNames(allocMeasure);
descMeasures.retainAll(this.targetMsrs);
for (String targetMeasure : descMeasures) {
Intersection targetCell = allocCell.clone();
targetCell.setCoordinate(msrDim, targetMeasure);
allocTargets.addAll(EvalUtil.buildFloorIntersections(targetCell, evalState));
}
// gather the user lock target intersections. These are user locks "only" and
// don't include elapsed period locks. Also gather the allocation locks that
// need to be preserved when performing the allocation of the "msrToAlloc" (TTN-1743)
userLockTargets.clear();
msrToAllocPreservedLocks.clear();
for (Intersection origLockedCell : evalState.getOrigLockedCells()) {
String measure = origLockedCell.getCoordinate(msrDim);
if (aggMsrs.contains(measure)) {
if (!EvalUtil.isElapsedIs(origLockedCell, evalState)) {
userLockTargets.addAll(EvalUtil.buildFloorIntersections(origLockedCell, evalState, true));
// Determine which locks need to be preserved when allocating the current
// "msrToAlloc" intersection. Pick all descendant locked intersections.
if (allocMeasure.equals(msrToAlloc) && isDescendantIs(origLockedCell, allocCell, evalState)) {
List<Intersection> floorLocks = EvalUtil.buildFloorIntersections(origLockedCell,evalState);
msrToAllocPreservedLocks.addAll(floorLocks);
}
}
}
}
// for (Intersection origChangedCell : evalState.getOrigChangedCells()) {
// String measure = origChangedCell.getCoordinate(msrDim);
// if (aggMsrs.contains(measure)) {
// userLockTargets.addAll(EvalUtil.buildFloorIntersections(origChangedCell, evalState, true));
// // Determine which locks need to be preserved when allocating the current
// // "msrToAlloc" intersection. Pick all descendant locked intersections.
// if (allocMeasure.equals(msrToAlloc) && isDescendantIs(origChangedCell, allocCell, evalState)) {
// List<Intersection> floorLocks = EvalUtil.buildFloorIntersections(origChangedCell,evalState);
// msrToAllocPreservedLocks.addAll(floorLocks);
// }
// }
// }
// Allocate cell
allocateChange(allocCell, allocTargets, evalState, dataCache);
}
// indicate additional aggregations required by this operation
evalState.getTriggeredAggMsrs().addAll(this.targetMsrs);
// actual intersection in question should remain unchanged by this operation
return dataCache.getCellValue(sourceIs);
}
| public double calculate(Intersection sourceIs, IPafDataCache dataCache, IPafEvalState evalState) throws PafException {
// This method uses allocation logic cloned from the Evaluation package. All
// locked or changed "msrToAllocate" intersections will be allocated in
// ascending intersection order. This allocation of multiple "msrToAllocate"
// intersections will be interleaved with the re-allocation of any impacted
// "msrToAllocate" component measure intersections, that are descendants
// of the next "msrToAllocate" to be calculated. (TTN-1743)
// Convenience variables
String msrDim = dataCache.getMeasureDim();
String[] axisSortSeq = evalState.getAxisSortPriority();
HashSet<Intersection> allocMsrComponentIntersections = new HashSet<Intersection>(evalState.getLoadFactor());
HashSet<Intersection> allocMsrIntersections = new HashSet<Intersection>(evalState.getLoadFactor());
PafDimTree measureTree = evalState.getClientState().getUowTrees().getTree(msrDim);
List<Intersection> allocCellList = new ArrayList<Intersection>(100);
// Validate function parameters
validateParms(evalState);
// targets holds all intersections to allocate into.
// The lists have been processed by validateParms
// Get the list of intersections to allocate. This would include the current
// intersection as well as any non-elapsed locked intersections for the
// "msrToAlloc" or any of its descendants along the measure hierarchy.
// (TTN-1743)
for (Intersection lockedCell : evalState.getCurrentLockedCells()) {
// Skip elapsed periods
if (EvalUtil.isElapsedIs(lockedCell, evalState)) continue;
// Split locked intersections into two groups by measure: the ones
// belonging to "msrToAlloc" and the ones belonging to the "msrToAlloc"
// components.
String measure = lockedCell.getCoordinate(msrDim);
if (this.aggMsrs.contains(measure)) {
if (!measure.equals(msrToAlloc)) {
allocMsrComponentIntersections.add(lockedCell);
} else {
allocMsrIntersections.add(lockedCell);
}
}
}
// Sort intersections to allocate in ascending, but interleaved order. All
// component measure intersections need to be allocated before any ancestor
// "msrToAlloc" intersections, but after any "msrToAlloc" intersection that
// contain any descendant targets.
//
// The one exception is that component intersections that are descendants to
// the first "msrToAlloc" intersection, are not re-allocated, since there is
// no need reason to recalculate them.
// (TTN-1743)
Intersection[] allocComponentCells = EvalUtil.sortIntersectionsByAxis(allocMsrComponentIntersections.toArray(new Intersection[0]),
evalState.getClientState().getMemberIndexLists(),axisSortSeq, SortOrder.Ascending);
List<Intersection> allocComponentCellList = new ArrayList<Intersection>(Arrays.asList(allocComponentCells));
Intersection[] allocMsrCells = EvalUtil.sortIntersectionsByAxis(allocMsrIntersections.toArray(new Intersection[0]),
evalState.getClientState().getMemberIndexLists(),axisSortSeq, SortOrder.Ascending);
boolean bFirstAllocMsrIs = true;
for (Intersection allocMsrIs : allocMsrCells) {
List<Intersection> processedCompIntersections = new ArrayList<Intersection>();
for (Intersection componentIs : allocComponentCellList) {
if (isDescendantIs(componentIs, allocMsrIs, evalState)) {
processedCompIntersections.add(componentIs);
if (!bFirstAllocMsrIs) {
allocCellList.add(componentIs);
}
} else {
// Since this is the first "msrToAllocate" intersection, skip
// any descendant component intersections.
break;
}
}
// Add "msrToAlloc" intersection to list after it's descendant component
// intersections.
allocCellList.add(allocMsrIs);
// Add any remaining component intersections
allocComponentCellList.removeAll(processedCompIntersections);
bFirstAllocMsrIs = false;
}
allocCellList.addAll(allocComponentCellList);
// Exit if we're already called this function on the current rule
Intersection topMsrToAllocIs = allocCellList.get(0);
if (!sourceIs.equals(topMsrToAllocIs)) {
// actual intersection in question should remain unchanged by this operation
return dataCache.getCellValue(sourceIs);
}
// Get the list of the source intersection target intersections. (TTN-1743)
sourceIsTargetCells.clear();
sourceIsTargetCells.addAll(EvalUtil.buildFloorIntersections(topMsrToAllocIs, evalState, true));
// Allocate the selected intersections in the optimal calculation order. This logic
// assumes that any component/descendant measures were already allocated in a
// previous rule step. (TTN-1743)
for (Intersection allocCell : allocCellList) {
// Find the targets of the cell to allocate
Set<Intersection> allocTargets = new HashSet<Intersection>();
String allocMeasure = allocCell.getCoordinate(msrDim);
List<String> descMeasures = measureTree.getLowestMemberNames(allocMeasure);
descMeasures.retainAll(this.targetMsrs);
for (String targetMeasure : descMeasures) {
Intersection targetCell = allocCell.clone();
targetCell.setCoordinate(msrDim, targetMeasure);
allocTargets.addAll(EvalUtil.buildFloorIntersections(targetCell, evalState));
}
// gather the user lock target intersections. These are user locks "only" and
// don't include elapsed period locks. Also gather the allocation locks that
// need to be preserved when performing the allocation of the "msrToAlloc" (TTN-1743)
userLockTargets.clear();
msrToAllocPreservedLocks.clear();
for (Intersection origLockedCell : evalState.getOrigLockedCells()) {
String measure = origLockedCell.getCoordinate(msrDim);
if (aggMsrs.contains(measure)) {
if (!EvalUtil.isElapsedIs(origLockedCell, evalState)) {
userLockTargets.addAll(EvalUtil.buildFloorIntersections(origLockedCell, evalState, true));
// Determine which locks need to be preserved when allocating the current
// "msrToAlloc" intersection. Pick all descendant locked intersections.
if (allocMeasure.equals(msrToAlloc) && isDescendantIs(origLockedCell, allocCell, evalState)) {
List<Intersection> floorLocks = EvalUtil.buildFloorIntersections(origLockedCell,evalState);
msrToAllocPreservedLocks.addAll(floorLocks);
}
}
}
}
// for (Intersection origChangedCell : evalState.getOrigChangedCells()) {
// String measure = origChangedCell.getCoordinate(msrDim);
// if (aggMsrs.contains(measure)) {
// userLockTargets.addAll(EvalUtil.buildFloorIntersections(origChangedCell, evalState, true));
// // Determine which locks need to be preserved when allocating the current
// // "msrToAlloc" intersection. Pick all descendant locked intersections.
// if (allocMeasure.equals(msrToAlloc) && isDescendantIs(origChangedCell, allocCell, evalState)) {
// List<Intersection> floorLocks = EvalUtil.buildFloorIntersections(origChangedCell,evalState);
// msrToAllocPreservedLocks.addAll(floorLocks);
// }
// }
// }
// Allocate cell
allocateChange(allocCell, allocTargets, evalState, dataCache);
}
// indicate additional aggregations required by this operation
evalState.getTriggeredAggMsrs().addAll(this.targetMsrs);
// actual intersection in question should remain unchanged by this operation
return dataCache.getCellValue(sourceIs);
}
|
diff --git a/browser/org/eclipse/cdt/core/browser/IndexTypeInfo.java b/browser/org/eclipse/cdt/core/browser/IndexTypeInfo.java
index ccb97656a..8d4d52de7 100644
--- a/browser/org/eclipse/cdt/core/browser/IndexTypeInfo.java
+++ b/browser/org/eclipse/cdt/core/browser/IndexTypeInfo.java
@@ -1,281 +1,282 @@
/*******************************************************************************
* Copyright (c) 2006, 2007 QNX Software Systems 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:
* QNX - Initial API and implementation
* IBM Corporation
* Andrew Ferguson (Symbian)
* Anton Leherbauer (Wind River Systems)
*******************************************************************************/
package org.eclipse.cdt.core.browser;
import java.util.Arrays;
import org.eclipse.cdt.core.CCorePlugin;
import org.eclipse.cdt.core.dom.ast.DOMException;
import org.eclipse.cdt.core.dom.ast.IBinding;
import org.eclipse.cdt.core.dom.ast.IFunction;
import org.eclipse.cdt.core.index.IIndex;
import org.eclipse.cdt.core.index.IIndexBinding;
import org.eclipse.cdt.core.index.IIndexFileLocation;
import org.eclipse.cdt.core.index.IIndexName;
import org.eclipse.cdt.core.index.IndexFilter;
import org.eclipse.cdt.core.model.ICElement;
import org.eclipse.cdt.core.model.ICProject;
import org.eclipse.cdt.core.parser.ast.ASTAccessVisibility;
import org.eclipse.cdt.internal.core.browser.IndexTypeReference;
import org.eclipse.cdt.internal.core.browser.util.IndexModelUtil;
import org.eclipse.cdt.internal.core.pdom.dom.PDOMNotImplementedError;
import org.eclipse.core.filesystem.URIUtil;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Path;
/**
* @author Doug Schaefer
*
*/
public class IndexTypeInfo implements ITypeInfo, IFunctionInfo {
private final String[] fqn;
private final int elementType;
private final IIndex index;
private final String[] params;
private final String returnType;
private ITypeReference reference; // lazily constructed
public IndexTypeInfo(String[] fqn, int elementType, IIndex index) {
this.fqn = fqn;
this.elementType = elementType;
this.index = index;
this.params= null;
this.returnType= null;
}
public IndexTypeInfo(String[] fqn, int elementType, String[] params, String returnType, IIndex index) {
this.fqn = fqn;
this.elementType = elementType;
this.params= params;
this.returnType= returnType;
this.index = index;
}
public void addDerivedReference(ITypeReference location) {
throw new PDOMNotImplementedError();
}
public void addReference(ITypeReference location) {
throw new PDOMNotImplementedError();
}
public boolean canSubstituteFor(ITypeInfo info) {
throw new PDOMNotImplementedError();
}
public boolean encloses(ITypeInfo info) {
throw new PDOMNotImplementedError();
}
public boolean exists() {
throw new PDOMNotImplementedError();
}
public int getCElementType() {
return elementType;
}
public ITypeReference[] getDerivedReferences() {
throw new PDOMNotImplementedError();
}
public ITypeInfo[] getEnclosedTypes() {
throw new PDOMNotImplementedError();
}
public ITypeInfo[] getEnclosedTypes(int[] kinds) {
throw new PDOMNotImplementedError();
}
public ITypeInfo getEnclosingNamespace(boolean includeGlobalNamespace) {
throw new PDOMNotImplementedError();
}
public ICProject getEnclosingProject() {
if(getResolvedReference()!=null) {
IProject project = reference.getProject();
if(project!=null) {
return CCorePlugin.getDefault().getCoreModel().getCModel().getCProject(project.getName());
}
}
return null;
}
public ITypeInfo getEnclosingType() {
// TODO not sure
return null;
}
public ITypeInfo getEnclosingType(int[] kinds) {
throw new PDOMNotImplementedError();
}
public String getName() {
return fqn[fqn.length-1];
}
public IQualifiedTypeName getQualifiedTypeName() {
return new QualifiedTypeName(fqn);
}
public ITypeReference[] getReferences() {
throw new PDOMNotImplementedError();
}
public ITypeReference getResolvedReference() {
if(reference==null) {
try {
index.acquireReadLock();
char[][] cfqn = new char[fqn.length][];
for(int i=0; i<fqn.length; i++)
cfqn[i] = fqn[i].toCharArray();
IIndexBinding[] ibs = index.findBindings(cfqn, new IndexFilter() {
public boolean acceptBinding(IBinding binding) {
boolean sameType= IndexModelUtil.bindingHasCElementType(binding, new int[]{elementType});
if (sameType && binding instanceof IFunction && params != null) {
- String[] otherParams;
try {
- otherParams= IndexModelUtil.extractParameterTypes((IFunction)binding);
+ String[]otherParams= IndexModelUtil.extractParameterTypes((IFunction)binding);
return Arrays.equals(params, otherParams);
} catch (DOMException exc) {
CCorePlugin.log(exc);
}
}
return sameType;
}
}, new NullProgressMonitor());
if(ibs.length>0) {
IIndexName[] names;
- if (elementType == ICElement.C_TYPEDEF) {
+ names= index.findNames(ibs[0], IIndex.FIND_DEFINITIONS);
+ if (names.length == 0 && elementType == ICElement.C_VARIABLE || elementType == ICElement.C_FUNCTION) {
names= index.findNames(ibs[0], IIndex.FIND_DECLARATIONS);
- } else {
- names= index.findNames(ibs[0], IIndex.FIND_DEFINITIONS);
}
- if(names.length>0) {
- IIndexFileLocation ifl = names[0].getFile().getLocation();
+ for (int i = 0; i < names.length; i++) {
+ IIndexName indexName = names[i];
+ IIndexFileLocation ifl = indexName.getFile().getLocation();
String fullPath = ifl.getFullPath();
- if(fullPath!=null) {
+ if (fullPath != null) {
IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(fullPath));
if(file!=null) {
reference = new IndexTypeReference(
ibs[0], file, file.getProject(), names[0].getNodeOffset(), names[0].getNodeLength()
);
}
+ break;
} else {
IPath path = URIUtil.toPath(ifl.getURI());
if(path!=null) {
reference = new IndexTypeReference(
ibs[0], path, null, names[0].getNodeOffset(), names[0].getNodeLength()
);
+ break;
}
}
}
}
} catch(CoreException ce) {
CCorePlugin.log(ce);
} catch (InterruptedException ie) {
CCorePlugin.log(ie);
} finally {
index.releaseReadLock();
}
}
return reference;
}
public ITypeInfo getRootNamespace(boolean includeGlobalNamespace) {
throw new PDOMNotImplementedError();
}
public ITypeInfo[] getSubTypes() {
throw new PDOMNotImplementedError();
}
public ASTAccessVisibility getSuperTypeAccess(ITypeInfo subType) {
throw new PDOMNotImplementedError();
}
public ITypeInfo[] getSuperTypes() {
throw new PDOMNotImplementedError();
}
public boolean hasEnclosedTypes() {
throw new PDOMNotImplementedError();
}
public boolean hasSubTypes() {
throw new PDOMNotImplementedError();
}
public boolean hasSuperTypes() {
throw new PDOMNotImplementedError();
}
public boolean isClass() {
throw new PDOMNotImplementedError();
}
public boolean isEnclosed(ITypeInfo info) {
throw new PDOMNotImplementedError();
}
public boolean isEnclosed(ITypeSearchScope scope) {
throw new PDOMNotImplementedError();
}
public boolean isEnclosedType() {
throw new PDOMNotImplementedError();
}
public boolean isEnclosingType() {
throw new PDOMNotImplementedError();
}
public boolean isReferenced(ITypeSearchScope scope) {
throw new PDOMNotImplementedError();
}
public boolean isUndefinedType() {
throw new PDOMNotImplementedError();
}
public void setCElementType(int type) {
throw new PDOMNotImplementedError();
}
public int compareTo(Object arg0) {
throw new PDOMNotImplementedError();
}
/*
* @see org.eclipse.cdt.internal.core.browser.IFunctionInfo#getParameters()
*/
public String[] getParameters() {
return params;
}
/*
* @see org.eclipse.cdt.internal.core.browser.IFunctionInfo#getReturnType()
*/
public String getReturnType() {
return returnType;
}
}
| false | true | public ITypeReference getResolvedReference() {
if(reference==null) {
try {
index.acquireReadLock();
char[][] cfqn = new char[fqn.length][];
for(int i=0; i<fqn.length; i++)
cfqn[i] = fqn[i].toCharArray();
IIndexBinding[] ibs = index.findBindings(cfqn, new IndexFilter() {
public boolean acceptBinding(IBinding binding) {
boolean sameType= IndexModelUtil.bindingHasCElementType(binding, new int[]{elementType});
if (sameType && binding instanceof IFunction && params != null) {
String[] otherParams;
try {
otherParams= IndexModelUtil.extractParameterTypes((IFunction)binding);
return Arrays.equals(params, otherParams);
} catch (DOMException exc) {
CCorePlugin.log(exc);
}
}
return sameType;
}
}, new NullProgressMonitor());
if(ibs.length>0) {
IIndexName[] names;
if (elementType == ICElement.C_TYPEDEF) {
names= index.findNames(ibs[0], IIndex.FIND_DECLARATIONS);
} else {
names= index.findNames(ibs[0], IIndex.FIND_DEFINITIONS);
}
if(names.length>0) {
IIndexFileLocation ifl = names[0].getFile().getLocation();
String fullPath = ifl.getFullPath();
if(fullPath!=null) {
IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(fullPath));
if(file!=null) {
reference = new IndexTypeReference(
ibs[0], file, file.getProject(), names[0].getNodeOffset(), names[0].getNodeLength()
);
}
} else {
IPath path = URIUtil.toPath(ifl.getURI());
if(path!=null) {
reference = new IndexTypeReference(
ibs[0], path, null, names[0].getNodeOffset(), names[0].getNodeLength()
);
}
}
}
}
} catch(CoreException ce) {
CCorePlugin.log(ce);
} catch (InterruptedException ie) {
CCorePlugin.log(ie);
} finally {
index.releaseReadLock();
}
}
return reference;
}
| public ITypeReference getResolvedReference() {
if(reference==null) {
try {
index.acquireReadLock();
char[][] cfqn = new char[fqn.length][];
for(int i=0; i<fqn.length; i++)
cfqn[i] = fqn[i].toCharArray();
IIndexBinding[] ibs = index.findBindings(cfqn, new IndexFilter() {
public boolean acceptBinding(IBinding binding) {
boolean sameType= IndexModelUtil.bindingHasCElementType(binding, new int[]{elementType});
if (sameType && binding instanceof IFunction && params != null) {
try {
String[]otherParams= IndexModelUtil.extractParameterTypes((IFunction)binding);
return Arrays.equals(params, otherParams);
} catch (DOMException exc) {
CCorePlugin.log(exc);
}
}
return sameType;
}
}, new NullProgressMonitor());
if(ibs.length>0) {
IIndexName[] names;
names= index.findNames(ibs[0], IIndex.FIND_DEFINITIONS);
if (names.length == 0 && elementType == ICElement.C_VARIABLE || elementType == ICElement.C_FUNCTION) {
names= index.findNames(ibs[0], IIndex.FIND_DECLARATIONS);
}
for (int i = 0; i < names.length; i++) {
IIndexName indexName = names[i];
IIndexFileLocation ifl = indexName.getFile().getLocation();
String fullPath = ifl.getFullPath();
if (fullPath != null) {
IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(fullPath));
if(file!=null) {
reference = new IndexTypeReference(
ibs[0], file, file.getProject(), names[0].getNodeOffset(), names[0].getNodeLength()
);
}
break;
} else {
IPath path = URIUtil.toPath(ifl.getURI());
if(path!=null) {
reference = new IndexTypeReference(
ibs[0], path, null, names[0].getNodeOffset(), names[0].getNodeLength()
);
break;
}
}
}
}
} catch(CoreException ce) {
CCorePlugin.log(ce);
} catch (InterruptedException ie) {
CCorePlugin.log(ie);
} finally {
index.releaseReadLock();
}
}
return reference;
}
|
diff --git a/src/FE_SRC_COMMON/com/ForgeEssentials/commands/util/AFKdata.java b/src/FE_SRC_COMMON/com/ForgeEssentials/commands/util/AFKdata.java
index f79d93d74..6377d697a 100644
--- a/src/FE_SRC_COMMON/com/ForgeEssentials/commands/util/AFKdata.java
+++ b/src/FE_SRC_COMMON/com/ForgeEssentials/commands/util/AFKdata.java
@@ -1,48 +1,48 @@
package com.ForgeEssentials.commands.util;
import com.ForgeEssentials.commands.CommandAFK;
import com.ForgeEssentials.util.AreaSelector.WarpPoint;
import com.ForgeEssentials.util.AreaSelector.WorldPoint;
import net.minecraft.entity.player.EntityPlayerMP;
public class AFKdata
{
public EntityPlayerMP player;
private WorldPoint lastPos;
private WorldPoint currentPos;
int waittime;
public boolean needstowait;
public AFKdata(EntityPlayerMP player)
{
this.player = player;
waittime = CommandAFK.warmup;
lastPos = new WarpPoint(player);
needstowait = true;
}
public void count()
{
if(player == null)
{
TickHandlerCommands.afkListToRemove.add(this);
return;
}
currentPos = new WarpPoint(player);
if (!lastPos.equals(currentPos))
{
CommandAFK.abort(this);
}
if(needstowait)
{
- waittime--;
if (waittime == 0)
{
CommandAFK.makeAFK(this);
- }
+ }
+ waittime--;
}
}
}
| false | true | public void count()
{
if(player == null)
{
TickHandlerCommands.afkListToRemove.add(this);
return;
}
currentPos = new WarpPoint(player);
if (!lastPos.equals(currentPos))
{
CommandAFK.abort(this);
}
if(needstowait)
{
waittime--;
if (waittime == 0)
{
CommandAFK.makeAFK(this);
}
}
}
| public void count()
{
if(player == null)
{
TickHandlerCommands.afkListToRemove.add(this);
return;
}
currentPos = new WarpPoint(player);
if (!lastPos.equals(currentPos))
{
CommandAFK.abort(this);
}
if(needstowait)
{
if (waittime == 0)
{
CommandAFK.makeAFK(this);
}
waittime--;
}
}
|
diff --git a/org.eclipse.mylyn.tasks.core/src/org/eclipse/mylyn/internal/tasks/core/DateRange.java b/org.eclipse.mylyn.tasks.core/src/org/eclipse/mylyn/internal/tasks/core/DateRange.java
index 4cbe5d5df..f21bb7b5b 100644
--- a/org.eclipse.mylyn.tasks.core/src/org/eclipse/mylyn/internal/tasks/core/DateRange.java
+++ b/org.eclipse.mylyn.tasks.core/src/org/eclipse/mylyn/internal/tasks/core/DateRange.java
@@ -1,247 +1,249 @@
/*******************************************************************************
* 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.internal.tasks.core;
import java.text.DateFormat;
import java.util.Calendar;
import org.eclipse.core.runtime.Assert;
/**
* @author Rob Elves
* @since 3.0
*/
public class DateRange implements Comparable<DateRange> {
private static final long DAY = 1000 * 60 * 60 * 24;
private static final String DESCRIPTION_PREVIOUS_WEEK = "Previous Week";
private static final String DESCRIPTION_THIS_WEEK = "This Week";
private static final String DESCRIPTION_NEXT_WEEK = "Next Week";
private static final String DESCRIPTION_WEEK_AFTER_NEXT = "Two Weeks";
private final Calendar startDate;
private final Calendar endDate;
/**
* create an instance of a date range that represents a finite point in time
*/
public DateRange(Calendar time) {
startDate = time;
endDate = time;
}
public DateRange(Calendar startDate, Calendar endDate) {
Assert.isNotNull(startDate);
Assert.isNotNull(endDate);
this.startDate = startDate;
this.endDate = endDate;
}
public boolean includes(DateRange range) {
return (startDate.getTimeInMillis() <= range.getStartDate().getTimeInMillis())
&& (endDate.getTimeInMillis() >= range.getEndDate().getTimeInMillis());
}
public boolean includes(Calendar cal) {
return (startDate.getTimeInMillis() <= cal.getTimeInMillis())
&& (endDate.getTimeInMillis() >= cal.getTimeInMillis());
}
public Calendar getStartDate() {
return startDate;
}
public Calendar getEndDate() {
return endDate;
}
/**
* TODO: Move into label provider
*/
@Override
public String toString() {
boolean isThisWeek = TaskActivityUtil.getCurrentWeek().includes(this);
- boolean isNextWeek = TaskActivityUtil.getNextWeek().includes(this);
+ Calendar endNextWeek = TaskActivityUtil.getCalendar();
+ endNextWeek.add(Calendar.DAY_OF_YEAR, 7);
+ boolean isNextWeek = TaskActivityUtil.getNextWeek().includes(this) && this.before(endNextWeek);
if (isDay() && (isThisWeek || isNextWeek)) {
String day = "";
switch (getStartDate().get(Calendar.DAY_OF_WEEK)) {
case Calendar.MONDAY:
day = "Monday";
break;
case Calendar.TUESDAY:
day = "Tuesday";
break;
case Calendar.WEDNESDAY:
day = "Wednesday";
break;
case Calendar.THURSDAY:
day = "Thursday";
break;
case Calendar.FRIDAY:
day = "Friday";
break;
case Calendar.SATURDAY:
day = "Saturday";
break;
case Calendar.SUNDAY:
day = "Sunday";
break;
}
if (Calendar.getInstance().get(Calendar.DAY_OF_WEEK) == getStartDate().get(Calendar.DAY_OF_WEEK)) {
return day + " - Today";
} else {
return day;
}
} else if (isThisWeek()) {
return DESCRIPTION_THIS_WEEK;
} else if (isNextWeek()) {
return DESCRIPTION_NEXT_WEEK;
} else if (isWeekAfterNext()) {
return DESCRIPTION_WEEK_AFTER_NEXT;
} else if (isPreviousWeek()) {
return DESCRIPTION_PREVIOUS_WEEK;
}
return DateFormat.getDateInstance(DateFormat.MEDIUM).format(startDate.getTime());
/* + " to "+ DateFormat.getDateInstance(DateFormat.MEDIUM).format(endDate.getTime());*/
}
private boolean isWeekAfterNext() {
return TaskActivityUtil.getCurrentWeek().next().next().compareTo(this) == 0;
}
public DateRange next() {
if (isDay()) {
return create(Calendar.DAY_OF_YEAR, 1);
} else if (isWeek()) {
return create(Calendar.WEEK_OF_YEAR, 1);
}
return null;
}
public DateRange previous() {
if (isDay()) {
return create(Calendar.DAY_OF_YEAR, -1);
} else if (isWeek()) {
return create(Calendar.WEEK_OF_YEAR, -1);
}
return null;
}
private DateRange create(int field, int multiplier) {
Calendar previousStart = (Calendar) getStartDate().clone();
Calendar previousEnd = (Calendar) getEndDate().clone();
previousStart.add(field, 1 * multiplier);
previousEnd.add(field, 1 * multiplier);
return new DateRange(previousStart, previousEnd);
}
private boolean isNextWeek() {
return TaskActivityUtil.getCurrentWeek().next().compareTo(this) == 0;
}
public boolean isThisWeek() {
if (isWeek()) {
return this.includes(Calendar.getInstance());
}
return false;
}
private boolean isPreviousWeek() {
if (isWeek()) {
Calendar cal = Calendar.getInstance();
cal.add(Calendar.WEEK_OF_YEAR, -1);
return this.includes(cal);
}
return false;
}
public boolean isDay() {
return ((getEndDate().getTimeInMillis() - getStartDate().getTimeInMillis()) == DAY - 1);
}
public boolean isWeek() {
return ((getEndDate().getTimeInMillis() - getStartDate().getTimeInMillis()) == (DAY * 7) - 1);
}
public boolean isPast() {
return getEndDate().compareTo(Calendar.getInstance()) < 0;
}
public boolean isBefore(DateRange scheduledDate) {
return this.getEndDate().compareTo(scheduledDate.getStartDate()) < 0;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((endDate == null) ? 0 : endDate.hashCode());
result = prime * result + ((startDate == null) ? 0 : startDate.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof DateRange)) {
return false;
}
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
// if (getClass() != obj.getClass()) {
// return false;
// }
DateRange other = (DateRange) obj;
if (endDate == null) {
if (other.endDate != null) {
return false;
}
} else if (!endDate.equals(other.endDate)) {
return false;
}
if (startDate == null) {
if (other.startDate != null) {
return false;
}
} else if (!startDate.equals(other.startDate)) {
return false;
}
return true;
}
public boolean before(Calendar cal) {
return getEndDate().before(cal);
}
public boolean after(Calendar cal) {
return cal.before(getEndDate());
}
public int compareTo(DateRange range) {
if (range.getStartDate().equals(startDate) && range.getEndDate().equals(endDate)) {
return 0;
} else if (includes(range)) {
return 1;
} else if (before(range.getStartDate())) {
return -1;
} else if (after(range.getEndDate())) {
return 1;
}
return -1;
}
}
| true | true | public String toString() {
boolean isThisWeek = TaskActivityUtil.getCurrentWeek().includes(this);
boolean isNextWeek = TaskActivityUtil.getNextWeek().includes(this);
if (isDay() && (isThisWeek || isNextWeek)) {
String day = "";
switch (getStartDate().get(Calendar.DAY_OF_WEEK)) {
case Calendar.MONDAY:
day = "Monday";
break;
case Calendar.TUESDAY:
day = "Tuesday";
break;
case Calendar.WEDNESDAY:
day = "Wednesday";
break;
case Calendar.THURSDAY:
day = "Thursday";
break;
case Calendar.FRIDAY:
day = "Friday";
break;
case Calendar.SATURDAY:
day = "Saturday";
break;
case Calendar.SUNDAY:
day = "Sunday";
break;
}
if (Calendar.getInstance().get(Calendar.DAY_OF_WEEK) == getStartDate().get(Calendar.DAY_OF_WEEK)) {
return day + " - Today";
} else {
return day;
}
} else if (isThisWeek()) {
return DESCRIPTION_THIS_WEEK;
} else if (isNextWeek()) {
return DESCRIPTION_NEXT_WEEK;
} else if (isWeekAfterNext()) {
return DESCRIPTION_WEEK_AFTER_NEXT;
} else if (isPreviousWeek()) {
return DESCRIPTION_PREVIOUS_WEEK;
}
return DateFormat.getDateInstance(DateFormat.MEDIUM).format(startDate.getTime());
/* + " to "+ DateFormat.getDateInstance(DateFormat.MEDIUM).format(endDate.getTime());*/
}
| public String toString() {
boolean isThisWeek = TaskActivityUtil.getCurrentWeek().includes(this);
Calendar endNextWeek = TaskActivityUtil.getCalendar();
endNextWeek.add(Calendar.DAY_OF_YEAR, 7);
boolean isNextWeek = TaskActivityUtil.getNextWeek().includes(this) && this.before(endNextWeek);
if (isDay() && (isThisWeek || isNextWeek)) {
String day = "";
switch (getStartDate().get(Calendar.DAY_OF_WEEK)) {
case Calendar.MONDAY:
day = "Monday";
break;
case Calendar.TUESDAY:
day = "Tuesday";
break;
case Calendar.WEDNESDAY:
day = "Wednesday";
break;
case Calendar.THURSDAY:
day = "Thursday";
break;
case Calendar.FRIDAY:
day = "Friday";
break;
case Calendar.SATURDAY:
day = "Saturday";
break;
case Calendar.SUNDAY:
day = "Sunday";
break;
}
if (Calendar.getInstance().get(Calendar.DAY_OF_WEEK) == getStartDate().get(Calendar.DAY_OF_WEEK)) {
return day + " - Today";
} else {
return day;
}
} else if (isThisWeek()) {
return DESCRIPTION_THIS_WEEK;
} else if (isNextWeek()) {
return DESCRIPTION_NEXT_WEEK;
} else if (isWeekAfterNext()) {
return DESCRIPTION_WEEK_AFTER_NEXT;
} else if (isPreviousWeek()) {
return DESCRIPTION_PREVIOUS_WEEK;
}
return DateFormat.getDateInstance(DateFormat.MEDIUM).format(startDate.getTime());
/* + " to "+ DateFormat.getDateInstance(DateFormat.MEDIUM).format(endDate.getTime());*/
}
|
diff --git a/core/src/main/java/com/github/srec/testng/AbstractSRecTestNGTest.java b/core/src/main/java/com/github/srec/testng/AbstractSRecTestNGTest.java
index 3d0d789..79e5612 100644
--- a/core/src/main/java/com/github/srec/testng/AbstractSRecTestNGTest.java
+++ b/core/src/main/java/com/github/srec/testng/AbstractSRecTestNGTest.java
@@ -1,110 +1,110 @@
/*
* Copyright 2010 Victor Tatai
*
* 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.srec.testng;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.fail;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import com.github.srec.command.parser.ParseException;
import com.github.srec.play.Player;
import com.github.srec.util.Utils;
/**
* An abstract classe to be used when writing TestNG tests.
*
* @author Victor Tatai
*/
public abstract class AbstractSRecTestNGTest {
protected String scriptDir;
protected String className;
protected String[] params;
private final boolean singleInstanceMode;
public AbstractSRecTestNGTest(String scriptDir, boolean singleInstanceMode) {
this.scriptDir = scriptDir;
this.singleInstanceMode = singleInstanceMode;
}
protected AbstractSRecTestNGTest(String scriptDir, String className, String[] params, boolean singleInstanceMode) {
this.scriptDir = scriptDir;
this.className = className;
this.params = params;
this.singleInstanceMode = singleInstanceMode;
}
/**
* Runs an entire suite or a single test case.
*
* @param script The name of the script to run, located inside {@link #scriptDir}
* @param testCases The names of the test cases to run
* @param failOnError true if an error should result in a test failure
* @return The errors
*/
protected Player runTest(String script, boolean failOnError, boolean failFast, String... testCases) {
try {
Player p = new Player(singleInstanceMode)
.init(failFast)
.play(new File(scriptDir + File.separator + script), testCases,
className, params, getProperties());
p.printErrors();
if (failOnError) {
assertEquals(p.getErrors().size(), 0);
}
return p;
} catch (ParseException e) {
if (failOnError) {
e.printErrors();
- fail("Errors encountered during srec script run, failing");
+ fail("Errors encountered during srec script run: " + e.getMessage());
} else {
throw e;
}
} catch (IOException e) {
e.printStackTrace();
fail(e.getMessage());
} finally {
Utils.closeWindows();
}
return null;
}
/**
* Runs an entire suite or a single test case, failing if there is an error.
*
* @param script The name of the script to run, located inside {@link #scriptDir}
* @param testCases The names of the test cases to run
* @return The errors
*/
protected Player runTest(String script, String... testCases) {
return runTest(script, true, true, testCases);
}
/**
* Runs an entire suite, failing if there is an error.
*
* @param script The name of the script to run, located inside {@link #scriptDir}
* @return The player errors
*/
protected Player runTest(String script) {
return runTest(script, true, true);
}
protected Map<String, Object> getProperties() {
return new HashMap<String, Object>();
}
}
| true | true | protected Player runTest(String script, boolean failOnError, boolean failFast, String... testCases) {
try {
Player p = new Player(singleInstanceMode)
.init(failFast)
.play(new File(scriptDir + File.separator + script), testCases,
className, params, getProperties());
p.printErrors();
if (failOnError) {
assertEquals(p.getErrors().size(), 0);
}
return p;
} catch (ParseException e) {
if (failOnError) {
e.printErrors();
fail("Errors encountered during srec script run, failing");
} else {
throw e;
}
} catch (IOException e) {
e.printStackTrace();
fail(e.getMessage());
} finally {
Utils.closeWindows();
}
return null;
}
| protected Player runTest(String script, boolean failOnError, boolean failFast, String... testCases) {
try {
Player p = new Player(singleInstanceMode)
.init(failFast)
.play(new File(scriptDir + File.separator + script), testCases,
className, params, getProperties());
p.printErrors();
if (failOnError) {
assertEquals(p.getErrors().size(), 0);
}
return p;
} catch (ParseException e) {
if (failOnError) {
e.printErrors();
fail("Errors encountered during srec script run: " + e.getMessage());
} else {
throw e;
}
} catch (IOException e) {
e.printStackTrace();
fail(e.getMessage());
} finally {
Utils.closeWindows();
}
return null;
}
|
diff --git a/trunk/hecl/core/org/hecl/ParseList.java b/trunk/hecl/core/org/hecl/ParseList.java
index 800f710b..0c8df648 100644
--- a/trunk/hecl/core/org/hecl/ParseList.java
+++ b/trunk/hecl/core/org/hecl/ParseList.java
@@ -1,128 +1,118 @@
/* Copyright 2004-2006 David N. Welton
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.hecl;
/**
* <code>ParseList</code> parses up Hecl lists.
*
* @author <a href="mailto:[email protected]">David N. Welton </a>
* @version 1.0
*/
public class ParseList extends Parse {
/**
* Creates a new <code>ParseList</code> instance.
*
* @param in_in a <code>String</code> value
*/
public ParseList(String in_in) {
in = in_in;
state = new ParseState(in);
parselist = true;
}
/**
* <code>parseLine</code> parses a line of Hecl code.
*
* @param state a <code>ParseState</code> value
* @exception HeclException if an error occurs
*/
public void parseLine(ParseState state) throws HeclException {
char ch;
while (true) {
ch = state.nextchar();
if (state.done()) {
return;
}
if (ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r') {
continue;
}
switch (ch) {
case '{' :
parseBlock(state);
addCurrent();
break;
- case '[' :
- parseCommand(state);
- addCurrent();
- break;
case '"' :
parseText(state);
addCurrent();
break;
- case '\\':
- if (!parseEscape(state)) {
- parseWord(state);
- addCurrent();
- }
- break;
default :
appendToCurrent(ch);
parseWord(state);
addCurrent();
break;
}
}
}
/**
* <code>parseText</code> parses some text, such as that enclosed in
* quotes "".
*
* @param state a <code>ParseState</code> value
* @exception HeclException if an error occurs
*/
public void parseText(ParseState state) throws HeclException {
char ch;
while (true) {
ch = state.nextchar();
if (state.done()) {
return;
}
switch (ch) {
case '\\' :
parseEscape(state);
break;
case '"' :
return;
default :
appendToCurrent(ch);
break;
}
}
}
/**
* <code>parseWord</code> parses a plain Hecl word.
*
* @param state a <code>ParseState</code> value
* @exception HeclException if an error occurs
*/
public void parseWord(ParseState state) throws HeclException {
char ch;
while (true) {
ch = state.nextchar();
if (state.done()) {
return;
}
if (ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r') {
return;
}
appendToCurrent(ch);
}
}
}
| false | true | public void parseLine(ParseState state) throws HeclException {
char ch;
while (true) {
ch = state.nextchar();
if (state.done()) {
return;
}
if (ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r') {
continue;
}
switch (ch) {
case '{' :
parseBlock(state);
addCurrent();
break;
case '[' :
parseCommand(state);
addCurrent();
break;
case '"' :
parseText(state);
addCurrent();
break;
case '\\':
if (!parseEscape(state)) {
parseWord(state);
addCurrent();
}
break;
default :
appendToCurrent(ch);
parseWord(state);
addCurrent();
break;
}
}
}
| public void parseLine(ParseState state) throws HeclException {
char ch;
while (true) {
ch = state.nextchar();
if (state.done()) {
return;
}
if (ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r') {
continue;
}
switch (ch) {
case '{' :
parseBlock(state);
addCurrent();
break;
case '"' :
parseText(state);
addCurrent();
break;
default :
appendToCurrent(ch);
parseWord(state);
addCurrent();
break;
}
}
}
|
diff --git a/src/java/org/apache/nutch/fetcher/Fetcher.java b/src/java/org/apache/nutch/fetcher/Fetcher.java
index df152ecc..06c4a2c7 100644
--- a/src/java/org/apache/nutch/fetcher/Fetcher.java
+++ b/src/java/org/apache/nutch/fetcher/Fetcher.java
@@ -1,404 +1,405 @@
/**
* Copyright 2005 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.nutch.fetcher;
import java.io.IOException;
import java.io.File;
import org.apache.hadoop.io.*;
import org.apache.hadoop.fs.*;
import org.apache.hadoop.conf.*;
import org.apache.hadoop.util.LogFormatter;
import org.apache.hadoop.mapred.*;
import org.apache.nutch.crawl.CrawlDatum;
import org.apache.nutch.crawl.SignatureFactory;
import org.apache.nutch.metadata.Metadata;
import org.apache.nutch.net.*;
import org.apache.nutch.protocol.*;
import org.apache.nutch.parse.*;
import org.apache.nutch.util.*;
import java.util.logging.*;
/** The fetcher. Most of the work is done by plugins. */
public class Fetcher extends Configured implements MapRunnable {
public static final Logger LOG =
LogFormatter.getLogger("org.apache.nutch.fetcher.Fetcher");
public static final String SIGNATURE_KEY = "nutch.content.digest";
public static final String SEGMENT_NAME_KEY = "nutch.segment.name";
public static final String SCORE_KEY = "nutch.crawl.score";
public static class InputFormat extends SequenceFileInputFormat {
/** Don't split inputs, to keep things polite. */
public FileSplit[] getSplits(FileSystem fs, JobConf job, int nSplits)
throws IOException {
File[] files = listFiles(fs, job);
FileSplit[] splits = new FileSplit[files.length];
for (int i = 0; i < files.length; i++) {
splits[i] = new FileSplit(files[i], 0, fs.getLength(files[i]));
}
return splits;
}
}
private RecordReader input;
private OutputCollector output;
private Reporter reporter;
private String segmentName;
private int activeThreads;
private int maxRedirect;
private long start = System.currentTimeMillis(); // start time of fetcher run
private long lastRequestStart = start;
private long bytes; // total bytes fetched
private int pages; // total pages fetched
private int errors; // total pages errored
private boolean storingContent;
private boolean parsing;
private class FetcherThread extends Thread {
private Configuration conf;
private URLFilters urlFilters;
private ParseUtil parseUtil;
private ProtocolFactory protocolFactory;
public FetcherThread(Configuration conf) {
this.setDaemon(true); // don't hang JVM on exit
this.setName("FetcherThread"); // use an informative name
this.conf = conf;
this.urlFilters = new URLFilters(conf);
this.parseUtil = new ParseUtil(conf);
this.protocolFactory = new ProtocolFactory(conf);
}
public void run() {
synchronized (Fetcher.this) {activeThreads++;} // count threads
try {
UTF8 key = new UTF8();
CrawlDatum datum = new CrawlDatum();
while (true) {
if (LogFormatter.hasLoggedSevere()) // something bad happened
break; // exit
try { // get next entry from input
if (!input.next(key, datum)) {
break; // at eof, exit
}
} catch (IOException e) {
e.printStackTrace();
LOG.severe("fetcher caught:"+e.toString());
break;
}
synchronized (Fetcher.this) {
lastRequestStart = System.currentTimeMillis();
}
+ // url may be changed through redirects.
String url = key.toString();
try {
LOG.info("fetching " + url); // fetch the page
boolean redirecting;
int redirectCount = 0;
do {
redirecting = false;
LOG.fine("redirectCount=" + redirectCount);
Protocol protocol = this.protocolFactory.getProtocol(url);
- ProtocolOutput output = protocol.getProtocolOutput(key, datum);
+ ProtocolOutput output = protocol.getProtocolOutput(new UTF8(url), datum);
ProtocolStatus status = output.getStatus();
Content content = output.getContent();
switch(status.getCode()) {
case ProtocolStatus.SUCCESS: // got a page
output(key, datum, content, CrawlDatum.STATUS_FETCH_SUCCESS);
updateStatus(content.getContent().length);
break;
case ProtocolStatus.MOVED: // redirect
case ProtocolStatus.TEMP_MOVED:
String newUrl = status.getMessage();
newUrl = this.urlFilters.filter(newUrl);
if (newUrl != null && !newUrl.equals(url)) {
url = newUrl;
redirecting = true;
redirectCount++;
- LOG.fine(" - redirect to " + url);
+ LOG.fine(" - protocol redirect to " + url);
} else {
- LOG.fine(" - redirect skipped: " +
+ LOG.fine(" - protocol redirect skipped: " +
(url.equals(newUrl) ? "to same url" : "filtered"));
}
break;
case ProtocolStatus.EXCEPTION:
logError(url, status.getMessage());
case ProtocolStatus.RETRY: // retry
datum.setRetriesSinceFetch(datum.getRetriesSinceFetch()+1);
output(key, datum, null, CrawlDatum.STATUS_FETCH_RETRY);
break;
case ProtocolStatus.GONE: // gone
case ProtocolStatus.NOTFOUND:
case ProtocolStatus.ACCESS_DENIED:
case ProtocolStatus.ROBOTS_DENIED:
case ProtocolStatus.NOTMODIFIED:
output(key, datum, null, CrawlDatum.STATUS_FETCH_GONE);
break;
default:
LOG.warning("Unknown ProtocolStatus: " + status.getCode());
output(key, datum, null, CrawlDatum.STATUS_FETCH_GONE);
}
if (redirecting && redirectCount >= maxRedirect) {
LOG.info(" - redirect count exceeded " + url);
output(key, datum, null, CrawlDatum.STATUS_FETCH_GONE);
}
} while (redirecting && (redirectCount < maxRedirect));
} catch (Throwable t) { // unexpected exception
logError(url, t.toString());
output(key, datum, null, CrawlDatum.STATUS_FETCH_GONE);
}
}
} catch (Throwable e) {
e.printStackTrace();
LOG.severe("fetcher caught:"+e.toString());
} finally {
synchronized (Fetcher.this) {activeThreads--;} // count threads
}
}
private void logError(String url, String message) {
LOG.info("fetch of " + url + " failed with: " + message);
synchronized (Fetcher.this) { // record failure
errors++;
}
}
private void output(UTF8 key, CrawlDatum datum,
Content content, int status) {
datum.setStatus(status);
if (content == null) {
String url = key.toString();
content = new Content(url, url, new byte[0], "", new Metadata(), this.conf);
}
Metadata metadata = content.getMetadata();
// add segment to metadata
metadata.set(SEGMENT_NAME_KEY, segmentName);
// add score to metadata
metadata.set(SCORE_KEY, Float.toString(datum.getScore()));
Parse parse = null;
if (parsing && status == CrawlDatum.STATUS_FETCH_SUCCESS) {
ParseStatus parseStatus;
try {
parse = this.parseUtil.parse(content);
parseStatus = parse.getData().getStatus();
} catch (Exception e) {
parseStatus = new ParseStatus(e);
}
if (!parseStatus.isSuccess()) {
LOG.warning("Error parsing: " + key + ": " + parseStatus);
parse = parseStatus.getEmptyParse(getConf());
}
// Calculate page signature. For non-parsing fetchers this will
// be done in ParseSegment
byte[] signature = SignatureFactory.getSignature(getConf()).calculate(content, parse);
metadata.set(SIGNATURE_KEY, StringUtil.toHexString(signature));
datum.setSignature(signature);
// Ensure segment name and score are in parseData metadata
parse.getData().getContentMeta().set(SEGMENT_NAME_KEY, segmentName);
parse.getData().getContentMeta().set(SCORE_KEY, Float.toString(datum.getScore()));
parse.getData().getContentMeta().set(SIGNATURE_KEY, StringUtil.toHexString(signature));
}
try {
output.collect
(key,
new FetcherOutput(datum,
storingContent ? content : null,
parse != null ? new ParseImpl(parse) : null));
} catch (IOException e) {
e.printStackTrace();
LOG.severe("fetcher caught:"+e.toString());
}
}
}
public Fetcher() { super(null); }
public Fetcher(Configuration conf) { super(conf); }
private synchronized void updateStatus(int bytesInPage) throws IOException {
pages++;
bytes += bytesInPage;
}
private void reportStatus() throws IOException {
String status;
synchronized (this) {
long elapsed = (System.currentTimeMillis() - start)/1000;
status =
pages+" pages, "+errors+" errors, "
+ Math.round(((float)pages*10)/elapsed)/10.0+" pages/s, "
+ Math.round(((((float)bytes)*8)/1024)/elapsed)+" kb/s, ";
}
reporter.setStatus(status);
}
public void configure(JobConf job) {
setConf(job);
this.segmentName = job.get(SEGMENT_NAME_KEY);
this.storingContent = isStoringContent(job);
this.parsing = isParsing(job);
if (job.getBoolean("fetcher.verbose", false)) {
LOG.setLevel(Level.FINE);
}
}
public void close() {}
public static boolean isParsing(Configuration conf) {
return conf.getBoolean("fetcher.parse", true);
}
public static boolean isStoringContent(Configuration conf) {
return conf.getBoolean("fetcher.store.content", true);
}
public void run(RecordReader input, OutputCollector output,
Reporter reporter) throws IOException {
this.input = input;
this.output = output;
this.reporter = reporter;
this.maxRedirect = getConf().getInt("http.redirect.max", 3);
int threadCount = getConf().getInt("fetcher.threads.fetch", 10);
LOG.info("Fetcher: threads: " + threadCount);
for (int i = 0; i < threadCount; i++) { // spawn threads
new FetcherThread(getConf()).start();
}
// select a timeout that avoids a task timeout
long timeout = getConf().getInt("mapred.task.timeout", 10*60*1000)/2;
do { // wait for threads to exit
try {
Thread.sleep(1000);
} catch (InterruptedException e) {}
reportStatus();
// some requests seem to hang, despite all intentions
synchronized (this) {
if ((System.currentTimeMillis() - lastRequestStart) > timeout) {
LOG.warning("Aborting with "+activeThreads+" hung threads.");
return;
}
}
} while (activeThreads > 0);
}
public void fetch(File segment, int threads, boolean parsing)
throws IOException {
LOG.info("Fetcher: starting");
LOG.info("Fetcher: segment: " + segment);
JobConf job = new NutchJob(getConf());
job.setJobName("fetch " + segment);
job.setInt("fetcher.threads.fetch", threads);
job.set(SEGMENT_NAME_KEY, segment.getName());
job.setBoolean("fetcher.parse", parsing);
// for politeness, don't permit parallel execution of a single task
job.setBoolean("mapred.speculative.execution", false);
job.setInputDir(new File(segment, CrawlDatum.GENERATE_DIR_NAME));
job.setInputFormat(InputFormat.class);
job.setInputKeyClass(UTF8.class);
job.setInputValueClass(CrawlDatum.class);
job.setMapRunnerClass(Fetcher.class);
job.setOutputDir(segment);
job.setOutputFormat(FetcherOutputFormat.class);
job.setOutputKeyClass(UTF8.class);
job.setOutputValueClass(FetcherOutput.class);
JobClient.runJob(job);
LOG.info("Fetcher: done");
}
/** Run the fetcher. */
public static void main(String[] args) throws Exception {
String usage = "Usage: Fetcher <segment> [-threads n] [-noParsing]";
if (args.length < 1) {
System.err.println(usage);
System.exit(-1);
}
File segment = new File(args[0]);
Configuration conf = NutchConfiguration.create();
int threads = conf.getInt("fetcher.threads.fetch", 10);
boolean parsing = true;
for (int i = 1; i < args.length; i++) { // parse command line
if (args[i].equals("-threads")) { // found -threads option
threads = Integer.parseInt(args[++i]);
} else if (args[i].equals("-noParsing")) parsing = false;
}
conf.setInt("fetcher.threads.fetch", threads);
if (!parsing) {
conf.setBoolean("fetcher.parse", parsing);
}
Fetcher fetcher = new Fetcher(conf); // make a Fetcher
fetcher.fetch(segment, threads, parsing); // run the Fetcher
}
}
| false | true | public void run() {
synchronized (Fetcher.this) {activeThreads++;} // count threads
try {
UTF8 key = new UTF8();
CrawlDatum datum = new CrawlDatum();
while (true) {
if (LogFormatter.hasLoggedSevere()) // something bad happened
break; // exit
try { // get next entry from input
if (!input.next(key, datum)) {
break; // at eof, exit
}
} catch (IOException e) {
e.printStackTrace();
LOG.severe("fetcher caught:"+e.toString());
break;
}
synchronized (Fetcher.this) {
lastRequestStart = System.currentTimeMillis();
}
String url = key.toString();
try {
LOG.info("fetching " + url); // fetch the page
boolean redirecting;
int redirectCount = 0;
do {
redirecting = false;
LOG.fine("redirectCount=" + redirectCount);
Protocol protocol = this.protocolFactory.getProtocol(url);
ProtocolOutput output = protocol.getProtocolOutput(key, datum);
ProtocolStatus status = output.getStatus();
Content content = output.getContent();
switch(status.getCode()) {
case ProtocolStatus.SUCCESS: // got a page
output(key, datum, content, CrawlDatum.STATUS_FETCH_SUCCESS);
updateStatus(content.getContent().length);
break;
case ProtocolStatus.MOVED: // redirect
case ProtocolStatus.TEMP_MOVED:
String newUrl = status.getMessage();
newUrl = this.urlFilters.filter(newUrl);
if (newUrl != null && !newUrl.equals(url)) {
url = newUrl;
redirecting = true;
redirectCount++;
LOG.fine(" - redirect to " + url);
} else {
LOG.fine(" - redirect skipped: " +
(url.equals(newUrl) ? "to same url" : "filtered"));
}
break;
case ProtocolStatus.EXCEPTION:
logError(url, status.getMessage());
case ProtocolStatus.RETRY: // retry
datum.setRetriesSinceFetch(datum.getRetriesSinceFetch()+1);
output(key, datum, null, CrawlDatum.STATUS_FETCH_RETRY);
break;
case ProtocolStatus.GONE: // gone
case ProtocolStatus.NOTFOUND:
case ProtocolStatus.ACCESS_DENIED:
case ProtocolStatus.ROBOTS_DENIED:
case ProtocolStatus.NOTMODIFIED:
output(key, datum, null, CrawlDatum.STATUS_FETCH_GONE);
break;
default:
LOG.warning("Unknown ProtocolStatus: " + status.getCode());
output(key, datum, null, CrawlDatum.STATUS_FETCH_GONE);
}
if (redirecting && redirectCount >= maxRedirect) {
LOG.info(" - redirect count exceeded " + url);
output(key, datum, null, CrawlDatum.STATUS_FETCH_GONE);
}
} while (redirecting && (redirectCount < maxRedirect));
} catch (Throwable t) { // unexpected exception
logError(url, t.toString());
output(key, datum, null, CrawlDatum.STATUS_FETCH_GONE);
}
}
} catch (Throwable e) {
e.printStackTrace();
LOG.severe("fetcher caught:"+e.toString());
} finally {
synchronized (Fetcher.this) {activeThreads--;} // count threads
}
}
| public void run() {
synchronized (Fetcher.this) {activeThreads++;} // count threads
try {
UTF8 key = new UTF8();
CrawlDatum datum = new CrawlDatum();
while (true) {
if (LogFormatter.hasLoggedSevere()) // something bad happened
break; // exit
try { // get next entry from input
if (!input.next(key, datum)) {
break; // at eof, exit
}
} catch (IOException e) {
e.printStackTrace();
LOG.severe("fetcher caught:"+e.toString());
break;
}
synchronized (Fetcher.this) {
lastRequestStart = System.currentTimeMillis();
}
// url may be changed through redirects.
String url = key.toString();
try {
LOG.info("fetching " + url); // fetch the page
boolean redirecting;
int redirectCount = 0;
do {
redirecting = false;
LOG.fine("redirectCount=" + redirectCount);
Protocol protocol = this.protocolFactory.getProtocol(url);
ProtocolOutput output = protocol.getProtocolOutput(new UTF8(url), datum);
ProtocolStatus status = output.getStatus();
Content content = output.getContent();
switch(status.getCode()) {
case ProtocolStatus.SUCCESS: // got a page
output(key, datum, content, CrawlDatum.STATUS_FETCH_SUCCESS);
updateStatus(content.getContent().length);
break;
case ProtocolStatus.MOVED: // redirect
case ProtocolStatus.TEMP_MOVED:
String newUrl = status.getMessage();
newUrl = this.urlFilters.filter(newUrl);
if (newUrl != null && !newUrl.equals(url)) {
url = newUrl;
redirecting = true;
redirectCount++;
LOG.fine(" - protocol redirect to " + url);
} else {
LOG.fine(" - protocol redirect skipped: " +
(url.equals(newUrl) ? "to same url" : "filtered"));
}
break;
case ProtocolStatus.EXCEPTION:
logError(url, status.getMessage());
case ProtocolStatus.RETRY: // retry
datum.setRetriesSinceFetch(datum.getRetriesSinceFetch()+1);
output(key, datum, null, CrawlDatum.STATUS_FETCH_RETRY);
break;
case ProtocolStatus.GONE: // gone
case ProtocolStatus.NOTFOUND:
case ProtocolStatus.ACCESS_DENIED:
case ProtocolStatus.ROBOTS_DENIED:
case ProtocolStatus.NOTMODIFIED:
output(key, datum, null, CrawlDatum.STATUS_FETCH_GONE);
break;
default:
LOG.warning("Unknown ProtocolStatus: " + status.getCode());
output(key, datum, null, CrawlDatum.STATUS_FETCH_GONE);
}
if (redirecting && redirectCount >= maxRedirect) {
LOG.info(" - redirect count exceeded " + url);
output(key, datum, null, CrawlDatum.STATUS_FETCH_GONE);
}
} while (redirecting && (redirectCount < maxRedirect));
} catch (Throwable t) { // unexpected exception
logError(url, t.toString());
output(key, datum, null, CrawlDatum.STATUS_FETCH_GONE);
}
}
} catch (Throwable e) {
e.printStackTrace();
LOG.severe("fetcher caught:"+e.toString());
} finally {
synchronized (Fetcher.this) {activeThreads--;} // count threads
}
}
|
diff --git a/jbpm-form-modeler-integrations/jbpm-form-modeler-bpmn-form-builder/src/main/java/org/jbpm/formModeler/designer/integration/impl/BPMNFormBuilderServiceImpl.java b/jbpm-form-modeler-integrations/jbpm-form-modeler-bpmn-form-builder/src/main/java/org/jbpm/formModeler/designer/integration/impl/BPMNFormBuilderServiceImpl.java
index ffe9cb00..71f746c6 100644
--- a/jbpm-form-modeler-integrations/jbpm-form-modeler-bpmn-form-builder/src/main/java/org/jbpm/formModeler/designer/integration/impl/BPMNFormBuilderServiceImpl.java
+++ b/jbpm-form-modeler-integrations/jbpm-form-modeler-bpmn-form-builder/src/main/java/org/jbpm/formModeler/designer/integration/impl/BPMNFormBuilderServiceImpl.java
@@ -1,259 +1,259 @@
/**
* Copyright (C) 2012 JBoss 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.jbpm.formModeler.designer.integration.impl;
import org.apache.commons.lang.StringUtils;
import org.eclipse.bpmn2.*;
import org.eclipse.bpmn2.Process;
import org.jbpm.formModeler.api.model.DataHolder;
import org.jbpm.formModeler.api.model.Form;
import org.jbpm.formModeler.core.config.DataHolderManager;
import org.jbpm.formModeler.core.config.FieldTypeManager;
import org.jbpm.formModeler.core.config.FormManager;
import org.jbpm.formModeler.core.config.FormSerializationManager;
import org.jbpm.formModeler.core.config.builders.DataHolderBuilder;
import org.jbpm.formModeler.designer.integration.BPMNFormBuilderService;
import org.kie.commons.io.IOService;
import org.uberfire.backend.server.util.Paths;
import org.uberfire.backend.vfs.FileSystem;
import org.uberfire.backend.vfs.Path;
import org.uberfire.backend.vfs.PathFactory;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.inject.Named;
import java.util.*;
@ApplicationScoped
public class BPMNFormBuilderServiceImpl implements BPMNFormBuilderService {
@Inject
private Paths paths;
@Inject
@Named("ioStrategy")
private IOService ioService;
@Inject
private FormManager formManager;
@Inject
private FormSerializationManager formSerializationManager;
@Inject
private DataHolderManager dataHolderManager;
@Inject
private FieldTypeManager fieldTypeManager;
public String buildEmptyFormXML(String fileName) {
Form form = formManager.createForm(fileName);
String xmlForm = formSerializationManager.generateFormXML(form);
return xmlForm;
}
public String buildFormXML(FileSystem fs, String fileName, String uri, Definitions source, String id) throws Exception {
Path formPath = PathFactory.newPath(fs, fileName, uri);
org.kie.commons.java.nio.file.Path kiePath = paths.convert(formPath);
String xml = null;
String xmlForm = null;
Set holders = getDataHolders(source, formPath, id);
//TODO check this criteria. By the moment if we don't have data holders there's no data to enter.
if (holders == null || holders.size() == 0) return null;
if (ioService.exists(kiePath)) {
xml = ioService.readAllString(kiePath).trim();
}
if (StringUtils.isEmpty(xml)) {
Form form = formManager.createForm(fileName);
for(Iterator it = holders.iterator(); it.hasNext();) {
DataHolder holder = (DataHolder) it.next();
formManager.addAllDataHolderFieldsToForm(form, holder);
}
xmlForm = formSerializationManager.generateFormXML(form);
} else {
Form form = formSerializationManager.loadFormFromXML(xml);
for(Iterator it = holders.iterator(); it.hasNext();) {
DataHolder holder = (DataHolder) it.next();
if (!form.containsHolder(holder)) {
//Version 1 merge algorithm.
formManager.addAllDataHolderFieldsToForm(form, holder);
}
}
xmlForm = formSerializationManager.generateFormXML(form);
}
return xmlForm;
}
public Set<DataHolder> getDataHolders(Definitions source, Path context, String resourceId) {
if (source == null || context == null) return null;
Map<String, Map> associations = new HashMap<String, Map>();
List<RootElement> rootElements = source.getRootElements();
for(RootElement re : rootElements) {
if(re instanceof org.eclipse.bpmn2.Process) {
Process process = (Process) re;
if(process != null && process.getId() != null && process.getId().length() > 0) {
List<Property> processProperties = process.getProperties();
// if resourceId is null we want to create the process starting form, so we only check process vars.
if (StringUtils.isEmpty(resourceId)) return getProcessDataHolders(processProperties, context);
String[] colors = dataHolderManager.getHolderColors().keySet().toArray(new String[0]);
int index = 0;
for (Property prop : processProperties) {
Map<String, Object> config = new HashMap<String, Object>();
config.put("value", prop.getItemSubjectRef().getStructureRef());
config.put("path", context);
config.put("color", colors[index]);
config.put("id", prop.getId());
associations.put(prop.getId(), config);
if (index == colors.length - 1) index = 0;
else index++;
}
for(FlowElement fe : process.getFlowElements()) {
if(fe instanceof UserTask && fe.getId().equals(resourceId)) {
UserTask utask = (UserTask) fe;
List<DataInputAssociation> dataInputAssociations = utask.getDataInputAssociations();
if (dataInputAssociations != null) {
for (DataInputAssociation inputAssociation : dataInputAssociations) {
if (inputAssociation.getSourceRef() != null && inputAssociation.getSourceRef().size() > 0 && inputAssociation.getTargetRef() != null) {
String variableId = inputAssociation.getSourceRef().get(0).getId();
DataInput input = (DataInput)inputAssociation.getTargetRef();
String id = input != null ? input.getName() : null;
Map config = ((variableId != null) && (id != null)) ? associations.get(variableId) : null;
if (config != null) config.put("inputId", id);
}
}
}
List<DataOutputAssociation> dataOutputAssociations = utask.getDataOutputAssociations();
if (dataOutputAssociations != null) {
for (DataOutputAssociation outputAssociation : dataOutputAssociations) {
if (outputAssociation.getSourceRef() != null && outputAssociation.getSourceRef().size() > 0 && outputAssociation.getTargetRef() != null) {
String variableId = outputAssociation.getTargetRef().getId();
DataOutput output = (DataOutput) outputAssociation.getSourceRef().get(0);
String outId = output != null ? output.getName() : null;
Map config = ((variableId != null) && (outId != null)) ? associations.get(variableId) : null;
if (config != null) config.put("outId", outId);
}
}
}
}
}
}
}
}
Set<DataHolder> result = new TreeSet<DataHolder>();
for (Iterator it = associations.keySet().iterator(); it.hasNext();) {
Map config = associations.get(it.next());
DataHolder dataHolder;
- if (config.size() > 3) {
+ if (config.size() > 4) {
dataHolder = createDataHolder(config);
if (dataHolder != null) result.add(dataHolder);
}
}
return result;
}
private Set<DataHolder> getProcessDataHolders(List<Property> processProperties, Path path) {
Set<DataHolder> result = new TreeSet<DataHolder>();
String[] colors = dataHolderManager.getHolderColors().keySet().toArray(new String[0]);
int index = 0;
for (Property prop : processProperties) {
String propertyName = prop.getId();
String propertyType = prop.getItemSubjectRef().getStructureRef();
DataHolder dataHolder = null;
Map<String, Object> config = new HashMap<String, Object>();
config.put("id", propertyName);
config.put("outId", propertyName);
config.put("color", colors[index]);
config.put("value", propertyType);
config.put("path", path);
dataHolder = createDataHolder(config);
if (dataHolder != null) result.add(dataHolder);
if (index == colors.length - 1) index = 0;
else index++;
}
return result;
}
private DataHolder createDataHolder(Map<String, Object> config) {
String type = (String) config.get("value");
if (isBaseType(type)) type = normalizeBaseType(type);
DataHolderBuilder builder = dataHolderManager.getBuilderByHolderValueType(type, config.get("path"));
config.put("value", type);
if (builder != null) return builder.buildDataHolder(config);
return null;
}
//TODO move this methods to another place
private boolean isBaseType(String type) {
return
"String".equals(type) || String.class.getName().equals(type) ||
"Integer".equals(type) || Integer.class.getName().equals(type) ||
"Short".equals(type) || Short.class.getName().equals(type) ||
"Long".equals(type) || Long.class.getName().equals(type) ||
"Float".equals(type) || Float.class.getName().equals(type) ||
"Double".equals(type) || Double.class.getName().equals(type) ||
"Boolean".equals(type) || Boolean.class.getName().equals(type) ||
"Date".equals(type) || Date.class.getName().equals(type) ||
"BigDecimal".equals(type) || java.math.BigDecimal.class.getName().equals(type);
}
private String normalizeBaseType(String type) {
if (type.length() < 10) {
if ("String".equals(type)) return String.class.getName();
if ("Integer".equals(type)) return Integer.class.getName();
if ("Short".equals(type)) return Short.class.getName();
if ("Long".equals(type)) return Long.class.getName();
if ("Float".equals(type)) return Float.class.getName();
if ("Double".equals(type)) return Double.class.getName();
if ("Boolean".equals(type)) return Boolean.class.getName();
if ("Date".equals(type)) return Date.class.getName();
if ("BigDecimal".equals(type)) return java.math.BigDecimal.class.getName();
}
return type;
}
}
| true | true | public Set<DataHolder> getDataHolders(Definitions source, Path context, String resourceId) {
if (source == null || context == null) return null;
Map<String, Map> associations = new HashMap<String, Map>();
List<RootElement> rootElements = source.getRootElements();
for(RootElement re : rootElements) {
if(re instanceof org.eclipse.bpmn2.Process) {
Process process = (Process) re;
if(process != null && process.getId() != null && process.getId().length() > 0) {
List<Property> processProperties = process.getProperties();
// if resourceId is null we want to create the process starting form, so we only check process vars.
if (StringUtils.isEmpty(resourceId)) return getProcessDataHolders(processProperties, context);
String[] colors = dataHolderManager.getHolderColors().keySet().toArray(new String[0]);
int index = 0;
for (Property prop : processProperties) {
Map<String, Object> config = new HashMap<String, Object>();
config.put("value", prop.getItemSubjectRef().getStructureRef());
config.put("path", context);
config.put("color", colors[index]);
config.put("id", prop.getId());
associations.put(prop.getId(), config);
if (index == colors.length - 1) index = 0;
else index++;
}
for(FlowElement fe : process.getFlowElements()) {
if(fe instanceof UserTask && fe.getId().equals(resourceId)) {
UserTask utask = (UserTask) fe;
List<DataInputAssociation> dataInputAssociations = utask.getDataInputAssociations();
if (dataInputAssociations != null) {
for (DataInputAssociation inputAssociation : dataInputAssociations) {
if (inputAssociation.getSourceRef() != null && inputAssociation.getSourceRef().size() > 0 && inputAssociation.getTargetRef() != null) {
String variableId = inputAssociation.getSourceRef().get(0).getId();
DataInput input = (DataInput)inputAssociation.getTargetRef();
String id = input != null ? input.getName() : null;
Map config = ((variableId != null) && (id != null)) ? associations.get(variableId) : null;
if (config != null) config.put("inputId", id);
}
}
}
List<DataOutputAssociation> dataOutputAssociations = utask.getDataOutputAssociations();
if (dataOutputAssociations != null) {
for (DataOutputAssociation outputAssociation : dataOutputAssociations) {
if (outputAssociation.getSourceRef() != null && outputAssociation.getSourceRef().size() > 0 && outputAssociation.getTargetRef() != null) {
String variableId = outputAssociation.getTargetRef().getId();
DataOutput output = (DataOutput) outputAssociation.getSourceRef().get(0);
String outId = output != null ? output.getName() : null;
Map config = ((variableId != null) && (outId != null)) ? associations.get(variableId) : null;
if (config != null) config.put("outId", outId);
}
}
}
}
}
}
}
}
Set<DataHolder> result = new TreeSet<DataHolder>();
for (Iterator it = associations.keySet().iterator(); it.hasNext();) {
Map config = associations.get(it.next());
DataHolder dataHolder;
if (config.size() > 3) {
dataHolder = createDataHolder(config);
if (dataHolder != null) result.add(dataHolder);
}
}
return result;
}
| public Set<DataHolder> getDataHolders(Definitions source, Path context, String resourceId) {
if (source == null || context == null) return null;
Map<String, Map> associations = new HashMap<String, Map>();
List<RootElement> rootElements = source.getRootElements();
for(RootElement re : rootElements) {
if(re instanceof org.eclipse.bpmn2.Process) {
Process process = (Process) re;
if(process != null && process.getId() != null && process.getId().length() > 0) {
List<Property> processProperties = process.getProperties();
// if resourceId is null we want to create the process starting form, so we only check process vars.
if (StringUtils.isEmpty(resourceId)) return getProcessDataHolders(processProperties, context);
String[] colors = dataHolderManager.getHolderColors().keySet().toArray(new String[0]);
int index = 0;
for (Property prop : processProperties) {
Map<String, Object> config = new HashMap<String, Object>();
config.put("value", prop.getItemSubjectRef().getStructureRef());
config.put("path", context);
config.put("color", colors[index]);
config.put("id", prop.getId());
associations.put(prop.getId(), config);
if (index == colors.length - 1) index = 0;
else index++;
}
for(FlowElement fe : process.getFlowElements()) {
if(fe instanceof UserTask && fe.getId().equals(resourceId)) {
UserTask utask = (UserTask) fe;
List<DataInputAssociation> dataInputAssociations = utask.getDataInputAssociations();
if (dataInputAssociations != null) {
for (DataInputAssociation inputAssociation : dataInputAssociations) {
if (inputAssociation.getSourceRef() != null && inputAssociation.getSourceRef().size() > 0 && inputAssociation.getTargetRef() != null) {
String variableId = inputAssociation.getSourceRef().get(0).getId();
DataInput input = (DataInput)inputAssociation.getTargetRef();
String id = input != null ? input.getName() : null;
Map config = ((variableId != null) && (id != null)) ? associations.get(variableId) : null;
if (config != null) config.put("inputId", id);
}
}
}
List<DataOutputAssociation> dataOutputAssociations = utask.getDataOutputAssociations();
if (dataOutputAssociations != null) {
for (DataOutputAssociation outputAssociation : dataOutputAssociations) {
if (outputAssociation.getSourceRef() != null && outputAssociation.getSourceRef().size() > 0 && outputAssociation.getTargetRef() != null) {
String variableId = outputAssociation.getTargetRef().getId();
DataOutput output = (DataOutput) outputAssociation.getSourceRef().get(0);
String outId = output != null ? output.getName() : null;
Map config = ((variableId != null) && (outId != null)) ? associations.get(variableId) : null;
if (config != null) config.put("outId", outId);
}
}
}
}
}
}
}
}
Set<DataHolder> result = new TreeSet<DataHolder>();
for (Iterator it = associations.keySet().iterator(); it.hasNext();) {
Map config = associations.get(it.next());
DataHolder dataHolder;
if (config.size() > 4) {
dataHolder = createDataHolder(config);
if (dataHolder != null) result.add(dataHolder);
}
}
return result;
}
|
diff --git a/web/src/main/java/org/fao/geonet/services/thesaurus/Upload.java b/web/src/main/java/org/fao/geonet/services/thesaurus/Upload.java
index 236d11fb16..d21f9cdca9 100644
--- a/web/src/main/java/org/fao/geonet/services/thesaurus/Upload.java
+++ b/web/src/main/java/org/fao/geonet/services/thesaurus/Upload.java
@@ -1,242 +1,242 @@
//=============================================================================
//=== Copyright (C) 2001-2005 Food and Agriculture Organization of the
//=== United Nations (FAO-UN), United Nations World Food Programme (WFP)
//=== and United Nations Environment Programme (UNEP)
//===
//=== 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//===
//=== Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2,
//=== Rome - Italy. email: [email protected]
//==============================================================================
package org.fao.geonet.services.thesaurus;
import java.io.File;
import java.io.FileOutputStream;
import java.net.URI;
import jeeves.exceptions.BadParameterEx;
import jeeves.exceptions.OperationAbortedEx;
import jeeves.interfaces.Service;
import jeeves.server.ServiceConfig;
import jeeves.server.context.ServiceContext;
import jeeves.utils.Log;
import jeeves.utils.Util;
import jeeves.utils.Xml;
import jeeves.utils.XmlRequest;
import org.fao.geonet.GeonetContext;
import org.fao.geonet.constants.Geonet;
import org.fao.geonet.constants.Params;
import org.fao.geonet.kernel.Thesaurus;
import org.fao.geonet.kernel.ThesaurusManager;
import org.fao.geonet.lib.Lib;
import org.jdom.Document;
import org.jdom.Element;
/**
* Upload one thesaurus file using file upload or file URL. <br/>
* Thesaurus may be in W3C SKOS format with an RDF extension. Optionnaly an XSL
* transformation could be run to convert the thesaurus to SKOS.
*
*/
public class Upload implements Service {
static String FS = System.getProperty("file.separator", "/");
private String stylePath;
public void init(String appPath, ServiceConfig params) throws Exception {
this.stylePath = appPath + FS + Geonet.Path.STYLESHEETS + FS;
}
/**
* Load a thesaurus to GeoNetwork codelist directory.
*
* @param params
* <ul>
* <li>fname: if set, do a file upload</li>
* <li>url: if set, try to download from the Internet</li>
* <li>type: local or external (default)</li>
* <li>dir: type of thesaurus, usually one of the ISO thesaurus
* type codelist value. Default is theme.</li>
* <li>stylesheet: XSL to be use to convert the thesaurus before
* load. Default _none_.</li>
* </ul>
*
*/
public Element exec(Element params, ServiceContext context)
throws Exception {
long start = System.currentTimeMillis();
Element uploadResult;
uploadResult = upload(params, context);
long end = System.currentTimeMillis();
long duration = (end - start) / 1000;
Log.debug("Thesaurus", "Uploaded in " + duration + " s.");
Element response = new Element("response");
response.setAttribute("time", duration + "");
if (uploadResult != null)
response.addContent(uploadResult);
return response;
}
/**
*
* @param params
* @param context
* @return
* @throws Exception
*/
private Element upload(Element params, ServiceContext context)
throws Exception {
String uploadDir = context.getUploadDir();
Element uploadResult = null;
// Upload RDF file
String fname = null;
String url = null;
File rdfFile = null;
Element param = params.getChild(Params.FNAME);
if (param == null) {
url = Util.getParam(params, "url", "");
// -- get the rdf file from the net
if (!"".equals(url)) {
Log.debug("Thesaurus", "Uploading thesaurus: " + url);
URI uri = new URI(url);
rdfFile = File.createTempFile("thesaurus", ".rdf");
XmlRequest httpReq = new XmlRequest(uri.getHost(),
uri.getPort());
httpReq.setAddress(uri.getPath());
Lib.net.setupProxy(context, httpReq);
httpReq.executeLarge(rdfFile);
fname = url.substring(url.lastIndexOf("/") + 1, url.length());
} else {
Log.debug("Thesaurus",
"No URL or file name provided for thesaurus upload.");
}
} else {
+ fname = param.getTextTrim();
if (fname.contains("..")) {
throw new BadParameterEx("Invalid character found in thesaurus name.", fname);
}
- fname = param.getTextTrim();
rdfFile = new File(uploadDir, fname);
}
if (fname == null || "".equals(fname)) {
throw new OperationAbortedEx(
"File upload from URL or file return null.");
}
long fsize = 0;
if (rdfFile.exists()) {
fsize = rdfFile.length();
} else {
throw new OperationAbortedEx("Thesaurus file doesn't exist");
}
// -- check that the archive actually has something in it
if (fsize == 0) {
throw new OperationAbortedEx("Thesaurus file has zero size");
}
// Thesaurus Type (local, external)
String type = Util.getParam(params, Params.TYPE, "external");
// Thesaurus directory - one of the ISO theme (Discipline, Place,
// Stratum, Temporal, Theme)
String dir = Util.getParam(params, Params.DIR, "theme");
// no XSL to be applied
String style = Util.getParam(params, Params.STYLESHEET, "_none_");
Element eTSResult;
String extension = fname.substring(fname.lastIndexOf('.'))
.toLowerCase();
if (extension.equals(".rdf") || extension.equals(".xml")) {
Log.debug("Thesaurus", "Uploading thesaurus: " + fname);
eTSResult = UploadThesaurus(rdfFile, style, context, fname, type,
dir);
} else {
Log.debug("Thesaurus", "Incorrect extension for thesaurus named: "
+ fname);
throw new Exception("Incorrect extension for thesaurus named: "
+ fname);
}
uploadResult = new Element("record").setText("Thesaurus uploaded");
uploadResult.addContent(eTSResult);
return uploadResult;
}
/**
* Load a thesaurus in the catalogue and optionnaly convert it using XSL.
*
* @return Element thesaurus uploaded
* @throws Exception
*/
private Element UploadThesaurus(File rdfFile, String style,
ServiceContext context, String fname, String type, String dir)
throws Exception {
Element TS_xml = null;
Element xml = Xml.loadFile(rdfFile);
xml.detach();
if (!style.equals("_none_")) {
TS_xml = Xml.transform(xml, stylePath + "/" + style);
TS_xml.detach();
} else
TS_xml = xml;
// Load document and check namespace
if (TS_xml.getNamespacePrefix().equals("rdf")
&& TS_xml.getName().equals("RDF")) {
GeonetContext gc = (GeonetContext) context
.getHandlerContext(Geonet.CONTEXT_NAME);
ThesaurusManager thesaurusMan = gc.getThesaurusManager();
// copy to directory according to type
String path = thesaurusMan.buildThesaurusFilePath(fname, type, dir);
File newFile = new File(path);
Xml.writeResponse(new Document(TS_xml), new FileOutputStream(
newFile));
Thesaurus gst = new Thesaurus(fname, type, dir, newFile);
thesaurusMan.addThesaurus(gst);
} else {
rdfFile.delete();
throw new Exception("Unknown format (Must be in SKOS format).");
}
return new Element("Thesaurus").setText(fname);
}
}
| false | true | private Element upload(Element params, ServiceContext context)
throws Exception {
String uploadDir = context.getUploadDir();
Element uploadResult = null;
// Upload RDF file
String fname = null;
String url = null;
File rdfFile = null;
Element param = params.getChild(Params.FNAME);
if (param == null) {
url = Util.getParam(params, "url", "");
// -- get the rdf file from the net
if (!"".equals(url)) {
Log.debug("Thesaurus", "Uploading thesaurus: " + url);
URI uri = new URI(url);
rdfFile = File.createTempFile("thesaurus", ".rdf");
XmlRequest httpReq = new XmlRequest(uri.getHost(),
uri.getPort());
httpReq.setAddress(uri.getPath());
Lib.net.setupProxy(context, httpReq);
httpReq.executeLarge(rdfFile);
fname = url.substring(url.lastIndexOf("/") + 1, url.length());
} else {
Log.debug("Thesaurus",
"No URL or file name provided for thesaurus upload.");
}
} else {
if (fname.contains("..")) {
throw new BadParameterEx("Invalid character found in thesaurus name.", fname);
}
fname = param.getTextTrim();
rdfFile = new File(uploadDir, fname);
}
if (fname == null || "".equals(fname)) {
throw new OperationAbortedEx(
"File upload from URL or file return null.");
}
long fsize = 0;
if (rdfFile.exists()) {
fsize = rdfFile.length();
} else {
throw new OperationAbortedEx("Thesaurus file doesn't exist");
}
// -- check that the archive actually has something in it
if (fsize == 0) {
throw new OperationAbortedEx("Thesaurus file has zero size");
}
// Thesaurus Type (local, external)
String type = Util.getParam(params, Params.TYPE, "external");
// Thesaurus directory - one of the ISO theme (Discipline, Place,
// Stratum, Temporal, Theme)
String dir = Util.getParam(params, Params.DIR, "theme");
// no XSL to be applied
String style = Util.getParam(params, Params.STYLESHEET, "_none_");
Element eTSResult;
String extension = fname.substring(fname.lastIndexOf('.'))
.toLowerCase();
if (extension.equals(".rdf") || extension.equals(".xml")) {
Log.debug("Thesaurus", "Uploading thesaurus: " + fname);
eTSResult = UploadThesaurus(rdfFile, style, context, fname, type,
dir);
} else {
Log.debug("Thesaurus", "Incorrect extension for thesaurus named: "
+ fname);
throw new Exception("Incorrect extension for thesaurus named: "
+ fname);
}
uploadResult = new Element("record").setText("Thesaurus uploaded");
uploadResult.addContent(eTSResult);
return uploadResult;
}
| private Element upload(Element params, ServiceContext context)
throws Exception {
String uploadDir = context.getUploadDir();
Element uploadResult = null;
// Upload RDF file
String fname = null;
String url = null;
File rdfFile = null;
Element param = params.getChild(Params.FNAME);
if (param == null) {
url = Util.getParam(params, "url", "");
// -- get the rdf file from the net
if (!"".equals(url)) {
Log.debug("Thesaurus", "Uploading thesaurus: " + url);
URI uri = new URI(url);
rdfFile = File.createTempFile("thesaurus", ".rdf");
XmlRequest httpReq = new XmlRequest(uri.getHost(),
uri.getPort());
httpReq.setAddress(uri.getPath());
Lib.net.setupProxy(context, httpReq);
httpReq.executeLarge(rdfFile);
fname = url.substring(url.lastIndexOf("/") + 1, url.length());
} else {
Log.debug("Thesaurus",
"No URL or file name provided for thesaurus upload.");
}
} else {
fname = param.getTextTrim();
if (fname.contains("..")) {
throw new BadParameterEx("Invalid character found in thesaurus name.", fname);
}
rdfFile = new File(uploadDir, fname);
}
if (fname == null || "".equals(fname)) {
throw new OperationAbortedEx(
"File upload from URL or file return null.");
}
long fsize = 0;
if (rdfFile.exists()) {
fsize = rdfFile.length();
} else {
throw new OperationAbortedEx("Thesaurus file doesn't exist");
}
// -- check that the archive actually has something in it
if (fsize == 0) {
throw new OperationAbortedEx("Thesaurus file has zero size");
}
// Thesaurus Type (local, external)
String type = Util.getParam(params, Params.TYPE, "external");
// Thesaurus directory - one of the ISO theme (Discipline, Place,
// Stratum, Temporal, Theme)
String dir = Util.getParam(params, Params.DIR, "theme");
// no XSL to be applied
String style = Util.getParam(params, Params.STYLESHEET, "_none_");
Element eTSResult;
String extension = fname.substring(fname.lastIndexOf('.'))
.toLowerCase();
if (extension.equals(".rdf") || extension.equals(".xml")) {
Log.debug("Thesaurus", "Uploading thesaurus: " + fname);
eTSResult = UploadThesaurus(rdfFile, style, context, fname, type,
dir);
} else {
Log.debug("Thesaurus", "Incorrect extension for thesaurus named: "
+ fname);
throw new Exception("Incorrect extension for thesaurus named: "
+ fname);
}
uploadResult = new Element("record").setText("Thesaurus uploaded");
uploadResult.addContent(eTSResult);
return uploadResult;
}
|
diff --git a/tests/org.jboss.tools.ws.ui.bot.test/src/org/jboss/tools/ws/ui/bot/test/utils/ProjectHelper.java b/tests/org.jboss.tools.ws.ui.bot.test/src/org/jboss/tools/ws/ui/bot/test/utils/ProjectHelper.java
index b12b5353..b51c1c30 100644
--- a/tests/org.jboss.tools.ws.ui.bot.test/src/org/jboss/tools/ws/ui/bot/test/utils/ProjectHelper.java
+++ b/tests/org.jboss.tools.ws.ui.bot.test/src/org/jboss/tools/ws/ui/bot/test/utils/ProjectHelper.java
@@ -1,167 +1,172 @@
/*******************************************************************************
* Copyright (c) 2010-2011 Red Hat, Inc.
* Distributed under license by Red Hat, Inc. All rights reserved.
* This program is made available under the terms of the
* Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Red Hat, Inc. - initial API and implementation
******************************************************************************/
package org.jboss.tools.ws.ui.bot.test.utils;
import org.eclipse.swtbot.eclipse.finder.widgets.SWTBotEditor;
import org.eclipse.swtbot.swt.finder.SWTBot;
import org.eclipse.swtbot.swt.finder.widgets.SWTBotCombo;
import org.eclipse.swtbot.swt.finder.widgets.SWTBotShell;
import org.eclipse.swtbot.swt.finder.widgets.SWTBotTable;
import org.eclipse.swtbot.swt.finder.widgets.SWTBotTree;
import org.eclipse.swtbot.swt.finder.widgets.SWTBotTreeItem;
import org.jboss.tools.ui.bot.ext.SWTBotExt;
import org.jboss.tools.ui.bot.ext.SWTOpenExt;
import org.jboss.tools.ui.bot.ext.SWTUtilExt;
import org.jboss.tools.ui.bot.ext.condition.ShellIsActiveCondition;
import org.jboss.tools.ui.bot.ext.condition.TaskDuration;
import org.jboss.tools.ui.bot.ext.gen.ActionItem.NewObject.JavaEEEnterpriseApplicationProject;
import org.jboss.tools.ui.bot.ext.gen.ActionItem.NewObject.WebServicesWSDL;
import org.jboss.tools.ui.bot.ext.types.IDELabel;
import org.jboss.tools.ui.bot.ext.view.ProjectExplorer;
import org.jboss.tools.ws.ui.bot.test.uiutils.actions.NewFileWizardAction;
import org.jboss.tools.ws.ui.bot.test.uiutils.actions.TreeItemAction;
import org.jboss.tools.ws.ui.bot.test.uiutils.wizards.DynamicWebProjectWizard;
import org.jboss.tools.ws.ui.bot.test.uiutils.wizards.Wizard;
public class ProjectHelper {
private final SWTBotExt bot = new SWTBotExt();
private final ProjectExplorer projectExplorer = new ProjectExplorer();
private final SWTOpenExt open = new SWTOpenExt(bot);
private final SWTUtilExt util = new SWTUtilExt(bot);
/**
* Method creates basic java class for entered project with
* entered package and class name
* @param projectName
* @param pkg
* @param cName
* @return
*/
public SWTBotEditor createClass(String projectName, String pkg, String cName) {
new NewFileWizardAction().run().selectTemplate("Java", "Class").next();
Wizard w = new Wizard();
w.bot().textWithLabel("Package:").setText(pkg);
w.bot().textWithLabel("Name:").setText(cName);
w.bot().textWithLabel("Source folder:")
.setText(projectName + "/src");
w.finish();
bot.sleep(4500);
return bot.editorByTitle(cName + ".java");
}
/**
* Method creates wsdl file for entered project with
* entered package name
* @param projectName
* @param s
* @return
*/
public SWTBotEditor createWsdl(String projectName, String s) {
SWTBot wiz1 = open.newObject(WebServicesWSDL.LABEL);
wiz1.textWithLabel(WebServicesWSDL.TEXT_FILE_NAME).setText(s + ".wsdl");
wiz1.textWithLabel(
WebServicesWSDL.TEXT_ENTER_OR_SELECT_THE_PARENT_FOLDER)
.setText(projectName + "/src");
wiz1.button(IDELabel.Button.NEXT).click();
open.finish(wiz1);
return bot.editorByTitle(s + ".wsdl");
}
/**
* Method creates new Dynamic Web Project with entered name
* @param name
*/
public void createProject(String name) {
new NewFileWizardAction().run()
.selectTemplate("Web", "Dynamic Web Project").next();
new DynamicWebProjectWizard().setProjectName(name).finish();
util.waitForNonIgnoredJobs();
projectExplorer.selectProject(name);
}
/**
* Method creates new Dynamic Web Project with entered name for
* ear project
* @param name
*/
public void createProjectForEAR(String name, String earProject) {
new NewFileWizardAction().run()
.selectTemplate("Web", "Dynamic Web Project").next();
new DynamicWebProjectWizard().setProjectName(name).
addProjectToEar(earProject).finish();
util.waitForNonIgnoredJobs();
projectExplorer.selectProject(name);
}
/**
* Method creates new EAR Project with entered name
* @param name
*/
public void createEARProject(String name) {
SWTBot wiz = open.newObject(JavaEEEnterpriseApplicationProject.LABEL);
wiz.textWithLabel(JavaEEEnterpriseApplicationProject.TEXT_PROJECT_NAME)
.setText(name);
// set EAR version
SWTBotCombo combo = wiz.comboBox(1);
combo.setSelection(combo.itemCount() - 1);
wiz.button(IDELabel.Button.NEXT).click();
wiz.checkBox("Generate application.xml deployment descriptor").click();
open.finish(wiz);
bot.sleep(5000);
projectExplorer.selectProject(name);
}
/**
* Method generates Deployment Descriptor for entered project
* @param project
*/
public void createDD(String project) {
SWTBotTree tree = projectExplorer.bot().tree();
SWTBotTreeItem ti = tree.expandNode(project);
bot.sleep(1500);
ti = ti.getNode("Deployment Descriptor: " + project);
new TreeItemAction(ti, "Generate Deployment Descriptor Stub").run();
bot.sleep(1500);
util.waitForNonIgnoredJobs();
bot.sleep(1500);
}
/**
* Add first defined runtime into project as targeted runtime
* @param project
*/
- public void addDefaultRuntimeIntoProject(String project) {
+ public void addConfiguredRuntimeIntoProject(String project,
+ String configuredRuntime) {
projectExplorer.selectProject(project);
bot.menu(IDELabel.Menu.FILE).menu(
IDELabel.Menu.PROPERTIES).click();
bot.waitForShell(IDELabel.Shell.PROPERTIES_FOR + " " + project);
SWTBotShell propertiesShell = bot.shell(
IDELabel.Shell.PROPERTIES_FOR + " " + project);
propertiesShell.activate();
SWTBotTreeItem item = bot.tree().getTreeItem("Targeted Runtimes");
item.select();
SWTBotTable runtimes = bot.table();
for (int i = 0; i < runtimes.rowCount(); i++) {
runtimes.getTableItem(i).uncheck();
}
- bot.table().getTableItem(0).check();
+ for (int i = 0; i < runtimes.rowCount(); i++) {
+ if (runtimes.getTableItem(i).getText().equals(configuredRuntime)) {
+ runtimes.getTableItem(i).check();
+ }
+ }
bot.button(IDELabel.Button.OK).click();
bot.waitWhile(new ShellIsActiveCondition(propertiesShell),
TaskDuration.LONG.getTimeout());
}
}
| false | true | public void addDefaultRuntimeIntoProject(String project) {
projectExplorer.selectProject(project);
bot.menu(IDELabel.Menu.FILE).menu(
IDELabel.Menu.PROPERTIES).click();
bot.waitForShell(IDELabel.Shell.PROPERTIES_FOR + " " + project);
SWTBotShell propertiesShell = bot.shell(
IDELabel.Shell.PROPERTIES_FOR + " " + project);
propertiesShell.activate();
SWTBotTreeItem item = bot.tree().getTreeItem("Targeted Runtimes");
item.select();
SWTBotTable runtimes = bot.table();
for (int i = 0; i < runtimes.rowCount(); i++) {
runtimes.getTableItem(i).uncheck();
}
bot.table().getTableItem(0).check();
bot.button(IDELabel.Button.OK).click();
bot.waitWhile(new ShellIsActiveCondition(propertiesShell),
TaskDuration.LONG.getTimeout());
}
| public void addConfiguredRuntimeIntoProject(String project,
String configuredRuntime) {
projectExplorer.selectProject(project);
bot.menu(IDELabel.Menu.FILE).menu(
IDELabel.Menu.PROPERTIES).click();
bot.waitForShell(IDELabel.Shell.PROPERTIES_FOR + " " + project);
SWTBotShell propertiesShell = bot.shell(
IDELabel.Shell.PROPERTIES_FOR + " " + project);
propertiesShell.activate();
SWTBotTreeItem item = bot.tree().getTreeItem("Targeted Runtimes");
item.select();
SWTBotTable runtimes = bot.table();
for (int i = 0; i < runtimes.rowCount(); i++) {
runtimes.getTableItem(i).uncheck();
}
for (int i = 0; i < runtimes.rowCount(); i++) {
if (runtimes.getTableItem(i).getText().equals(configuredRuntime)) {
runtimes.getTableItem(i).check();
}
}
bot.button(IDELabel.Button.OK).click();
bot.waitWhile(new ShellIsActiveCondition(propertiesShell),
TaskDuration.LONG.getTimeout());
}
|
diff --git a/src/beads_main/net/beadsproject/beads/data/Sample.java b/src/beads_main/net/beadsproject/beads/data/Sample.java
index f4a0c7c..6d4732f 100644
--- a/src/beads_main/net/beadsproject/beads/data/Sample.java
+++ b/src/beads_main/net/beadsproject/beads/data/Sample.java
@@ -1,1178 +1,1178 @@
package net.beadsproject.beads.data;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.lang.Thread.State;
import java.util.Arrays;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.UnsupportedAudioFileException;
import net.beadsproject.beads.core.AudioUtils;
/**
* A Buffered Sample provides random access to an audio file.
*
* Only supports 16-bit samples at the moment.
* TODO: Fix MP3 region boundary issues..
*
* Notes:
* - BufferedSample is not particularly thread-safe.
* This shouldn't matter because SamplePlayers are not executed in parallel
* when used in a UGen chain.
*
* @author ben
*/
public class Sample implements Runnable {
private Regime bufferingRegime;
static public class Regime
{
// defaults
static final public TotalRegime TOTAL = new TotalRegime();
static final public TimedRegime TIMED = new TimedRegime();
};
/**
* Only some parts of the audio file are stored in memory.
* Useful for very large audio files.
* Various parameters affect the buffering behaviour.
*/
static public class TimedRegime extends Regime
{
public int lookAhead; // time lookahead, ms
public int lookBack; // time lookback, ms
public long memory; // age (ms) at which regions get removed
public float regionSize; // size of each region (by default 10s)
static public enum Order {
NEAREST,
ORDERED
};
public Order loadingOrder;
public TimedRegime()
{
lookAhead = 100;
lookBack = 0;
memory = 1000;
regionSize = 100;
loadingOrder = Order.ORDERED;
}
public TimedRegime(int regionSize,
int lookAhead,
int lookBack,
int memory,
Order loadingOrder)
{
this.regionSize = regionSize;
this.lookAhead = lookAhead;
this.lookBack = lookBack;
this.memory = memory;
this.loadingOrder = loadingOrder;
}
/**
* Set how many milliseconds from last loaded point to look ahead.
*
* @param lookahead time to look ahead in ms.
*/
public void setLookAhead(float lookahead)
{
this.lookAhead = (int)lookahead;
}
/**
* Set how many milliseconds from last loaded point to look backwards.
*
* @param lookback time to look backwards in ms.
*/
public void setLookBack(float lookback)
{
this.lookBack = (int)lookback;
}
/**
* If a part of an audio file has not been accessed for some amount of time it is discarded.
* The time that the part remains in memory is specified by setMemory().
* Passing a value of -1 to this function will set the memory to the maximum value possible.
*
* @param ms Duration in milliseconds that unaccessed regions remain loaded.
*/
public void setMemory(float ms)
{
this.memory = (int)ms;
}
/**
* Specify the size of each buffered region.
*
* @param ms Size of the region (ms)
*/
public void setRegionSize(float ms)
{
this.regionSize = ms;
}
/**
* When a region is loaded, nearby regions are put on a queue to be
* loaded also. The loading regime affects the order in which the nearby
* regions (defined by lookback and lookahead) are loaded.
*
* NEAREST (the default) will load regions nearest to the region first.
* ORDERED will load the regions from lowest to highest.
*
* NEAREST makes sense if you are accessing the near regions first, e.g., playing a sample backwards or forwards.
* ORDERED makes sense if you are accessing random nearby regions. Loading regions in order is generally quicker.
*
* @param lr The order to load regions.
*/
public void setLoadingRegime(Order lr)
{
this.loadingOrder = lr;
}
};
/**
* The entire file is read into memory, providing fast access at the cost of more memory used.
*/
static public class TotalRegime extends Regime
{
};
/**
* Store the sample data with native bit-depth.
* Storing in native bit-depth reduces memory load, but increases cpu-load.
*/
public boolean storeInNativeBitDepth = false;
private boolean verbose;
private AudioFile audioFile;
/** The audio format. */
private AudioFormat audioFormat;
/** The number of channels. */
private int nChannels;
/** The number of sample frames. */
private long nFrames;
/** The length in milliseconds. */
private float length;
private boolean isBigEndian;
// regionSize is the number of frames per region
// these parameters are only used in the TIMED regime
private int r_regionSize;
private int r_lookahead; // num region lookahead
private int r_lookback; // num regions lookback
private long r_memory;
private int regionSizeInBytes; // the number of bytes per region (regionSize * nChannels * bitconversionfactor)
private int numberOfRegions; // total number of regions
private int numberOfRegionsLoaded; // number of loaded regions
private byte[][] regions; // the actual data
private float[][][] f_regions; // uninterleaved data
private long[] regionAge; // the age of each region (in ms)
private long timeAtLastAgeUpdate; // the time at the last age updated operation
private boolean[] regionQueued; // true if a region is currently queued
private ConcurrentLinkedQueue<Integer> regionQueue; // a queue of regions to be loaded
private Thread regionThread; // the thread that loads regions in the background
private Lock[] regionLocks; // to support safe deletion/writing of regions
// this parameter is only used if regime==TOTAL
private byte[] sampleData;
private float[][] f_sampleData;
/**
* Instantiates a new empty buffer with the specified audio format and
* number of frames.
*
* @param audioFormat the audio format.
* @param totalFrames the number of sample frames.
*/
public Sample(AudioFormat audioFormat, long totalFrames) {
this();
this.audioFormat = audioFormat;
nChannels = audioFormat.getChannels();
nFrames = totalFrames;
storeInNativeBitDepth = true;
sampleData = new byte[2*nChannels*(int)totalFrames]; //16-bit
Arrays.fill(sampleData,(byte)0);
length = totalFrames / audioFormat.getSampleRate() * 1000f;
}
/**
* Create a sample.
* Call setFile to initialise the sample.
*
*/
public Sample()
{
bufferingRegime = Regime.TOTAL;
isBigEndian = true;
verbose = false;
}
/**
* Create a sample from a file. This constructor immediately loads the entire audio file into memory.
*
* @throws UnsupportedAudioFileException
* @throws IOException
*/
public Sample(String filename) throws IOException, UnsupportedAudioFileException
{
this();
setFile(filename);
}
/**
* Create a sample from an Audio File, using the default buffering scheme.
*
* @throws UnsupportedAudioFileException
* @throws IOException
*/
public Sample(AudioFile af) throws IOException, UnsupportedAudioFileException
{
this();
setFile(af);
}
/**
* Create a sample from an Audio File, using the buffering scheme suggested.
*
* @throws UnsupportedAudioFileException
* @throws IOException
*/
public Sample(AudioFile af, Regime r) throws IOException, UnsupportedAudioFileException
{
this();
setBufferingRegime(r);
setFile(af);
}
/**
* Create a sample from a file, using the buffering scheme suggested.
*
* @throws UnsupportedAudioFileException
* @throws IOException
*/
public Sample(String filename, Regime r) throws IOException, UnsupportedAudioFileException
{
this();
setBufferingRegime(r);
setFile(filename);
}
/**
* The buffering regime affects how the sample accesses the audio data.
*
*
* @param r The buffering regime to use.
*/
public void setBufferingRegime(Regime r)
{
bufferingRegime = r;
}
/**
* Specify an audio file that the Sample reads from.
*
* If BufferedRegime is TOTAL, this will block until the sample is loaded.
*
*/
private void setFile(String file) throws IOException, UnsupportedAudioFileException
{
audioFile = new AudioFile(file);
setFile(audioFile);
}
/**
* Specify an explicit AudioFile that the Sample reads from.
* NOTE: Only one sample should reference a particular AudioFile.
*
* If BufferedRegime is TOTAL, this will block until the sample is loaded.
*
*/
private void setFile(AudioFile af) throws IOException, UnsupportedAudioFileException
{
audioFile = af;
audioFile.open();
audioFormat = audioFile.getDecodedFormat();
nFrames = audioFile.nFrames;
nChannels = audioFile.nChannels;
length = audioFile.length;
isBigEndian = audioFile.getDecodedFormat().isBigEndian();
init();
}
/// set everything up, ready to use
private void init() throws IOException
{
if (isTotal())
{
// load all the sample data into a byte buffer
loadEntireSample();
// lot of crap left over, so call the gc
// TODO: should probably call gc() only once after ALL samples are loaded
// Can do this in sample manager, for instance
// Ollie: or two alternatives: advise user to do this, or AudioContext calls gc() before starting
//which assumes that most samples are loaded before system is turned on.
//On the other hand, this is probably fine since it is only a hint to the system.
System.gc();
}
else // bufferingRegime instanceof TimedRegime
{
if (nFrames==AudioSystem.NOT_SPECIFIED)
{
// TODO: Do a quick run through and guess the length?
System.out.println("BufferedSample needs to know the length of the audio file it uses, but cannot determine the length.");
System.exit(1);
}
TimedRegime tr = (TimedRegime) bufferingRegime;
// initialise params
r_regionSize = (int)Math.ceil(((tr.regionSize/1000.) * audioFile.getDecodedFormat().getSampleRate()));
r_lookahead = (int)Math.ceil(((tr.lookAhead/1000.) * audioFile.getDecodedFormat().getSampleRate())/r_regionSize);
r_lookback = (int)Math.ceil(((tr.lookBack/1000.) * audioFile.getDecodedFormat().getSampleRate())/r_regionSize);
if (tr.memory==-1) r_memory = Long.MAX_VALUE;
r_memory = tr.memory;
regionSizeInBytes = r_regionSize * 2 * nChannels;
numberOfRegions = 1 + (int)(nFrames / r_regionSize);
// the last region may contain 0 to (regionSize-1) samples
numberOfRegionsLoaded = 0;
if (storeInNativeBitDepth)
{
regions = new byte[numberOfRegions][];
Arrays.fill(regions,null);
}
else
{
f_regions = new float[numberOfRegions][][];
Arrays.fill(f_regions,null);
}
regionAge = new long[numberOfRegions];
Arrays.fill(regionAge,0);
if(verbose) System.out.printf("Timed Sample has %d regions of %d bytes each.\n",numberOfRegions,regionSizeInBytes);
// initialise region thread stuff
regionQueue = new ConcurrentLinkedQueue<Integer>();
regionQueued = new boolean[numberOfRegions];
regionLocks = new Lock[numberOfRegions];
for (int j=0;j<regionLocks.length;j++)
{
regionLocks[j] = new ReentrantLock();
}
//TODO might want to actually switch thread on and off
regionThread = new Thread(this);
regionThread.setDaemon(true);
timeAtLastAgeUpdate = 0; //System.nanoTime()/1000;
regionThread.start();
// regionThread.setPriority()
}
}
/// are we using the total regime?
private boolean isTotal()
{
return (bufferingRegime instanceof TotalRegime);
}
/**
* Return a single frame.
* If the data is not readily available this function blocks until it is.
*
* @param frame Must be in range, else framedata is unchanged.
* @param frameData
*
*/
public void getFrame(int frame, float[] frameData)
{
if (frame >= nFrames) return;
if (isTotal())
{
if (storeInNativeBitDepth)
{
int startIndex = frame * 2 * nChannels;
AudioUtils.byteToFloat(frameData,sampleData,isBigEndian,startIndex,frameData.length);
}
else
{
for(int i=0;i<nChannels;i++)
frameData[i] = f_sampleData[i][frame];
}
}
else // bufferingRegime==BufferingRegime.TIMED
{
int whichRegion = frame / r_regionSize;
// When someone requests a region, it may not be loaded yet.
// Alternatively it may currently be being deleted, in which case we have to wait.
// lock access to region r, load it, and return it...
// wait until it is free...
try {
while (!regionLocks[whichRegion].tryLock(10, TimeUnit.MILLISECONDS)){}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
if (storeInNativeBitDepth)
{
byte[] regionData = getRegion(whichRegion);
if (regionData!=null)
{
// convert it to the correct format,
int startIndex = (frame % r_regionSize) * 2 * nChannels;
AudioUtils.byteToFloat(frameData,regionData,isBigEndian,startIndex,frameData.length);
}
else
{
System.err.println("Sample.java:409 no region data!");
//System.exit(1);
}
}
else
{
float[][] regionData = getRegionF(whichRegion);
if (regionData!=null)
{
// convert it to the correct format,
int startIndex = frame % r_regionSize;
//System.arraycopy(regionData[startIndex], srcPos, dest, destPos, length)
for(int i=0;i<nChannels;i++)
frameData[i] = regionData[i][startIndex];
//AudioUtils.byteToFloat(frameData,regionData,isBigEndian,startIndex,frameData.length);
}
}
}
finally {
regionLocks[whichRegion].unlock();
}
}
}
/**
* Get a series of frames. FrameData will only be filled with the available frames.
* It is the caller's responsibility to count how many frames are valid.
* e.g., min(nFrames - frame, frameData[0].length) frames in frameData are valid.
*
* If the data is not readily available this function blocks until it is.
*
* @param frame
* @param frameData
*/
public void getFrames(int frame, float[][] frameData)
{
if (frame >= nFrames) return;
if (isTotal())
{
- int numFloats = Math.min(frameData[0].length,(int)(nFrames-frame))*nChannels;
+ int numFloats = Math.min(frameData[0].length,(int)(nFrames-frame));
if (storeInNativeBitDepth)
{
int startIndex = frame * 2 * nChannels;
- float[] floatdata = new float[numFloats];
- AudioUtils.byteToFloat(floatdata, sampleData, isBigEndian, startIndex, numFloats);
+ float[] floatdata = new float[numFloats*nChannels];
+ AudioUtils.byteToFloat(floatdata, sampleData, isBigEndian, startIndex, numFloats*nChannels);
AudioUtils.deinterleave(floatdata,nChannels,frameData[0].length,frameData);
}
else
{
for(int i=0;i<nChannels;i++)
System.arraycopy(f_sampleData[i],frame,frameData[i],0,numFloats);
}
}
else // bufferingRegime==BufferingRegime.TIMED
{
int numFloats = Math.min(frameData[0].length,(int)(nFrames-frame))*nChannels;
float[] floatdata = null;
if (storeInNativeBitDepth)
floatdata = new float[numFloats];
// fill floatdata with successive regions of byte data
int floatdataindex = 0;
int regionindex = frame % r_regionSize;
int whichregion = frame / r_regionSize;
int numfloatstocopy = Math.min(r_regionSize - regionindex,numFloats - floatdataindex);
while (numfloatstocopy>0)
{
// see getFrame() for explanation
try {
while (!regionLocks[whichregion].tryLock(10, TimeUnit.MILLISECONDS)){}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
if (storeInNativeBitDepth)
{
byte[] regionData = getRegion(whichregion);
if (regionData!=null)
AudioUtils.byteToFloat(floatdata, regionData, isBigEndian, regionindex*2*nChannels, floatdataindex*nChannels, numfloatstocopy*nChannels);
}
else
{
float[][] regionData = getRegionF(whichregion);
if (regionData!=null)
{
// copy all channels...
for(int i=0;i<nChannels;i++)
{
System.arraycopy(regionData[i], 0, frameData[i], floatdataindex, numfloatstocopy);
}
}
}
}
finally {
regionLocks[whichregion].unlock();
}
floatdataindex += numfloatstocopy;
regionindex = 0;
numfloatstocopy = Math.min(r_regionSize,numFloats - floatdataindex);
whichregion++;
}
// deinterleave the whole thing
AudioUtils.deinterleave(floatdata,nChannels,frameData[0].length,frameData);
}
}
// Region loading, handling, queuing, removing, etc...
/// Region handling, loading, etc...
private byte[] getRegion(int r)
{
// first determine whether the region is valid
if (!isRegionAvailable(r))
{
//System.out.println("REGION NOT THERE!");
loadRegion(r);
}
touchRegion(r);
// then return it
return regions[r];
}
/// Region handling, loading, etc...
// assume region r exists
private float[][] getRegionF(int r)
{
// first determine whether the region is valid
if (!isRegionAvailable(r))
{
//System.out.println("REGION NOT THERE!");
loadRegion(r);
}
touchRegion(r);
// then return it
return f_regions[r];
}
private void touchRegion(int r)
{
if (((TimedRegime)bufferingRegime).loadingOrder==TimedRegime.Order.ORDERED)
{
// queue the regions from back to front
for(int i=Math.max(0,r-r_lookback);i<Math.min(r+r_lookahead,numberOfRegions);i++)
{
if (i!=r) queueRegionForLoading(i);
}
}
else // loadingOrder==LoadingRegime.NEAREST
{
// queue the regions from nearest to furthest, back to front...
int br = Math.min(r,r_lookback); // number of back regions
int fr = Math.min(r_lookahead,numberOfRegions-1-r); // number of ahead regions
// have two pointers, one going backwards the other going forwards
int bp = 1;
int fp = 1;
boolean backwards = (bp<=br); // start backwards (if there are backward regions)
while(bp<=br || fp<=fr)
{
if (backwards)
{
queueRegionForLoading(r-bp);
bp++;
if (fp<=fr) backwards = false;
}
else // if forwards
{
queueRegionForLoading(r+fp);
fp++;
if (bp<=br) backwards = true;
}
}
}
// touch the region, make it new
synchronized (regionAge)
{ regionAge[r] = 0; }
}
private boolean isRegionAvailable(int r)
{
if (storeInNativeBitDepth)
return regions[r]!=null;
else
return f_regions[r]!=null;
}
private boolean isRegionQueued(int r)
{
return regionQueued[r];
}
/// loads the region IMMEDIATELY, blocks until it is loaded
// this is called by the regionloader as it loads,
// but also by the main thread when it needs a region RIGHT AWAY
synchronized private void loadRegion(int r)
{
// for now, just seek to the correct position
try {
if (storeInNativeBitDepth)
{
regions[r] = new byte[regionSizeInBytes];
numberOfRegionsLoaded++;
audioFile.seek(r_regionSize*r);
int bytesRead = audioFile.read(regions[r]);
if (bytesRead<=0)
regions[r] = null;
}
else // store in float[][] format
{
// load the bytes and convert them on the spot
byte[] region = new byte[regionSizeInBytes];
numberOfRegionsLoaded++;
audioFile.seek(r_regionSize*r);
int bytesRead = audioFile.read(region);
if (bytesRead<=0)
regions[r] = null;
// now convert
f_regions[r] = new float[nChannels][r_regionSize];
float[] interleaved = new float[nChannels*r_regionSize];
AudioUtils.byteToFloat(interleaved, region, isBigEndian);
AudioUtils.deinterleave(interleaved, nChannels, r_regionSize, f_regions[r]);
}
synchronized(regionAge)
{
regionAge[r] = 0;
}
} catch (Exception e) {
e.printStackTrace();
}
}
/// load the region r when you can, non-blocking
private void queueRegionForLoading(int r)
{
if (!isRegionAvailable(r) && !isRegionQueued(r))
{
regionQueued[r] = true;
regionQueue.add(r);
// wake up the region thread master
if (regionThread.getState()==State.TIMED_WAITING)
regionThread.interrupt();
}
}
private void unloadRegion(int r)
{
if (storeInNativeBitDepth)
regions[r]=null;
else
f_regions[r]=null;
}
public void run() {
while (true)
{
// if there's a region on the queue then load it
boolean queuedregion = !regionQueue.isEmpty();
if (queuedregion)
{
int r = regionQueue.poll();
if (regionLocks[r].tryLock())
{
try {
if (!isRegionAvailable(r))
loadRegion(r);
synchronized(regionQueued)
{
regionQueued[r] = false;
}
}
finally {
regionLocks[r].unlock();
}
}
}
// age all the loaded regions
// remove the oldest ones if we exceed the memory limit
// TODO: don't need to age things all the time, this should be based on some tunable param
if (timeAtLastAgeUpdate==0) timeAtLastAgeUpdate = System.currentTimeMillis();
long dt = System.currentTimeMillis() - timeAtLastAgeUpdate;
//System.out.println(dt);
//System.out.println();
//int numRegionsToRemove = numberOfRegionsLoaded - maxRegionsLoadedAtOnce;
//SortedSet sortedByAge = new TreeSet<Integer>(new Comparator(){});
//if (numRegionsToRemove>0)
for (int i=0;i<numberOfRegions;i++)
{
//System.out.printf("%d ",regionAge[i]);
if (!isRegionAvailable(i))
{
synchronized(regionAge)
{
regionAge[i] += dt;
}
if (regionAge[i]>r_memory)
{
// if it is unlocked, then remove it...
if (regionLocks[i].tryLock())
{
try {
unloadRegion(i);
numberOfRegionsLoaded--;
}
finally {
regionLocks[i].unlock();
}
}
// else, ignore and try again next time...
}
}
}
timeAtLastAgeUpdate += dt;
if (!queuedregion)
{
try {
Thread.sleep(10000);
} catch (InterruptedException ignore)
{
//System.out.println("Wake up!");
}
}
}
}
// a helper function, loads the entire sample into sampleData
private void loadEntireSample() throws IOException
{
final int BUFFERSIZE = 4096;
byte[] audioBytes = new byte[BUFFERSIZE];
int sampleBufferSize = 4096;
byte[] data = new byte[sampleBufferSize];
int bytesRead;
int totalBytesRead = 0;
int numberOfFrames = 0;
while ((bytesRead = audioFile.read(audioBytes))!=-1) {
int numFramesJustRead = bytesRead / (2 * nChannels);
// resize buf if necessary
if (bytesRead > (sampleBufferSize-totalBytesRead))
{
sampleBufferSize = Math.max(sampleBufferSize*2, sampleBufferSize + bytesRead);
//System.out.printf("Adjusted samplebuffersize to %d\n",sampleBufferSize);
// resize buffer
byte[] newBuf = new byte[sampleBufferSize];
System.arraycopy(data, 0, newBuf, 0, data.length);
data = newBuf;
}
System.arraycopy(audioBytes, 0, data, totalBytesRead, bytesRead);
numberOfFrames += numFramesJustRead;
totalBytesRead += bytesRead;
}
// resize buf to proper length
// resize buf if necessary
if (sampleBufferSize > totalBytesRead)
{
sampleBufferSize = totalBytesRead;
// resize buffer
byte[] newBuf = new byte[sampleBufferSize];
System.arraycopy(data, 0, newBuf, 0, sampleBufferSize);
data = newBuf;
}
nFrames = sampleBufferSize / (2*nChannels);
if (!storeInNativeBitDepth)
{
// copy and deinterleave entire data
f_sampleData = new float[nChannels][(int) nFrames];
float[] interleaved = new float[(int) (nChannels*nFrames)];
AudioUtils.byteToFloat(interleaved, data, isBigEndian);
AudioUtils.deinterleave(interleaved, nChannels, (int) nFrames, f_sampleData);
}
else
{
// store the data in this sample in native format
sampleData = data;
}
audioFile.close();
}
/**
* Prints audio format info to System.out.
*/
public void printAudioFormatInfo() {
System.out.println("Sample Rate: " + audioFormat.getSampleRate());
System.out.println("Channels: " + nChannels);
System.out.println("Frame size in Bytes: " + audioFormat.getFrameSize());
System.out.println("Encoding: " + audioFormat.getEncoding());
System.out.println("Big Endian: " + audioFormat.isBigEndian());
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
public String toString() {
return getFileName();
}
/**
* Gets the full file path.
*
* @return the file path.
*/
public String getFileName() {
return audioFile.file.getAbsolutePath();
}
/**
* Gets the simple file name.
*
* @return the file name.
*/
public String getSimpleFileName() {
return audioFile.file.getName();
}
/**
* Converts from milliseconds to samples based on the sample rate specified by {@link #audioFormat}.
*
* @param msTime the time in milliseconds.
*
* @return the time in samples.
*/
public double msToSamples(double msTime) {
return msTime * audioFormat.getSampleRate() / 1000.0f;
}
/**
* Converts from samples to milliseconds based on the sample rate specified by {@link #audioFormat}.
*
* @param sampleTime the time in samples.
*
* @return the time in milliseconds.
*/
public double samplesToMs(double sampleTime) {
return sampleTime / audioFormat.getSampleRate() * 1000.0f;
}
/**
* Retrieves a frame of audio using linear interpolation.
*
* @param currentSample the current sample.
* @param fractionOffset the offset from the current sample as a fraction of the time
* to the next sample.
*
* @return the interpolated frame.
*/
public float[] getFrameLinear(int currentSample, float fractionOffset) {
float[] result = new float[nChannels];
if(currentSample >= 0 && currentSample < nFrames) {
if (currentSample == nFrames-1)
{
getFrame(currentSample,result);
}
else
{
float[] current = new float[nChannels];
getFrame(currentSample,current);
float[] next = new float[nChannels];
getFrame(currentSample+1,next);
for (int i = 0; i < nChannels; i++) {
result[i] = (1 - fractionOffset) * current[i] +
fractionOffset * next[i];
}
}
} else {
for(int i = 0; i < nChannels; i++) {
result[i] = 0.0f;
}
}
return result;
}
/**
* Retrieves a frame of audio using cubic interpolation.
*
* @param currentSample the current sample.
* @param fractionOffset the offset from the current sample as a fraction of the time
* to the next sample.
*
* @return the interpolated frame.
*/
public float[] getFrameCubic(int currentSample, float fractionOffset) {
float[] result = new float[nChannels];
float[] buf = new float[nChannels];
float a0,a1,a2,a3,mu2;
float ym1,y0,y1,y2;
for (int i = 0; i < nChannels; i++) {
int realCurrentSample = currentSample;
if(realCurrentSample >= 0 && realCurrentSample < (nFrames - 1)) {
realCurrentSample--;
if (realCurrentSample < 0) {
getFrame(0, buf);
ym1 = buf[i];
realCurrentSample = 0;
} else {
getFrame(realCurrentSample++, buf);
ym1 = buf[i];
}
getFrame(realCurrentSample++, buf);
y0 = buf[i];
if (realCurrentSample >= nFrames) {
getFrame((int)nFrames - 1, buf);
y1 = buf[i]; //??
} else {
getFrame(realCurrentSample++, buf);
y1 = buf[i];
}
if (realCurrentSample >= nFrames) {
getFrame((int)nFrames - 1, buf);
y2 = buf[i]; //??
} else {
getFrame(realCurrentSample++, buf);
y2 = buf[i];
}
mu2 = fractionOffset * fractionOffset;
a0 = y2 - y1 - ym1 + y0;
a1 = ym1 - y0 - a0;
a2 = y1 - ym1;
a3 = y0;
result[i] = a0 * fractionOffset * mu2 + a1 * mu2 + a2 * fractionOffset + a3;
} else {
result[i] = 0.0f;
}
}
return result;
}
/**
* A Sample needs to be writeable in order to be recorded into.
* Currently buffered samples are not writeable, but TOTAL (file or empty) samples are.
*/
public boolean isWriteable()
{
return isTotal();
}
/**
* Write a single frame into this sample. Takes care of format conversion.
*
* This only makes sense if this.isWriteable() returns true.
* If isWriteable() is false, the behaviour is undefined/unstable.
*
* @param frame The frame to write into.
* @param frameData The frame data to write.
*/
public void putFrame(int frame, float[] frameData)
{
int startIndex = frame * 2 * nChannels;
AudioUtils.floatToByte(sampleData, startIndex, frameData, 0, frameData.length, isBigEndian);
}
/**
* Write multiple frames data into the sample.
*
* This only makes sense if this.isWriteable() returns true.
* If isWriteable() is false, the behaviour is undefined/unstable.
*
* @param frame The frame to write into.
* @param frameData The frames to write.
*/
public void putFrames(int frame, float[][] frameData)
{
int startIndex = frame * 2 * nChannels;
int numFloats = Math.min(frameData[0].length,(int)(nFrames-frame))*nChannels;
float[] floatdata = new float[numFloats];
AudioUtils.interleave(frameData,nChannels,frameData[0].length,floatdata);
AudioUtils.floatToByte(sampleData, startIndex, floatdata, 0, floatdata.length, isBigEndian);
}
/**
* Write multiple frames data into the sample.
*
* This only makes sense if this.isWriteable() returns true.
* If isWriteable() is false, the behaviour is undefined/unstable.
*
* @param frame The frame to write into.
* @param frameData The frames to write.
* @param offset The offset into frameData
* @param numFrames The number of frames from frameData to write
*/
public void putFrames(int frame, float[][] frameData, int offset, int numFrames)
{
if (numFrames<=0) return;
int startIndex = frame * 2 * nChannels;
int numFloats = Math.min(numFrames,(int)(nFrames-frame))*nChannels;
float[] floatdata = new float[numFloats];
AudioUtils.interleave(frameData,nChannels,offset,frameData[0].length,floatdata);
AudioUtils.floatToByte(sampleData, startIndex, floatdata, 0, floatdata.length, isBigEndian);
}
/**
* Write Sample to a file.
* This will record the entire sample to a file.
* BLOCKING.
*
* @param fn the file name.
*
* @throws IOException Signals that an I/O exception has occurred.
*/
public void write(String fn) throws IOException {
if (isTotal())
{
ByteArrayInputStream bais = new ByteArrayInputStream(sampleData);
AudioInputStream aos = new AudioInputStream(bais, audioFormat, nFrames);
AudioSystem.write(aos, AudioFileFormat.Type.AIFF, new File(fn));
}
else // bufferingRegime==BufferingRegime.TIMED
{
System.out.println("Writing buffered samples to disk is not yet supported.");
System.exit(1);
/*
// for each region, load it if necessary and write out the data
File file = new File(fn);
for(int i=0;i<numberOfRegions;i++)
{
try {
while (!regionLocks[i].tryLock(10, TimeUnit.MILLISECONDS)){}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
byte[] regionData = getRegion(i);
if (regionData!=null)
{
ByteArrayInputStream bais = new ByteArrayInputStream(regionData);
AudioInputStream aos = new AudioInputStream(bais, audioFormat, regionSize);
AudioSystem.write(aos, AudioFileFormat.Type.AIFF, file);
}
}
finally {
regionLocks[i].unlock();
}
}
*/
}
}
public AudioFile getAudioFile() {
return audioFile;
}
public AudioFormat getAudioFormat() {
return audioFormat;
}
public int getNumChannels() {
return nChannels;
}
public long getNumFrames() {
return nFrames;
}
public float getLength() {
return length;
}
public float getSampleRate() {
return audioFormat.getSampleRate();
}
public int getNumberOfRegionsLoaded() {
return numberOfRegionsLoaded;
}
}
| false | true | public void getFrames(int frame, float[][] frameData)
{
if (frame >= nFrames) return;
if (isTotal())
{
int numFloats = Math.min(frameData[0].length,(int)(nFrames-frame))*nChannels;
if (storeInNativeBitDepth)
{
int startIndex = frame * 2 * nChannels;
float[] floatdata = new float[numFloats];
AudioUtils.byteToFloat(floatdata, sampleData, isBigEndian, startIndex, numFloats);
AudioUtils.deinterleave(floatdata,nChannels,frameData[0].length,frameData);
}
else
{
for(int i=0;i<nChannels;i++)
System.arraycopy(f_sampleData[i],frame,frameData[i],0,numFloats);
}
}
else // bufferingRegime==BufferingRegime.TIMED
{
int numFloats = Math.min(frameData[0].length,(int)(nFrames-frame))*nChannels;
float[] floatdata = null;
if (storeInNativeBitDepth)
floatdata = new float[numFloats];
// fill floatdata with successive regions of byte data
int floatdataindex = 0;
int regionindex = frame % r_regionSize;
int whichregion = frame / r_regionSize;
int numfloatstocopy = Math.min(r_regionSize - regionindex,numFloats - floatdataindex);
while (numfloatstocopy>0)
{
// see getFrame() for explanation
try {
while (!regionLocks[whichregion].tryLock(10, TimeUnit.MILLISECONDS)){}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
if (storeInNativeBitDepth)
{
byte[] regionData = getRegion(whichregion);
if (regionData!=null)
AudioUtils.byteToFloat(floatdata, regionData, isBigEndian, regionindex*2*nChannels, floatdataindex*nChannels, numfloatstocopy*nChannels);
}
else
{
float[][] regionData = getRegionF(whichregion);
if (regionData!=null)
{
// copy all channels...
for(int i=0;i<nChannels;i++)
{
System.arraycopy(regionData[i], 0, frameData[i], floatdataindex, numfloatstocopy);
}
}
}
}
finally {
regionLocks[whichregion].unlock();
}
floatdataindex += numfloatstocopy;
regionindex = 0;
numfloatstocopy = Math.min(r_regionSize,numFloats - floatdataindex);
whichregion++;
}
// deinterleave the whole thing
AudioUtils.deinterleave(floatdata,nChannels,frameData[0].length,frameData);
}
}
| public void getFrames(int frame, float[][] frameData)
{
if (frame >= nFrames) return;
if (isTotal())
{
int numFloats = Math.min(frameData[0].length,(int)(nFrames-frame));
if (storeInNativeBitDepth)
{
int startIndex = frame * 2 * nChannels;
float[] floatdata = new float[numFloats*nChannels];
AudioUtils.byteToFloat(floatdata, sampleData, isBigEndian, startIndex, numFloats*nChannels);
AudioUtils.deinterleave(floatdata,nChannels,frameData[0].length,frameData);
}
else
{
for(int i=0;i<nChannels;i++)
System.arraycopy(f_sampleData[i],frame,frameData[i],0,numFloats);
}
}
else // bufferingRegime==BufferingRegime.TIMED
{
int numFloats = Math.min(frameData[0].length,(int)(nFrames-frame))*nChannels;
float[] floatdata = null;
if (storeInNativeBitDepth)
floatdata = new float[numFloats];
// fill floatdata with successive regions of byte data
int floatdataindex = 0;
int regionindex = frame % r_regionSize;
int whichregion = frame / r_regionSize;
int numfloatstocopy = Math.min(r_regionSize - regionindex,numFloats - floatdataindex);
while (numfloatstocopy>0)
{
// see getFrame() for explanation
try {
while (!regionLocks[whichregion].tryLock(10, TimeUnit.MILLISECONDS)){}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
if (storeInNativeBitDepth)
{
byte[] regionData = getRegion(whichregion);
if (regionData!=null)
AudioUtils.byteToFloat(floatdata, regionData, isBigEndian, regionindex*2*nChannels, floatdataindex*nChannels, numfloatstocopy*nChannels);
}
else
{
float[][] regionData = getRegionF(whichregion);
if (regionData!=null)
{
// copy all channels...
for(int i=0;i<nChannels;i++)
{
System.arraycopy(regionData[i], 0, frameData[i], floatdataindex, numfloatstocopy);
}
}
}
}
finally {
regionLocks[whichregion].unlock();
}
floatdataindex += numfloatstocopy;
regionindex = 0;
numfloatstocopy = Math.min(r_regionSize,numFloats - floatdataindex);
whichregion++;
}
// deinterleave the whole thing
AudioUtils.deinterleave(floatdata,nChannels,frameData[0].length,frameData);
}
}
|
diff --git a/src/com/android/deskclock/AlarmPreference.java b/src/com/android/deskclock/AlarmPreference.java
index c6603c89..0d58352f 100644
--- a/src/com/android/deskclock/AlarmPreference.java
+++ b/src/com/android/deskclock/AlarmPreference.java
@@ -1,101 +1,105 @@
/*
* 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.deskclock;
import android.content.Context;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.preference.RingtonePreference;
import android.provider.Settings;
import android.util.AttributeSet;
/**
* The RingtonePreference does not have a way to get/set the current ringtone so
* we override onSaveRingtone and onRestoreRingtone to get the same behavior.
*/
public class AlarmPreference extends RingtonePreference {
private Uri mAlert;
private boolean mChangeDefault;
private AsyncTask mRingtoneTask;
public AlarmPreference(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onSaveRingtone(Uri ringtoneUri) {
setAlert(ringtoneUri);
if (mChangeDefault) {
// Update the default alert in the system.
Settings.System.putString(getContext().getContentResolver(),
Settings.System.ALARM_ALERT,
ringtoneUri == null ? null : ringtoneUri.toString());
}
}
@Override
protected Uri onRestoreRingtone() {
if (RingtoneManager.isDefault(mAlert)) {
return RingtoneManager.getActualDefaultRingtoneUri(getContext(),
RingtoneManager.TYPE_ALARM);
}
return mAlert;
}
public void setAlert(Uri alert) {
+ if (RingtoneManager.isDefault(alert)) {
+ alert = RingtoneManager.getActualDefaultRingtoneUri(getContext(),
+ RingtoneManager.TYPE_ALARM);
+ }
mAlert = alert;
if (alert != null) {
setSummary(R.string.loading_ringtone);
if (mRingtoneTask != null) {
mRingtoneTask.cancel(true);
}
mRingtoneTask = new AsyncTask<Uri, Void, String>() {
@Override
protected String doInBackground(Uri... params) {
Ringtone r = RingtoneManager.getRingtone(
getContext(), params[0]);
if (r != null) {
return r.getTitle(getContext());
}
return null;
}
@Override
protected void onPostExecute(String title) {
if (!isCancelled()) {
if (title != null) {
setSummary(title);
}
mRingtoneTask = null;
}
}
}.execute(alert);
} else {
setSummary(R.string.silent_alarm_summary);
}
}
public Uri getAlert() {
return mAlert;
}
public void setChangeDefault() {
mChangeDefault = true;
}
}
| true | true | public void setAlert(Uri alert) {
mAlert = alert;
if (alert != null) {
setSummary(R.string.loading_ringtone);
if (mRingtoneTask != null) {
mRingtoneTask.cancel(true);
}
mRingtoneTask = new AsyncTask<Uri, Void, String>() {
@Override
protected String doInBackground(Uri... params) {
Ringtone r = RingtoneManager.getRingtone(
getContext(), params[0]);
if (r != null) {
return r.getTitle(getContext());
}
return null;
}
@Override
protected void onPostExecute(String title) {
if (!isCancelled()) {
if (title != null) {
setSummary(title);
}
mRingtoneTask = null;
}
}
}.execute(alert);
} else {
setSummary(R.string.silent_alarm_summary);
}
}
| public void setAlert(Uri alert) {
if (RingtoneManager.isDefault(alert)) {
alert = RingtoneManager.getActualDefaultRingtoneUri(getContext(),
RingtoneManager.TYPE_ALARM);
}
mAlert = alert;
if (alert != null) {
setSummary(R.string.loading_ringtone);
if (mRingtoneTask != null) {
mRingtoneTask.cancel(true);
}
mRingtoneTask = new AsyncTask<Uri, Void, String>() {
@Override
protected String doInBackground(Uri... params) {
Ringtone r = RingtoneManager.getRingtone(
getContext(), params[0]);
if (r != null) {
return r.getTitle(getContext());
}
return null;
}
@Override
protected void onPostExecute(String title) {
if (!isCancelled()) {
if (title != null) {
setSummary(title);
}
mRingtoneTask = null;
}
}
}.execute(alert);
} else {
setSummary(R.string.silent_alarm_summary);
}
}
|
diff --git a/osmorc/src/org/osmorc/facet/OsgiCoreLibraryType.java b/osmorc/src/org/osmorc/facet/OsgiCoreLibraryType.java
index 656b2475a3..8e2291ee8b 100644
--- a/osmorc/src/org/osmorc/facet/OsgiCoreLibraryType.java
+++ b/osmorc/src/org/osmorc/facet/OsgiCoreLibraryType.java
@@ -1,73 +1,76 @@
package org.osmorc.facet;
import com.intellij.framework.library.DownloadableLibraryTypeBase;
import com.intellij.framework.library.LibraryVersionProperties;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.roots.OrderRootType;
import com.intellij.openapi.roots.libraries.LibrariesHelper;
import com.intellij.openapi.roots.libraries.Library;
import com.intellij.openapi.roots.libraries.LibraryUtil;
import com.intellij.openapi.vfs.JarFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.ArrayUtil;
import org.jetbrains.annotations.NotNull;
import org.osgi.framework.Constants;
import org.osgi.framework.Version;
import org.osmorc.i18n.OsmorcBundle;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
public class OsgiCoreLibraryType extends DownloadableLibraryTypeBase {
private static final String ID = "org.osgi.core";
private static final String DETECTOR_CLASS = "org.osgi.framework.Constants";
public OsgiCoreLibraryType() {
super("OSGi Core API", ID, ID, OsmorcBundle.getSmallIcon(), OsgiCoreLibraryType.class.getResource("osgi.core.xml"));
}
@Override
public LibraryVersionProperties detect(@NotNull List<VirtualFile> roots) {
if (!LibraryUtil.isClassAvailableInLibrary(roots, DETECTOR_CLASS)) {
return null;
}
VirtualFile jar = LibrariesHelper.getInstance().findRootByClass(roots, DETECTOR_CLASS);
if (jar != null && jar.getFileSystem() instanceof JarFileSystem) {
VirtualFile manifestFile = jar.findFileByRelativePath(JarFile.MANIFEST_NAME);
if (manifestFile != null) {
try {
InputStream input = manifestFile.getInputStream();
try {
String version = new Manifest(input).getMainAttributes().getValue(Constants.BUNDLE_VERSION);
if (version != null) {
- Version v = new Version(version);
- return new LibraryVersionProperties(v.getMajor() + "." + v.getMinor() + "." + v.getMicro());
+ try {
+ Version v = new Version(version);
+ return new LibraryVersionProperties(v.getMajor() + "." + v.getMinor() + "." + v.getMicro());
+ }
+ catch (IllegalArgumentException ignored) { }
}
}
finally {
input.close();
}
}
catch (IOException ignored) { }
}
}
// unknown version
return new LibraryVersionProperties(null);
}
@Override
protected String[] getDetectionClassNames() {
Logger.getInstance(getClass()).error(new AssertionError("shouldn't be called"));
return ArrayUtil.EMPTY_STRING_ARRAY;
}
public static boolean isOsgiCoreLibrary(@NotNull Library library) {
VirtualFile[] roots = library.getFiles(OrderRootType.CLASSES);
return LibraryUtil.isClassAvailableInLibrary(roots, DETECTOR_CLASS);
}
}
| true | true | public LibraryVersionProperties detect(@NotNull List<VirtualFile> roots) {
if (!LibraryUtil.isClassAvailableInLibrary(roots, DETECTOR_CLASS)) {
return null;
}
VirtualFile jar = LibrariesHelper.getInstance().findRootByClass(roots, DETECTOR_CLASS);
if (jar != null && jar.getFileSystem() instanceof JarFileSystem) {
VirtualFile manifestFile = jar.findFileByRelativePath(JarFile.MANIFEST_NAME);
if (manifestFile != null) {
try {
InputStream input = manifestFile.getInputStream();
try {
String version = new Manifest(input).getMainAttributes().getValue(Constants.BUNDLE_VERSION);
if (version != null) {
Version v = new Version(version);
return new LibraryVersionProperties(v.getMajor() + "." + v.getMinor() + "." + v.getMicro());
}
}
finally {
input.close();
}
}
catch (IOException ignored) { }
}
}
// unknown version
return new LibraryVersionProperties(null);
}
| public LibraryVersionProperties detect(@NotNull List<VirtualFile> roots) {
if (!LibraryUtil.isClassAvailableInLibrary(roots, DETECTOR_CLASS)) {
return null;
}
VirtualFile jar = LibrariesHelper.getInstance().findRootByClass(roots, DETECTOR_CLASS);
if (jar != null && jar.getFileSystem() instanceof JarFileSystem) {
VirtualFile manifestFile = jar.findFileByRelativePath(JarFile.MANIFEST_NAME);
if (manifestFile != null) {
try {
InputStream input = manifestFile.getInputStream();
try {
String version = new Manifest(input).getMainAttributes().getValue(Constants.BUNDLE_VERSION);
if (version != null) {
try {
Version v = new Version(version);
return new LibraryVersionProperties(v.getMajor() + "." + v.getMinor() + "." + v.getMicro());
}
catch (IllegalArgumentException ignored) { }
}
}
finally {
input.close();
}
}
catch (IOException ignored) { }
}
}
// unknown version
return new LibraryVersionProperties(null);
}
|
diff --git a/src/main/java/syndeticlogic/catena/text/BlockMerger.java b/src/main/java/syndeticlogic/catena/text/BlockMerger.java
index e6bc83e..58c0c98 100644
--- a/src/main/java/syndeticlogic/catena/text/BlockMerger.java
+++ b/src/main/java/syndeticlogic/catena/text/BlockMerger.java
@@ -1,109 +1,111 @@
package syndeticlogic.catena.text;
import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import syndeticlogic.catena.utility.Config;
public class BlockMerger {
private static int BLOCK_SIZE=10*1048576;
private static double MEMORY_PERCENTAGE=0.3;
private HashMap<Integer, String> idToWord;
private String prefix;
public BlockMerger(String prefix, HashMap<Integer, String> idToWord) {
this.prefix = prefix;
this.idToWord = idToWord;
}
public List<InvertedListDescriptor> mergeBlocks(String mergeTarget, LinkedList<Map.Entry<String, List<InvertedListDescriptor>>> blockDescriptors) {
long memory = (long)(((double)Config.getPhysicalMemorySize()) * MEMORY_PERCENTAGE);
int readBlocksAndWriteBlock = Math.min((int)(memory/BLOCK_SIZE), blockDescriptors.size()+1);
int readBlocks = readBlocksAndWriteBlock - 1;
int sources = blockDescriptors.size();
String intermediateMerge = prefix+File.separator+"intermediate-merge-target.";
List<InvertedListDescriptor> mergedDescriptors=null;
String fileName=null;
int totalMergeFiles = 0;
while(sources > 0) {
assert sources >= readBlocks;
InvertedFileReader[] readers = new InvertedFileReader[readBlocks];
@SuppressWarnings("unchecked")
List<InvertedListDescriptor>[] descriptors = new List[readBlocks];
Iterator<Map.Entry<String, List<InvertedListDescriptor>>> bditerator = blockDescriptors.iterator();
int i=0;
if(mergedDescriptors != null) {
assert fileName != null;
descriptors[0] = mergedDescriptors;
readers[0] = new InvertedFileReader();
readers[0].setBlockSize(BLOCK_SIZE);
readers[0].open(fileName);
i = 1;
}
for(; i < readBlocks; i++) {
Map.Entry<String, List<InvertedListDescriptor>> id = bditerator.next();
descriptors[i] = id.getValue();
readers[i] = new InvertedFileReader();
readers[i].setBlockSize(BLOCK_SIZE);
readers[i].open(id.getKey());
}
- boolean finalPass = (((sources - readBlocks) > 0) ? false : true);
+ boolean finalPass = (((sources - readBlocks) > 0) ? true : false);
if(finalPass) {
fileName = intermediateMerge+Integer.toString(totalMergeFiles);
totalMergeFiles++;
} else {
fileName = mergeTarget;
}
InvertedFileWriter writer = new RawInvertedFileWriter();
writer.setBlockSize(BLOCK_SIZE);
writer.open(fileName);
mergedDescriptors = merge(readers, descriptors, writer);
sources -= readBlocks;
readBlocks = Math.min((int)(memory/BLOCK_SIZE), sources);
}
+ /*
for(int i = 0; i < totalMergeFiles-1; i++) {
String name = intermediateMerge+Integer.toString(totalMergeFiles);
if(!(new File(name).delete())) {
System.err.println("failed to delete "+name);
}
}
+ */
return mergedDescriptors;
}
public List<InvertedListDescriptor> merge(InvertedFileReader[] readers, List<InvertedListDescriptor>[] descriptors,
InvertedFileWriter writer) {
assert readers.length == descriptors.length;
TreeMap<String, InvertedList> ret=null;
int[] positions = new int[readers.length];
for(int i = 0; i < readers.length; i++) {
TreeMap<String, InvertedList> newPostings = new TreeMap<String, InvertedList>();
positions[i] = readers[i].scanBlock(positions[i], descriptors[i], idToWord, newPostings);
if(ret == null) {
ret = newPostings;
} else {
for(InvertedList list : newPostings.values()) {
InvertedList retList = ret.get(list.getWord());
if(retList == null) {
ret.put(list.getWord(), list);
} else {
retList.merge(list);
}
}
}
}
List<InvertedListDescriptor> newDescriptors = new LinkedList<InvertedListDescriptor>();
writer.writeFile(ret, newDescriptors);
return newDescriptors;
}
}
| false | true | public List<InvertedListDescriptor> mergeBlocks(String mergeTarget, LinkedList<Map.Entry<String, List<InvertedListDescriptor>>> blockDescriptors) {
long memory = (long)(((double)Config.getPhysicalMemorySize()) * MEMORY_PERCENTAGE);
int readBlocksAndWriteBlock = Math.min((int)(memory/BLOCK_SIZE), blockDescriptors.size()+1);
int readBlocks = readBlocksAndWriteBlock - 1;
int sources = blockDescriptors.size();
String intermediateMerge = prefix+File.separator+"intermediate-merge-target.";
List<InvertedListDescriptor> mergedDescriptors=null;
String fileName=null;
int totalMergeFiles = 0;
while(sources > 0) {
assert sources >= readBlocks;
InvertedFileReader[] readers = new InvertedFileReader[readBlocks];
@SuppressWarnings("unchecked")
List<InvertedListDescriptor>[] descriptors = new List[readBlocks];
Iterator<Map.Entry<String, List<InvertedListDescriptor>>> bditerator = blockDescriptors.iterator();
int i=0;
if(mergedDescriptors != null) {
assert fileName != null;
descriptors[0] = mergedDescriptors;
readers[0] = new InvertedFileReader();
readers[0].setBlockSize(BLOCK_SIZE);
readers[0].open(fileName);
i = 1;
}
for(; i < readBlocks; i++) {
Map.Entry<String, List<InvertedListDescriptor>> id = bditerator.next();
descriptors[i] = id.getValue();
readers[i] = new InvertedFileReader();
readers[i].setBlockSize(BLOCK_SIZE);
readers[i].open(id.getKey());
}
boolean finalPass = (((sources - readBlocks) > 0) ? false : true);
if(finalPass) {
fileName = intermediateMerge+Integer.toString(totalMergeFiles);
totalMergeFiles++;
} else {
fileName = mergeTarget;
}
InvertedFileWriter writer = new RawInvertedFileWriter();
writer.setBlockSize(BLOCK_SIZE);
writer.open(fileName);
mergedDescriptors = merge(readers, descriptors, writer);
sources -= readBlocks;
readBlocks = Math.min((int)(memory/BLOCK_SIZE), sources);
}
for(int i = 0; i < totalMergeFiles-1; i++) {
String name = intermediateMerge+Integer.toString(totalMergeFiles);
if(!(new File(name).delete())) {
System.err.println("failed to delete "+name);
}
}
return mergedDescriptors;
}
| public List<InvertedListDescriptor> mergeBlocks(String mergeTarget, LinkedList<Map.Entry<String, List<InvertedListDescriptor>>> blockDescriptors) {
long memory = (long)(((double)Config.getPhysicalMemorySize()) * MEMORY_PERCENTAGE);
int readBlocksAndWriteBlock = Math.min((int)(memory/BLOCK_SIZE), blockDescriptors.size()+1);
int readBlocks = readBlocksAndWriteBlock - 1;
int sources = blockDescriptors.size();
String intermediateMerge = prefix+File.separator+"intermediate-merge-target.";
List<InvertedListDescriptor> mergedDescriptors=null;
String fileName=null;
int totalMergeFiles = 0;
while(sources > 0) {
assert sources >= readBlocks;
InvertedFileReader[] readers = new InvertedFileReader[readBlocks];
@SuppressWarnings("unchecked")
List<InvertedListDescriptor>[] descriptors = new List[readBlocks];
Iterator<Map.Entry<String, List<InvertedListDescriptor>>> bditerator = blockDescriptors.iterator();
int i=0;
if(mergedDescriptors != null) {
assert fileName != null;
descriptors[0] = mergedDescriptors;
readers[0] = new InvertedFileReader();
readers[0].setBlockSize(BLOCK_SIZE);
readers[0].open(fileName);
i = 1;
}
for(; i < readBlocks; i++) {
Map.Entry<String, List<InvertedListDescriptor>> id = bditerator.next();
descriptors[i] = id.getValue();
readers[i] = new InvertedFileReader();
readers[i].setBlockSize(BLOCK_SIZE);
readers[i].open(id.getKey());
}
boolean finalPass = (((sources - readBlocks) > 0) ? true : false);
if(finalPass) {
fileName = intermediateMerge+Integer.toString(totalMergeFiles);
totalMergeFiles++;
} else {
fileName = mergeTarget;
}
InvertedFileWriter writer = new RawInvertedFileWriter();
writer.setBlockSize(BLOCK_SIZE);
writer.open(fileName);
mergedDescriptors = merge(readers, descriptors, writer);
sources -= readBlocks;
readBlocks = Math.min((int)(memory/BLOCK_SIZE), sources);
}
/*
for(int i = 0; i < totalMergeFiles-1; i++) {
String name = intermediateMerge+Integer.toString(totalMergeFiles);
if(!(new File(name).delete())) {
System.err.println("failed to delete "+name);
}
}
*/
return mergedDescriptors;
}
|
diff --git a/ui/dwr/demo/java/com/example/dwr/simple/Demo.java b/ui/dwr/demo/java/com/example/dwr/simple/Demo.java
index a9ed5907..7a15672a 100755
--- a/ui/dwr/demo/java/com/example/dwr/simple/Demo.java
+++ b/ui/dwr/demo/java/com/example/dwr/simple/Demo.java
@@ -1,52 +1,52 @@
/*
* Copyright 2005 Joe Walker
*
* 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.example.dwr.simple;
import java.io.IOException;
import javax.servlet.ServletException;
import org.directwebremoting.WebContext;
import org.directwebremoting.WebContextFactory;
/**
* Some simple text demos
* @author Joe Walker [joe at getahead dot ltd dot uk]
*/
public class Demo
{
/**
* Return a server side string to display on the client in real time
* @param name The name of person to say hello to
* @return A demo string
*/
public String sayHello(String name)
{
return "Hello, " + name;
}
/**
* Fetch a resource using forwardToString()
* @return a demo HTML page
* @throws ServletException If the servlet engine breaks
* @throws IOException If the servlet engine breaks
*/
public String getInclude() throws ServletException, IOException
{
WebContext wctx = WebContextFactory.get();
- return wctx.forwardToString("/simpletext/forward.html");
+ return wctx.forwardToString("/simple/forward.html");
}
}
| true | true | public String getInclude() throws ServletException, IOException
{
WebContext wctx = WebContextFactory.get();
return wctx.forwardToString("/simpletext/forward.html");
}
| public String getInclude() throws ServletException, IOException
{
WebContext wctx = WebContextFactory.get();
return wctx.forwardToString("/simple/forward.html");
}
|
diff --git a/src/java/org/httpkit/server/HttpRequest.java b/src/java/org/httpkit/server/HttpRequest.java
index 952aaf7..b8e0926 100644
--- a/src/java/org/httpkit/server/HttpRequest.java
+++ b/src/java/org/httpkit/server/HttpRequest.java
@@ -1,112 +1,112 @@
package org.httpkit.server;
import static org.httpkit.HttpUtils.CHARSET;
import static org.httpkit.HttpUtils.CONNECTION;
import static org.httpkit.HttpUtils.CONTENT_TYPE;
import static org.httpkit.HttpVersion.HTTP_1_1;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.util.Map;
import org.httpkit.*;
public class HttpRequest {
public final String queryString;
public final String uri;
public final HttpMethod method;
public final HttpVersion version;
private byte[] body;
// package visible
int serverPort = 80;
String serverName;
Map<String, String> headers;
int contentLength = 0;
String contentType;
String charset = "utf8";
boolean isKeepAlive = false;
boolean isWebSocket = false;
InetSocketAddress remoteAddr;
AsyncChannel channel;
public HttpRequest(HttpMethod method, String url, HttpVersion version) {
this.method = method;
this.version = version;
int idx = url.indexOf('?');
if (idx > 0) {
uri = url.substring(0, idx);
queryString = url.substring(idx + 1);
} else {
uri = url;
queryString = null;
}
}
public InputStream getBody() {
if (body != null) {
return new BytesInputStream(body, contentLength);
}
return null;
}
public String getRemoteAddr() {
String h = headers.get(HttpUtils.X_FORWARDED_FOR);
if (null != h) {
int idx = h.indexOf(',');
if (idx == -1) {
return h;
} else {
// X-Forwarded-For: client, proxy1, proxy2
return h.substring(0, idx);
}
} else {
return remoteAddr.getAddress().getHostAddress();
}
}
public void setBody(byte[] body, int count) {
this.body = body;
this.contentLength = count;
}
public void setHeaders(Map<String, String> headers) {
String h = headers.get("host");
if (h != null) {
- int idx = h.indexOf(':');
+ int idx = h.lastIndexOf(':');
if (idx != -1) {
this.serverName = h.substring(0, idx);
serverPort = Integer.valueOf(h.substring(idx + 1));
} else {
this.serverName = h;
}
}
String ct = headers.get(CONTENT_TYPE);
if (ct != null) {
int idx = ct.indexOf(";");
if (idx != -1) {
int cidx = ct.indexOf(CHARSET, idx);
if (cidx != -1) {
contentType = ct.substring(0, idx);
charset = ct.substring(cidx + CHARSET.length());
} else {
contentType = ct;
}
} else {
contentType = ct;
}
}
String con = headers.get(CONNECTION);
if (con != null) {
con = con.toLowerCase();
}
isKeepAlive = (version == HTTP_1_1 && !"close".equals(con)) || "keep-alive".equals(con);
isWebSocket = "websocket".equalsIgnoreCase(headers.get("upgrade"));
this.headers = headers;
}
}
| true | true | public void setHeaders(Map<String, String> headers) {
String h = headers.get("host");
if (h != null) {
int idx = h.indexOf(':');
if (idx != -1) {
this.serverName = h.substring(0, idx);
serverPort = Integer.valueOf(h.substring(idx + 1));
} else {
this.serverName = h;
}
}
String ct = headers.get(CONTENT_TYPE);
if (ct != null) {
int idx = ct.indexOf(";");
if (idx != -1) {
int cidx = ct.indexOf(CHARSET, idx);
if (cidx != -1) {
contentType = ct.substring(0, idx);
charset = ct.substring(cidx + CHARSET.length());
} else {
contentType = ct;
}
} else {
contentType = ct;
}
}
String con = headers.get(CONNECTION);
if (con != null) {
con = con.toLowerCase();
}
isKeepAlive = (version == HTTP_1_1 && !"close".equals(con)) || "keep-alive".equals(con);
isWebSocket = "websocket".equalsIgnoreCase(headers.get("upgrade"));
this.headers = headers;
}
| public void setHeaders(Map<String, String> headers) {
String h = headers.get("host");
if (h != null) {
int idx = h.lastIndexOf(':');
if (idx != -1) {
this.serverName = h.substring(0, idx);
serverPort = Integer.valueOf(h.substring(idx + 1));
} else {
this.serverName = h;
}
}
String ct = headers.get(CONTENT_TYPE);
if (ct != null) {
int idx = ct.indexOf(";");
if (idx != -1) {
int cidx = ct.indexOf(CHARSET, idx);
if (cidx != -1) {
contentType = ct.substring(0, idx);
charset = ct.substring(cidx + CHARSET.length());
} else {
contentType = ct;
}
} else {
contentType = ct;
}
}
String con = headers.get(CONNECTION);
if (con != null) {
con = con.toLowerCase();
}
isKeepAlive = (version == HTTP_1_1 && !"close".equals(con)) || "keep-alive".equals(con);
isWebSocket = "websocket".equalsIgnoreCase(headers.get("upgrade"));
this.headers = headers;
}
|
diff --git a/de.walware.statet.r.ui/srcDebug/de/walware/statet/r/internal/debug/preferences/RInteractionPreferencePage.java b/de.walware.statet.r.ui/srcDebug/de/walware/statet/r/internal/debug/preferences/RInteractionPreferencePage.java
index 41674dfc..0152eeb9 100644
--- a/de.walware.statet.r.ui/srcDebug/de/walware/statet/r/internal/debug/preferences/RInteractionPreferencePage.java
+++ b/de.walware.statet.r.ui/srcDebug/de/walware/statet/r/internal/debug/preferences/RInteractionPreferencePage.java
@@ -1,157 +1,159 @@
/*******************************************************************************
* Copyright (c) 2005 StatET-Project (www.walware.de/goto/statet).
* 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:
* Stephan Wahlbrink - initial API and implementation
*******************************************************************************/
package de.walware.statet.r.internal.debug.preferences;
import static de.walware.statet.r.launching.RCodeLaunchRegistry.PREF_R_CONNECTOR;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.ScrolledComposite;
import org.eclipse.swt.events.ControlListener;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Link;
import org.eclipse.ui.preferences.IWorkbenchPreferenceContainer;
import de.walware.eclipsecommon.preferences.Preference;
import de.walware.eclipsecommon.ui.dialogs.Layouter;
import de.walware.eclipsecommon.ui.preferences.ConfigurationBlockPreferencePage;
import de.walware.eclipsecommon.ui.util.PixelConverter;
import de.walware.statet.base.StatetPlugin;
import de.walware.statet.ext.ui.preferences.ManagedConfigurationBlock;
import de.walware.statet.r.launching.RCodeLaunchRegistry;
public class RInteractionPreferencePage extends ConfigurationBlockPreferencePage<RInteractionConfigurationBlock> {
public RInteractionPreferencePage() {
setPreferenceStore(StatetPlugin.getDefault().getPreferenceStore());
setDescription(Messages.RInteraction_description);
}
@Override
protected RInteractionConfigurationBlock createConfigurationBlock() {
return new RInteractionConfigurationBlock();
}
}
class RInteractionConfigurationBlock extends ManagedConfigurationBlock {
private RCodeLaunchRegistry.ConnectorConfig[] fConnectors;
private Combo fConnectorsSelector;
private Link fConnectorsDescription;
RInteractionConfigurationBlock () {
super(null);
}
@Override
public void createContents(Layouter layouter, IWorkbenchPreferenceContainer container, IPreferenceStore preferenceStore) {
super.createContents(layouter, container, preferenceStore);
layouter.addFiller();
createConnectorComponent(layouter, container);
loadValues();
}
private void createConnectorComponent(Layouter parent, IWorkbenchPreferenceContainer container) {
fConnectors = RCodeLaunchRegistry.getAvailableConnectors();
setupPreferenceManager(container, new Preference[] {
PREF_R_CONNECTOR,
} );
String[] connectorLabels = new String[fConnectors.length];
for (int i = 0; i < fConnectors.length; i++) {
connectorLabels[i] = fConnectors[i].fName;
}
Group group = parent.addGroup(Messages.RInteraction_RConnector);
Layouter layouter = new Layouter(group, 2);
fConnectorsSelector = layouter.addComboControl(connectorLabels, 2);
// Description
layouter.addLabel(Messages.RInteraction_RConnector_Description_label, 0, 1);
ScrolledComposite scrolled = new ScrolledComposite(layouter.fComposite, SWT.V_SCROLL);
fConnectorsDescription = addLinkControl(scrolled, "");
scrolled.addControlListener(new ControlListener() {
public void controlMoved(org.eclipse.swt.events.ControlEvent e) {};
public void controlResized(org.eclipse.swt.events.ControlEvent e) {
updateDescriptionSize();
};
});
GridData gd = new GridData(SWT.FILL, SWT.FILL, true, false);
PixelConverter pixelConverter = new PixelConverter(fConnectorsDescription);
gd.horizontalSpan = 1;
gd.widthHint = pixelConverter.convertWidthInCharsToPixels(40);
gd.heightHint = pixelConverter.convertHeightInCharsToPixels(3);
scrolled.setLayoutData(gd);
scrolled.setContent(fConnectorsDescription);
fConnectorsSelector.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
int idx = fConnectorsSelector.getSelectionIndex();
- setPrefValue(PREF_R_CONNECTOR, fConnectors[idx].fId);
- String description = fConnectors[idx].fDescription;
- if (description == null) {
- description = "";
+ if (idx >= 0) {
+ setPrefValue(PREF_R_CONNECTOR, fConnectors[idx].fId);
+ String description = fConnectors[idx].fDescription;
+ if (description == null) {
+ description = "";
+ }
+ fConnectorsDescription.setText(description);
+ updateDescriptionSize();
}
- fConnectorsDescription.setText(description);
- updateDescriptionSize();
};
});
}
private void updateDescriptionSize() {
Composite scroller = fConnectorsDescription.getParent();
int widthHint = fConnectorsDescription.getParent().getClientArea().width;
if (!scroller.getVerticalBar().isVisible())
widthHint -= scroller.getVerticalBar().getSize().x;
fConnectorsDescription.setSize(fConnectorsDescription.computeSize(
widthHint, SWT.DEFAULT));
}
@Override
protected void updateControls() {
loadValues();
}
private void loadValues() {
String selectedConnector = getPreferenceValue(PREF_R_CONNECTOR);
for (int i = 0; i < fConnectors.length; i++) {
if (selectedConnector.equals(fConnectors[i].fId))
fConnectorsSelector.select(i);
}
}
}
| false | true | private void createConnectorComponent(Layouter parent, IWorkbenchPreferenceContainer container) {
fConnectors = RCodeLaunchRegistry.getAvailableConnectors();
setupPreferenceManager(container, new Preference[] {
PREF_R_CONNECTOR,
} );
String[] connectorLabels = new String[fConnectors.length];
for (int i = 0; i < fConnectors.length; i++) {
connectorLabels[i] = fConnectors[i].fName;
}
Group group = parent.addGroup(Messages.RInteraction_RConnector);
Layouter layouter = new Layouter(group, 2);
fConnectorsSelector = layouter.addComboControl(connectorLabels, 2);
// Description
layouter.addLabel(Messages.RInteraction_RConnector_Description_label, 0, 1);
ScrolledComposite scrolled = new ScrolledComposite(layouter.fComposite, SWT.V_SCROLL);
fConnectorsDescription = addLinkControl(scrolled, "");
scrolled.addControlListener(new ControlListener() {
public void controlMoved(org.eclipse.swt.events.ControlEvent e) {};
public void controlResized(org.eclipse.swt.events.ControlEvent e) {
updateDescriptionSize();
};
});
GridData gd = new GridData(SWT.FILL, SWT.FILL, true, false);
PixelConverter pixelConverter = new PixelConverter(fConnectorsDescription);
gd.horizontalSpan = 1;
gd.widthHint = pixelConverter.convertWidthInCharsToPixels(40);
gd.heightHint = pixelConverter.convertHeightInCharsToPixels(3);
scrolled.setLayoutData(gd);
scrolled.setContent(fConnectorsDescription);
fConnectorsSelector.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
int idx = fConnectorsSelector.getSelectionIndex();
setPrefValue(PREF_R_CONNECTOR, fConnectors[idx].fId);
String description = fConnectors[idx].fDescription;
if (description == null) {
description = "";
}
fConnectorsDescription.setText(description);
updateDescriptionSize();
};
});
}
| private void createConnectorComponent(Layouter parent, IWorkbenchPreferenceContainer container) {
fConnectors = RCodeLaunchRegistry.getAvailableConnectors();
setupPreferenceManager(container, new Preference[] {
PREF_R_CONNECTOR,
} );
String[] connectorLabels = new String[fConnectors.length];
for (int i = 0; i < fConnectors.length; i++) {
connectorLabels[i] = fConnectors[i].fName;
}
Group group = parent.addGroup(Messages.RInteraction_RConnector);
Layouter layouter = new Layouter(group, 2);
fConnectorsSelector = layouter.addComboControl(connectorLabels, 2);
// Description
layouter.addLabel(Messages.RInteraction_RConnector_Description_label, 0, 1);
ScrolledComposite scrolled = new ScrolledComposite(layouter.fComposite, SWT.V_SCROLL);
fConnectorsDescription = addLinkControl(scrolled, "");
scrolled.addControlListener(new ControlListener() {
public void controlMoved(org.eclipse.swt.events.ControlEvent e) {};
public void controlResized(org.eclipse.swt.events.ControlEvent e) {
updateDescriptionSize();
};
});
GridData gd = new GridData(SWT.FILL, SWT.FILL, true, false);
PixelConverter pixelConverter = new PixelConverter(fConnectorsDescription);
gd.horizontalSpan = 1;
gd.widthHint = pixelConverter.convertWidthInCharsToPixels(40);
gd.heightHint = pixelConverter.convertHeightInCharsToPixels(3);
scrolled.setLayoutData(gd);
scrolled.setContent(fConnectorsDescription);
fConnectorsSelector.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
int idx = fConnectorsSelector.getSelectionIndex();
if (idx >= 0) {
setPrefValue(PREF_R_CONNECTOR, fConnectors[idx].fId);
String description = fConnectors[idx].fDescription;
if (description == null) {
description = "";
}
fConnectorsDescription.setText(description);
updateDescriptionSize();
}
};
});
}
|
diff --git a/aufgabe2/GeometryTest.java b/aufgabe2/GeometryTest.java
index a8862f2..4e310ea 100644
--- a/aufgabe2/GeometryTest.java
+++ b/aufgabe2/GeometryTest.java
@@ -1,104 +1,104 @@
class GeometryTest {
public static void main(String[] args) {
if (args.length != 0) {
switch(Integer.parseInt(args[0])) {
case 1:
double x = Double.parseDouble(args[1]);
double y = Double.parseDouble(args[2]);
Point p = new Point(x,y);
System.out.println(p);
break;
case 2:
double x1 = Double.parseDouble(args[1]);
double x2 = Double.parseDouble(args[2]);
double y1 = Double.parseDouble(args[3]);
double y2 = Double.parseDouble(args[4]);
Line l = new Line(x1,x2,y1,y2);
System.out.println(l);
break;
default:
break;
}
}
- public class Square {
+ class Square {
/**
* k is the length of one side of a square.
*/
double k;
/**
* a,b,c,d are the points of a square
*/
Point a;
Point b;
Point c;
Point d;
/**
* Empty constructor, creates a square at coordinates ((0,0),(1,0),(0,1),(1,1)) with edge length 1
*/
Square() {
a = new Point(0,0);
b = new Point(1,0);
c = new Point(0,1);
d = new Point(1,1);
k = 1;
}
/**
* Constructor that creates specified square
* @param a is the point
* @param k is the edge length
*/
Square(Point a, double k) {
a = a;
b = new Point((a.getX()+k),(a.getY()));
c = new Point(a.getX(),a.getY()+k);
d = new Point(a.getX()+k,a.getY()+k);
k = k;
}
Square(double x1, double y1, double k){
a = new Point(x1,y1);
this.k = k;
}
/**
* Move this square to a new position.
* @param x1 the distance from current position in x direction
* @param y1 the distance from current position in y direction
*/
void shiftSquare(double x1, double y1){
this.a.shift(x1,y1);
this.b.shift(x1,y1);
this.c.shift(x1,y1);
this.d.shift(x1,y1);
}
/**
* Creates a line from the point a and b
* @param q is the square
* @return the line from the point a and b of the square
*/
Line lineBack(Square q){
Line qline = new Line(q.a,q.b);
return qline;
}
/**
* Creates a string with the coordinates of the points of the square and the edge length
* @param q is the square
* @return a string with the coordinates of the points and the edge length
*/
static String toString(Square q){
String x = "Punkt a: ("+q.a.getX()+","+q.a.getY()+") "+
"Punkt b: ("+q.b.getX()+","+q.b.getY()+") "+
"Punkt c: ("+q.c.getX()+","+q.c.getY()+") "+
"Punkt d: ("+q.d.getX()+","+q.d.getY()+") "+
- "Kantenl�nge:"+q.k;
+ "Kantenlaenge:"+q.k;
return x;
}
}
}
}
| false | true | public static void main(String[] args) {
if (args.length != 0) {
switch(Integer.parseInt(args[0])) {
case 1:
double x = Double.parseDouble(args[1]);
double y = Double.parseDouble(args[2]);
Point p = new Point(x,y);
System.out.println(p);
break;
case 2:
double x1 = Double.parseDouble(args[1]);
double x2 = Double.parseDouble(args[2]);
double y1 = Double.parseDouble(args[3]);
double y2 = Double.parseDouble(args[4]);
Line l = new Line(x1,x2,y1,y2);
System.out.println(l);
break;
default:
break;
}
}
public class Square {
/**
* k is the length of one side of a square.
*/
double k;
/**
* a,b,c,d are the points of a square
*/
Point a;
Point b;
Point c;
Point d;
/**
* Empty constructor, creates a square at coordinates ((0,0),(1,0),(0,1),(1,1)) with edge length 1
*/
Square() {
a = new Point(0,0);
b = new Point(1,0);
c = new Point(0,1);
d = new Point(1,1);
k = 1;
}
/**
* Constructor that creates specified square
* @param a is the point
* @param k is the edge length
*/
Square(Point a, double k) {
a = a;
b = new Point((a.getX()+k),(a.getY()));
c = new Point(a.getX(),a.getY()+k);
d = new Point(a.getX()+k,a.getY()+k);
k = k;
}
Square(double x1, double y1, double k){
a = new Point(x1,y1);
this.k = k;
}
/**
* Move this square to a new position.
* @param x1 the distance from current position in x direction
* @param y1 the distance from current position in y direction
*/
void shiftSquare(double x1, double y1){
this.a.shift(x1,y1);
this.b.shift(x1,y1);
this.c.shift(x1,y1);
this.d.shift(x1,y1);
}
/**
* Creates a line from the point a and b
* @param q is the square
* @return the line from the point a and b of the square
*/
Line lineBack(Square q){
Line qline = new Line(q.a,q.b);
return qline;
}
/**
* Creates a string with the coordinates of the points of the square and the edge length
* @param q is the square
* @return a string with the coordinates of the points and the edge length
*/
static String toString(Square q){
String x = "Punkt a: ("+q.a.getX()+","+q.a.getY()+") "+
"Punkt b: ("+q.b.getX()+","+q.b.getY()+") "+
"Punkt c: ("+q.c.getX()+","+q.c.getY()+") "+
"Punkt d: ("+q.d.getX()+","+q.d.getY()+") "+
"Kantenl�nge:"+q.k;
return x;
}
}
}
| public static void main(String[] args) {
if (args.length != 0) {
switch(Integer.parseInt(args[0])) {
case 1:
double x = Double.parseDouble(args[1]);
double y = Double.parseDouble(args[2]);
Point p = new Point(x,y);
System.out.println(p);
break;
case 2:
double x1 = Double.parseDouble(args[1]);
double x2 = Double.parseDouble(args[2]);
double y1 = Double.parseDouble(args[3]);
double y2 = Double.parseDouble(args[4]);
Line l = new Line(x1,x2,y1,y2);
System.out.println(l);
break;
default:
break;
}
}
class Square {
/**
* k is the length of one side of a square.
*/
double k;
/**
* a,b,c,d are the points of a square
*/
Point a;
Point b;
Point c;
Point d;
/**
* Empty constructor, creates a square at coordinates ((0,0),(1,0),(0,1),(1,1)) with edge length 1
*/
Square() {
a = new Point(0,0);
b = new Point(1,0);
c = new Point(0,1);
d = new Point(1,1);
k = 1;
}
/**
* Constructor that creates specified square
* @param a is the point
* @param k is the edge length
*/
Square(Point a, double k) {
a = a;
b = new Point((a.getX()+k),(a.getY()));
c = new Point(a.getX(),a.getY()+k);
d = new Point(a.getX()+k,a.getY()+k);
k = k;
}
Square(double x1, double y1, double k){
a = new Point(x1,y1);
this.k = k;
}
/**
* Move this square to a new position.
* @param x1 the distance from current position in x direction
* @param y1 the distance from current position in y direction
*/
void shiftSquare(double x1, double y1){
this.a.shift(x1,y1);
this.b.shift(x1,y1);
this.c.shift(x1,y1);
this.d.shift(x1,y1);
}
/**
* Creates a line from the point a and b
* @param q is the square
* @return the line from the point a and b of the square
*/
Line lineBack(Square q){
Line qline = new Line(q.a,q.b);
return qline;
}
/**
* Creates a string with the coordinates of the points of the square and the edge length
* @param q is the square
* @return a string with the coordinates of the points and the edge length
*/
static String toString(Square q){
String x = "Punkt a: ("+q.a.getX()+","+q.a.getY()+") "+
"Punkt b: ("+q.b.getX()+","+q.b.getY()+") "+
"Punkt c: ("+q.c.getX()+","+q.c.getY()+") "+
"Punkt d: ("+q.d.getX()+","+q.d.getY()+") "+
"Kantenlaenge:"+q.k;
return x;
}
}
}
|
diff --git a/src/main/java/org/primefaces/component/behavior/ajax/AjaxBehaviorRenderer.java b/src/main/java/org/primefaces/component/behavior/ajax/AjaxBehaviorRenderer.java
index f521e73b1..c40e3d95c 100644
--- a/src/main/java/org/primefaces/component/behavior/ajax/AjaxBehaviorRenderer.java
+++ b/src/main/java/org/primefaces/component/behavior/ajax/AjaxBehaviorRenderer.java
@@ -1,139 +1,137 @@
/*
* Copyright 2009-2011 Prime Technology.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.primefaces.component.behavior.ajax;
import javax.faces.component.ActionSource;
import javax.faces.component.EditableValueHolder;
import javax.faces.component.UIComponent;
import javax.faces.component.UIParameter;
import javax.faces.component.behavior.ClientBehavior;
import javax.faces.component.behavior.ClientBehaviorContext;
import javax.faces.context.FacesContext;
import javax.faces.event.AjaxBehaviorEvent;
import javax.faces.event.PhaseId;
import javax.faces.render.ClientBehaviorRenderer;
import org.primefaces.util.ComponentUtils;
public class AjaxBehaviorRenderer extends ClientBehaviorRenderer {
@Override
public void decode(FacesContext context, UIComponent component, ClientBehavior behavior) {
AjaxBehavior ajaxBehavior = (AjaxBehavior) behavior;
if(!ajaxBehavior.isDisabled()) {
AjaxBehaviorEvent event = new AjaxBehaviorEvent(component, behavior);
PhaseId phaseId = isImmediate(component, ajaxBehavior) ? PhaseId.APPLY_REQUEST_VALUES : PhaseId.INVOKE_APPLICATION;
event.setPhaseId(phaseId);
component.queueEvent(event);
}
}
@Override
public String getScript(ClientBehaviorContext behaviorContext, ClientBehavior behavior) {
AjaxBehavior ajaxBehavior = (AjaxBehavior) behavior;
if(ajaxBehavior.isDisabled()) {
return null;
}
FacesContext fc = behaviorContext.getFacesContext();
UIComponent component = behaviorContext.getComponent();
String clientId = component.getClientId(fc);
String source = behaviorContext.getSourceId();
- if(source == null) {
- source = component.getClientId(fc);
- }
+ source = source == null ? "this" : "'" + source + "'";
StringBuilder req = new StringBuilder();
req.append("PrimeFaces.ab(");
//source
- req.append("{source:").append("'").append(source).append("'");
+ req.append("{source:").append(source);
//process
String process = ajaxBehavior.getProcess() != null ? ComponentUtils.findClientIds(fc, component, ajaxBehavior.getProcess()) : clientId;
req.append(",process:'").append(process).append("'");
//update
if (ajaxBehavior.getUpdate() != null) {
req.append(",update:'").append(ComponentUtils.findClientIds(fc, component, ajaxBehavior.getUpdate())).append("'");
}
//behavior event
req.append(",event:'").append(behaviorContext.getEventName()).append("'");
//async
if(ajaxBehavior.isAsync())
req.append(",async:true");
//global
if(!ajaxBehavior.isGlobal())
req.append(",global:false");
//callbacks
if(ajaxBehavior.getOnstart() != null)
req.append(",onstart:function(xhr){").append(ajaxBehavior.getOnstart()).append(";}");
if(ajaxBehavior.getOnerror() != null)
req.append(",onerror:function(xhr, status, error){").append(ajaxBehavior.getOnerror()).append(";}");
if(ajaxBehavior.getOnsuccess() != null)
req.append(",onsuccess:function(data, status, xhr){").append(ajaxBehavior.getOnsuccess()).append(";}");
if(ajaxBehavior.getOncomplete() != null)
req.append(",oncomplete:function(xhr, status, args){").append(ajaxBehavior.getOncomplete()).append(";}");
//params
boolean paramWritten = false;
for(UIComponent child : component.getChildren()) {
if(child instanceof UIParameter) {
UIParameter parameter = (UIParameter) child;
if(!paramWritten) {
paramWritten = true;
req.append(",params:{");
} else {
req.append(",");
}
req.append("'").append(parameter.getName()).append("':'").append(parameter.getValue()).append("'");
}
}
if(paramWritten) {
req.append("}");
}
req.append("}, arguments[1]);");
return req.toString();
}
private boolean isImmediate(UIComponent component, AjaxBehavior ajaxBehavior) {
boolean immediate = false;
if(ajaxBehavior.isImmediateSet()) {
immediate = ajaxBehavior.isImmediate();
} else if(component instanceof EditableValueHolder) {
immediate = ((EditableValueHolder)component).isImmediate();
} else if(component instanceof ActionSource) {
immediate = ((ActionSource)component).isImmediate();
}
return immediate;
}
}
| false | true | public String getScript(ClientBehaviorContext behaviorContext, ClientBehavior behavior) {
AjaxBehavior ajaxBehavior = (AjaxBehavior) behavior;
if(ajaxBehavior.isDisabled()) {
return null;
}
FacesContext fc = behaviorContext.getFacesContext();
UIComponent component = behaviorContext.getComponent();
String clientId = component.getClientId(fc);
String source = behaviorContext.getSourceId();
if(source == null) {
source = component.getClientId(fc);
}
StringBuilder req = new StringBuilder();
req.append("PrimeFaces.ab(");
//source
req.append("{source:").append("'").append(source).append("'");
//process
String process = ajaxBehavior.getProcess() != null ? ComponentUtils.findClientIds(fc, component, ajaxBehavior.getProcess()) : clientId;
req.append(",process:'").append(process).append("'");
//update
if (ajaxBehavior.getUpdate() != null) {
req.append(",update:'").append(ComponentUtils.findClientIds(fc, component, ajaxBehavior.getUpdate())).append("'");
}
//behavior event
req.append(",event:'").append(behaviorContext.getEventName()).append("'");
//async
if(ajaxBehavior.isAsync())
req.append(",async:true");
//global
if(!ajaxBehavior.isGlobal())
req.append(",global:false");
//callbacks
if(ajaxBehavior.getOnstart() != null)
req.append(",onstart:function(xhr){").append(ajaxBehavior.getOnstart()).append(";}");
if(ajaxBehavior.getOnerror() != null)
req.append(",onerror:function(xhr, status, error){").append(ajaxBehavior.getOnerror()).append(";}");
if(ajaxBehavior.getOnsuccess() != null)
req.append(",onsuccess:function(data, status, xhr){").append(ajaxBehavior.getOnsuccess()).append(";}");
if(ajaxBehavior.getOncomplete() != null)
req.append(",oncomplete:function(xhr, status, args){").append(ajaxBehavior.getOncomplete()).append(";}");
//params
boolean paramWritten = false;
for(UIComponent child : component.getChildren()) {
if(child instanceof UIParameter) {
UIParameter parameter = (UIParameter) child;
if(!paramWritten) {
paramWritten = true;
req.append(",params:{");
} else {
req.append(",");
}
req.append("'").append(parameter.getName()).append("':'").append(parameter.getValue()).append("'");
}
}
if(paramWritten) {
req.append("}");
}
req.append("}, arguments[1]);");
return req.toString();
}
| public String getScript(ClientBehaviorContext behaviorContext, ClientBehavior behavior) {
AjaxBehavior ajaxBehavior = (AjaxBehavior) behavior;
if(ajaxBehavior.isDisabled()) {
return null;
}
FacesContext fc = behaviorContext.getFacesContext();
UIComponent component = behaviorContext.getComponent();
String clientId = component.getClientId(fc);
String source = behaviorContext.getSourceId();
source = source == null ? "this" : "'" + source + "'";
StringBuilder req = new StringBuilder();
req.append("PrimeFaces.ab(");
//source
req.append("{source:").append(source);
//process
String process = ajaxBehavior.getProcess() != null ? ComponentUtils.findClientIds(fc, component, ajaxBehavior.getProcess()) : clientId;
req.append(",process:'").append(process).append("'");
//update
if (ajaxBehavior.getUpdate() != null) {
req.append(",update:'").append(ComponentUtils.findClientIds(fc, component, ajaxBehavior.getUpdate())).append("'");
}
//behavior event
req.append(",event:'").append(behaviorContext.getEventName()).append("'");
//async
if(ajaxBehavior.isAsync())
req.append(",async:true");
//global
if(!ajaxBehavior.isGlobal())
req.append(",global:false");
//callbacks
if(ajaxBehavior.getOnstart() != null)
req.append(",onstart:function(xhr){").append(ajaxBehavior.getOnstart()).append(";}");
if(ajaxBehavior.getOnerror() != null)
req.append(",onerror:function(xhr, status, error){").append(ajaxBehavior.getOnerror()).append(";}");
if(ajaxBehavior.getOnsuccess() != null)
req.append(",onsuccess:function(data, status, xhr){").append(ajaxBehavior.getOnsuccess()).append(";}");
if(ajaxBehavior.getOncomplete() != null)
req.append(",oncomplete:function(xhr, status, args){").append(ajaxBehavior.getOncomplete()).append(";}");
//params
boolean paramWritten = false;
for(UIComponent child : component.getChildren()) {
if(child instanceof UIParameter) {
UIParameter parameter = (UIParameter) child;
if(!paramWritten) {
paramWritten = true;
req.append(",params:{");
} else {
req.append(",");
}
req.append("'").append(parameter.getName()).append("':'").append(parameter.getValue()).append("'");
}
}
if(paramWritten) {
req.append("}");
}
req.append("}, arguments[1]);");
return req.toString();
}
|
diff --git a/ui_swing/src/com/dmdirc/addons/ui_swing/components/GenericTableModel.java b/ui_swing/src/com/dmdirc/addons/ui_swing/components/GenericTableModel.java
index e216e10a..186375e4 100644
--- a/ui_swing/src/com/dmdirc/addons/ui_swing/components/GenericTableModel.java
+++ b/ui_swing/src/com/dmdirc/addons/ui_swing/components/GenericTableModel.java
@@ -1,249 +1,249 @@
/*
* Copyright (c) 2006-2015 DMDirc Developers
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.dmdirc.addons.ui_swing.components;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import javax.swing.table.AbstractTableModel;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkElementIndex;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* Table model that display fields from a type of object.
*
* @param <T> Type of object to display
*/
public class GenericTableModel<T> extends AbstractTableModel {
/**
* Serialisation version.
*/
private static final long serialVersionUID = 1L;
/**
* List of values in the model.
*/
private final List<T> values;
/**
* List of getters for each value, used as columns.
*/
private final String[] getters;
/**
* List of header names for each column.
*/
private final String[] headers;
/**
* Generic type this table contains, used to verify getters exist.
*/
private final Class<T> clazz;
/**
* Cached return types for the getters.
*/
private final Class<?>[] columnTypes;
/**
* Creates a new generic table model.
*
* @param type Type to be displayed, used to verify getters
* @param getterValues Names of the getters to display in the table
*/
public GenericTableModel(final Class<T> type, final String... getterValues) {
checkArgument(getterValues.length > 0, "Getters must be set");
clazz = type;
for (String getter : getterValues) {
checkNotNull(getter, "Getter must not be null");
checkArgument(!getter.isEmpty(), "Getter must not be empty");
checkArgument(getGetter(getter).isPresent(), "Getter must exist in type");
}
values = new ArrayList<>();
headers = new String[getterValues.length];
getters = new String[getterValues.length];
- columnTypes = new Class[getterValues.length];
+ columnTypes = new Class<?>[getterValues.length];
for (int i = 0; i < getterValues.length; i++) {
getters[i] = getterValues[i];
headers[i] = getterValues[i];
columnTypes[i] = getGetter(getterValues[i]).get().getReturnType();
}
}
@Override
public int getRowCount() {
return values.size();
}
@Override
public int getColumnCount() {
return getters.length;
}
@Override
public String getColumnName(final int column) {
checkElementIndex(column, headers.length, "Column must exist");
return headers[column];
}
@Override
public Class<?> getColumnClass(final int columnIndex) {
checkElementIndex(columnIndex, getters.length, "Column must exist");
return columnTypes[columnIndex];
}
@Override
public Object getValueAt(final int rowIndex, final int columnIndex) {
checkElementIndex(rowIndex, values.size(), "Row index must exist");
checkElementIndex(columnIndex, getters.length, "Column index must exist");
try {
final T value = values.get(rowIndex);
final Method method = getGetter(getters[columnIndex]).get();
return method.invoke(value);
} catch (IndexOutOfBoundsException | ReflectiveOperationException ex) {
return ex.getMessage();
}
}
/**
* Returns the value at the specified row.
*
* @param rowIndex Index to retrieve
*
* @return Value at the specified row
*/
public T getValue(final int rowIndex) {
checkElementIndex(rowIndex, values.size(), "Row index must exist");
return values.get(rowIndex);
}
/**
* Returns the index of the specified object, or -1 if the object does not exist.
*
* @param object Object to find
*
* @return Item index, or -1 if it did not exist
*/
public int getIndex(final T object) {
return values.indexOf(object);
}
/**
* Sets the name of the header for a specific column.
*
* @param column Column index
* @param header Header name
*/
public void setHeaderName(final int column, final String header) {
checkNotNull(header, "Header must not be null");
checkElementIndex(column, getters.length, "There must be a column for the header");
headers[column] = header;
fireTableStructureChanged();
}
/**
* Sets all of the header names. Must include all the headers, otherwise use
* {@link #setHeaderName(int, String)}.
*
* @param headerValues Names for all headers in the table
*/
public void setHeaderNames(final String... headerValues) {
checkArgument(headerValues.length == getters.length,
"There must be as many headers as columns");
System.arraycopy(headerValues, 0, this.headers, 0, headerValues.length);
fireTableStructureChanged();
}
/**
* Adds the specified value at the specified index, the column is ignored.
*
* @param value Value to add
* @param rowIndex Index of the row to add
* @param columnIndex This is ignored
*/
@Override
@SuppressWarnings("unchecked")
public void setValueAt(final Object value, final int rowIndex, final int columnIndex) {
checkElementIndex(rowIndex, values.size(), "Row index must exist");
checkElementIndex(columnIndex, getters.length, "Column index must exist");
try {
values.add(rowIndex, (T) value);
fireTableRowsInserted(rowIndex, rowIndex);
} catch (ClassCastException ex) {
throw new IllegalArgumentException("Value of incorrect type.", ex);
}
}
/**
* Replaces the value at the specified index with the specified value.
*
* @param value New value to insert
* @param rowIndex Index to replace
*/
public void replaceValueAt(final T value, final int rowIndex) {
checkNotNull(value, "Value must not be null");
checkElementIndex(rowIndex, values.size(), "RowIndex must be valid");
values.remove(rowIndex);
values.add(rowIndex, value);
fireTableRowsUpdated(rowIndex, rowIndex);
}
/**
* Removes a value from the model.
*
* @param value Value to be removed.
*/
public void removeValue(final T value) {
checkArgument(values.contains(value), "Value must exist");
final int index = values.indexOf(value);
values.remove(value);
fireTableRowsDeleted(index, index);
}
/**
* Adds the specified value at the end of the model.
*
* @param value Value to add
*/
public void addValue(final T value) {
values.add(value);
final int index = values.indexOf(value);
fireTableRowsInserted(index, index);
}
/**
* Returns an optional method for the specified name.
*
* @param name Name of the getter
*
* @return Optional method
*/
private Optional<Method> getGetter(final String name) {
try {
return Optional.ofNullable(clazz.getMethod(name));
} catch (NoSuchMethodException ex) {
return Optional.empty();
}
}
}
| true | true | public GenericTableModel(final Class<T> type, final String... getterValues) {
checkArgument(getterValues.length > 0, "Getters must be set");
clazz = type;
for (String getter : getterValues) {
checkNotNull(getter, "Getter must not be null");
checkArgument(!getter.isEmpty(), "Getter must not be empty");
checkArgument(getGetter(getter).isPresent(), "Getter must exist in type");
}
values = new ArrayList<>();
headers = new String[getterValues.length];
getters = new String[getterValues.length];
columnTypes = new Class[getterValues.length];
for (int i = 0; i < getterValues.length; i++) {
getters[i] = getterValues[i];
headers[i] = getterValues[i];
columnTypes[i] = getGetter(getterValues[i]).get().getReturnType();
}
}
| public GenericTableModel(final Class<T> type, final String... getterValues) {
checkArgument(getterValues.length > 0, "Getters must be set");
clazz = type;
for (String getter : getterValues) {
checkNotNull(getter, "Getter must not be null");
checkArgument(!getter.isEmpty(), "Getter must not be empty");
checkArgument(getGetter(getter).isPresent(), "Getter must exist in type");
}
values = new ArrayList<>();
headers = new String[getterValues.length];
getters = new String[getterValues.length];
columnTypes = new Class<?>[getterValues.length];
for (int i = 0; i < getterValues.length; i++) {
getters[i] = getterValues[i];
headers[i] = getterValues[i];
columnTypes[i] = getGetter(getterValues[i]).get().getReturnType();
}
}
|
diff --git a/deprecated/org.atl.eclipse.adt.builder/src/org/atl/eclipse/adt/builder/MarkerMaker.java b/deprecated/org.atl.eclipse.adt.builder/src/org/atl/eclipse/adt/builder/MarkerMaker.java
index cb07b85f..99e64458 100644
--- a/deprecated/org.atl.eclipse.adt.builder/src/org/atl/eclipse/adt/builder/MarkerMaker.java
+++ b/deprecated/org.atl.eclipse.adt.builder/src/org/atl/eclipse/adt/builder/MarkerMaker.java
@@ -1,120 +1,120 @@
/*
* Created on 21 juil. 2004
* @author idrissi
*/
package org.atl.eclipse.adt.builder;
import java.util.HashMap;
import java.util.Map;
import org.atl.eclipse.engine.AtlNbCharFile;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.IWorkspaceRunnable;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EEnumLiteral;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.EStructuralFeature;
/**
* @author idrissi
*
*/
public class MarkerMaker {
private static boolean initialized = false;
private static EPackage pkProblem = null;
private static EClass clProblem = null;
private static EStructuralFeature sfSeverity = null;
private static EStructuralFeature sfLocation = null;
private static EStructuralFeature sfDescription = null;
// private static EEnum enSeverity = null;
private static Map severities = new HashMap();
static {
severities.put("error", new Integer(IMarker.SEVERITY_ERROR));
severities.put("warning", new Integer(IMarker.SEVERITY_WARNING));
severities.put("critic", new Integer(IMarker.SEVERITY_INFO));
}
private void initialize(EObject problem) {
pkProblem = problem.eClass().getEPackage();
clProblem = (EClass)pkProblem.getEClassifier("Problem");
sfSeverity = clProblem.getEStructuralFeature("severity");
sfLocation = clProblem.getEStructuralFeature("location");
sfDescription = clProblem.getEStructuralFeature("description");
// enSeverity = (EEnum)pkProblem.getEClassifier("Severity");
initialized = true;
}
/**
* creates a problem marker from an Eobject. This EObject contain the required information.
* @see org.atl.eclipse.engine.resources#Problem.ecore
* @param res the resource associated to the created marker
* @param eo the EObject representing a problem
*/
private void eObjectToPbmMarker(IResource res, EObject eo) {
String description = (String)eo.eGet(sfDescription);
String location = (String)eo.eGet(sfLocation);
int lineNumber = Integer.parseInt(location.split(":")[0]);
int charStart = 0, charEnd = 0;
try {
AtlNbCharFile help = new AtlNbCharFile(((IFile)res).getContents());
if (location.indexOf('-') == -1) {
location += '-' + location;
}
int[] pos = help.getIndexChar(location);
charStart = pos[0];
charEnd = pos[1];
} catch (CoreException e1) {
e1.printStackTrace();
}
String severity = ((EEnumLiteral)eo.eGet(sfSeverity)).getName();
int eclipseSeverity = ((Integer)severities.get(severity)).intValue();
try {
IMarker pbmMarker = res.createMarker(IMarker.PROBLEM);
pbmMarker.setAttribute(IMarker.SEVERITY, eclipseSeverity);
pbmMarker.setAttribute(IMarker.MESSAGE, description);
pbmMarker.setAttribute(IMarker.LINE_NUMBER, lineNumber);
pbmMarker.setAttribute(IMarker.CHAR_START, charStart);
- pbmMarker.setAttribute(IMarker.CHAR_END, charEnd + 1);
+ pbmMarker.setAttribute(IMarker.CHAR_END, charEnd);
} catch (CoreException e) {
e.printStackTrace();
}
}
private void createPbmMarkers(IResource res, EObject[] eos) {
if (!initialized && eos.length > 0) {
initialize(eos[0]);
}
for (int i = 0; i < eos.length; i++) {
eObjectToPbmMarker(res, eos[i]);
}
}
public void resetPbmMarkers(final IResource res, final EObject[] eos) throws CoreException {
try {
res.deleteMarkers(IMarker.PROBLEM, true, IResource.DEPTH_INFINITE);
} catch (CoreException e) {
e.printStackTrace();
}
IWorkspaceRunnable r = new IWorkspaceRunnable() {
public void run(IProgressMonitor monitor) throws CoreException {
createPbmMarkers(res, eos);
}
};
res.getWorkspace().run(r, null, IWorkspace.AVOID_UPDATE, null);
}
}
| true | true | private void eObjectToPbmMarker(IResource res, EObject eo) {
String description = (String)eo.eGet(sfDescription);
String location = (String)eo.eGet(sfLocation);
int lineNumber = Integer.parseInt(location.split(":")[0]);
int charStart = 0, charEnd = 0;
try {
AtlNbCharFile help = new AtlNbCharFile(((IFile)res).getContents());
if (location.indexOf('-') == -1) {
location += '-' + location;
}
int[] pos = help.getIndexChar(location);
charStart = pos[0];
charEnd = pos[1];
} catch (CoreException e1) {
e1.printStackTrace();
}
String severity = ((EEnumLiteral)eo.eGet(sfSeverity)).getName();
int eclipseSeverity = ((Integer)severities.get(severity)).intValue();
try {
IMarker pbmMarker = res.createMarker(IMarker.PROBLEM);
pbmMarker.setAttribute(IMarker.SEVERITY, eclipseSeverity);
pbmMarker.setAttribute(IMarker.MESSAGE, description);
pbmMarker.setAttribute(IMarker.LINE_NUMBER, lineNumber);
pbmMarker.setAttribute(IMarker.CHAR_START, charStart);
pbmMarker.setAttribute(IMarker.CHAR_END, charEnd + 1);
} catch (CoreException e) {
e.printStackTrace();
}
}
| private void eObjectToPbmMarker(IResource res, EObject eo) {
String description = (String)eo.eGet(sfDescription);
String location = (String)eo.eGet(sfLocation);
int lineNumber = Integer.parseInt(location.split(":")[0]);
int charStart = 0, charEnd = 0;
try {
AtlNbCharFile help = new AtlNbCharFile(((IFile)res).getContents());
if (location.indexOf('-') == -1) {
location += '-' + location;
}
int[] pos = help.getIndexChar(location);
charStart = pos[0];
charEnd = pos[1];
} catch (CoreException e1) {
e1.printStackTrace();
}
String severity = ((EEnumLiteral)eo.eGet(sfSeverity)).getName();
int eclipseSeverity = ((Integer)severities.get(severity)).intValue();
try {
IMarker pbmMarker = res.createMarker(IMarker.PROBLEM);
pbmMarker.setAttribute(IMarker.SEVERITY, eclipseSeverity);
pbmMarker.setAttribute(IMarker.MESSAGE, description);
pbmMarker.setAttribute(IMarker.LINE_NUMBER, lineNumber);
pbmMarker.setAttribute(IMarker.CHAR_START, charStart);
pbmMarker.setAttribute(IMarker.CHAR_END, charEnd);
} catch (CoreException e) {
e.printStackTrace();
}
}
|
diff --git a/src/main/java/org/mapdb/DBMaker.java b/src/main/java/org/mapdb/DBMaker.java
index 5ebf1044..c87c9a24 100644
--- a/src/main/java/org/mapdb/DBMaker.java
+++ b/src/main/java/org/mapdb/DBMaker.java
@@ -1,610 +1,610 @@
/*
* Copyright (c) 2012 Jan Kotek
*
* 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.mapdb;
import java.io.File;
import java.io.IOError;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.NavigableSet;
import java.util.Set;
import org.jetbrains.annotations.NotNull;
import org.mapdb.EngineWrapper.*;
/**
* A builder class for creating and opening a database.
*
* @author Jan Kotek
*/
public class DBMaker {
protected static final byte CACHE_DISABLE = 0;
protected static final byte CACHE_FIXED_HASH_TABLE = 1;
protected static final byte CACHE_HARD_REF = 2;
protected static final byte CACHE_WEAK_REF = 3;
protected static final byte CACHE_SOFT_REF = 4;
protected static final byte CACHE_LRU = 5;
protected byte _cache = CACHE_FIXED_HASH_TABLE;
protected int _cacheSize = 1024*32;
/** file to open, if null opens in memory store */
protected File _file;
protected boolean _journalEnabled = true;
protected boolean _asyncWriteEnabled = true;
protected int _asyncFlushDelay = 0;
protected boolean _asyncThreadDaemon = false;
protected boolean _deleteFilesAfterClose = false;
protected boolean _readOnly = false;
protected boolean _closeOnJvmShutdown = false;
protected boolean _compressionEnabled = false;
protected byte[] _xteaEncryptionKey = null;
protected boolean _appendOnlyEnabled = false;
protected boolean _checksumEnabled = false;
protected boolean _ifInMemoryUseDirectBuffer = false;
protected boolean _failOnWrongHeader = false;
protected boolean _RAF = false;
protected boolean _powerSavingMode = false; //TODO add power saving option
/** use static factory methods, or make subclass */
protected DBMaker(){}
/** Creates new in-memory database. Changes are lost after JVM exits.
* <p/>
* This will use HEAP memory so Garbage Collector is affected.
*/
@NotNull
public static DBMaker newMemoryDB(){
DBMaker m = new DBMaker();
m._file = null;
return m;
}
/** Creates new in-memory database. Changes are lost after JVM exits.
* <p/>
* This will use DirectByteBuffer outside of HEAP, so Garbage Collector is not affected
*
*/
@NotNull
public static DBMaker newDirectMemoryDB(){
DBMaker m = new DBMaker();
m._file = null;
m._ifInMemoryUseDirectBuffer = true;
return m;
}
/**
* Create new BTreeMap backed by temporary file storage.
* This is quick way to create 'throw away' collection.
*
* </p>Storage is created in temp folder and deleted on JVM shutdown
*/
@NotNull
public static <K,V> BTreeMap<K,V> newTempTreeMap(){
return newTempFileDB()
.deleteFilesAfterClose()
.closeOnJvmShutdown()
.journalDisable()
.make()
.getTreeMap("temp");
}
/**
* Create new HTreeMap backed by temporary file storage.
* This is quick way to create 'throw away' collection.
*
* </p>Storage is created in temp folder and deleted on JVM shutdown
*/
@NotNull
public static <K,V> HTreeMap<K,V> newTempHashMap(){
return newTempFileDB()
.deleteFilesAfterClose()
.closeOnJvmShutdown()
.journalDisable()
.make()
.getHashMap("temp");
}
/**
* Create new TreeSet backed by temporary file storage.
* This is quick way to create 'throw away' collection.
*
* </p>Storage is created in temp folder and deleted on JVM shutdown
*/
@NotNull
public static <K> NavigableSet<K> newTempTreeSet(){
return newTempFileDB()
.deleteFilesAfterClose()
.closeOnJvmShutdown()
.journalDisable()
.make()
.getTreeSet("temp");
}
/**
* Create new HashSet backed by temporary file storage.
* This is quick way to create 'throw away' collection.
*
* </p>Storage is created in temp folder and deleted on JVM shutdown
*/
@NotNull
public static <K> Set<K> newTempHashSet(){
return newTempFileDB()
.deleteFilesAfterClose()
.closeOnJvmShutdown()
.journalDisable()
.make()
.getHashSet("temp");
}
/**
* Creates new database in temporary folder.
*
* @return
*/
@NotNull
public static DBMaker newTempFileDB() {
try {
return newFileDB(File.createTempFile("JDBM-temp","db"));
} catch (IOException e) {
throw new IOError(e);
}
}
/** Creates or open database stored in file. */
@NotNull
public static DBMaker newFileDB(File file){
DBMaker m = new DBMaker();
m._file = file;
return m;
}
/** Creates or open database stored in file.
* <p/>
* This methods opens DB with `RAF` mode.
* It does not use NIO memory mapped buffers, so is slower but safer and more compatible.
* Use this if you are experiencing <b>java.lang.OutOfMemoryError: Map failed</b> exceptions
*/
@NotNull
public static DBMaker newRandomAccessFileDB(File file){
DBMaker m = new DBMaker();
m._file = file;
m._RAF = true;
return m;
}
/**
* Transaction journal is enabled by default
* You must call <b>DB.commit()</b> to save your changes.
* It is possible to disable transaction journal for better write performance
* In this case all integrity checks are sacrificed for faster speed.
* <p/>
* If transaction journal is disabled, all changes are written DIRECTLY into store.
* You must call DB.close() method before exit,
* otherwise your store <b>WILL BE CORRUPTED</b>
*
*
* @return this builder
*/
@NotNull
public DBMaker journalDisable(){
this._journalEnabled = false;
return this;
}
/**
* Instance cache is enabled by default.
* This greatly decreases serialization overhead and improves performance.
* Call this method to disable instance cache, so an object will always be deserialized.
* <p/>
* This may workaround some problems
*
* @return this builder
*/
@NotNull
public DBMaker cacheDisable(){
this._cache = CACHE_DISABLE;
return this;
}
/**
* Enables unbounded hard reference cache.
* This cache is good if you have lot of available memory.
* <p/>
* All fetched records are added to HashMap and stored with hard reference.
* To prevent OutOfMemoryExceptions JDBM monitors free memory,
* if it is bellow 25% cache is cleared.
*
* @return this builder
*/
@NotNull
public DBMaker cacheHardRefEnable(){
this._cache = CACHE_HARD_REF;
return this;
}
/**
* Enables unbounded cache which uses <code>WeakReference</code>.
* Items are removed from cache by Garbage Collector
*
* @return this builder
*/
@NotNull
public DBMaker cacheWeakRefEnable(){
this._cache = CACHE_WEAK_REF;
return this;
}
/**
* Enables unbounded cache which uses <code>SoftReference</code>.
* Items are removed from cache by Garbage Collector
*
* @return this builder
*/
@NotNull
public DBMaker cacheSoftRefEnable(){
this._cache = CACHE_SOFT_REF;
return this;
}
/**
* Enables Least Recently Used cache. It is fixed size cache and it removes less used items to make space.
*
* @return this builder
*/
@NotNull
public DBMaker cacheLRUEnable(){
this._cache = CACHE_LRU;
return this;
}
/**
* Set cache size. Interpretations depends on cache type.
* For fixed size caches (such as FixedHashTable cache) it is maximal number of items in cache.
* <p/>
* For unbounded caches (such as HardRef cache) it is initial capacity of underlying table (HashMap).
* <p/>
* Default cache size is 32768.
*
* @param cacheSize new cache size
* @return this builder
*/
@NotNull
public DBMaker cacheSize(int cacheSize){
this._cacheSize = cacheSize;
return this;
}
/**
* By default all modifications are queued and written into disk on Background Writer Thread.
* So all modifications are performed in asynchronous mode and do not block.
* <p/>
* It is possible to disable Background Writer Thread, but this greatly hurts concurrency.
* Without async writes, all threads blocks until all previous writes are not finished (single big lock).
*
* <p/>
* This may workaround some problems
*
* @return this builder
*/
@NotNull
public DBMaker asyncWriteDisable(){
this._asyncWriteEnabled = false;
return this;
}
/**
* In async mode writes are done in Writer Thread.
* If main thread dies Writer Thread still lives and prevents JVM from exiting.
* This is good as it prevents data loss.
* However in some modes shuting down JVM may be more important than preserving data.
* So you may set Writer Thread to 'daemon mode' so JVM can exit
*
* @return this builder
*/
@NotNull
public DBMaker asyncThreadDaemonEnable(){
this._asyncThreadDaemon = true;
return this;
}
/**
* //TODO put this nice comment somewhere
* By default all objects are serialized in Background Writer Thread.
* <p/>
* This may improve performance. For example with single thread access, Async Serialization offloads
* lot of work to second core. Or when multiple values are added into single tree node,
* node has to be serialized only once. Without Async Serialization node is serialized each time
* node is updated.
* <p/>
* On other side Async Serialization moves all serialization into single thread. This
* hurts performance with many concurrent-independent updates.
* <p/>
* Async Serialization may also produce some unexpected results when your data classes are not
* immutable. Consider example bellow. If Async Serialization is disabled, it always prints 'Peter'.
* If it is enabled (by default) it creates race condition and randomly prints 'Peter' or 'Jack',
* <pre>
* Person person = new Person();
* person.setName("Peter");
* map.put(id, person)
* person.setName("Jack");
* //long pause
* println(map.get(id).getName());
* </pre>
*
* <p/>
* This may also workaround some problems
*
* @return this builder
*/
/**
* Set flush iterval for write cache, by default is 0
* <p/>
* When BTreeMap is constructed from ordered set, tree node size is increasing linearly with each
* item added. Each time new key is added to tree node, its size changes and
* storage needs to find new place. So constructing BTreeMap from ordered set leads to large
* store fragmentation.
* <p/>
* Setting flush interval is workaround as BTreeMap node is always updated in memory (write cache)
* and only final version of node is stored on disk.
*
*
* @param delay flush write cache every N miliseconds
* @return this builder
*/
@NotNull
public DBMaker asyncFlushDelay(int delay){
_asyncFlushDelay = delay;
return this;
}
/**
* Try to delete files after DB is closed.
* File deletion may silently fail, especially on Windows where buffer needs to be unmapped file delete.
*
* @return this builder
*/
@NotNull
public DBMaker deleteFilesAfterClose(){
this._deleteFilesAfterClose = true;
return this;
}
/**
* Adds JVM shutdown hook and closes DB just before JVM;
*
* @return this builder
*/
@NotNull
public DBMaker closeOnJvmShutdown(){
this._closeOnJvmShutdown = true;
return this;
}
/**
* Enables record compression.
* <p/>
* Make sure you enable this every time you reopen store, otherwise record de-serialization fails unpredictably.
*
* @return this builder
*/
@NotNull
public DBMaker compressionEnable(){
this._compressionEnabled = true;
return this;
}
/**
* Encrypt storage using XTEA algorithm.
* <p/>
* XTEA is sound encryption algorithm. However implementation in JDBM was not peer-reviewed.
* JDBM only encrypts records data, so attacker may see number of records and their sizes.
* <p/>
* Make sure you enable this every time you reopen store, otherwise record de-serialization fails unpredictably.
*
* @param password for encryption
* @return this builder
*/
@NotNull
public DBMaker encryptionEnable(String password){
try {
return encryptionEnable(password.getBytes(Utils.UTF8));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
/**
* Encrypt storage using XTEA algorithm.
* <p/>
* XTEA is sound encryption algorithm. However implementation in JDBM was not peer-reviewed.
* JDBM only encrypts records data, so attacker may see number of records and their sizes.
* <p/>
* Make sure you enable this every time you reopen store, otherwise record de-serialization fails unpredictably.
*
* @param password for encryption
* @return this builder
*/
@NotNull
public DBMaker encryptionEnable(byte[] password){
_xteaEncryptionKey = password;
return this;
}
/**
* Adds CRC32 checksum at end of each record to check data integrity.
* It throws 'IOException("CRC32 does not match, data broken")' on de-serialization if data are corrupted
* <p/>
* Make sure you enable this every time you reopen store, otherwise record de-serialization fails.
*
* @return this builder
*/
@NotNull
public DBMaker checksumEnable(){
this._checksumEnabled = true;
return this;
}
/**
* Open store in read-only mode. Any modification attempt will throw
* <code>UnsupportedOperationException("Read-only")</code>
*
* @return this builder
*/
@NotNull
public DBMaker readOnly(){
this._readOnly = true;
return this;
}
/**
* In 'appendOnly' mode existing free space is not reused,
* but records are added to the end of the store.
* <p/>
* This slightly improves write performance as store does not have
* to traverse list of free records to find and reuse existing position.
* <p/>
* It also decreases chance for store corruption, as existing data
* are not overwritten with new record.
* <p/>
* When this mode is used for longer time, store becomes fragmented.
* It is necessary to run defragmentation then.
*
* @return this builder
*/
@NotNull
public DBMaker appendOnlyEnable(){
this._appendOnlyEnabled = true;
return this;
}
/** constructs DB using current settings */
@NotNull
public DB make(){
return new DB(makeEngine());
}
/** constructs Engine using current settings */
@NotNull
public Engine makeEngine(){
if(_readOnly && _file==null)
throw new UnsupportedOperationException("Can not open in-memory DB in read-only mode.");
if(_readOnly && !_file.exists()){
throw new UnsupportedOperationException("Can not open non-existing file in read-only mode.");
}
Volume.Factory folFac = _file == null?
Volume.memoryFactory(_ifInMemoryUseDirectBuffer):
Volume.fileFactory(_readOnly, _RAF, _file);
Engine engine = _journalEnabled ?
new StorageJournaled(folFac, _appendOnlyEnabled, _deleteFilesAfterClose, _failOnWrongHeader, _readOnly):
new StorageDirect(folFac, _appendOnlyEnabled, _deleteFilesAfterClose , _failOnWrongHeader, _readOnly);
AsyncWriteEngine engineAsync = null;
if(_asyncWriteEnabled && !_readOnly){
engineAsync = new AsyncWriteEngine(engine, _asyncThreadDaemon, _powerSavingMode);
engine = engineAsync;
}
if(_checksumEnabled){
engine = new ByteTransformEngine(engine, Serializer.CRC32_CHECKSUM);
}
if(_xteaEncryptionKey!=null){
engine = new ByteTransformEngine(engine, new EncryptionXTEA(_xteaEncryptionKey));
}
if(_compressionEnabled){
engine = new ByteTransformEngine(engine, CompressLZF.SERIALIZER);
}
engine = new SnapshotEngine(engine, _cache==CACHE_DISABLE? 0 : 1024);
if(_cache == CACHE_DISABLE){
//do not wrap engine in cache
}if(_cache == CACHE_FIXED_HASH_TABLE){
engine = new CacheHashTable(engine,_cacheSize);
}else if (_cache == CACHE_HARD_REF){
engine = new CacheHardRef(engine,_cacheSize);
}else if (_cache == CACHE_WEAK_REF){
engine = new CacheWeakSoftRef(engine,true);
}else if (_cache == CACHE_SOFT_REF){
engine = new CacheWeakSoftRef(engine,false);
}else if (_cache == CACHE_LRU){
engine = new CacheLRU(engine, _cacheSize);
}
if(_readOnly)
engine = new ReadOnlyEngine(engine);
if(engineAsync!=null)
engineAsync.setParentEngineReference(engine);
if(_closeOnJvmShutdown){
final Engine engine2 = engine;
Runtime.getRuntime().addShutdownHook(new Thread("JDBM shutdown") {
@Override
public void run() {
- //TODO handle already closed engine
- engine2.close();
+ if(!engine2.isClosed())
+ engine2.close();
}
});
}
return engine;
}
}
| true | true | public Engine makeEngine(){
if(_readOnly && _file==null)
throw new UnsupportedOperationException("Can not open in-memory DB in read-only mode.");
if(_readOnly && !_file.exists()){
throw new UnsupportedOperationException("Can not open non-existing file in read-only mode.");
}
Volume.Factory folFac = _file == null?
Volume.memoryFactory(_ifInMemoryUseDirectBuffer):
Volume.fileFactory(_readOnly, _RAF, _file);
Engine engine = _journalEnabled ?
new StorageJournaled(folFac, _appendOnlyEnabled, _deleteFilesAfterClose, _failOnWrongHeader, _readOnly):
new StorageDirect(folFac, _appendOnlyEnabled, _deleteFilesAfterClose , _failOnWrongHeader, _readOnly);
AsyncWriteEngine engineAsync = null;
if(_asyncWriteEnabled && !_readOnly){
engineAsync = new AsyncWriteEngine(engine, _asyncThreadDaemon, _powerSavingMode);
engine = engineAsync;
}
if(_checksumEnabled){
engine = new ByteTransformEngine(engine, Serializer.CRC32_CHECKSUM);
}
if(_xteaEncryptionKey!=null){
engine = new ByteTransformEngine(engine, new EncryptionXTEA(_xteaEncryptionKey));
}
if(_compressionEnabled){
engine = new ByteTransformEngine(engine, CompressLZF.SERIALIZER);
}
engine = new SnapshotEngine(engine, _cache==CACHE_DISABLE? 0 : 1024);
if(_cache == CACHE_DISABLE){
//do not wrap engine in cache
}if(_cache == CACHE_FIXED_HASH_TABLE){
engine = new CacheHashTable(engine,_cacheSize);
}else if (_cache == CACHE_HARD_REF){
engine = new CacheHardRef(engine,_cacheSize);
}else if (_cache == CACHE_WEAK_REF){
engine = new CacheWeakSoftRef(engine,true);
}else if (_cache == CACHE_SOFT_REF){
engine = new CacheWeakSoftRef(engine,false);
}else if (_cache == CACHE_LRU){
engine = new CacheLRU(engine, _cacheSize);
}
if(_readOnly)
engine = new ReadOnlyEngine(engine);
if(engineAsync!=null)
engineAsync.setParentEngineReference(engine);
if(_closeOnJvmShutdown){
final Engine engine2 = engine;
Runtime.getRuntime().addShutdownHook(new Thread("JDBM shutdown") {
@Override
public void run() {
//TODO handle already closed engine
engine2.close();
}
});
}
return engine;
}
| public Engine makeEngine(){
if(_readOnly && _file==null)
throw new UnsupportedOperationException("Can not open in-memory DB in read-only mode.");
if(_readOnly && !_file.exists()){
throw new UnsupportedOperationException("Can not open non-existing file in read-only mode.");
}
Volume.Factory folFac = _file == null?
Volume.memoryFactory(_ifInMemoryUseDirectBuffer):
Volume.fileFactory(_readOnly, _RAF, _file);
Engine engine = _journalEnabled ?
new StorageJournaled(folFac, _appendOnlyEnabled, _deleteFilesAfterClose, _failOnWrongHeader, _readOnly):
new StorageDirect(folFac, _appendOnlyEnabled, _deleteFilesAfterClose , _failOnWrongHeader, _readOnly);
AsyncWriteEngine engineAsync = null;
if(_asyncWriteEnabled && !_readOnly){
engineAsync = new AsyncWriteEngine(engine, _asyncThreadDaemon, _powerSavingMode);
engine = engineAsync;
}
if(_checksumEnabled){
engine = new ByteTransformEngine(engine, Serializer.CRC32_CHECKSUM);
}
if(_xteaEncryptionKey!=null){
engine = new ByteTransformEngine(engine, new EncryptionXTEA(_xteaEncryptionKey));
}
if(_compressionEnabled){
engine = new ByteTransformEngine(engine, CompressLZF.SERIALIZER);
}
engine = new SnapshotEngine(engine, _cache==CACHE_DISABLE? 0 : 1024);
if(_cache == CACHE_DISABLE){
//do not wrap engine in cache
}if(_cache == CACHE_FIXED_HASH_TABLE){
engine = new CacheHashTable(engine,_cacheSize);
}else if (_cache == CACHE_HARD_REF){
engine = new CacheHardRef(engine,_cacheSize);
}else if (_cache == CACHE_WEAK_REF){
engine = new CacheWeakSoftRef(engine,true);
}else if (_cache == CACHE_SOFT_REF){
engine = new CacheWeakSoftRef(engine,false);
}else if (_cache == CACHE_LRU){
engine = new CacheLRU(engine, _cacheSize);
}
if(_readOnly)
engine = new ReadOnlyEngine(engine);
if(engineAsync!=null)
engineAsync.setParentEngineReference(engine);
if(_closeOnJvmShutdown){
final Engine engine2 = engine;
Runtime.getRuntime().addShutdownHook(new Thread("JDBM shutdown") {
@Override
public void run() {
if(!engine2.isClosed())
engine2.close();
}
});
}
return engine;
}
|
diff --git a/src/org/napile/idea/plugin/run/NapileConfigurationProducer.java b/src/org/napile/idea/plugin/run/NapileConfigurationProducer.java
index 2a5263b..f2c4f15 100644
--- a/src/org/napile/idea/plugin/run/NapileConfigurationProducer.java
+++ b/src/org/napile/idea/plugin/run/NapileConfigurationProducer.java
@@ -1,133 +1,133 @@
/*
* Copyright 2010-2013 napile.org
*
* 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.napile.idea.plugin.run;
import org.jetbrains.annotations.Nullable;
import org.napile.asm.resolve.name.FqName;
import org.napile.compiler.analyzer.AnalyzeExhaust;
import org.napile.compiler.lang.descriptors.MutableClassDescriptor;
import org.napile.compiler.lang.descriptors.SimpleMethodDescriptor;
import org.napile.compiler.lang.psi.NapileClass;
import org.napile.compiler.lang.psi.NapileDeclaration;
import org.napile.compiler.lang.psi.NapileFile;
import org.napile.compiler.lang.resolve.BindingContext;
import org.napile.compiler.lang.resolve.DescriptorUtils;
import org.napile.compiler.util.RunUtil;
import org.napile.idea.plugin.module.Analyzer;
import com.intellij.execution.Location;
import com.intellij.execution.RunnerAndConfigurationSettings;
import com.intellij.execution.actions.ConfigurationContext;
import com.intellij.execution.junit.RuntimeConfigurationProducer;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleUtilCore;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.openapi.roots.ModuleRootManager;
import com.intellij.psi.PsiElement;
/**
* @author VISTALL
* @date 13:22/08.01.13
*/
public class NapileConfigurationProducer extends RuntimeConfigurationProducer implements Cloneable
{
private PsiElement element;
public NapileConfigurationProducer()
{
super(NapileConfigurationType.getInstance());
}
@Override
public PsiElement getSourceElement()
{
return element;
}
@Nullable
@Override
protected RunnerAndConfigurationSettings createConfigurationByElement(Location location, ConfigurationContext context)
{
PsiElement element = location.getPsiElement();
NapileClass napileClass = null;
AnalyzeExhaust analyzeExhaust = null;
if(element instanceof NapileFile)
{
analyzeExhaust = Analyzer.analyzeAll((NapileFile) element);
- if(((NapileFile) element).getDeclarations().length == 2)
+ if(((NapileFile) element).getDeclarations().length == 0)
return null;
napileClass = ((NapileFile) element).getDeclarations()[0];
}
else if(element instanceof NapileClass)
{
napileClass = (NapileClass) element;
analyzeExhaust = Analyzer.analyzeAll(((NapileClass) element).getContainingFile());
}
else
return null;
MutableClassDescriptor descriptor = (MutableClassDescriptor) analyzeExhaust.getBindingContext().get(BindingContext.CLASS, napileClass);
if(descriptor == null)
return null;
NapileDeclaration mainMethod = null;
for(NapileDeclaration inner : napileClass.getDeclarations())
{
SimpleMethodDescriptor methodDescriptor = analyzeExhaust.getBindingContext().get(BindingContext.METHOD, inner);
if(methodDescriptor != null && RunUtil.isRunPoint(methodDescriptor))
{
mainMethod = inner;
break;
}
}
if(mainMethod != null)
{
this.element = mainMethod;
Module module = mainMethod.isValid() ? ModuleUtilCore.findModuleForPsiElement(mainMethod) : null;
if(module == null)
return null;
FqName fqName = DescriptorUtils.getFQName(descriptor).toSafe();
ModuleRootManager rootManager = ModuleRootManager.getInstance(module);
Sdk sdk = rootManager.getSdk();
if(sdk == null)
return null;
RunnerAndConfigurationSettings settings = cloneTemplateConfiguration(location.getProject(), context);
NapileRunConfiguration configuration = (NapileRunConfiguration) settings.getConfiguration();
configuration.setModule(module);
configuration.setName(fqName.getFqName());
configuration.mainClass = fqName.getFqName();
configuration.jdkName = sdk.getName();
return settings;
}
return null;
}
@Override
public int compareTo(Object o)
{
return PREFERED;
}
}
| true | true | protected RunnerAndConfigurationSettings createConfigurationByElement(Location location, ConfigurationContext context)
{
PsiElement element = location.getPsiElement();
NapileClass napileClass = null;
AnalyzeExhaust analyzeExhaust = null;
if(element instanceof NapileFile)
{
analyzeExhaust = Analyzer.analyzeAll((NapileFile) element);
if(((NapileFile) element).getDeclarations().length == 2)
return null;
napileClass = ((NapileFile) element).getDeclarations()[0];
}
else if(element instanceof NapileClass)
{
napileClass = (NapileClass) element;
analyzeExhaust = Analyzer.analyzeAll(((NapileClass) element).getContainingFile());
}
else
return null;
MutableClassDescriptor descriptor = (MutableClassDescriptor) analyzeExhaust.getBindingContext().get(BindingContext.CLASS, napileClass);
if(descriptor == null)
return null;
NapileDeclaration mainMethod = null;
for(NapileDeclaration inner : napileClass.getDeclarations())
{
SimpleMethodDescriptor methodDescriptor = analyzeExhaust.getBindingContext().get(BindingContext.METHOD, inner);
if(methodDescriptor != null && RunUtil.isRunPoint(methodDescriptor))
{
mainMethod = inner;
break;
}
}
if(mainMethod != null)
{
this.element = mainMethod;
Module module = mainMethod.isValid() ? ModuleUtilCore.findModuleForPsiElement(mainMethod) : null;
if(module == null)
return null;
FqName fqName = DescriptorUtils.getFQName(descriptor).toSafe();
ModuleRootManager rootManager = ModuleRootManager.getInstance(module);
Sdk sdk = rootManager.getSdk();
if(sdk == null)
return null;
RunnerAndConfigurationSettings settings = cloneTemplateConfiguration(location.getProject(), context);
NapileRunConfiguration configuration = (NapileRunConfiguration) settings.getConfiguration();
configuration.setModule(module);
configuration.setName(fqName.getFqName());
configuration.mainClass = fqName.getFqName();
configuration.jdkName = sdk.getName();
return settings;
}
return null;
}
| protected RunnerAndConfigurationSettings createConfigurationByElement(Location location, ConfigurationContext context)
{
PsiElement element = location.getPsiElement();
NapileClass napileClass = null;
AnalyzeExhaust analyzeExhaust = null;
if(element instanceof NapileFile)
{
analyzeExhaust = Analyzer.analyzeAll((NapileFile) element);
if(((NapileFile) element).getDeclarations().length == 0)
return null;
napileClass = ((NapileFile) element).getDeclarations()[0];
}
else if(element instanceof NapileClass)
{
napileClass = (NapileClass) element;
analyzeExhaust = Analyzer.analyzeAll(((NapileClass) element).getContainingFile());
}
else
return null;
MutableClassDescriptor descriptor = (MutableClassDescriptor) analyzeExhaust.getBindingContext().get(BindingContext.CLASS, napileClass);
if(descriptor == null)
return null;
NapileDeclaration mainMethod = null;
for(NapileDeclaration inner : napileClass.getDeclarations())
{
SimpleMethodDescriptor methodDescriptor = analyzeExhaust.getBindingContext().get(BindingContext.METHOD, inner);
if(methodDescriptor != null && RunUtil.isRunPoint(methodDescriptor))
{
mainMethod = inner;
break;
}
}
if(mainMethod != null)
{
this.element = mainMethod;
Module module = mainMethod.isValid() ? ModuleUtilCore.findModuleForPsiElement(mainMethod) : null;
if(module == null)
return null;
FqName fqName = DescriptorUtils.getFQName(descriptor).toSafe();
ModuleRootManager rootManager = ModuleRootManager.getInstance(module);
Sdk sdk = rootManager.getSdk();
if(sdk == null)
return null;
RunnerAndConfigurationSettings settings = cloneTemplateConfiguration(location.getProject(), context);
NapileRunConfiguration configuration = (NapileRunConfiguration) settings.getConfiguration();
configuration.setModule(module);
configuration.setName(fqName.getFqName());
configuration.mainClass = fqName.getFqName();
configuration.jdkName = sdk.getName();
return settings;
}
return null;
}
|
diff --git a/src/main/java/org/sukrupa/event/EventRepository.java b/src/main/java/org/sukrupa/event/EventRepository.java
index 0076b592..3ee52985 100644
--- a/src/main/java/org/sukrupa/event/EventRepository.java
+++ b/src/main/java/org/sukrupa/event/EventRepository.java
@@ -1,52 +1,53 @@
package org.sukrupa.event;
import com.google.common.base.Splitter;
import com.google.common.collect.Sets;
import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Disjunction;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.sukrupa.student.Student;
import java.util.List;
import java.util.Set;
@Repository
public class EventRepository {
private static final String STUDENT_ID = "studentId";
static final String ATTENDEES_SEPARATOR = ",";
private SessionFactory sessionFactory;
@Autowired
public EventRepository(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public List<Event> getAll() {
return sessionFactory.getCurrentSession().createCriteria(Event.class).list();
}
public void save(EventRecord eventRecord) {
Set<Student> attendees = retrieveStudent(eventRecord.getAttendees());
sessionFactory.getCurrentSession().save(Event.createFrom(eventRecord, attendees));
}
private Set<Student> retrieveStudent(String studentIds) {
Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Student.class);
- Criterion attendee = Restrictions.in(STUDENT_ID, createStudentIds(studentIds));
- Disjunction disjunction = Restrictions.disjunction();
- disjunction.add(attendee);
- criteria.add(disjunction);
+ criteria.add(
+ Restrictions.disjunction().add(
+ Restrictions.in(STUDENT_ID, createStudentIds(studentIds))
+ )
+ );
return Sets.newHashSet(criteria.list());
}
private Set<String> createStudentIds(String studentIds) {
return Sets.newLinkedHashSet(Splitter.on(ATTENDEES_SEPARATOR).omitEmptyStrings().trimResults().split(studentIds));
}
}
| true | true | private Set<Student> retrieveStudent(String studentIds) {
Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Student.class);
Criterion attendee = Restrictions.in(STUDENT_ID, createStudentIds(studentIds));
Disjunction disjunction = Restrictions.disjunction();
disjunction.add(attendee);
criteria.add(disjunction);
return Sets.newHashSet(criteria.list());
}
| private Set<Student> retrieveStudent(String studentIds) {
Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Student.class);
criteria.add(
Restrictions.disjunction().add(
Restrictions.in(STUDENT_ID, createStudentIds(studentIds))
)
);
return Sets.newHashSet(criteria.list());
}
|
diff --git a/core/src/visad/trunk/data/text/TextAdapter.java b/core/src/visad/trunk/data/text/TextAdapter.java
index e8509301e..f38bdeab4 100644
--- a/core/src/visad/trunk/data/text/TextAdapter.java
+++ b/core/src/visad/trunk/data/text/TextAdapter.java
@@ -1,1612 +1,1615 @@
//
// TextAdapter.java
//
/*
VisAD system for interactive analysis and visualization of numerical
data. Copyright (C) 1996 - 2009 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.data.text;
import java.io.IOException;
import java.io.*;
import java.util.*;
import visad.Set;
import java.net.URL;
import visad.*;
import visad.VisADException;
import visad.data.in.ArithProg;
/** this is an VisAD file adapter for comma-, tab- and blank-separated
* ASCII text file data. It will attempt to create a FlatField from
* the data and descriptions given in the file and/or the constructor.
*
* The text files contained delimited data. The delimiter is
* determined as follows: if the file has a well-known extension
* (.csv, .tsv, .bsv) then the delimiter is implied by the extension.
* In all other cases, the delimiter for the data (and for the
* "column labels") is determined by reading the first line and
* looking, in order, for a tab, comma, or blank. Which ever one
* is found first is taken as the delimiter.
*
* Two extra pieces of information are needed: the VisAD "MathType"
* which is specified as a string (e.g., (x,y)->(temperature))
* and may either be the first line of the file or passed in through
* one of the constructors.
*
* The second item are the "column labels" which contain the names
* of each field in the data. The names of all range components
* specified in the "MathType" must appear. The names of domain
* components are optional. The values in this string are separated
* by the delimiter, as defined above.
*
* See visad.data.text.README.text for more details.
*
* @author Tom Whittaker
*
*/
public class TextAdapter {
private static final String ATTR_COLSPAN = "colspan";
private static final String ATTR_VALUE = "value";
private static final String ATTR_OFFSET = "off";
private static final String ATTR_ERROR = "err";
private static final String ATTR_SCALE = "sca";
private static final String ATTR_POSITION ="pos";
private static final String ATTR_FORMAT = "fmt";
private static final String ATTR_TIMEZONE = "tz";
private static final String ATTR_UNIT= "unit";
private static final String ATTR_MISSING = "mis";
private static final String ATTR_INTERVAL = "int";
private static final String COMMA = ",";
private static final String SEMICOLON = ";";
private static final String TAB = "\t";
private static final String BLANK = " ";
private static final String BLANK_DELIM = "\\s+";
private FlatField ff = null;
private Field field = null;
private boolean debug = false;
private String DELIM;
private boolean DOQUOTE = true;
private boolean GOTTIME = false;
HeaderInfo []infos;
double[] rangeErrorEstimates;
Unit[] rangeUnits;
Set[] rangeSets;
double[] domainErrorEstimates;
Unit[] domainUnits;
int[][] hdrColumns;
int[][] values_to_index;
private Hashtable properties;
private boolean onlyReadOneLine = false;
/** Create a VisAD FlatField from a local Text (comma-, tab- or
* blank-separated values) ASCII file
* @param filename name of local file.
* @exception IOException if there was a problem reading the file.
* @exception VisADException if an unexpected problem occurs.
*/
public TextAdapter(String filename) throws IOException, VisADException {
this(filename, null, null);
}
/** Create a VisAD FlatField from a local Text (comma-, tab- or
* blank-separated values) ASCII file
* @param filename name of local file.
* @param map the VisAD "MathType" as a string defining the FlatField
* @param params the list of parameters used to define what columns
* of the text file correspond to what MathType parameters.
* @exception IOException if there was a problem reading the file.
* @exception VisADException if an unexpected problem occurs.
*/
public TextAdapter(String filename, String map, String params)
throws IOException, VisADException {
InputStream is = new FileInputStream(filename);
DELIM = getDelimiter(filename);
readit(is, map, params);
}
/** Create a VisAD FlatField from a remote Text (comma-, tab- or
* blank-separated values) ASCII file
*
* @param url File URL.
* @exception IOException if there was a problem reading the file.
* @exception VisADException if an unexpected problem occurs.
*/
public TextAdapter(URL url) throws IOException, VisADException {
this(url, null, null);
}
/** Create a VisAD FlatField from a local Text (comma-, tab- or
* blank-separated values) ASCII file
* @param url File URL.
* @param map the VisAD "MathType" as a string defining the FlatField
* @param params the list of parameters used to define what columns
* of the text file correspond to what MathType parameters.
* @exception IOException if there was a problem reading the file.
* @exception VisADException if an unexpected problem occurs.
*/
public TextAdapter(URL url, String map, String params)
throws IOException, VisADException {
DELIM = getDelimiter(url.getFile());
InputStream is = url.openStream();
readit(is, map, params);
}
/** Create a VisAD FlatField from a local Text (comma-, tab- or
* blank-separated values) ASCII file
* @param inputStream The input stream to read from
* @param delimiter the delimiter
* @param map the VisAD "MathType" as a string defining the FlatField
* @param params the list of parameters used to define what columns
* of the text file correspond to what MathType parameters.
* @exception IOException if there was a problem reading the file.
* @exception VisADException if an unexpected problem occurs.
*/
public TextAdapter(InputStream inputStream, String delimiter, String map, String params)
throws IOException, VisADException {
this(inputStream, delimiter, map,params,false);
}
/** Create a VisAD FlatField from a local Text (comma-, tab- or
* blank-separated values) ASCII file
* @param inputStream The input stream to read from
* @param delimiter the delimiter
* @param map the VisAD "MathType" as a string defining the FlatField
* @param params the list of parameters used to define what columns
* of the text file correspond to what MathType parameters.
* @param onlyReadOneLine If true then only read one line of data. This is used so client code can
* read the meta data.
* @exception IOException if there was a problem reading the file.
* @exception VisADException if an unexpected problem occurs.
*/
public TextAdapter(InputStream inputStream, String delimiter, String map, String params,boolean onlyReadOneLine)
throws IOException, VisADException {
this(inputStream, delimiter, map, params, null, onlyReadOneLine);
}
public TextAdapter(InputStream inputStream, String delimiter, String map, String params,Hashtable properties, boolean onlyReadOneLine)
throws IOException, VisADException {
this.onlyReadOneLine = onlyReadOneLine;
DELIM = delimiter;
this.properties = properties;
readit(inputStream, map, params);
}
public static String getDelimiter(String filename) {
if(filename == null) return null;
filename = filename.trim().toLowerCase();
if (filename.endsWith(".csv")) return COMMA;
if (filename.endsWith(".tsv")) return TAB;
if (filename.endsWith(".bsv")) return BLANK;
return null;
}
/**
* Is the given text line a comment
*
* @return is it a comment line
*/
public static boolean isComment(String line) {
return (line.startsWith("#") ||
line.startsWith("!") ||
line.startsWith("%") ||
line.length() < 1);
}
public static String readLine(BufferedReader bis)
throws IOException {
while (true) {
String line = bis.readLine();
if (line == null) return null;
if (!isText(line)) return null;
if (isComment(line)) continue;
return line;
}
}
void readit(InputStream is, String map, String params)
throws IOException, VisADException {
// read the ASCII file, using commas as field separators
// first line is a header line
List realTypes = new ArrayList();
ff = null;
field = null;
if (debug) System.out.println("#### Text Adapter v2.x running");
BufferedReader bis = new BufferedReader(new InputStreamReader(is));
// mapping defines how the names are mapped
// for example: (x,y) => (one, two, three)
String maps = null;
if (map == null) {
maps = readLine(bis);
if(maps != null) {
maps = maps.trim();
}
} else {
maps = map;
}
if (maps != null) {
maps = makeMT(maps);
}
if (maps == null) {
throw new visad.data.BadFormException(
"TextAdapter: Invalid or missing MathType");
}
if (debug) System.out.println("Specified MathType = "+maps);
// but first, we need to get the column headers because they
// may have [units] associated with them. The column headers
// primarily define where the data are.
String hdr = null;
if (params == null) {
hdr = readLine(bis);
} else {
hdr = params;
}
String hdrDelim = DELIM;
if (DELIM == null) {
if (hdr.indexOf(BLANK) != -1) hdrDelim = BLANK_DELIM;
if (hdr.indexOf(COMMA) != -1) hdrDelim = COMMA;
if (hdr.indexOf(SEMICOLON) != -1) hdrDelim = SEMICOLON;
if (hdr.indexOf(TAB) != -1) hdrDelim = TAB;
if (debug) System.out.println("Using header delimiter = "+ hdrDelim + "("+
(hdrDelim.getBytes())[0] + ")");
}
String[] sthdr = hdr.split(hdrDelim);
int nhdr = sthdr.length;
infos = new HeaderInfo[nhdr];
for(int i=0;i<infos.length;i++) {
infos[i] = new HeaderInfo();
}
Real[] prototypeReals = new Real[nhdr];
hdrColumns = new int[2][nhdr];
int numHdrValues=0;
// pre-scan of the header names to seek out Units
// since we cannot change a RealType once it's defined!!
for (int i=0; i<nhdr; i++) {
String name = sthdr[i].trim();
String hdrUnitString = null;
hdrColumns[0][i] = -1; // indicating no fixed columns
int m = name.indexOf("[");
if (m == -1) {
infos[i].name = name;
hdrUnitString = null;
} else {
int m2 = name.indexOf("]");
if (m2 == -1) {
throw new VisADException("TextAdapter: Bad [descriptor] named in:"+name);
}
// now parse items: unit=xxx miss=xxx interval=xxx error=xxx
// 1. tokenize on " "
// 2. scan each token, retokenizing on "="
// 3. if (has no "=") && (is first one) then treat as Unit
// 4. otherwise, look for keys "unit" "miss" "inter" "err" "scale" "offset" "pos"
// and fill in the values in array[i]
if (m2 >= name.length()) {
infos[i].name = name.substring(0,m).trim();
} else {
infos[i].name = (name.substring(0,m)+name.substring(m2+1)).trim();
}
String cl = name.substring(m+1,m2).trim();
String[] stcl = cl.split(BLANK_DELIM);
int ncl = stcl.length;
if (ncl == 1 && cl.indexOf("=") == -1) {
hdrUnitString = cl; // backward compatible...
} else {
for (int l = 0; l < ncl; l++) {
String s = stcl[l];
String[] sts = s.split("=");
if (sts.length != 2) {
throw new VisADException("TextAdapter: Invalid clause in: "+s);
}
String tok = sts[0];
String val = sts[1];
// check for quoted strings
if (val.startsWith("\"")) {
// see if ending quote also fetched
if (val.endsWith("\"")) {
String v2 = val.substring(1,val.length()-1);
val = v2;
} else {
// if not, then reparse stcl to suck up spaces...
try {
String v2="";
for (int q=l+1; q < ncl; q++) {
String vTmp = stcl[q];
// find next token that has a " in it
int pos = vTmp.indexOf("\"");
l++;
if (pos < 0) { // no "
v2 = v2+" "+vTmp;
} else {
v2 = v2+" "+vTmp.substring(0,pos);
break;
}
}
String v3 = val.substring(1)+v2;
val = v3;
//} catch (NoSuchElementException nse2) {
} catch (ArrayIndexOutOfBoundsException nse2) {
val="";
}
}
}
if (debug) System.out.println("#### tok = "+tok+ " val = '"+val+"'");
if (tok.toLowerCase().startsWith(ATTR_UNIT)) {
hdrUnitString = val;
} else if (tok.toLowerCase().startsWith(ATTR_MISSING)) {
infos[i].missingString = val.trim();
try {
infos[i].missingValue = Double.parseDouble(val);
} catch (java.lang.NumberFormatException me) {
infos[i].missingValue = Double.NaN;
}
} else if (tok.toLowerCase().startsWith(ATTR_INTERVAL)) {
infos[i].isInterval = -1;
if (val.toLowerCase().startsWith("t")) infos[i].isInterval = 1;
if (val.toLowerCase().startsWith("f")) infos[i].isInterval = 0;
if (infos[i].isInterval == -1) {
throw new VisADException("TextAdapter: Value of \'interval\' must be \'true\' or \'false\'");
}
} else if (tok.toLowerCase().startsWith(ATTR_ERROR)) {
infos[i].errorEstimate = Double.parseDouble(val);
} else if (tok.toLowerCase().startsWith(ATTR_SCALE)) {
infos[i].scale = Double.parseDouble(val);
} else if (tok.toLowerCase().startsWith(ATTR_OFFSET)) {
infos[i].offset = Double.parseDouble(val);
} else if (tok.toLowerCase().startsWith(ATTR_VALUE)) {
infos[i].fixedValue = val.trim();
numHdrValues++;
} else if (tok.toLowerCase().startsWith(ATTR_COLSPAN)) {
infos[i].colspan = (int)Double.parseDouble(val.trim());
} else if (tok.toLowerCase().startsWith(ATTR_POSITION)) {
String[] stp = val.split(":");
if (stp.length != 2) {
throw new VisADException("TextAdapter: invalid Position parameter in:"+s);
}
hdrColumns[0][i] = Integer.parseInt(stp[0].trim());
hdrColumns[1][i] = Integer.parseInt(stp[1].trim());
} else if (tok.toLowerCase().startsWith(ATTR_FORMAT)) {
infos[i].formatString = val.trim();
} else if (tok.toLowerCase().startsWith(ATTR_TIMEZONE)) {
infos[i].tzString = val.trim();
} else {
throw new VisADException("TextAdapter: invalid token name: "+s);
}
}
}
}
if(properties!=null) {
for(int headerIdx=0;headerIdx<infos.length;headerIdx++) {
String value = (String)properties.get(infos[headerIdx].name+".value");
if(value!=null) infos[headerIdx].fixedValue = value;
}
}
if (debug)
System.out.println("hdr name = "+infos[i]+" units="+
hdrUnitString+
" miss="+infos[i].missingValue+" interval="+infos[i].isInterval+
" errorest="+infos[i].errorEstimate+" scale="+infos[i].scale+
" offset="+infos[i].offset+" pos="+hdrColumns[0][i]+":"+
hdrColumns[1][i]);
Unit u = null;
if (hdrUnitString != null &&
!hdrUnitString.trim().equalsIgnoreCase("null") ) {
try {
u = visad.data.units.Parser.parse(hdrUnitString.trim());
} catch (Exception ue) {
try {
u = visad.data.units.Parser.parse(
hdrUnitString.trim().replace(' ','_'));
} catch (Exception ue2) {
System.out.println("Unit name problem:"+ue+" with: "+hdrUnitString);
u = null;
}
}
}
if (debug) System.out.println("#### assigned Unit as u="+u);
String rttemp = infos[i].name.trim();
if (rttemp.indexOf("(Text)") == -1) {
int parenIndex = rttemp.indexOf("(");
if (parenIndex < 0) parenIndex = rttemp.indexOf("[");
if (parenIndex < 0) parenIndex = rttemp.indexOf("{");
if (parenIndex < 0) parenIndex = rttemp.indexOf(" ");
String rtname = parenIndex < 0 ? rttemp.trim() : rttemp.substring(0,parenIndex);
RealType rt = RealType.getRealType(rtname, u, null, infos[i].isInterval);
if (rt == null) { // tried to re-use with different units
if (debug) System.out.println("#### rt was returned as null");
if (u != null) System.out.println("#### Could not make RealType using specified Unit ("+hdrUnitString+") for parameter name: "+rtname);
rt = RealType.getRealType(rtname);
}
//Add the realType here because its possible that it can be GC'ed
//and removed from the global list of realtypes before we
//get back to it. Then the MathType.stringToType(maps) below
//will produce a realtype with no units
realTypes.add(rt);
// get a compatible unit, if necessary
if (rt.equals(visad.RealType.Time)) {
GOTTIME = true;
if (debug) System.out.println("#### found a visad.RealType.Time component");
} else {
GOTTIME = false;
}
if (u == null) u = rt.getDefaultUnit();
if(debug) System.out.println("#### retrieve units from RealType = "+u);
}
infos[i].unit = u;
}
// get the MathType of the function
MathType mt = null;
try {
mt = MathType.stringToType(maps);
} catch (Exception mte) {
System.out.println("#### Exception: "+mte);
throw new VisADException("TextAdapter: MathType badly formed or missing: "+maps);
}
if (debug) {
System.out.println(mt);
new visad.jmet.DumpType().dumpMathType(mt,System.out);
}
// now get the names of the domain variables and range variables.
String[] domainNames = null;
String[] rangeNames = null;
int numDom = 0;
int numRng = 0;
RealTupleType domType;
TupleType rngType;
if (mt instanceof FunctionType) {
domType = ((FunctionType)mt).getDomain();
numDom = domType.getDimension();
domainNames = new String[numDom];
for (int i=0; i<numDom; i++) {
MathType comp = domType.getComponent(i);
domainNames[i] = ((RealType)comp).toString().trim();
if (debug) System.out.println("dom "+i+" = "+domainNames[i]);
}
rngType = (TupleType) ((FunctionType)mt).getRange();
numRng = rngType.getDimension();
rangeNames = new String[numRng];
rangeSets = new Set[numRng];
for (int i=0; i<numRng; i++) {
MathType comp = rngType.getComponent(i);
rangeNames[i] = (comp).toString().trim();
if (debug) System.out.println("range "+i+" = "+rangeNames[i]);
if (comp instanceof RealType) {
rangeSets[i] = ((RealType) comp).getDefaultSet();
if (rangeSets[i] == null) {
if (comp.equals(RealType.Time)) {
rangeSets[i] = new DoubleSet(new SetType(comp));
} else {
rangeSets[i] = new FloatSet(new SetType(comp));
}
}
} else {
rangeSets[i] = null; // something else is wrong here...
}
if (debug) System.out.println("#### rangeSet = "+rangeSets[i]);
;
}
} else {
throw new visad.VisADException("TextAdapter: Math Type is not a simple FunctionType");
}
// now for each header label, determine if it's a domain or
// range component -- and if so, which one.
// also, if it's a domain component, allow for name(first:last[:number])
//
// and if none of the domain components appear in the list, then
// they are computed as name(0:N-1)
int[] domainPointer = new int[numDom];
double[][] domainRanges = new double[3][numDom]; // min, max, numb
boolean[] gotDomainRanges = new boolean[numDom];
domainErrorEstimates = new double[numDom];
domainUnits = new Unit[numDom];
rangeErrorEstimates = new double[numRng];
rangeUnits = new Unit[numRng];
int countDomain = 0;
for (int i=0; i<numDom; i++) {
domainPointer[i] = -1;
gotDomainRanges[i] = false;
domainErrorEstimates[i] = Double.NaN;
domainUnits[i] = null;
}
int[] rangePointer = new int[numRng];
int countRange = 0;
for (int i=0; i<numRng; i++) {
rangePointer[i] = -1;
rangeErrorEstimates[i] = Double.NaN;
rangeUnits[i] = null;
}
int countValues = -1;
values_to_index = new int[3][nhdr];
for (int i=0; i<nhdr; i++) {
values_to_index[0][i] = -1; // points to domains
values_to_index[1][i] = -1; // points to ranges
values_to_index[2][i] = -1; // points to names/units/etc
countValues ++;
String name = infos[i].name;
// see if it's a domain name
boolean gotName = false;
// is there a "min:max" clause?
String test_name = name;
int n = test_name.indexOf("(");
if (n != -1) {
// but allow for "(Text)"
if ((test_name.indexOf("(Text)")) == -1) {
test_name = name.substring(0,n).trim();
countValues --; // this value wont appear in data!
countDomain --; // and is a pre-defined, linear set
}
}
// try to find the column header name in the domain name list
for (int k=0; k<numDom; k++) {
if (test_name.equals(domainNames[k]) ) {
domainPointer[k] = countValues;
domainErrorEstimates[k] = infos[i].errorEstimate;
domainUnits[k] = infos[i].unit;
gotName = true;
countDomain ++;
// now see if a list is given...
if (n != -1) {
try {
String ss = name.substring(n+1,name.length()-1);
String[] sct = ss.split(":");
String first = sct[0].trim();
String second = sct[1].trim();
String third = "1";
if (sct.length == 3) third = sct[2].trim();
domainRanges[0][k] = Double.parseDouble(first);
domainRanges[1][k] = Double.parseDouble(second);
domainRanges[2][k] = Double.parseDouble(third);
gotDomainRanges[k] = true;
} catch (Exception ef) {
throw new VisADException(
"TextAdapter: Error while interpreting min:max values for domain "+name);
}
} else if (countValues > -1) { // if no list, get from file
values_to_index[0][countValues] = k;
values_to_index[2][countValues] = i;
}
break;
}
}
if (gotName) continue;
// or see if its a range name...
for (int k=0; k<numRng; k++) {
if (name.equals(rangeNames[k]) ) {
rangePointer[k] = countValues;
rangeErrorEstimates[k] = infos[i].errorEstimate;
rangeUnits[k] = infos[i].unit;
countRange ++;
values_to_index[1][countValues] = k;
values_to_index[2][countValues] = i;
gotName = true;
}
}
}
// huge debug printout...
// *****************************************************************
if (debug) {
System.out.println("countDom/numDom="+countDomain+" "+numDom);
System.out.println("countRange/numRng="+countRange+" "+numRng);
System.out.println("Domain info:");
for (int i=0; i<numDom; i++) {
System.out.println("Dom name / index = "+domainNames[i]+" "+
domainPointer[i]);
if (gotDomainRanges[i]) {
System.out.println(" ..."+domainRanges[0][i]+" "+
domainRanges[1][i]+" "+domainRanges[2][i]);
}
}
System.out.println("Range info:");
for (int i=0; i<numRng; i++) {
System.out.println("Rng name / index / error est = "+rangeNames[i]+" "+
rangePointer[i]+ " " + rangeErrorEstimates[i] +" "+
rangeUnits[i]);
}
System.out.println("values_to_index pointers = ");
for (int i=0; i<nhdr; i++) {
System.out.println(" inx / value = "+i+
" "+values_to_index[0][i]+" "+values_to_index[1][i]+
" "+values_to_index[2][i]);
}
}
// ***************************************************************
// for each line of text, put the values into the ArrayList
ArrayList domainValues = new ArrayList();
ArrayList rangeValues = new ArrayList();
ArrayList tupleValues = new ArrayList();
boolean tryToMakeTuple = true;
Tuple tuple = null;
String dataDelim = DELIM;
boolean isRaster = false;
int numElements = 1;
// in the 'raster array' case, the numRng value will be 1,
// along with the countRange. numDomain must be 2.
// if the domain is 2D, then get values from the first
// matching column to the end...
if (countRange == 1 && numRng == 1 &&
numDom == 2 && countDomain < 2) isRaster = true;
int index;
+ int lineCnt = 0;
while (true) {
- String s = bis.readLine();
- if (debug) System.out.println("read:"+s);
- if (s == null) break;
- if (!isText(s)) return;
- if (isComment(s)) continue;
- if((index=s.indexOf("="))>=0) { // fixed value
- String name = s.substring(0,index).trim();
- String value = s.substring(index+1).trim();
+ String line = bis.readLine();
+ if (debug) System.out.println("read:"+line);
+ if (line == null) break;
+ if (!isText(line)) return;
+ if (isComment(line)) continue;
+ if((index=line.indexOf("="))>=0) { // fixed value
+ String name = line.substring(0,index).trim();
+ String value = line.substring(index+1).trim();
boolean foundIt = false;
for(int paramIdx=0;paramIdx<infos.length;paramIdx++) {
if(infos[paramIdx].isParam(name)) {
if(infos[paramIdx].fixedValue==null) {
numHdrValues++;
}
infos[paramIdx].fixedValue = value;
foundIt = true;
break;
}
}
if(!foundIt) {
throw new VisADException(
- "TextAdapter: Cannot find field with name:" +name +" from line:" + s);
+ "TextAdapter: Cannot find field with name:" +name +" from line:" + line);
}
continue;
}
if (dataDelim == null) {
- if (s.indexOf(BLANK) != -1) dataDelim = BLANK_DELIM;
- if (s.indexOf(COMMA) != -1) dataDelim = COMMA;
- if (s.indexOf(SEMICOLON) != -1) dataDelim = SEMICOLON;
- if (s.indexOf(TAB) != -1) dataDelim = TAB;
+ if (line.indexOf(BLANK) != -1) dataDelim = BLANK_DELIM;
+ if (line.indexOf(COMMA) != -1) dataDelim = COMMA;
+ if (line.indexOf(SEMICOLON) != -1) dataDelim = SEMICOLON;
+ if (line.indexOf(TAB) != -1) dataDelim = TAB;
if (debug) System.out.println("Using data delimiter = "+
((dataDelim == null)
? "null"
: dataDelim + " (" + (dataDelim.getBytes())[0] +")"));
}
- String[] st = s.split(dataDelim);
+ String[] st = line.split(dataDelim);
int n = st.length;
if (n < 1) continue; // something is wrong if this happens!
+ lineCnt++;
double [] dValues = new double[numDom];
double [] rValues = null;
Data [] tValues = null;
if (isRaster) {
if (debug) System.out.println("probably a raster...");
boolean gotFirst = false;
int rvaluePointer = 0;
int irange = 0;
for (int i=0; i<n; i++) {
String sa = st[i];
if (i >= nhdr) { // are we past where domain would be found?
if (!gotFirst) {
throw new VisADException(
"TextAdapter: Cannot find first raster value");
}
rvaluePointer ++;
rValues[rvaluePointer] = getVal(sa, irange);
} else { // or are we still looking for domain?
if (values_to_index[0][i] != -1) {
dValues[values_to_index[0][i]] = getVal(sa, i);
}
if (gotFirst) { // already gathering data
rvaluePointer ++;
rValues[rvaluePointer] = getVal(sa, irange);
} else {
if (values_to_index[1][i] != -1) {
// cannot dimension the array until we have found
// the first set of range values!!
rValues = new double[n - i];
irange = i;
rValues[rvaluePointer] = getVal(sa, irange);
gotFirst = true;
}
}
}
}
} else { // is probably NOT a raster
tValues = new Data[numRng];
if (debug) System.out.println("probably not a raster...");
rValues = new double[numRng];
double thisDouble;
MathType thisMT;
if (n > nhdr) n = nhdr; // in case the # tokens > # parameters
n +=numHdrValues;
int l = 0; // token counter
for (int i=0; i<nhdr; i++) { // loop over the columns
String sa=null;
if(sa == null) {
if(infos[i].fixedValue!=null) {
sa = infos[i].fixedValue;
} else if (l >= st.length) { // more params than tokens
sa = ""; // need to have a missing value
} else {
sa = st[l++].trim();
int moreColumns = infos[i].colspan-1;
while (moreColumns>0) {
sa = sa + " " + st[l++].trim();
moreColumns--;
}
}
}
String sThisText;
if (values_to_index[0][i] != -1) {
dValues[values_to_index[0][i]] = getVal(sa, i);
} else if (values_to_index[1][i] != -1) {
thisMT = rngType.getComponent(values_to_index[1][i]);
if (thisMT instanceof TextType) {
// if Text, then check for quoted string
if (sa.startsWith("\"")) {
if (sa.endsWith("\"")) { // if single token ends with quote
String sa2 = sa.substring(1,sa.length()-1);
sThisText = sa2;
} else {
// TODO: work on this
try {
String delim =
dataDelim.equals(BLANK_DELIM) ? BLANK : dataDelim;
String sa2="";
for (int q=l; q < st.length; q++) {
String saTmp = st[q];
// find next token that has a " in it
int pos = saTmp.indexOf("\"");
l++;
if (pos < 0) { // no dataDelim
sa2 = sa2+delim+saTmp;
} else {
sa2 = sa2+saTmp.substring(0,pos);
//st[l] = saTmp.substring(pos+1);
break;
}
}
//sThisText = sa.substring(1)+sa2;
sThisText = sa.substring(1)+delim+sa2;
//} catch (NoSuchElementException nse) {
} catch (ArrayIndexOutOfBoundsException nse) {
sThisText = "";
}
}
if (debug) System.out.println("#### Text value='"+sThisText+"'");
// if not quoted, then take "as is"
} else {
sThisText = sa;
}
// now make the VisAD Data
try {
tValues[values_to_index[1][i]] =
new Text((TextType) thisMT, sThisText);
if (debug) System.out.println("tValues[" +
values_to_index[1][i] + "] = " +
tValues[values_to_index[1][i]]);
} catch (Exception e) {
System.out.println(" Exception converting " +
thisMT + " to TextType " + e);
}
// if not Text, then treat as numeric
} else {
double value = getVal(sa,i);
rValues[values_to_index[1][i]] = value;
try {
if(prototypeReals[i]==null) {
prototypeReals[i] = new Real((RealType) thisMT, getVal(sa,i), infos[i].unit);
}
tValues[values_to_index[1][i]] =
prototypeReals[i].cloneButValue(value);
if(debug)System.out.println("tValues[" +
values_to_index[1][i] + "] = " +
tValues[values_to_index[1][i]]);
} catch (Exception e) {
System.out.println(" Exception converting " + thisMT + " " + e);
}
}
}
}
}
if(tryToMakeTuple) {
try {
if (tValues != null) tuple = new Tuple(tValues);
} catch (visad.TypeException te) {
// do nothing: it means they are all reals
// tuple = new RealTuple(tValues);
tuple = null;
tryToMakeTuple = false;
} catch(NullPointerException npe) {
for(int i=0;i<tValues.length;i++) {
if(tValues[i] == null) {
- throw new IllegalArgumentException("An error occurred reading column number:" + (i+1));
+ throw new IllegalArgumentException("An error occurred reading line number:" + lineCnt+" column number:" + (i+1)+"\n" +
+ line);
}
}
throw npe;
}
}
domainValues.add(dValues);
rangeValues.add(rValues);
if (tuple != null) tupleValues.add(tuple);
if (isRaster) numElements = rValues.length;
if(onlyReadOneLine) break;
}
int numSamples = rangeValues.size(); // # lines of data
// ***********************************************************
if (debug) {
try {
System.out.println("domain size = "+domainValues.size());
double[] dt = (double[]) domainValues.get(1);
System.out.println("domain.array[0] = "+dt[0]);
System.out.println("range size = "+rangeValues.size());
System.out.println("# samples = "+numSamples);
} catch (Exception er) {System.out.println("out range");}
}
// ***********************************************************
// make Linear1DSets for each possible domain component
Linear1DSet[] lset = new Linear1DSet[numDom];
boolean keepConstant = false;
int numVal = numRng;
if (numDom == 1) numVal = numSamples;
if (numDom == 2 && numRng == 1 && numElements > 1) numVal = numElements;
if (numDom > 2 && numRng == 1 && numElements == 1) {
numVal = numSamples / (2 * numDom);
keepConstant = true;
}
for (int i=0; i<numDom; i++) {
if (gotDomainRanges[i]) {
// if domain was given with a count, use it for 'raster'-type
if (numDom == 2 && numRng == 1 && numElements == 1)
numVal = (int) domainRanges[2][i];
lset[i] = new Linear1DSet(domType.getComponent(i), domainRanges[0][i],
domainRanges[1][i], numVal);
if (debug) System.out.println("lset from domain = "+lset[i]);
} else if (domainPointer[i] == -1 ) {
lset[i] = new Linear1DSet(0., (double)(numVal-1), numVal);
if (debug) System.out.println("lset from range = "+lset[i]);
} else {
lset[i] = null;
}
if (!keepConstant) numVal = numSamples;
}
// now make up the actual domain sets for the function
Set domain = null;
if (numDom == 1) { // for 1-D domains
if (lset[0] == null) {
domain = createAppropriate1DDomain(domType, numSamples, domainValues);
} else {
domain = lset[0];
}
} else if (numDom == 2) { // for 2-D domains
if (lset[0] != null && lset[1] != null) {
domain = new Linear2DSet(domType, lset);
} else {
float[][] samples = new float[numDom][numSamples];
for (int k = 0; k < numDom; k++) {
if (lset[k] == null) {
samples[k] = (getDomSamples(k, numSamples, domainValues))[0];
} else {
samples[k] = (lset[k].getSamples())[0];
}
}
domain = (Set) new Irregular2DSet(domType, samples);
}
} else if (numDom == 3) { // for 3-D domains
if (lset[0] != null && lset[1] != null && lset[2] != null) {
domain = new Linear3DSet(domType, lset);
} else {
float[][] samples = new float[numDom][numSamples];
for (int k = 0; k < numDom; k++) {
if (lset[k] == null) {
samples[k] = (getDomSamples(k, numSamples, domainValues))[0];
} else {
samples[k] = (lset[k].getSamples())[0];
}
}
domain = (Set) new Irregular3DSet(domType, samples);
}
} else { // N-D domains (can only use LinearSets!!
boolean allLinear = true;
for (int k = 0; k<numDom; k++) {
if (lset[k] == null) allLinear = false;
}
if (allLinear) {
if (debug) System.out.println("#### Making LinearNDset");
domain = new LinearNDSet(domType, lset);
} else {
if (debug) System.out.println("#### Making IrregularSet");
float[][] samples = new float[numDom][numSamples];
for (int k=0; k<numDom; k++) {
if (lset[k] == null) {
samples[k] = (getDomSamples(k, numSamples, domainValues))[0];
} else {
samples[k] = (lset[k].getSamples())[0];
}
}
domain = new IrregularSet(domType, samples);
}
}
try {
ff = new FlatField((FunctionType) mt, domain,
null, null, rangeSets, rangeUnits);
} catch (FieldException fe) {
field = new FieldImpl((FunctionType) mt, domain);
} catch (UnitException fe) {
System.out.println("#### Problem with Units; attempting to make Field anyway");
field = new FieldImpl((FunctionType) mt, domain);
}
//*************************************************
if (debug) {
if (ff != null) {
System.out.println("ff.Length "+ff.getLength());
System.out.println("ff.getType "+ff.getType());
}
if (field != null) {
System.out.println("field.Length "+field.getLength());
System.out.println("field.getType "+field.getType());
}
System.out.println("domain = "+domain);
System.out.println("size of a = "+numRng+" x "+(numSamples*numElements));
}
//*************************************************
double[][]a = new double[numRng][numSamples * numElements];
Tuple[] at = new Tuple[numSamples];
// if this is a raster then the samples are in a slightly
// difielderent form ...
if (isRaster) {
int samPointer = 0;
for (int i=0; i<numSamples; i++) {
double[] rs = (double[])(rangeValues.get(i));
for (int j=0; j<numElements; j++) {
a[0][samPointer] = rs[j];
samPointer ++;
}
}
} else {
for (int i=0; i<numSamples; i++) {
double[] rs = (double[])(rangeValues.get(i));
for (int j=0; j<numRng; j++) {
a[j][i] = rs[j];
}
if (!tupleValues.isEmpty()) {
at[i] = (Tuple) tupleValues.get(i);
}
}
}
// set samples
if (debug) System.out.println("about to field.setSamples");
try {
if (ff != null) {
if (debug) System.out.println("#### ff is not null");
ff.setSamples(a, false);
field = (Field) ff;
} else {
if (debug) System.out.println("#### ff is null..use FieldImpl");
field.setSamples(at, false);
}
} catch (Exception ffe) {ffe.printStackTrace(); }
// make up error estimates and set them
ErrorEstimate[] es = new ErrorEstimate[numRng];
for (int i=0; i<numRng; i++) {
es[i] = new ErrorEstimate(a[i], rangeErrorEstimates[i], rangeUnits[i]);
}
try {
((FlatField) field).setRangeErrors(es);
} catch (FieldException fe) {
if (debug) System.out.println("caught "+fe);
// not a flatfield
// don't setRangeErrors
} catch (ClassCastException cce) {
if (debug) System.out.println("caught "+cce);
// not a flatfield
// don't setRangeErrors
}
if (debug) {
new visad.jmet.DumpType().dumpDataType(field,System.out);
System.out.println("field = "+field);
}
bis.close();
}
// munges a pseudo MathType string into something legal
private String makeMT(String s) {
int k = s.indexOf("->");
if (k < 0) {
// System.out.println("TextAdapter: invalid MathType form; -> required");
return null;
}
StringBuffer sb = new StringBuffer("");
for (int i=0; i<s.length(); i++) {
String r = s.substring(i,i+1);
if (!r.equals(" ") && !r.equals("\t") && !r.equals("\n")) {
sb.append(r);
}
}
String t = sb.toString();
k = t.indexOf("->");
if (t.charAt(k-1) != ')' ) {
if (t.charAt(k+2) != '(' ) {
String t2 = "("+t.substring(0,k) + ")->("+t.substring(k+2)+")";
t = t2;
} else {
String t2 = "("+t.substring(0,k) + ")"+t.substring(k);
t = t2;
}
} else if (t.charAt(k+2) != '(' ) {
String t2 = t.substring(0,k+2)+"("+t.substring(k+2)+")";
t = t2;
}
if (!t.startsWith("((") ) {
String t2= "("+t+")";
t = t2;
}
return t;
}
private static final boolean isText(String s)
{
final int len = (s == null ? -1 : s.length());
if (len <= 0) {
// well, it's not really *binary*, so pretend it's text
return true;
}
for (int i = 0; i < len; i++) {
final char ch = s.charAt(i);
if (Character.isISOControl(ch) && !Character.isWhitespace(ch)) {
// we might want to special-case formfeed/linefeed/newline here...
return false;
}
}
return true;
}
/**
* generate a DateTime from a string
* @param string - Formatted date/time string
*
* @return - the equivalent VisAD DateTime for the string
*
* (lifted from au.gov.bom.aifs.common.ada.VisADXMLAdapter.java)
*/
private static visad.DateTime makeDateTimeFromString(String string,
String format, String tz)
throws java.text.ParseException
{
visad.DateTime dt = null;
// try to parse the string using the supplied DateTime format
try {
if(dateParsers!=null) {
for(int i=0;i<dateParsers.size();i++) {
DateParser dateParser = (DateParser) dateParsers.get(i);
dt = dateParser.createDateTime(string, format, TimeZone.getTimeZone(tz));
if(dt !=null) {
return dt;
}
}
}
dt = visad.DateTime.createDateTime(string, format, TimeZone.getTimeZone(tz));
} catch (VisADException e) {}
if (dt==null) {
throw new java.text.ParseException("Couldn't parse visad.DateTime from \""
+string+"\"", -1);
} else {
return dt;
}
}
/** This list of DateFormatter-s will be checked when we are making a DateTime wiht a given format */
private static List dateParsers;
/** used to allow applications to define their own date parsing */
public static interface DateParser {
/** If this particular DateParser does not know how to handle the give format then this method should return null */
public DateTime createDateTime(String value, String format, TimeZone timezone) throws VisADException;
}
/** used to allow applications to define their own date parsing */
public static void addDateParser(DateParser dateParser) {
if(dateParsers==null) {
dateParsers = new ArrayList();
}
dateParsers.add(dateParser);
}
double getVal(String s, int k) {
int i = values_to_index[2][k];
if (i < 0 || s == null || s.length()<1 || s.equals(infos[i].missingString)) {
return Double.NaN;
}
// try parsing as a double first
if (infos[i].formatString == null) {
// no format provided : parse as a double
try {
double v;
try {
v = Double.parseDouble(s);
} catch (java.lang.NumberFormatException nfe1) {
//If units are degrees then try to decode this as a lat/lon
// We should probably not rely on throwing an exception to handle this but...
if(infos[i].unit !=null && Unit.canConvert(infos[i].unit, visad.CommonUnit.degree)) {
v=decodeLatLon(s);
} else {
throw nfe1;
}
if(v!=v) throw new java.lang.NumberFormatException(s);
}
if (v == infos[i].missingValue) {
return Double.NaN;
}
v = v * infos[i].scale + infos[i].offset;
return v;
} catch (java.lang.NumberFormatException ne) {
System.out.println("Invalid number format for "+s);
}
} else {
// a format was specified: only support DateTime format
// so try to parse as a DateTime
try{
visad.DateTime dt = makeDateTimeFromString(s, infos[i].formatString, infos[i].tzString);
return dt.getReal().getValue();
} catch (java.text.ParseException pe) {
System.out.println("Invalid number/time format for "+s);
}
}
return Double.NaN;
}
// get the samples from the ArrayList.
float[][] getDomSamples(int comp, int numDomValues, ArrayList domValues) {
float [][] a = new float[1][numDomValues];
for (int i=0; i<numDomValues; i++) {
double[] d = (double[])(domValues.get(i));
a[0][i] = (float)d[comp];
}
return a;
}
/** get the data
* @return a Field of the data read from the file
*
*/
public Field getData() {
return field;
}
/**
* Returns an appropriate 1D domain.
*
* @param type the math-type of the domain
* @param numSamples the number of samples in the domain
* @param domValues domain values are extracted from this array list.
*
* @return a Linear1DSet if the domain samples form an arithmetic
* progression, a Gridded1DDoubleSet if the domain samples are ordered
* but do not form an arithmetic progression, otherwise an Irregular1DSet.
*
* @throws VisADException there was a problem creating the domain set.
*/
private Set createAppropriate1DDomain(MathType type, int numSamples,
ArrayList domValues)
throws VisADException {
if (0 == numSamples) {
// Can't create a domain set with zero samples.
return null;
}
// Extract the first element from each element of the array list.
double[][] values = new double[1][numSamples];
for (int i=0; i<numSamples; ++i) {
double[] d = (double []) domValues.get(i);
values[0][i] = d[0];
}
// This implementation for testing that the values are ordered
// is based on visad.Gridded1DDoubleSet.java
boolean ordered = true;
boolean ascending = values[0][numSamples -1] > values[0][0];
if (ascending) {
for (int i=1; i<numSamples; ++i) {
if (values[0][i] < values[0][i - 1]) {
ordered = false;
break;
}
}
} else {
for (int i=1; i<numSamples; ++i) {
if (values[0][i] > values[0][i - 1]) {
ordered = false;
break;
}
}
}
Set set = null;
if (ordered) {
ArithProg arithProg = new ArithProg();
if (arithProg.accumulate(values[0])) {
// The domain values form an arithmetic progression (ordered and
// equally spaced) so use a linear set.
set = new Linear1DSet(type, values[0][0], values[0][numSamples - 1],
numSamples);
} else {
// The samples are ordered, so use a gridded set.
set = new Gridded1DDoubleSet(type, values, numSamples);
}
} else {
set = new Irregular1DSet(type, Set.doubleToFloat(values));
}
return set;
}
private static class HeaderInfo {
String name;
Unit unit;
double missingValue = Double.NaN;
String missingString;
String formatString;
String tzString = "GMT";
int isInterval = 0;
double errorEstimate=0;
double scale=1.0;
double offset=0.0;
String fixedValue;
int colspan = 1;
public boolean isParam(String param) {
return name.equals(param) || name.equals(param+"(Text)");
}
public String toString() {
return name;
}
}
// uncomment to test
public static void main(String[] args) throws Exception {
if (args.length == 0) {
System.out.println("Must supply a filename");
System.exit(1);
}
TextAdapter ta = new TextAdapter(args[0]);
System.out.println(ta.getData().getType());
new visad.jmet.DumpType().dumpMathType(ta.getData().getType(),System.out);
new visad.jmet.DumpType().dumpDataType(ta.getData(),System.out);
System.out.println("#### Data = "+ta.getData());
System.out.println("EOF... ");
}
/**
* A cut-and-paste from the IDV Misc method
* Decodes a string representation of a latitude or longitude and
* returns a double version (in degrees). Acceptible formats are:
* <pre>
* +/- ddd:mm, ddd:mm:, ddd:mm:ss, ddd::ss, ddd.fffff ===> [+/-] ddd.fffff
* +/- ddd, ddd:, ddd:: ===> [+/-] ddd
* +/- :mm, :mm:, :mm:ss, ::ss, .fffff ===> [+/-] .fffff
* +/- :, :: ===> 0.0
* Any of the above with N,S,E,W appended
* </pre>
*
* @param latlon string representation of lat or lon
* @return the decoded value in degrees
*/
public static double decodeLatLon(String latlon) {
// first check to see if there is a N,S,E,or W on this
latlon = latlon.trim();
int dirIndex = -1;
int southOrWest = 1;
double value = Double.NaN;
if (latlon.indexOf("S") > 0) {
southOrWest = -1;
dirIndex = latlon.indexOf("S");
} else if (latlon.indexOf("W") > 0) {
southOrWest = -1;
dirIndex = latlon.indexOf("W");
} else if (latlon.indexOf("N") > 0) {
dirIndex = latlon.indexOf("N");
} else if (latlon.indexOf("E") > 0) {
dirIndex = latlon.indexOf("E");
}
if (dirIndex > 0) {
latlon = latlon.substring(0, dirIndex).trim();
}
// now see if this is a negative value
if (latlon.indexOf("-") == 0) {
southOrWest *= -1;
latlon = latlon.substring(latlon.indexOf("-") + 1).trim();
}
if (latlon.indexOf(":") >= 0) { //have something like DD:MM:SS, DD::, DD:MM:, etc
int firstIdx = latlon.indexOf(":");
String hours = latlon.substring(0, firstIdx);
String minutes = latlon.substring(firstIdx + 1);
String seconds = "";
if (minutes.indexOf(":") >= 0) {
firstIdx = minutes.indexOf(":");
String temp = minutes.substring(0, firstIdx);
seconds = minutes.substring(firstIdx + 1);
minutes = temp;
}
try {
value = (hours.equals("") == true)
? 0
: Double.parseDouble(hours);
if ( !minutes.equals("")) {
value += Double.parseDouble(minutes) / 60.;
}
if ( !seconds.equals("")) {
value += Double.parseDouble(seconds) / 3600.;
}
} catch (NumberFormatException nfe) {
value = Double.NaN;
}
} else { //have something like DD.ddd
try {
value = Double.parseDouble(latlon);
} catch (NumberFormatException nfe) {
value = Double.NaN;
}
}
return value * southOrWest;
}
}
| false | true | void readit(InputStream is, String map, String params)
throws IOException, VisADException {
// read the ASCII file, using commas as field separators
// first line is a header line
List realTypes = new ArrayList();
ff = null;
field = null;
if (debug) System.out.println("#### Text Adapter v2.x running");
BufferedReader bis = new BufferedReader(new InputStreamReader(is));
// mapping defines how the names are mapped
// for example: (x,y) => (one, two, three)
String maps = null;
if (map == null) {
maps = readLine(bis);
if(maps != null) {
maps = maps.trim();
}
} else {
maps = map;
}
if (maps != null) {
maps = makeMT(maps);
}
if (maps == null) {
throw new visad.data.BadFormException(
"TextAdapter: Invalid or missing MathType");
}
if (debug) System.out.println("Specified MathType = "+maps);
// but first, we need to get the column headers because they
// may have [units] associated with them. The column headers
// primarily define where the data are.
String hdr = null;
if (params == null) {
hdr = readLine(bis);
} else {
hdr = params;
}
String hdrDelim = DELIM;
if (DELIM == null) {
if (hdr.indexOf(BLANK) != -1) hdrDelim = BLANK_DELIM;
if (hdr.indexOf(COMMA) != -1) hdrDelim = COMMA;
if (hdr.indexOf(SEMICOLON) != -1) hdrDelim = SEMICOLON;
if (hdr.indexOf(TAB) != -1) hdrDelim = TAB;
if (debug) System.out.println("Using header delimiter = "+ hdrDelim + "("+
(hdrDelim.getBytes())[0] + ")");
}
String[] sthdr = hdr.split(hdrDelim);
int nhdr = sthdr.length;
infos = new HeaderInfo[nhdr];
for(int i=0;i<infos.length;i++) {
infos[i] = new HeaderInfo();
}
Real[] prototypeReals = new Real[nhdr];
hdrColumns = new int[2][nhdr];
int numHdrValues=0;
// pre-scan of the header names to seek out Units
// since we cannot change a RealType once it's defined!!
for (int i=0; i<nhdr; i++) {
String name = sthdr[i].trim();
String hdrUnitString = null;
hdrColumns[0][i] = -1; // indicating no fixed columns
int m = name.indexOf("[");
if (m == -1) {
infos[i].name = name;
hdrUnitString = null;
} else {
int m2 = name.indexOf("]");
if (m2 == -1) {
throw new VisADException("TextAdapter: Bad [descriptor] named in:"+name);
}
// now parse items: unit=xxx miss=xxx interval=xxx error=xxx
// 1. tokenize on " "
// 2. scan each token, retokenizing on "="
// 3. if (has no "=") && (is first one) then treat as Unit
// 4. otherwise, look for keys "unit" "miss" "inter" "err" "scale" "offset" "pos"
// and fill in the values in array[i]
if (m2 >= name.length()) {
infos[i].name = name.substring(0,m).trim();
} else {
infos[i].name = (name.substring(0,m)+name.substring(m2+1)).trim();
}
String cl = name.substring(m+1,m2).trim();
String[] stcl = cl.split(BLANK_DELIM);
int ncl = stcl.length;
if (ncl == 1 && cl.indexOf("=") == -1) {
hdrUnitString = cl; // backward compatible...
} else {
for (int l = 0; l < ncl; l++) {
String s = stcl[l];
String[] sts = s.split("=");
if (sts.length != 2) {
throw new VisADException("TextAdapter: Invalid clause in: "+s);
}
String tok = sts[0];
String val = sts[1];
// check for quoted strings
if (val.startsWith("\"")) {
// see if ending quote also fetched
if (val.endsWith("\"")) {
String v2 = val.substring(1,val.length()-1);
val = v2;
} else {
// if not, then reparse stcl to suck up spaces...
try {
String v2="";
for (int q=l+1; q < ncl; q++) {
String vTmp = stcl[q];
// find next token that has a " in it
int pos = vTmp.indexOf("\"");
l++;
if (pos < 0) { // no "
v2 = v2+" "+vTmp;
} else {
v2 = v2+" "+vTmp.substring(0,pos);
break;
}
}
String v3 = val.substring(1)+v2;
val = v3;
//} catch (NoSuchElementException nse2) {
} catch (ArrayIndexOutOfBoundsException nse2) {
val="";
}
}
}
if (debug) System.out.println("#### tok = "+tok+ " val = '"+val+"'");
if (tok.toLowerCase().startsWith(ATTR_UNIT)) {
hdrUnitString = val;
} else if (tok.toLowerCase().startsWith(ATTR_MISSING)) {
infos[i].missingString = val.trim();
try {
infos[i].missingValue = Double.parseDouble(val);
} catch (java.lang.NumberFormatException me) {
infos[i].missingValue = Double.NaN;
}
} else if (tok.toLowerCase().startsWith(ATTR_INTERVAL)) {
infos[i].isInterval = -1;
if (val.toLowerCase().startsWith("t")) infos[i].isInterval = 1;
if (val.toLowerCase().startsWith("f")) infos[i].isInterval = 0;
if (infos[i].isInterval == -1) {
throw new VisADException("TextAdapter: Value of \'interval\' must be \'true\' or \'false\'");
}
} else if (tok.toLowerCase().startsWith(ATTR_ERROR)) {
infos[i].errorEstimate = Double.parseDouble(val);
} else if (tok.toLowerCase().startsWith(ATTR_SCALE)) {
infos[i].scale = Double.parseDouble(val);
} else if (tok.toLowerCase().startsWith(ATTR_OFFSET)) {
infos[i].offset = Double.parseDouble(val);
} else if (tok.toLowerCase().startsWith(ATTR_VALUE)) {
infos[i].fixedValue = val.trim();
numHdrValues++;
} else if (tok.toLowerCase().startsWith(ATTR_COLSPAN)) {
infos[i].colspan = (int)Double.parseDouble(val.trim());
} else if (tok.toLowerCase().startsWith(ATTR_POSITION)) {
String[] stp = val.split(":");
if (stp.length != 2) {
throw new VisADException("TextAdapter: invalid Position parameter in:"+s);
}
hdrColumns[0][i] = Integer.parseInt(stp[0].trim());
hdrColumns[1][i] = Integer.parseInt(stp[1].trim());
} else if (tok.toLowerCase().startsWith(ATTR_FORMAT)) {
infos[i].formatString = val.trim();
} else if (tok.toLowerCase().startsWith(ATTR_TIMEZONE)) {
infos[i].tzString = val.trim();
} else {
throw new VisADException("TextAdapter: invalid token name: "+s);
}
}
}
}
if(properties!=null) {
for(int headerIdx=0;headerIdx<infos.length;headerIdx++) {
String value = (String)properties.get(infos[headerIdx].name+".value");
if(value!=null) infos[headerIdx].fixedValue = value;
}
}
if (debug)
System.out.println("hdr name = "+infos[i]+" units="+
hdrUnitString+
" miss="+infos[i].missingValue+" interval="+infos[i].isInterval+
" errorest="+infos[i].errorEstimate+" scale="+infos[i].scale+
" offset="+infos[i].offset+" pos="+hdrColumns[0][i]+":"+
hdrColumns[1][i]);
Unit u = null;
if (hdrUnitString != null &&
!hdrUnitString.trim().equalsIgnoreCase("null") ) {
try {
u = visad.data.units.Parser.parse(hdrUnitString.trim());
} catch (Exception ue) {
try {
u = visad.data.units.Parser.parse(
hdrUnitString.trim().replace(' ','_'));
} catch (Exception ue2) {
System.out.println("Unit name problem:"+ue+" with: "+hdrUnitString);
u = null;
}
}
}
if (debug) System.out.println("#### assigned Unit as u="+u);
String rttemp = infos[i].name.trim();
if (rttemp.indexOf("(Text)") == -1) {
int parenIndex = rttemp.indexOf("(");
if (parenIndex < 0) parenIndex = rttemp.indexOf("[");
if (parenIndex < 0) parenIndex = rttemp.indexOf("{");
if (parenIndex < 0) parenIndex = rttemp.indexOf(" ");
String rtname = parenIndex < 0 ? rttemp.trim() : rttemp.substring(0,parenIndex);
RealType rt = RealType.getRealType(rtname, u, null, infos[i].isInterval);
if (rt == null) { // tried to re-use with different units
if (debug) System.out.println("#### rt was returned as null");
if (u != null) System.out.println("#### Could not make RealType using specified Unit ("+hdrUnitString+") for parameter name: "+rtname);
rt = RealType.getRealType(rtname);
}
//Add the realType here because its possible that it can be GC'ed
//and removed from the global list of realtypes before we
//get back to it. Then the MathType.stringToType(maps) below
//will produce a realtype with no units
realTypes.add(rt);
// get a compatible unit, if necessary
if (rt.equals(visad.RealType.Time)) {
GOTTIME = true;
if (debug) System.out.println("#### found a visad.RealType.Time component");
} else {
GOTTIME = false;
}
if (u == null) u = rt.getDefaultUnit();
if(debug) System.out.println("#### retrieve units from RealType = "+u);
}
infos[i].unit = u;
}
// get the MathType of the function
MathType mt = null;
try {
mt = MathType.stringToType(maps);
} catch (Exception mte) {
System.out.println("#### Exception: "+mte);
throw new VisADException("TextAdapter: MathType badly formed or missing: "+maps);
}
if (debug) {
System.out.println(mt);
new visad.jmet.DumpType().dumpMathType(mt,System.out);
}
// now get the names of the domain variables and range variables.
String[] domainNames = null;
String[] rangeNames = null;
int numDom = 0;
int numRng = 0;
RealTupleType domType;
TupleType rngType;
if (mt instanceof FunctionType) {
domType = ((FunctionType)mt).getDomain();
numDom = domType.getDimension();
domainNames = new String[numDom];
for (int i=0; i<numDom; i++) {
MathType comp = domType.getComponent(i);
domainNames[i] = ((RealType)comp).toString().trim();
if (debug) System.out.println("dom "+i+" = "+domainNames[i]);
}
rngType = (TupleType) ((FunctionType)mt).getRange();
numRng = rngType.getDimension();
rangeNames = new String[numRng];
rangeSets = new Set[numRng];
for (int i=0; i<numRng; i++) {
MathType comp = rngType.getComponent(i);
rangeNames[i] = (comp).toString().trim();
if (debug) System.out.println("range "+i+" = "+rangeNames[i]);
if (comp instanceof RealType) {
rangeSets[i] = ((RealType) comp).getDefaultSet();
if (rangeSets[i] == null) {
if (comp.equals(RealType.Time)) {
rangeSets[i] = new DoubleSet(new SetType(comp));
} else {
rangeSets[i] = new FloatSet(new SetType(comp));
}
}
} else {
rangeSets[i] = null; // something else is wrong here...
}
if (debug) System.out.println("#### rangeSet = "+rangeSets[i]);
;
}
} else {
throw new visad.VisADException("TextAdapter: Math Type is not a simple FunctionType");
}
// now for each header label, determine if it's a domain or
// range component -- and if so, which one.
// also, if it's a domain component, allow for name(first:last[:number])
//
// and if none of the domain components appear in the list, then
// they are computed as name(0:N-1)
int[] domainPointer = new int[numDom];
double[][] domainRanges = new double[3][numDom]; // min, max, numb
boolean[] gotDomainRanges = new boolean[numDom];
domainErrorEstimates = new double[numDom];
domainUnits = new Unit[numDom];
rangeErrorEstimates = new double[numRng];
rangeUnits = new Unit[numRng];
int countDomain = 0;
for (int i=0; i<numDom; i++) {
domainPointer[i] = -1;
gotDomainRanges[i] = false;
domainErrorEstimates[i] = Double.NaN;
domainUnits[i] = null;
}
int[] rangePointer = new int[numRng];
int countRange = 0;
for (int i=0; i<numRng; i++) {
rangePointer[i] = -1;
rangeErrorEstimates[i] = Double.NaN;
rangeUnits[i] = null;
}
int countValues = -1;
values_to_index = new int[3][nhdr];
for (int i=0; i<nhdr; i++) {
values_to_index[0][i] = -1; // points to domains
values_to_index[1][i] = -1; // points to ranges
values_to_index[2][i] = -1; // points to names/units/etc
countValues ++;
String name = infos[i].name;
// see if it's a domain name
boolean gotName = false;
// is there a "min:max" clause?
String test_name = name;
int n = test_name.indexOf("(");
if (n != -1) {
// but allow for "(Text)"
if ((test_name.indexOf("(Text)")) == -1) {
test_name = name.substring(0,n).trim();
countValues --; // this value wont appear in data!
countDomain --; // and is a pre-defined, linear set
}
}
// try to find the column header name in the domain name list
for (int k=0; k<numDom; k++) {
if (test_name.equals(domainNames[k]) ) {
domainPointer[k] = countValues;
domainErrorEstimates[k] = infos[i].errorEstimate;
domainUnits[k] = infos[i].unit;
gotName = true;
countDomain ++;
// now see if a list is given...
if (n != -1) {
try {
String ss = name.substring(n+1,name.length()-1);
String[] sct = ss.split(":");
String first = sct[0].trim();
String second = sct[1].trim();
String third = "1";
if (sct.length == 3) third = sct[2].trim();
domainRanges[0][k] = Double.parseDouble(first);
domainRanges[1][k] = Double.parseDouble(second);
domainRanges[2][k] = Double.parseDouble(third);
gotDomainRanges[k] = true;
} catch (Exception ef) {
throw new VisADException(
"TextAdapter: Error while interpreting min:max values for domain "+name);
}
} else if (countValues > -1) { // if no list, get from file
values_to_index[0][countValues] = k;
values_to_index[2][countValues] = i;
}
break;
}
}
if (gotName) continue;
// or see if its a range name...
for (int k=0; k<numRng; k++) {
if (name.equals(rangeNames[k]) ) {
rangePointer[k] = countValues;
rangeErrorEstimates[k] = infos[i].errorEstimate;
rangeUnits[k] = infos[i].unit;
countRange ++;
values_to_index[1][countValues] = k;
values_to_index[2][countValues] = i;
gotName = true;
}
}
}
// huge debug printout...
// *****************************************************************
if (debug) {
System.out.println("countDom/numDom="+countDomain+" "+numDom);
System.out.println("countRange/numRng="+countRange+" "+numRng);
System.out.println("Domain info:");
for (int i=0; i<numDom; i++) {
System.out.println("Dom name / index = "+domainNames[i]+" "+
domainPointer[i]);
if (gotDomainRanges[i]) {
System.out.println(" ..."+domainRanges[0][i]+" "+
domainRanges[1][i]+" "+domainRanges[2][i]);
}
}
System.out.println("Range info:");
for (int i=0; i<numRng; i++) {
System.out.println("Rng name / index / error est = "+rangeNames[i]+" "+
rangePointer[i]+ " " + rangeErrorEstimates[i] +" "+
rangeUnits[i]);
}
System.out.println("values_to_index pointers = ");
for (int i=0; i<nhdr; i++) {
System.out.println(" inx / value = "+i+
" "+values_to_index[0][i]+" "+values_to_index[1][i]+
" "+values_to_index[2][i]);
}
}
// ***************************************************************
// for each line of text, put the values into the ArrayList
ArrayList domainValues = new ArrayList();
ArrayList rangeValues = new ArrayList();
ArrayList tupleValues = new ArrayList();
boolean tryToMakeTuple = true;
Tuple tuple = null;
String dataDelim = DELIM;
boolean isRaster = false;
int numElements = 1;
// in the 'raster array' case, the numRng value will be 1,
// along with the countRange. numDomain must be 2.
// if the domain is 2D, then get values from the first
// matching column to the end...
if (countRange == 1 && numRng == 1 &&
numDom == 2 && countDomain < 2) isRaster = true;
int index;
while (true) {
String s = bis.readLine();
if (debug) System.out.println("read:"+s);
if (s == null) break;
if (!isText(s)) return;
if (isComment(s)) continue;
if((index=s.indexOf("="))>=0) { // fixed value
String name = s.substring(0,index).trim();
String value = s.substring(index+1).trim();
boolean foundIt = false;
for(int paramIdx=0;paramIdx<infos.length;paramIdx++) {
if(infos[paramIdx].isParam(name)) {
if(infos[paramIdx].fixedValue==null) {
numHdrValues++;
}
infos[paramIdx].fixedValue = value;
foundIt = true;
break;
}
}
if(!foundIt) {
throw new VisADException(
"TextAdapter: Cannot find field with name:" +name +" from line:" + s);
}
continue;
}
if (dataDelim == null) {
if (s.indexOf(BLANK) != -1) dataDelim = BLANK_DELIM;
if (s.indexOf(COMMA) != -1) dataDelim = COMMA;
if (s.indexOf(SEMICOLON) != -1) dataDelim = SEMICOLON;
if (s.indexOf(TAB) != -1) dataDelim = TAB;
if (debug) System.out.println("Using data delimiter = "+
((dataDelim == null)
? "null"
: dataDelim + " (" + (dataDelim.getBytes())[0] +")"));
}
String[] st = s.split(dataDelim);
int n = st.length;
if (n < 1) continue; // something is wrong if this happens!
double [] dValues = new double[numDom];
double [] rValues = null;
Data [] tValues = null;
if (isRaster) {
if (debug) System.out.println("probably a raster...");
boolean gotFirst = false;
int rvaluePointer = 0;
int irange = 0;
for (int i=0; i<n; i++) {
String sa = st[i];
if (i >= nhdr) { // are we past where domain would be found?
if (!gotFirst) {
throw new VisADException(
"TextAdapter: Cannot find first raster value");
}
rvaluePointer ++;
rValues[rvaluePointer] = getVal(sa, irange);
} else { // or are we still looking for domain?
if (values_to_index[0][i] != -1) {
dValues[values_to_index[0][i]] = getVal(sa, i);
}
if (gotFirst) { // already gathering data
rvaluePointer ++;
rValues[rvaluePointer] = getVal(sa, irange);
} else {
if (values_to_index[1][i] != -1) {
// cannot dimension the array until we have found
// the first set of range values!!
rValues = new double[n - i];
irange = i;
rValues[rvaluePointer] = getVal(sa, irange);
gotFirst = true;
}
}
}
}
} else { // is probably NOT a raster
tValues = new Data[numRng];
if (debug) System.out.println("probably not a raster...");
rValues = new double[numRng];
double thisDouble;
MathType thisMT;
if (n > nhdr) n = nhdr; // in case the # tokens > # parameters
n +=numHdrValues;
int l = 0; // token counter
for (int i=0; i<nhdr; i++) { // loop over the columns
String sa=null;
if(sa == null) {
if(infos[i].fixedValue!=null) {
sa = infos[i].fixedValue;
} else if (l >= st.length) { // more params than tokens
sa = ""; // need to have a missing value
} else {
sa = st[l++].trim();
int moreColumns = infos[i].colspan-1;
while (moreColumns>0) {
sa = sa + " " + st[l++].trim();
moreColumns--;
}
}
}
String sThisText;
if (values_to_index[0][i] != -1) {
dValues[values_to_index[0][i]] = getVal(sa, i);
} else if (values_to_index[1][i] != -1) {
thisMT = rngType.getComponent(values_to_index[1][i]);
if (thisMT instanceof TextType) {
// if Text, then check for quoted string
if (sa.startsWith("\"")) {
if (sa.endsWith("\"")) { // if single token ends with quote
String sa2 = sa.substring(1,sa.length()-1);
sThisText = sa2;
} else {
// TODO: work on this
try {
String delim =
dataDelim.equals(BLANK_DELIM) ? BLANK : dataDelim;
String sa2="";
for (int q=l; q < st.length; q++) {
String saTmp = st[q];
// find next token that has a " in it
int pos = saTmp.indexOf("\"");
l++;
if (pos < 0) { // no dataDelim
sa2 = sa2+delim+saTmp;
} else {
sa2 = sa2+saTmp.substring(0,pos);
//st[l] = saTmp.substring(pos+1);
break;
}
}
//sThisText = sa.substring(1)+sa2;
sThisText = sa.substring(1)+delim+sa2;
//} catch (NoSuchElementException nse) {
} catch (ArrayIndexOutOfBoundsException nse) {
sThisText = "";
}
}
if (debug) System.out.println("#### Text value='"+sThisText+"'");
// if not quoted, then take "as is"
} else {
sThisText = sa;
}
// now make the VisAD Data
try {
tValues[values_to_index[1][i]] =
new Text((TextType) thisMT, sThisText);
if (debug) System.out.println("tValues[" +
values_to_index[1][i] + "] = " +
tValues[values_to_index[1][i]]);
} catch (Exception e) {
System.out.println(" Exception converting " +
thisMT + " to TextType " + e);
}
// if not Text, then treat as numeric
} else {
double value = getVal(sa,i);
rValues[values_to_index[1][i]] = value;
try {
if(prototypeReals[i]==null) {
prototypeReals[i] = new Real((RealType) thisMT, getVal(sa,i), infos[i].unit);
}
tValues[values_to_index[1][i]] =
prototypeReals[i].cloneButValue(value);
if(debug)System.out.println("tValues[" +
values_to_index[1][i] + "] = " +
tValues[values_to_index[1][i]]);
} catch (Exception e) {
System.out.println(" Exception converting " + thisMT + " " + e);
}
}
}
}
}
if(tryToMakeTuple) {
try {
if (tValues != null) tuple = new Tuple(tValues);
} catch (visad.TypeException te) {
// do nothing: it means they are all reals
// tuple = new RealTuple(tValues);
tuple = null;
tryToMakeTuple = false;
} catch(NullPointerException npe) {
for(int i=0;i<tValues.length;i++) {
if(tValues[i] == null) {
throw new IllegalArgumentException("An error occurred reading column number:" + (i+1));
}
}
throw npe;
}
}
domainValues.add(dValues);
rangeValues.add(rValues);
if (tuple != null) tupleValues.add(tuple);
if (isRaster) numElements = rValues.length;
if(onlyReadOneLine) break;
}
int numSamples = rangeValues.size(); // # lines of data
// ***********************************************************
if (debug) {
try {
System.out.println("domain size = "+domainValues.size());
double[] dt = (double[]) domainValues.get(1);
System.out.println("domain.array[0] = "+dt[0]);
System.out.println("range size = "+rangeValues.size());
System.out.println("# samples = "+numSamples);
} catch (Exception er) {System.out.println("out range");}
}
// ***********************************************************
// make Linear1DSets for each possible domain component
Linear1DSet[] lset = new Linear1DSet[numDom];
boolean keepConstant = false;
int numVal = numRng;
if (numDom == 1) numVal = numSamples;
if (numDom == 2 && numRng == 1 && numElements > 1) numVal = numElements;
if (numDom > 2 && numRng == 1 && numElements == 1) {
numVal = numSamples / (2 * numDom);
keepConstant = true;
}
for (int i=0; i<numDom; i++) {
if (gotDomainRanges[i]) {
// if domain was given with a count, use it for 'raster'-type
if (numDom == 2 && numRng == 1 && numElements == 1)
numVal = (int) domainRanges[2][i];
lset[i] = new Linear1DSet(domType.getComponent(i), domainRanges[0][i],
domainRanges[1][i], numVal);
if (debug) System.out.println("lset from domain = "+lset[i]);
} else if (domainPointer[i] == -1 ) {
lset[i] = new Linear1DSet(0., (double)(numVal-1), numVal);
if (debug) System.out.println("lset from range = "+lset[i]);
} else {
lset[i] = null;
}
if (!keepConstant) numVal = numSamples;
}
// now make up the actual domain sets for the function
Set domain = null;
if (numDom == 1) { // for 1-D domains
if (lset[0] == null) {
domain = createAppropriate1DDomain(domType, numSamples, domainValues);
} else {
domain = lset[0];
}
} else if (numDom == 2) { // for 2-D domains
if (lset[0] != null && lset[1] != null) {
domain = new Linear2DSet(domType, lset);
} else {
float[][] samples = new float[numDom][numSamples];
for (int k = 0; k < numDom; k++) {
if (lset[k] == null) {
samples[k] = (getDomSamples(k, numSamples, domainValues))[0];
} else {
samples[k] = (lset[k].getSamples())[0];
}
}
domain = (Set) new Irregular2DSet(domType, samples);
}
} else if (numDom == 3) { // for 3-D domains
if (lset[0] != null && lset[1] != null && lset[2] != null) {
domain = new Linear3DSet(domType, lset);
} else {
float[][] samples = new float[numDom][numSamples];
for (int k = 0; k < numDom; k++) {
if (lset[k] == null) {
samples[k] = (getDomSamples(k, numSamples, domainValues))[0];
} else {
samples[k] = (lset[k].getSamples())[0];
}
}
domain = (Set) new Irregular3DSet(domType, samples);
}
} else { // N-D domains (can only use LinearSets!!
boolean allLinear = true;
for (int k = 0; k<numDom; k++) {
if (lset[k] == null) allLinear = false;
}
if (allLinear) {
if (debug) System.out.println("#### Making LinearNDset");
domain = new LinearNDSet(domType, lset);
} else {
if (debug) System.out.println("#### Making IrregularSet");
float[][] samples = new float[numDom][numSamples];
for (int k=0; k<numDom; k++) {
if (lset[k] == null) {
samples[k] = (getDomSamples(k, numSamples, domainValues))[0];
} else {
samples[k] = (lset[k].getSamples())[0];
}
}
domain = new IrregularSet(domType, samples);
}
}
try {
ff = new FlatField((FunctionType) mt, domain,
null, null, rangeSets, rangeUnits);
} catch (FieldException fe) {
field = new FieldImpl((FunctionType) mt, domain);
} catch (UnitException fe) {
System.out.println("#### Problem with Units; attempting to make Field anyway");
field = new FieldImpl((FunctionType) mt, domain);
}
//*************************************************
if (debug) {
if (ff != null) {
System.out.println("ff.Length "+ff.getLength());
System.out.println("ff.getType "+ff.getType());
}
if (field != null) {
System.out.println("field.Length "+field.getLength());
System.out.println("field.getType "+field.getType());
}
System.out.println("domain = "+domain);
System.out.println("size of a = "+numRng+" x "+(numSamples*numElements));
}
//*************************************************
double[][]a = new double[numRng][numSamples * numElements];
Tuple[] at = new Tuple[numSamples];
// if this is a raster then the samples are in a slightly
// difielderent form ...
if (isRaster) {
int samPointer = 0;
for (int i=0; i<numSamples; i++) {
double[] rs = (double[])(rangeValues.get(i));
for (int j=0; j<numElements; j++) {
a[0][samPointer] = rs[j];
samPointer ++;
}
}
} else {
for (int i=0; i<numSamples; i++) {
double[] rs = (double[])(rangeValues.get(i));
for (int j=0; j<numRng; j++) {
a[j][i] = rs[j];
}
if (!tupleValues.isEmpty()) {
at[i] = (Tuple) tupleValues.get(i);
}
}
}
// set samples
if (debug) System.out.println("about to field.setSamples");
try {
if (ff != null) {
if (debug) System.out.println("#### ff is not null");
ff.setSamples(a, false);
field = (Field) ff;
} else {
if (debug) System.out.println("#### ff is null..use FieldImpl");
field.setSamples(at, false);
}
} catch (Exception ffe) {ffe.printStackTrace(); }
// make up error estimates and set them
ErrorEstimate[] es = new ErrorEstimate[numRng];
for (int i=0; i<numRng; i++) {
es[i] = new ErrorEstimate(a[i], rangeErrorEstimates[i], rangeUnits[i]);
}
try {
((FlatField) field).setRangeErrors(es);
} catch (FieldException fe) {
if (debug) System.out.println("caught "+fe);
// not a flatfield
// don't setRangeErrors
} catch (ClassCastException cce) {
if (debug) System.out.println("caught "+cce);
// not a flatfield
// don't setRangeErrors
}
if (debug) {
new visad.jmet.DumpType().dumpDataType(field,System.out);
System.out.println("field = "+field);
}
bis.close();
}
| void readit(InputStream is, String map, String params)
throws IOException, VisADException {
// read the ASCII file, using commas as field separators
// first line is a header line
List realTypes = new ArrayList();
ff = null;
field = null;
if (debug) System.out.println("#### Text Adapter v2.x running");
BufferedReader bis = new BufferedReader(new InputStreamReader(is));
// mapping defines how the names are mapped
// for example: (x,y) => (one, two, three)
String maps = null;
if (map == null) {
maps = readLine(bis);
if(maps != null) {
maps = maps.trim();
}
} else {
maps = map;
}
if (maps != null) {
maps = makeMT(maps);
}
if (maps == null) {
throw new visad.data.BadFormException(
"TextAdapter: Invalid or missing MathType");
}
if (debug) System.out.println("Specified MathType = "+maps);
// but first, we need to get the column headers because they
// may have [units] associated with them. The column headers
// primarily define where the data are.
String hdr = null;
if (params == null) {
hdr = readLine(bis);
} else {
hdr = params;
}
String hdrDelim = DELIM;
if (DELIM == null) {
if (hdr.indexOf(BLANK) != -1) hdrDelim = BLANK_DELIM;
if (hdr.indexOf(COMMA) != -1) hdrDelim = COMMA;
if (hdr.indexOf(SEMICOLON) != -1) hdrDelim = SEMICOLON;
if (hdr.indexOf(TAB) != -1) hdrDelim = TAB;
if (debug) System.out.println("Using header delimiter = "+ hdrDelim + "("+
(hdrDelim.getBytes())[0] + ")");
}
String[] sthdr = hdr.split(hdrDelim);
int nhdr = sthdr.length;
infos = new HeaderInfo[nhdr];
for(int i=0;i<infos.length;i++) {
infos[i] = new HeaderInfo();
}
Real[] prototypeReals = new Real[nhdr];
hdrColumns = new int[2][nhdr];
int numHdrValues=0;
// pre-scan of the header names to seek out Units
// since we cannot change a RealType once it's defined!!
for (int i=0; i<nhdr; i++) {
String name = sthdr[i].trim();
String hdrUnitString = null;
hdrColumns[0][i] = -1; // indicating no fixed columns
int m = name.indexOf("[");
if (m == -1) {
infos[i].name = name;
hdrUnitString = null;
} else {
int m2 = name.indexOf("]");
if (m2 == -1) {
throw new VisADException("TextAdapter: Bad [descriptor] named in:"+name);
}
// now parse items: unit=xxx miss=xxx interval=xxx error=xxx
// 1. tokenize on " "
// 2. scan each token, retokenizing on "="
// 3. if (has no "=") && (is first one) then treat as Unit
// 4. otherwise, look for keys "unit" "miss" "inter" "err" "scale" "offset" "pos"
// and fill in the values in array[i]
if (m2 >= name.length()) {
infos[i].name = name.substring(0,m).trim();
} else {
infos[i].name = (name.substring(0,m)+name.substring(m2+1)).trim();
}
String cl = name.substring(m+1,m2).trim();
String[] stcl = cl.split(BLANK_DELIM);
int ncl = stcl.length;
if (ncl == 1 && cl.indexOf("=") == -1) {
hdrUnitString = cl; // backward compatible...
} else {
for (int l = 0; l < ncl; l++) {
String s = stcl[l];
String[] sts = s.split("=");
if (sts.length != 2) {
throw new VisADException("TextAdapter: Invalid clause in: "+s);
}
String tok = sts[0];
String val = sts[1];
// check for quoted strings
if (val.startsWith("\"")) {
// see if ending quote also fetched
if (val.endsWith("\"")) {
String v2 = val.substring(1,val.length()-1);
val = v2;
} else {
// if not, then reparse stcl to suck up spaces...
try {
String v2="";
for (int q=l+1; q < ncl; q++) {
String vTmp = stcl[q];
// find next token that has a " in it
int pos = vTmp.indexOf("\"");
l++;
if (pos < 0) { // no "
v2 = v2+" "+vTmp;
} else {
v2 = v2+" "+vTmp.substring(0,pos);
break;
}
}
String v3 = val.substring(1)+v2;
val = v3;
//} catch (NoSuchElementException nse2) {
} catch (ArrayIndexOutOfBoundsException nse2) {
val="";
}
}
}
if (debug) System.out.println("#### tok = "+tok+ " val = '"+val+"'");
if (tok.toLowerCase().startsWith(ATTR_UNIT)) {
hdrUnitString = val;
} else if (tok.toLowerCase().startsWith(ATTR_MISSING)) {
infos[i].missingString = val.trim();
try {
infos[i].missingValue = Double.parseDouble(val);
} catch (java.lang.NumberFormatException me) {
infos[i].missingValue = Double.NaN;
}
} else if (tok.toLowerCase().startsWith(ATTR_INTERVAL)) {
infos[i].isInterval = -1;
if (val.toLowerCase().startsWith("t")) infos[i].isInterval = 1;
if (val.toLowerCase().startsWith("f")) infos[i].isInterval = 0;
if (infos[i].isInterval == -1) {
throw new VisADException("TextAdapter: Value of \'interval\' must be \'true\' or \'false\'");
}
} else if (tok.toLowerCase().startsWith(ATTR_ERROR)) {
infos[i].errorEstimate = Double.parseDouble(val);
} else if (tok.toLowerCase().startsWith(ATTR_SCALE)) {
infos[i].scale = Double.parseDouble(val);
} else if (tok.toLowerCase().startsWith(ATTR_OFFSET)) {
infos[i].offset = Double.parseDouble(val);
} else if (tok.toLowerCase().startsWith(ATTR_VALUE)) {
infos[i].fixedValue = val.trim();
numHdrValues++;
} else if (tok.toLowerCase().startsWith(ATTR_COLSPAN)) {
infos[i].colspan = (int)Double.parseDouble(val.trim());
} else if (tok.toLowerCase().startsWith(ATTR_POSITION)) {
String[] stp = val.split(":");
if (stp.length != 2) {
throw new VisADException("TextAdapter: invalid Position parameter in:"+s);
}
hdrColumns[0][i] = Integer.parseInt(stp[0].trim());
hdrColumns[1][i] = Integer.parseInt(stp[1].trim());
} else if (tok.toLowerCase().startsWith(ATTR_FORMAT)) {
infos[i].formatString = val.trim();
} else if (tok.toLowerCase().startsWith(ATTR_TIMEZONE)) {
infos[i].tzString = val.trim();
} else {
throw new VisADException("TextAdapter: invalid token name: "+s);
}
}
}
}
if(properties!=null) {
for(int headerIdx=0;headerIdx<infos.length;headerIdx++) {
String value = (String)properties.get(infos[headerIdx].name+".value");
if(value!=null) infos[headerIdx].fixedValue = value;
}
}
if (debug)
System.out.println("hdr name = "+infos[i]+" units="+
hdrUnitString+
" miss="+infos[i].missingValue+" interval="+infos[i].isInterval+
" errorest="+infos[i].errorEstimate+" scale="+infos[i].scale+
" offset="+infos[i].offset+" pos="+hdrColumns[0][i]+":"+
hdrColumns[1][i]);
Unit u = null;
if (hdrUnitString != null &&
!hdrUnitString.trim().equalsIgnoreCase("null") ) {
try {
u = visad.data.units.Parser.parse(hdrUnitString.trim());
} catch (Exception ue) {
try {
u = visad.data.units.Parser.parse(
hdrUnitString.trim().replace(' ','_'));
} catch (Exception ue2) {
System.out.println("Unit name problem:"+ue+" with: "+hdrUnitString);
u = null;
}
}
}
if (debug) System.out.println("#### assigned Unit as u="+u);
String rttemp = infos[i].name.trim();
if (rttemp.indexOf("(Text)") == -1) {
int parenIndex = rttemp.indexOf("(");
if (parenIndex < 0) parenIndex = rttemp.indexOf("[");
if (parenIndex < 0) parenIndex = rttemp.indexOf("{");
if (parenIndex < 0) parenIndex = rttemp.indexOf(" ");
String rtname = parenIndex < 0 ? rttemp.trim() : rttemp.substring(0,parenIndex);
RealType rt = RealType.getRealType(rtname, u, null, infos[i].isInterval);
if (rt == null) { // tried to re-use with different units
if (debug) System.out.println("#### rt was returned as null");
if (u != null) System.out.println("#### Could not make RealType using specified Unit ("+hdrUnitString+") for parameter name: "+rtname);
rt = RealType.getRealType(rtname);
}
//Add the realType here because its possible that it can be GC'ed
//and removed from the global list of realtypes before we
//get back to it. Then the MathType.stringToType(maps) below
//will produce a realtype with no units
realTypes.add(rt);
// get a compatible unit, if necessary
if (rt.equals(visad.RealType.Time)) {
GOTTIME = true;
if (debug) System.out.println("#### found a visad.RealType.Time component");
} else {
GOTTIME = false;
}
if (u == null) u = rt.getDefaultUnit();
if(debug) System.out.println("#### retrieve units from RealType = "+u);
}
infos[i].unit = u;
}
// get the MathType of the function
MathType mt = null;
try {
mt = MathType.stringToType(maps);
} catch (Exception mte) {
System.out.println("#### Exception: "+mte);
throw new VisADException("TextAdapter: MathType badly formed or missing: "+maps);
}
if (debug) {
System.out.println(mt);
new visad.jmet.DumpType().dumpMathType(mt,System.out);
}
// now get the names of the domain variables and range variables.
String[] domainNames = null;
String[] rangeNames = null;
int numDom = 0;
int numRng = 0;
RealTupleType domType;
TupleType rngType;
if (mt instanceof FunctionType) {
domType = ((FunctionType)mt).getDomain();
numDom = domType.getDimension();
domainNames = new String[numDom];
for (int i=0; i<numDom; i++) {
MathType comp = domType.getComponent(i);
domainNames[i] = ((RealType)comp).toString().trim();
if (debug) System.out.println("dom "+i+" = "+domainNames[i]);
}
rngType = (TupleType) ((FunctionType)mt).getRange();
numRng = rngType.getDimension();
rangeNames = new String[numRng];
rangeSets = new Set[numRng];
for (int i=0; i<numRng; i++) {
MathType comp = rngType.getComponent(i);
rangeNames[i] = (comp).toString().trim();
if (debug) System.out.println("range "+i+" = "+rangeNames[i]);
if (comp instanceof RealType) {
rangeSets[i] = ((RealType) comp).getDefaultSet();
if (rangeSets[i] == null) {
if (comp.equals(RealType.Time)) {
rangeSets[i] = new DoubleSet(new SetType(comp));
} else {
rangeSets[i] = new FloatSet(new SetType(comp));
}
}
} else {
rangeSets[i] = null; // something else is wrong here...
}
if (debug) System.out.println("#### rangeSet = "+rangeSets[i]);
;
}
} else {
throw new visad.VisADException("TextAdapter: Math Type is not a simple FunctionType");
}
// now for each header label, determine if it's a domain or
// range component -- and if so, which one.
// also, if it's a domain component, allow for name(first:last[:number])
//
// and if none of the domain components appear in the list, then
// they are computed as name(0:N-1)
int[] domainPointer = new int[numDom];
double[][] domainRanges = new double[3][numDom]; // min, max, numb
boolean[] gotDomainRanges = new boolean[numDom];
domainErrorEstimates = new double[numDom];
domainUnits = new Unit[numDom];
rangeErrorEstimates = new double[numRng];
rangeUnits = new Unit[numRng];
int countDomain = 0;
for (int i=0; i<numDom; i++) {
domainPointer[i] = -1;
gotDomainRanges[i] = false;
domainErrorEstimates[i] = Double.NaN;
domainUnits[i] = null;
}
int[] rangePointer = new int[numRng];
int countRange = 0;
for (int i=0; i<numRng; i++) {
rangePointer[i] = -1;
rangeErrorEstimates[i] = Double.NaN;
rangeUnits[i] = null;
}
int countValues = -1;
values_to_index = new int[3][nhdr];
for (int i=0; i<nhdr; i++) {
values_to_index[0][i] = -1; // points to domains
values_to_index[1][i] = -1; // points to ranges
values_to_index[2][i] = -1; // points to names/units/etc
countValues ++;
String name = infos[i].name;
// see if it's a domain name
boolean gotName = false;
// is there a "min:max" clause?
String test_name = name;
int n = test_name.indexOf("(");
if (n != -1) {
// but allow for "(Text)"
if ((test_name.indexOf("(Text)")) == -1) {
test_name = name.substring(0,n).trim();
countValues --; // this value wont appear in data!
countDomain --; // and is a pre-defined, linear set
}
}
// try to find the column header name in the domain name list
for (int k=0; k<numDom; k++) {
if (test_name.equals(domainNames[k]) ) {
domainPointer[k] = countValues;
domainErrorEstimates[k] = infos[i].errorEstimate;
domainUnits[k] = infos[i].unit;
gotName = true;
countDomain ++;
// now see if a list is given...
if (n != -1) {
try {
String ss = name.substring(n+1,name.length()-1);
String[] sct = ss.split(":");
String first = sct[0].trim();
String second = sct[1].trim();
String third = "1";
if (sct.length == 3) third = sct[2].trim();
domainRanges[0][k] = Double.parseDouble(first);
domainRanges[1][k] = Double.parseDouble(second);
domainRanges[2][k] = Double.parseDouble(third);
gotDomainRanges[k] = true;
} catch (Exception ef) {
throw new VisADException(
"TextAdapter: Error while interpreting min:max values for domain "+name);
}
} else if (countValues > -1) { // if no list, get from file
values_to_index[0][countValues] = k;
values_to_index[2][countValues] = i;
}
break;
}
}
if (gotName) continue;
// or see if its a range name...
for (int k=0; k<numRng; k++) {
if (name.equals(rangeNames[k]) ) {
rangePointer[k] = countValues;
rangeErrorEstimates[k] = infos[i].errorEstimate;
rangeUnits[k] = infos[i].unit;
countRange ++;
values_to_index[1][countValues] = k;
values_to_index[2][countValues] = i;
gotName = true;
}
}
}
// huge debug printout...
// *****************************************************************
if (debug) {
System.out.println("countDom/numDom="+countDomain+" "+numDom);
System.out.println("countRange/numRng="+countRange+" "+numRng);
System.out.println("Domain info:");
for (int i=0; i<numDom; i++) {
System.out.println("Dom name / index = "+domainNames[i]+" "+
domainPointer[i]);
if (gotDomainRanges[i]) {
System.out.println(" ..."+domainRanges[0][i]+" "+
domainRanges[1][i]+" "+domainRanges[2][i]);
}
}
System.out.println("Range info:");
for (int i=0; i<numRng; i++) {
System.out.println("Rng name / index / error est = "+rangeNames[i]+" "+
rangePointer[i]+ " " + rangeErrorEstimates[i] +" "+
rangeUnits[i]);
}
System.out.println("values_to_index pointers = ");
for (int i=0; i<nhdr; i++) {
System.out.println(" inx / value = "+i+
" "+values_to_index[0][i]+" "+values_to_index[1][i]+
" "+values_to_index[2][i]);
}
}
// ***************************************************************
// for each line of text, put the values into the ArrayList
ArrayList domainValues = new ArrayList();
ArrayList rangeValues = new ArrayList();
ArrayList tupleValues = new ArrayList();
boolean tryToMakeTuple = true;
Tuple tuple = null;
String dataDelim = DELIM;
boolean isRaster = false;
int numElements = 1;
// in the 'raster array' case, the numRng value will be 1,
// along with the countRange. numDomain must be 2.
// if the domain is 2D, then get values from the first
// matching column to the end...
if (countRange == 1 && numRng == 1 &&
numDom == 2 && countDomain < 2) isRaster = true;
int index;
int lineCnt = 0;
while (true) {
String line = bis.readLine();
if (debug) System.out.println("read:"+line);
if (line == null) break;
if (!isText(line)) return;
if (isComment(line)) continue;
if((index=line.indexOf("="))>=0) { // fixed value
String name = line.substring(0,index).trim();
String value = line.substring(index+1).trim();
boolean foundIt = false;
for(int paramIdx=0;paramIdx<infos.length;paramIdx++) {
if(infos[paramIdx].isParam(name)) {
if(infos[paramIdx].fixedValue==null) {
numHdrValues++;
}
infos[paramIdx].fixedValue = value;
foundIt = true;
break;
}
}
if(!foundIt) {
throw new VisADException(
"TextAdapter: Cannot find field with name:" +name +" from line:" + line);
}
continue;
}
if (dataDelim == null) {
if (line.indexOf(BLANK) != -1) dataDelim = BLANK_DELIM;
if (line.indexOf(COMMA) != -1) dataDelim = COMMA;
if (line.indexOf(SEMICOLON) != -1) dataDelim = SEMICOLON;
if (line.indexOf(TAB) != -1) dataDelim = TAB;
if (debug) System.out.println("Using data delimiter = "+
((dataDelim == null)
? "null"
: dataDelim + " (" + (dataDelim.getBytes())[0] +")"));
}
String[] st = line.split(dataDelim);
int n = st.length;
if (n < 1) continue; // something is wrong if this happens!
lineCnt++;
double [] dValues = new double[numDom];
double [] rValues = null;
Data [] tValues = null;
if (isRaster) {
if (debug) System.out.println("probably a raster...");
boolean gotFirst = false;
int rvaluePointer = 0;
int irange = 0;
for (int i=0; i<n; i++) {
String sa = st[i];
if (i >= nhdr) { // are we past where domain would be found?
if (!gotFirst) {
throw new VisADException(
"TextAdapter: Cannot find first raster value");
}
rvaluePointer ++;
rValues[rvaluePointer] = getVal(sa, irange);
} else { // or are we still looking for domain?
if (values_to_index[0][i] != -1) {
dValues[values_to_index[0][i]] = getVal(sa, i);
}
if (gotFirst) { // already gathering data
rvaluePointer ++;
rValues[rvaluePointer] = getVal(sa, irange);
} else {
if (values_to_index[1][i] != -1) {
// cannot dimension the array until we have found
// the first set of range values!!
rValues = new double[n - i];
irange = i;
rValues[rvaluePointer] = getVal(sa, irange);
gotFirst = true;
}
}
}
}
} else { // is probably NOT a raster
tValues = new Data[numRng];
if (debug) System.out.println("probably not a raster...");
rValues = new double[numRng];
double thisDouble;
MathType thisMT;
if (n > nhdr) n = nhdr; // in case the # tokens > # parameters
n +=numHdrValues;
int l = 0; // token counter
for (int i=0; i<nhdr; i++) { // loop over the columns
String sa=null;
if(sa == null) {
if(infos[i].fixedValue!=null) {
sa = infos[i].fixedValue;
} else if (l >= st.length) { // more params than tokens
sa = ""; // need to have a missing value
} else {
sa = st[l++].trim();
int moreColumns = infos[i].colspan-1;
while (moreColumns>0) {
sa = sa + " " + st[l++].trim();
moreColumns--;
}
}
}
String sThisText;
if (values_to_index[0][i] != -1) {
dValues[values_to_index[0][i]] = getVal(sa, i);
} else if (values_to_index[1][i] != -1) {
thisMT = rngType.getComponent(values_to_index[1][i]);
if (thisMT instanceof TextType) {
// if Text, then check for quoted string
if (sa.startsWith("\"")) {
if (sa.endsWith("\"")) { // if single token ends with quote
String sa2 = sa.substring(1,sa.length()-1);
sThisText = sa2;
} else {
// TODO: work on this
try {
String delim =
dataDelim.equals(BLANK_DELIM) ? BLANK : dataDelim;
String sa2="";
for (int q=l; q < st.length; q++) {
String saTmp = st[q];
// find next token that has a " in it
int pos = saTmp.indexOf("\"");
l++;
if (pos < 0) { // no dataDelim
sa2 = sa2+delim+saTmp;
} else {
sa2 = sa2+saTmp.substring(0,pos);
//st[l] = saTmp.substring(pos+1);
break;
}
}
//sThisText = sa.substring(1)+sa2;
sThisText = sa.substring(1)+delim+sa2;
//} catch (NoSuchElementException nse) {
} catch (ArrayIndexOutOfBoundsException nse) {
sThisText = "";
}
}
if (debug) System.out.println("#### Text value='"+sThisText+"'");
// if not quoted, then take "as is"
} else {
sThisText = sa;
}
// now make the VisAD Data
try {
tValues[values_to_index[1][i]] =
new Text((TextType) thisMT, sThisText);
if (debug) System.out.println("tValues[" +
values_to_index[1][i] + "] = " +
tValues[values_to_index[1][i]]);
} catch (Exception e) {
System.out.println(" Exception converting " +
thisMT + " to TextType " + e);
}
// if not Text, then treat as numeric
} else {
double value = getVal(sa,i);
rValues[values_to_index[1][i]] = value;
try {
if(prototypeReals[i]==null) {
prototypeReals[i] = new Real((RealType) thisMT, getVal(sa,i), infos[i].unit);
}
tValues[values_to_index[1][i]] =
prototypeReals[i].cloneButValue(value);
if(debug)System.out.println("tValues[" +
values_to_index[1][i] + "] = " +
tValues[values_to_index[1][i]]);
} catch (Exception e) {
System.out.println(" Exception converting " + thisMT + " " + e);
}
}
}
}
}
if(tryToMakeTuple) {
try {
if (tValues != null) tuple = new Tuple(tValues);
} catch (visad.TypeException te) {
// do nothing: it means they are all reals
// tuple = new RealTuple(tValues);
tuple = null;
tryToMakeTuple = false;
} catch(NullPointerException npe) {
for(int i=0;i<tValues.length;i++) {
if(tValues[i] == null) {
throw new IllegalArgumentException("An error occurred reading line number:" + lineCnt+" column number:" + (i+1)+"\n" +
line);
}
}
throw npe;
}
}
domainValues.add(dValues);
rangeValues.add(rValues);
if (tuple != null) tupleValues.add(tuple);
if (isRaster) numElements = rValues.length;
if(onlyReadOneLine) break;
}
int numSamples = rangeValues.size(); // # lines of data
// ***********************************************************
if (debug) {
try {
System.out.println("domain size = "+domainValues.size());
double[] dt = (double[]) domainValues.get(1);
System.out.println("domain.array[0] = "+dt[0]);
System.out.println("range size = "+rangeValues.size());
System.out.println("# samples = "+numSamples);
} catch (Exception er) {System.out.println("out range");}
}
// ***********************************************************
// make Linear1DSets for each possible domain component
Linear1DSet[] lset = new Linear1DSet[numDom];
boolean keepConstant = false;
int numVal = numRng;
if (numDom == 1) numVal = numSamples;
if (numDom == 2 && numRng == 1 && numElements > 1) numVal = numElements;
if (numDom > 2 && numRng == 1 && numElements == 1) {
numVal = numSamples / (2 * numDom);
keepConstant = true;
}
for (int i=0; i<numDom; i++) {
if (gotDomainRanges[i]) {
// if domain was given with a count, use it for 'raster'-type
if (numDom == 2 && numRng == 1 && numElements == 1)
numVal = (int) domainRanges[2][i];
lset[i] = new Linear1DSet(domType.getComponent(i), domainRanges[0][i],
domainRanges[1][i], numVal);
if (debug) System.out.println("lset from domain = "+lset[i]);
} else if (domainPointer[i] == -1 ) {
lset[i] = new Linear1DSet(0., (double)(numVal-1), numVal);
if (debug) System.out.println("lset from range = "+lset[i]);
} else {
lset[i] = null;
}
if (!keepConstant) numVal = numSamples;
}
// now make up the actual domain sets for the function
Set domain = null;
if (numDom == 1) { // for 1-D domains
if (lset[0] == null) {
domain = createAppropriate1DDomain(domType, numSamples, domainValues);
} else {
domain = lset[0];
}
} else if (numDom == 2) { // for 2-D domains
if (lset[0] != null && lset[1] != null) {
domain = new Linear2DSet(domType, lset);
} else {
float[][] samples = new float[numDom][numSamples];
for (int k = 0; k < numDom; k++) {
if (lset[k] == null) {
samples[k] = (getDomSamples(k, numSamples, domainValues))[0];
} else {
samples[k] = (lset[k].getSamples())[0];
}
}
domain = (Set) new Irregular2DSet(domType, samples);
}
} else if (numDom == 3) { // for 3-D domains
if (lset[0] != null && lset[1] != null && lset[2] != null) {
domain = new Linear3DSet(domType, lset);
} else {
float[][] samples = new float[numDom][numSamples];
for (int k = 0; k < numDom; k++) {
if (lset[k] == null) {
samples[k] = (getDomSamples(k, numSamples, domainValues))[0];
} else {
samples[k] = (lset[k].getSamples())[0];
}
}
domain = (Set) new Irregular3DSet(domType, samples);
}
} else { // N-D domains (can only use LinearSets!!
boolean allLinear = true;
for (int k = 0; k<numDom; k++) {
if (lset[k] == null) allLinear = false;
}
if (allLinear) {
if (debug) System.out.println("#### Making LinearNDset");
domain = new LinearNDSet(domType, lset);
} else {
if (debug) System.out.println("#### Making IrregularSet");
float[][] samples = new float[numDom][numSamples];
for (int k=0; k<numDom; k++) {
if (lset[k] == null) {
samples[k] = (getDomSamples(k, numSamples, domainValues))[0];
} else {
samples[k] = (lset[k].getSamples())[0];
}
}
domain = new IrregularSet(domType, samples);
}
}
try {
ff = new FlatField((FunctionType) mt, domain,
null, null, rangeSets, rangeUnits);
} catch (FieldException fe) {
field = new FieldImpl((FunctionType) mt, domain);
} catch (UnitException fe) {
System.out.println("#### Problem with Units; attempting to make Field anyway");
field = new FieldImpl((FunctionType) mt, domain);
}
//*************************************************
if (debug) {
if (ff != null) {
System.out.println("ff.Length "+ff.getLength());
System.out.println("ff.getType "+ff.getType());
}
if (field != null) {
System.out.println("field.Length "+field.getLength());
System.out.println("field.getType "+field.getType());
}
System.out.println("domain = "+domain);
System.out.println("size of a = "+numRng+" x "+(numSamples*numElements));
}
//*************************************************
double[][]a = new double[numRng][numSamples * numElements];
Tuple[] at = new Tuple[numSamples];
// if this is a raster then the samples are in a slightly
// difielderent form ...
if (isRaster) {
int samPointer = 0;
for (int i=0; i<numSamples; i++) {
double[] rs = (double[])(rangeValues.get(i));
for (int j=0; j<numElements; j++) {
a[0][samPointer] = rs[j];
samPointer ++;
}
}
} else {
for (int i=0; i<numSamples; i++) {
double[] rs = (double[])(rangeValues.get(i));
for (int j=0; j<numRng; j++) {
a[j][i] = rs[j];
}
if (!tupleValues.isEmpty()) {
at[i] = (Tuple) tupleValues.get(i);
}
}
}
// set samples
if (debug) System.out.println("about to field.setSamples");
try {
if (ff != null) {
if (debug) System.out.println("#### ff is not null");
ff.setSamples(a, false);
field = (Field) ff;
} else {
if (debug) System.out.println("#### ff is null..use FieldImpl");
field.setSamples(at, false);
}
} catch (Exception ffe) {ffe.printStackTrace(); }
// make up error estimates and set them
ErrorEstimate[] es = new ErrorEstimate[numRng];
for (int i=0; i<numRng; i++) {
es[i] = new ErrorEstimate(a[i], rangeErrorEstimates[i], rangeUnits[i]);
}
try {
((FlatField) field).setRangeErrors(es);
} catch (FieldException fe) {
if (debug) System.out.println("caught "+fe);
// not a flatfield
// don't setRangeErrors
} catch (ClassCastException cce) {
if (debug) System.out.println("caught "+cce);
// not a flatfield
// don't setRangeErrors
}
if (debug) {
new visad.jmet.DumpType().dumpDataType(field,System.out);
System.out.println("field = "+field);
}
bis.close();
}
|
diff --git a/src/main/java/org/dynmap/ClientUpdateComponent.java b/src/main/java/org/dynmap/ClientUpdateComponent.java
index 97fa8210..14173101 100644
--- a/src/main/java/org/dynmap/ClientUpdateComponent.java
+++ b/src/main/java/org/dynmap/ClientUpdateComponent.java
@@ -1,75 +1,77 @@
package org.dynmap;
import static org.dynmap.JSONUtils.a;
import static org.dynmap.JSONUtils.s;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.entity.Player;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
public class ClientUpdateComponent extends Component {
public ClientUpdateComponent(final DynmapPlugin plugin, ConfigurationNode configuration) {
super(plugin, configuration);
plugin.events.addListener("buildclientupdate", new Event.Listener<ClientUpdateEvent>() {
@Override
public void triggered(ClientUpdateEvent e) {
buildClientUpdate(e);
}
});
}
protected void buildClientUpdate(ClientUpdateEvent e) {
World world = e.world.world;
JSONObject u = e.update;
long since = e.timestamp;
String worldName = world.getName();
s(u, "servertime", world.getTime() % 24000);
s(u, "hasStorm", world.hasStorm());
s(u, "isThundering", world.isThundering());
s(u, "players", new JSONArray());
Player[] players = plugin.playerList.getVisiblePlayers();
for(int i=0;i<players.length;i++) {
Player p = players[i];
Location pl = p.getLocation();
JSONObject jp = new JSONObject();
s(jp, "type", "player");
s(jp, "name", ChatColor.stripColor(p.getDisplayName()));
s(jp, "account", p.getName());
/* Don't leak player location for world not visible on maps, or if sendposition disbaled */
DynmapWorld pworld = MapManager.mapman.worldsLookup.get(p.getWorld().getName());
- if(configuration.getBoolean("sendpositon", true) && (pworld != null) && pworld.sendposition) {
+ /* Fix typo on 'sendpositon' to 'sendposition', keep bad one in case someone used it */
+ if(configuration.getBoolean("sendposition", true) && configuration.getBoolean("sendpositon", true) &&
+ (pworld != null) && pworld.sendposition) {
s(jp, "world", p.getWorld().getName());
s(jp, "x", pl.getX());
s(jp, "y", pl.getY());
s(jp, "z", pl.getZ());
}
else {
s(jp, "world", "-some-other-bogus-world-");
s(jp, "x", 0.0);
s(jp, "y", 64.0);
s(jp, "z", 0.0);
}
/* Only send health if enabled AND we're on visible world */
if (configuration.getBoolean("sendhealth", false) && (pworld != null) && pworld.sendhealth) {
s(jp, "health", p.getHealth());
s(jp, "armor", Armor.getArmorPoints(p));
}
else {
s(jp, "health", 0);
s(jp, "armor", 0);
}
a(u, "players", jp);
}
s(u, "updates", new JSONArray());
for(Object update : plugin.mapManager.getWorldUpdates(worldName, since)) {
a(u, "updates", (Client.Update)update);
}
}
}
| true | true | protected void buildClientUpdate(ClientUpdateEvent e) {
World world = e.world.world;
JSONObject u = e.update;
long since = e.timestamp;
String worldName = world.getName();
s(u, "servertime", world.getTime() % 24000);
s(u, "hasStorm", world.hasStorm());
s(u, "isThundering", world.isThundering());
s(u, "players", new JSONArray());
Player[] players = plugin.playerList.getVisiblePlayers();
for(int i=0;i<players.length;i++) {
Player p = players[i];
Location pl = p.getLocation();
JSONObject jp = new JSONObject();
s(jp, "type", "player");
s(jp, "name", ChatColor.stripColor(p.getDisplayName()));
s(jp, "account", p.getName());
/* Don't leak player location for world not visible on maps, or if sendposition disbaled */
DynmapWorld pworld = MapManager.mapman.worldsLookup.get(p.getWorld().getName());
if(configuration.getBoolean("sendpositon", true) && (pworld != null) && pworld.sendposition) {
s(jp, "world", p.getWorld().getName());
s(jp, "x", pl.getX());
s(jp, "y", pl.getY());
s(jp, "z", pl.getZ());
}
else {
s(jp, "world", "-some-other-bogus-world-");
s(jp, "x", 0.0);
s(jp, "y", 64.0);
s(jp, "z", 0.0);
}
/* Only send health if enabled AND we're on visible world */
if (configuration.getBoolean("sendhealth", false) && (pworld != null) && pworld.sendhealth) {
s(jp, "health", p.getHealth());
s(jp, "armor", Armor.getArmorPoints(p));
}
else {
s(jp, "health", 0);
s(jp, "armor", 0);
}
a(u, "players", jp);
}
s(u, "updates", new JSONArray());
for(Object update : plugin.mapManager.getWorldUpdates(worldName, since)) {
a(u, "updates", (Client.Update)update);
}
}
| protected void buildClientUpdate(ClientUpdateEvent e) {
World world = e.world.world;
JSONObject u = e.update;
long since = e.timestamp;
String worldName = world.getName();
s(u, "servertime", world.getTime() % 24000);
s(u, "hasStorm", world.hasStorm());
s(u, "isThundering", world.isThundering());
s(u, "players", new JSONArray());
Player[] players = plugin.playerList.getVisiblePlayers();
for(int i=0;i<players.length;i++) {
Player p = players[i];
Location pl = p.getLocation();
JSONObject jp = new JSONObject();
s(jp, "type", "player");
s(jp, "name", ChatColor.stripColor(p.getDisplayName()));
s(jp, "account", p.getName());
/* Don't leak player location for world not visible on maps, or if sendposition disbaled */
DynmapWorld pworld = MapManager.mapman.worldsLookup.get(p.getWorld().getName());
/* Fix typo on 'sendpositon' to 'sendposition', keep bad one in case someone used it */
if(configuration.getBoolean("sendposition", true) && configuration.getBoolean("sendpositon", true) &&
(pworld != null) && pworld.sendposition) {
s(jp, "world", p.getWorld().getName());
s(jp, "x", pl.getX());
s(jp, "y", pl.getY());
s(jp, "z", pl.getZ());
}
else {
s(jp, "world", "-some-other-bogus-world-");
s(jp, "x", 0.0);
s(jp, "y", 64.0);
s(jp, "z", 0.0);
}
/* Only send health if enabled AND we're on visible world */
if (configuration.getBoolean("sendhealth", false) && (pworld != null) && pworld.sendhealth) {
s(jp, "health", p.getHealth());
s(jp, "armor", Armor.getArmorPoints(p));
}
else {
s(jp, "health", 0);
s(jp, "armor", 0);
}
a(u, "players", jp);
}
s(u, "updates", new JSONArray());
for(Object update : plugin.mapManager.getWorldUpdates(worldName, since)) {
a(u, "updates", (Client.Update)update);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.